latin: reuse common function to display code128
[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         # optional amends
109         push @{ $meta->{raw} }, (
110                 '<!--[if lte IE 6]><style> .help dl.legend dt {margin:0 0 1px} </style><![endif]-->',
111                 '<!--[if lte IE 7]><style> .help dl.legend dd {float:none} </style><![endif]-->',
112                 !$showkeys ? '<style type="text/css"> .no {visibility:hidden} </style>'
113                         : $showkeys eq 'ghost' ? '<style type="text/css"> .no, .alias {opacity:.5} </style>'
114                         : (),
115                 '<script type="text/javascript" src="/keys.js?1.6"></script>',
116         ) if $meta->{keys};
117
118         # leading output
119         $header{content_type} = "text/html; charset=$meta->{charset}";
120         say '<!DOCTYPE html>';
121         say '<html lang="en">';
122         say '';
123         say '<head>';
124         say sprintf '<meta http-equiv="content-type" content="%s">', $header{content_type};
125         say sprintf '<title>%s</title>', $meta->{title};
126         say sprintf '<meta name="description" content="%s">', EscapeHTML($_)
127                 for join(' ', @{ $meta->{description} }) || ();
128         say sprintf '<meta name="keywords" content="%s">', EscapeHTML($_)
129                 for join(', ', @{ $meta->{keywords} }) || ();
130         say '<meta name="viewport" content="width=device-width, initial-scale=1">';
131         say '<link rel="icon" type="image/png" href="/clip.png">';
132         say for stylesheet($meta->{stylesheet});
133         say for map { @{$_} } $meta->{raw} || ();
134         say '<meta name="robots" content="noindex">' if $Dev;
135         say '</head>';
136         say '';
137         say sprintf '<body id="%s">', $file;
138
139         # development version indicator
140         printf '<p style="%s">beta</p>', join('; ',
141                 'position: fixed',
142                 'right: 1em',
143                 'opacity: .5',
144                 'border: 1ex solid red',
145                 'border-width: 1ex 0',
146                 'z-index: 1',
147                 'background: inherit',
148         ) if $Dev;
149
150         # prepare trailing output
151         PLP_END {
152                 print <<"EOT";
153 <p class="footer">
154         <a href="/" rel="start">sheet.shiar.nl</a>/$file.<a href="/source/$file.plp"
155          rel="source" title="Written in Perl">plp</a>
156         version <a href="http://git.shiar.nl/sheet.git/history/HEAD:/$file.plp"
157          rel="vcs-git" title="Git repository">$meta->{version}</a>
158         created by <a href="http://shiar.nl/" rel="author">Shiar</a> •
159         <a href="http://www.fsf.org/licensing/licenses/agpl-3.0.html" rel="license copyright"
160          title="Licensed under the GNU Affero General Public License, version 3">AGPLv3</a>
161 EOT
162                 say sprintf '• %.3fs', Time::HiRes::tv_interval($Time) if $Dev;
163                 say '</p>';
164                 say '';
165                 say '</html>';
166         };
167 }
168