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