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