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