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