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