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