common: format page attribute "image" as og header
[sheet.git] / common.inc.plp
1 <:
2 use 5.014;
3 use strict;
4 use utf8;
5 use warnings;
6 no  warnings 'qw';  # you know what you doing
7 no  warnings 'uninitialized';  # save some useless checks for more legible code
8 use open ':std' => ':utf8';
9
10 use File::stat 'stat';
11 use HTTP::Date;
12 use Encode qw( decode_utf8 );
13
14 our $Dev;
15
16 sub Alert {
17         my ($html, $debug) = @_;
18         ref $html eq 'ARRAY' or $html = [$html];
19         my ($title, @lines) = @{$html};
20         my $body = "<h2>$title</h2>";
21         $body .= "\n<p>$_</p>" for @lines;
22         $body .= "\n<pre>$debug</pre>" if $Dev and $debug;
23         say "<div class=error>$body</div>\n";
24 }
25
26 sub Abort {
27         my ($html, $code, $debug) = @_;
28         unless ($PLP::sentheaders) {
29                 $header{Status} = $code || 500;
30         }
31         elsif ($Dev) {
32                 ref $html eq 'ARRAY' or $html = [$html];
33                 push @{$html}, "Also failed to set HTTP status <q>$code</q>"
34                         . " after output!";
35         }
36         Alert($html, $debug);
37         exit;
38 }
39
40 BEGIN {
41         require Time::HiRes;
42         our $Time = [Time::HiRes::gettimeofday()];
43
44         push @INC, '.';
45
46         # user request
47         our $Dev = $ENV{HTTP_HOST} =~ /\bdev\./;
48 }
49
50 our $Request //= decode_utf8($ENV{PATH_INFO} =~ s{^/}{}r);
51
52 our $style;
53
54 $header{content_type} = 'text/html; charset=utf-8';
55
56 sub stylesheet {
57         my ($avail) = @_;
58         my @avail = ref $avail eq 'ARRAY' ? @{$avail} : $avail or return;
59         my %styles = map {$_ => $_} @avail;
60
61         if (defined( my $setstyle = $get{style} )) {
62                 $style = $styles{ $setstyle };
63                 eval {
64                         require CGI::Cookie;
65                         my $cookie = CGI::Cookie->new(
66                                 -name    => 'style',
67                                 -value   => $setstyle || '',
68                                 -path    => '/',  # site-wide
69                                 -expires => $setstyle ? '+5y' : '-1d',
70                         ) or die "empty object returned\n";
71                         AddCookie($cookie->as_string);
72                 } or warn "Unable to create style cookie: $@";
73         }
74
75         $style ||= exists $cookie{style} && $styles{ $cookie{style} } || $avail[0];
76
77         return map { sprintf(
78                 '<link rel="%s" type="text/css" media="all" href="%s" title="%s">',
79                 $_ eq $style ? 'stylesheet' : 'alternate stylesheet', "/$_.css?1.14", $_
80         ) } @avail;
81 }
82
83 sub checkmodified {
84         my $lastmod = 0;
85         for (@_) {
86                 my $mod = stat $_ or next;
87                 $mod = $mod->mtime or next;
88                 $lastmod = $mod if $mod gt $lastmod;
89         }
90
91         for ($ENV{HTTP_IF_MODIFIED_SINCE} || ()) {
92                 next if str2time($_) < $lastmod;
93                 $header{status} = '304 Same old';
94                 exit;
95         }
96
97         $header{'Last-Modified'} = time2str($lastmod);
98 }
99
100 sub Data {
101         my ($filename) = @_;
102         my @data = eval {
103                 open my $cache, '<:raw', "data/$filename.json"
104                         or return do "./$filename.inc.pl"; # silent fallback to original code
105                 require JSON;
106                 local $/; # slurp
107                 return JSON::decode_json(readline $cache);
108         };
109         if ($! or $@ or !@data or !$data[0]) {
110                 die ['Table data not found', $@ || $!];
111         }
112         if (@data == 1 and ref $data[0] eq 'HASH' and not %{$data[0]}) {
113                 die ['Table data missing'];
114         }
115         return wantarray ? @data : $data[0]; # list compatibility like do does
116 }
117
118 sub Html {
119         my ($meta) = @_;
120
121         unless ($meta->{nocache}) {
122                 # announce and check data modification
123                 checkmodified(
124                         $ENV{SCRIPT_FILENAME},
125                         (grep { /\bShiar_/ } values %INC),
126                         $meta->{data} ? @{ $meta->{data} } : (),
127                 );
128                 $header{'Cache-Control'} = 'max-age='.(24*60*60);
129         }
130
131         # default fallbacks
132         $meta->{stylesheet} ||= [qw( light dark circus mono red )];
133         $meta->{charset} ||= 'utf-8';
134         $meta->{lang} ||= 'en';
135
136         # convert options to arrays
137         ref $_ eq 'ARRAY' or $_ = [$_]
138                 for grep {$_} $meta->{raw}, $meta->{description}, $meta->{keywords};
139
140         # document headers before output
141         $header{content_type} = "text/html; charset=$meta->{charset}"
142                 unless $PLP::sentheaders;
143         exit if $ENV{REQUEST_METHOD} eq 'HEAD';
144         unshift @{ $meta->{raw} }, stylesheet($meta->{stylesheet});
145
146         push @{ $meta->{raw} }, (
147                 '<link rel="stylesheet" type="text/css" media="monochrome" href="/mono.css?1.11" title="light">',
148         );
149
150         if (my $img = $meta->{image}) {
151                 my $proto = sprintf('http%s://', !!$ENV{HTTPS} && 's');
152                 my $url = "$proto$ENV{HTTP_HOST}/$img";
153                 push @{ $meta->{raw} }, (
154                         qq(<meta property="og:image" content="$url" />),
155                 );
156         }
157
158         my ($file) = $ENV{SCRIPT_FILENAME} =~ m{ ([^/]+) \.plp$ }x;
159
160         PLP_START {
161                 # leading output
162                 say '<!DOCTYPE html>';
163                 say qq(<html lang="$meta->{lang}">);
164                 say '';
165                 say '<head>';
166                 say sprintf '<meta http-equiv="content-type" content="%s">', $_
167                         for $header{content_type};
168                 say sprintf '<title>%s</title>', $meta->{title};
169                 say sprintf '<meta name="description" content="%s">', EscapeHTML($_)
170                         for join(' ', @{ $meta->{description} // [] }) || ();
171                 say sprintf '<meta name="keywords" content="%s">', EscapeHTML($_)
172                         for join(', ', @{ $meta->{keywords} // [] }) || ();
173                 say '<meta name="viewport" content="width=device-width, initial-scale=1">';
174                 say '<link rel="icon" type="image/png" href="/clip.png">';
175                 say for map { @{$_} } $meta->{raw} || ();
176                 say '<meta name="robots" content="noindex">' if $Dev;
177                 say '</head>';
178                 say '';
179                 say sprintf '<body id="%s">', $file;
180
181                 # development version indicator
182                 printf '<p style="%s">beta</p>', join('; ',
183                         'position: fixed',
184                         'right: 1em',
185                         'opacity: .5',
186                         'border: 1ex solid red',
187                         'border-width: 1ex 0',
188                         'z-index: 1',
189                         'background: inherit',
190                 ) if $Dev;
191         };
192
193         # prepare trailing output
194         PLP_END {
195                 print <<"EOT";
196 <p class="footer">
197         <a href="/" rel="start">sheet.shiar.nl</a>/$file.<a href="/source/$file.plp"
198          rel="source" title="Written in Perl">plp</a>
199         version <a href="http://git.shiar.nl/sheet.git/history/HEAD:/$file.plp"
200          rel="vcs-git" title="Git repository">$meta->{version}</a>
201         created by <a href="http://shiar.nl/" rel="author">Shiar</a> •
202         <a href="http://www.fsf.org/licensing/licenses/agpl-3.0.html"
203          title="Licensed under the GNU Affero General Public License, version 3"
204          rel="license">AGPLv3</a>
205 EOT
206                 our $Time;
207                 say sprintf '• %.3fs', Time::HiRes::tv_interval($Time) if $Dev and $Time;
208                 say '</p>';
209                 say '';
210                 say '</html>';
211         };
212 }
213
214 BEGIN {
215         $PLP::ERROR = sub {
216                 my ($message, $html) = @_;
217                 if (ref $message) {
218                         warn join ': ', @{$message};
219                         $html = shift @{$message};
220                 }
221                 else {
222                         warn $message;
223                         $message = [];
224                 }
225                 unless ($PLP::sentheaders) {
226                         Html({nocache => 1});
227                         say '<h1>Page unavailable</h1>';
228                 }
229                 Alert("Fatal error: $html.", @{$message});
230         };
231 }
232
233 sub showlink {
234         my ($title, $href, $selected) = @_;
235         EscapeHTML($title);
236         return $title if not $href;
237         return "<strong>$title</strong>" if $selected;
238         return sprintf '<a href="%s">%s</a>', EscapeHTML($href), $title;
239 }
240