4bc68a67ba10379fe6041fb19d1a70a060afb7d0
[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 ||= $styles{$_} for $cookie{style} || ();
76         my $setstyle = $style;
77         $style ||= $avail[0];
78         return $setstyle;
79 }
80
81 sub checkmodified {
82         my $lastmod = 0;
83         for (@_) {
84                 my $mod = stat $_ or next;
85                 $mod = $mod->mtime or next;
86                 $lastmod = $mod if $mod gt $lastmod;
87         }
88
89         for ($ENV{HTTP_IF_MODIFIED_SINCE} || ()) {
90                 next if str2time($_) < $lastmod;
91                 $header{status} = '304 Same old';
92                 exit;
93         }
94
95         $header{'Last-Modified'} = time2str($lastmod);
96 }
97
98 sub Data {
99         my ($filename) = @_;
100         my @data = eval {
101                 open my $cache, '<:raw', "data/$filename.json"
102                         or return do "./$filename.inc.pl"; # silent fallback to original code
103                 require JSON;
104                 local $/; # slurp
105                 return JSON::decode_json(readline $cache);
106         };
107         if ($@ or !@data or !$data[0]) {
108                 die ['Table data not found', $@ || $!];
109         }
110         if (@data == 1 and ref $data[0] eq 'HASH' and not %{$data[0]}) {
111                 die ['Table data missing'];
112         }
113         return wantarray ? @data : $data[0]; # list compatibility like do does
114 }
115
116 sub Html {
117         my ($meta) = @_;
118
119         unless ($meta->{nocache}) {
120                 # announce and check data modification
121                 checkmodified(
122                         $ENV{SCRIPT_FILENAME},
123                         (grep { /\bShiar_/ } values %INC),
124                         $meta->{data} ? @{ $meta->{data} } : (),
125                 );
126                 $header{'Cache-Control'} = 'max-age='.(24*60*60);
127         }
128
129         # default fallbacks
130         $meta->{stylesheet} ||= [qw( light dark circus mono red )];
131         $meta->{charset} ||= 'utf-8';
132         $meta->{lang} ||= 'en';
133
134         # convert options to arrays
135         ref $_ eq 'ARRAY' or $_ = [$_]
136                 for grep {$_} $meta->{raw}, $meta->{description}, $meta->{keywords};
137
138         # document headers before output
139         $header{content_type} = "text/html; charset=$meta->{charset}"
140                 unless $PLP::sentheaders;
141         exit if $ENV{REQUEST_METHOD} eq 'HEAD';
142
143         unshift @{ $meta->{raw} }, (
144                 '<link rel="stylesheet" type="text/css" media="all" href="/light.css?1.20">',
145         );
146         $meta->{stylesheet} = stylesheet($meta->{stylesheet});
147
148         if (my $img = $meta->{image}) {
149                 my $proto = sprintf('http%s://', !!$ENV{HTTPS} && 's');
150                 my $url = "$proto$ENV{HTTP_HOST}/$img";
151                 push @{ $meta->{raw} }, (
152                         qq(<meta property="og:image" content="$url" />),
153                 );
154         }
155
156         my ($file) = $ENV{SCRIPT_FILENAME} =~ m{ ([^/]+) \.plp$ }x;
157
158         $meta->{canonical} //= "/$file" . ($Request ne '' && "/$Request");
159         if (my $url = $meta->{canonical}) {
160                 $url = "https://sheet.shiar.nl$url";
161                 push @{ $meta->{raw} }, qq(<link rel="canonical" href="$url" />);
162         }
163
164         PLP_START {
165                 # leading output
166                 say '<!DOCTYPE html>';
167                 my $rootattr = '';
168                 $rootattr .= qq( class="s-$_") for $meta->{stylesheet} || ();
169                 say qq(<html lang="$meta->{lang}"$rootattr>);
170                 say '';
171                 say '<head>';
172                 say sprintf '<meta http-equiv="content-type" content="%s">', $_
173                         for $header{content_type};
174                 say sprintf '<title>%s</title>', $meta->{title};
175                 say sprintf '<meta name="description" content="%s">', EscapeHTML($_)
176                         for join(' ', @{ $meta->{description} // [] }) || ();
177                 say sprintf '<meta name="keywords" content="%s">', EscapeHTML($_)
178                         for join(', ', @{ $meta->{keywords} // [] }) || ();
179                 say '<meta name="viewport" content="width=device-width, initial-scale=1">';
180                 say '<link rel="icon" type="image/png" href="/clip.png">';
181                 say for map { @{$_} } $meta->{raw} || ();
182                 say '<meta name="robots" content="noindex">' if $Dev;
183                 say "<script>$_</script>" for join($/,
184                         "docroot = document.documentElement;",
185                         "if (docroot.className == '') {",
186                         "new Map([",
187                                 "['s-mono','(monochrome)'],",
188                                 "['s-dark','(prefers-color-scheme: dark)'],",
189                                 "['s-circus','(prefers-contrast: more)'],",
190                         "]).forEach((q,c) => {",
191                                 "if (m = window.matchMedia(q))",
192                                 "(m.onchange = e => docroot.classList.toggle(c, e.matches))(m)",
193                         "})",
194                         "}",
195                 );
196                 say '</head>';
197                 say '';
198                 say sprintf '<body id="%s">', $file;
199
200                 # development version indicator
201                 printf '<p style="%s">beta</p>', join('; ',
202                         'position: fixed',
203                         'right: 1em',
204                         'opacity: .5',
205                         'border: 1ex solid red',
206                         'border-width: 1ex 0',
207                         'z-index: 1',
208                         'background: inherit',
209                 ) if $Dev;
210         };
211
212         # prepare trailing output
213         PLP_END {
214                 print <<"EOT";
215 <p class="footer">
216         <a href="/" rel="start">sheet.shiar.nl</a>/$file.<a href="/source/$file.plp"
217          rel="source" title="Written in Perl">plp</a>
218         version <a href="http://git.shiar.nl/sheet.git/history/HEAD:/$file.plp"
219          rel="vcs-git" title="Git repository">$meta->{version}</a>
220         created by <a href="http://shiar.nl/" rel="author">Shiar</a> •
221         <a href="http://www.fsf.org/licensing/licenses/agpl-3.0.html"
222          title="Licensed under the GNU Affero General Public License, version 3"
223          rel="license">AGPLv3</a>
224 EOT
225                 our $Time;
226                 say sprintf '• %.3fs', Time::HiRes::tv_interval($Time) if $Dev and $Time;
227                 say '</p>';
228                 say '';
229                 say '</html>';
230         };
231 }
232
233 BEGIN {
234         $PLP::ERROR = sub {
235                 my ($message, $html) = @_;
236                 if (ref $message) {
237                         warn join ': ', @{$message};
238                         $html = shift @{$message};
239                 }
240                 else {
241                         warn $message;
242                         $message = [];
243                 }
244                 unless ($PLP::sentheaders) {
245                         Html({nocache => 1});
246                         say '<h1>Page unavailable</h1>';
247                 }
248                 Alert("Fatal error: $html.", @{$message});
249         };
250 }
251
252 sub showlink {
253         my ($title, $href, $selected) = @_;
254         EscapeHTML($title);
255         return $title if not $href;
256         return "<strong>$title</strong>" if $selected;
257         return sprintf '<a href="%s">%s</a>', EscapeHTML($href), $title;
258 }
259