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