vimperator: describe caret mode functionality
[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 )];
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         push @{ $meta->{raw} }, (
121                 '<link rel="stylesheet" type="text/css" media="monochrome" href="/mono.css?1.10" title="light">',
122         );
123
124         # optional amends
125         push @{ $meta->{raw} }, (
126                 '<!--[if lte IE 6]><style> .help dl.legend dt {margin:0 0 1px} </style><![endif]-->',
127                 '<!--[if lte IE 7]><style> .help dl.legend dd {float:none} </style><![endif]-->',
128                 !$showkeys ? '<style> .no {visibility:hidden} </style>' :
129                 $showkeys eq 'ghost' ? '<style> .no, .alias {opacity:.5} </style>' : (),
130                 '<script type="text/javascript" src="/keys.js?1.6" async></script>',
131         ) if $meta->{keys};
132
133         # leading output
134         say '<!DOCTYPE html>';
135         say '<html lang="en">';
136         say '';
137         say '<head>';
138         say sprintf '<meta http-equiv="content-type" content="%s">', $_
139                 for $header{content_type};
140         say sprintf '<title>%s</title>', $meta->{title};
141         say sprintf '<meta name="description" content="%s">', EscapeHTML($_)
142                 for join(' ', @{ $meta->{description} }) || ();
143         say sprintf '<meta name="keywords" content="%s">', EscapeHTML($_)
144                 for join(', ', @{ $meta->{keywords} }) || ();
145         say '<meta name="viewport" content="width=device-width, initial-scale=1">';
146         say '<link rel="icon" type="image/png" href="/clip.png">';
147         say for map { @{$_} } $meta->{raw} || ();
148         say '<meta name="robots" content="noindex">' if $Dev;
149         say '</head>';
150         say '';
151         say sprintf '<body id="%s">', $file;
152
153         # development version indicator
154         printf '<p style="%s">beta</p>', join('; ',
155                 'position: fixed',
156                 'right: 1em',
157                 'opacity: .5',
158                 'border: 1ex solid red',
159                 'border-width: 1ex 0',
160                 'z-index: 1',
161                 'background: inherit',
162         ) if $Dev;
163
164         # prepare trailing output
165         PLP_END {
166                 print <<"EOT";
167 <p class="footer">
168         <a href="/" rel="start">sheet.shiar.nl</a>/$file.<a href="/source/$file.plp"
169          rel="source" title="Written in Perl">plp</a>
170         version <a href="http://git.shiar.nl/sheet.git/history/HEAD:/$file.plp"
171          rel="vcs-git" title="Git repository">$meta->{version}</a>
172         created by <a href="http://shiar.nl/" rel="author">Shiar</a> •
173         <a href="http://www.fsf.org/licensing/licenses/agpl-3.0.html"
174          title="Licensed under the GNU Affero General Public License, version 3"
175          rel="license">AGPLv3</a>
176 EOT
177                 say sprintf '• %.3fs', Time::HiRes::tv_interval($Time) if $Dev and $Time;
178                 say '</p>';
179                 say '';
180                 say '</html>';
181         };
182 }
183
184 sub showlink {
185         my ($title, $href, $selected) = @_;
186         return sprintf(
187                 !$href ? '%s' :
188                 $selected ? '<strong>%s</strong>' : '<a href="%2$s">%s</a>',
189                 EscapeHTML($title), EscapeHTML($href)
190         );
191 }
192