common: global Data() to parse perl code includes
[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 our $showkeys //= !exists $get{keys} ? undef :
54         ($get{keys} ne '0' && ($get{keys} || 'always'));
55
56 $header{content_type} = 'text/html; charset=utf-8';
57
58 sub stylesheet {
59         my ($avail) = @_;
60         my @avail = ref $avail eq 'ARRAY' ? @{$avail} : $avail or return;
61         my %styles = map {$_ => $_} @avail;
62
63         if (defined( my $setstyle = $get{style} )) {
64                 $style = $styles{ $setstyle };
65                 eval {
66                         require CGI::Cookie;
67                         my $cookie = CGI::Cookie->new(
68                                 -name    => 'style',
69                                 -value   => $setstyle || '',
70                                 -path    => '/',  # site-wide
71                                 -expires => $setstyle ? '+5y' : '-1d',
72                         ) or die "empty object returned\n";
73                         AddCookie($cookie->as_string);
74                 } or warn "Unable to create style cookie: $@";
75         }
76
77         $style ||= exists $cookie{style} && $styles{ $cookie{style} } || $avail[0];
78
79         return map { sprintf(
80                 '<link rel="%s" type="text/css" media="all" href="%s" title="%s">',
81                 $_ eq $style ? 'stylesheet' : 'alternate stylesheet', "/$_.css?1.13", $_
82         ) } @avail;
83 }
84
85 sub checkmodified {
86         my $lastmod = 0;
87         for (@_) {
88                 my $mod = stat $_ or next;
89                 $mod = $mod->mtime or next;
90                 $lastmod = $mod if $mod gt $lastmod;
91         }
92
93         for ($ENV{HTTP_IF_MODIFIED_SINCE} || ()) {
94                 next if str2time($_) < $lastmod;
95                 $header{status} = '304 Same old';
96                 exit;
97         }
98
99         $header{'Last-Modified'} = time2str($lastmod);
100 }
101
102 sub Data {
103         my ($filename) = @_;
104         my @data = eval {
105                 do "$filename.inc.pl";
106         };
107         if ($! or $@ 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
133         # convert options to arrays
134         ref $_ eq 'ARRAY' or $_ = [$_]
135                 for grep {$_} $meta->{raw}, $meta->{description}, $meta->{keywords};
136
137         # document headers before output
138         $header{content_type} = "text/html; charset=$meta->{charset}"
139                 unless $PLP::sentheaders;
140         unshift @{ $meta->{raw} }, stylesheet($meta->{stylesheet});
141
142         push @{ $meta->{raw} }, (
143                 '<link rel="stylesheet" type="text/css" media="monochrome" href="/mono.css?1.11" title="light">',
144         );
145
146         # optional amends
147         push @{ $meta->{raw} }, (
148                 '<!--[if lte IE 6]><style> .help dl.legend dt {margin:0 0 1px} </style><![endif]-->',
149                 '<!--[if lte IE 7]><style> .help dl.legend dd {float:none} </style><![endif]-->',
150                 !$showkeys ? '<style> .no {visibility:hidden} </style>' :
151                 $showkeys eq 'ghost' ? '<style> .no, .alias {opacity:.5} </style>' : (),
152                 '<script type="text/javascript" src="/keys.js?1.6" async></script>',
153         ) if $meta->{keys};
154
155         my ($file) = $ENV{SCRIPT_FILENAME} =~ m{ ([^/]+) \.plp$ }x;
156
157         PLP_START {
158                 # leading output
159                 say '<!DOCTYPE html>';
160                 say '<html lang="en">';
161                 say '';
162                 say '<head>';
163                 say sprintf '<meta http-equiv="content-type" content="%s">', $_
164                         for $header{content_type};
165                 say sprintf '<title>%s</title>', $meta->{title};
166                 say sprintf '<meta name="description" content="%s">', EscapeHTML($_)
167                         for join(' ', @{ $meta->{description} // [] }) || ();
168                 say sprintf '<meta name="keywords" content="%s">', EscapeHTML($_)
169                         for join(', ', @{ $meta->{keywords} // [] }) || ();
170                 say '<meta name="viewport" content="width=device-width, initial-scale=1">';
171                 say '<link rel="icon" type="image/png" href="/clip.png">';
172                 say for map { @{$_} } $meta->{raw} || ();
173                 say '<meta name="robots" content="noindex">' if $Dev;
174                 say '</head>';
175                 say '';
176                 say sprintf '<body id="%s">', $file;
177
178                 # development version indicator
179                 printf '<p style="%s">beta</p>', join('; ',
180                         'position: fixed',
181                         'right: 1em',
182                         'opacity: .5',
183                         'border: 1ex solid red',
184                         'border-width: 1ex 0',
185                         'z-index: 1',
186                         'background: inherit',
187                 ) if $Dev;
188         };
189
190         # prepare trailing output
191         PLP_END {
192                 print <<"EOT";
193 <p class="footer">
194         <a href="/" rel="start">sheet.shiar.nl</a>/$file.<a href="/source/$file.plp"
195          rel="source" title="Written in Perl">plp</a>
196         version <a href="http://git.shiar.nl/sheet.git/history/HEAD:/$file.plp"
197          rel="vcs-git" title="Git repository">$meta->{version}</a>
198         created by <a href="http://shiar.nl/" rel="author">Shiar</a> •
199         <a href="http://www.fsf.org/licensing/licenses/agpl-3.0.html"
200          title="Licensed under the GNU Affero General Public License, version 3"
201          rel="license">AGPLv3</a>
202 EOT
203                 our $Time;
204                 say sprintf '• %.3fs', Time::HiRes::tv_interval($Time) if $Dev and $Time;
205                 say '</p>';
206                 say '';
207                 say '</html>';
208         };
209 }
210
211 BEGIN {
212         $PLP::ERROR = sub {
213                 my ($message, $html) = @_;
214                 if (ref $message) {
215                         warn join ': ', @{$message};
216                         $html = shift @{$message};
217                 }
218                 else {
219                         warn $message;
220                         $message = [];
221                 }
222                 unless ($PLP::sentheaders) {
223                         Html({nocache => 1});
224                         say '<h1>Page unavailable</h1>';
225                 }
226                 Alert("Fatal error: $html.", @{$message});
227         };
228 }
229
230 sub showlink {
231         my ($title, $href, $selected) = @_;
232         return sprintf(
233                 !$href ? '%s' :
234                 $selected ? '<strong>%s</strong>' : '<a href="%2$s">%s</a>',
235                 EscapeHTML($title), EscapeHTML($href)
236         );
237 }
238