]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WWW.pm
No ext_urls
[public-inbox.git] / lib / PublicInbox / WWW.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Main web interface for mailing list archives
5 #
6 # We focus on the lowest common denominators here:
7 # - targeted at text-only console browsers (w3m, links, etc..)
8 # - Only basic HTML, CSS only for line-wrapping <pre> text content for GUIs
9 #   and diff/syntax-highlighting (optional)
10 # - No JavaScript, graphics or icons allowed.
11 # - Must not rely on static content
12 # - UTF-8 is only for user-content, 7-bit US-ASCII for us
13 package PublicInbox::WWW;
14 use strict;
15 use v5.10.1;
16 use PublicInbox::Config;
17 use PublicInbox::Hval;
18 use URI::Escape qw(uri_unescape);
19 use PublicInbox::MID qw(mid_escape);
20 use PublicInbox::GitHTTPBackend;
21 use PublicInbox::UserContent;
22 use PublicInbox::WwwStatic qw(r path_info_raw);
23 use PublicInbox::Eml;
24
25 # TODO: consider a routing tree now that we have more endpoints:
26 our $INBOX_RE = qr!\A/([\w\-][\w\.\-\+]*)!;
27 our $MID_RE = qr!([^/]+)!;
28 our $END_RE = qr!(T/|t/|d/|t\.mbox(?:\.gz)?|t\.atom|raw|)!;
29 our $ATTACH_RE = qr!([0-9][0-9\.]*)-($PublicInbox::Hval::FN)!;
30 our $OID_RE = qr![a-f0-9]{7,}!;
31
32 sub new {
33         my ($class, $pi_cfg) = @_;
34         bless { pi_cfg => $pi_cfg // PublicInbox::Config->new }, $class;
35 }
36
37 # backwards compatibility, do not use
38 sub run {
39         my ($req, $method) = @_;
40         PublicInbox::WWW->new->call($req->env);
41 }
42
43 sub call {
44         my ($self, $env) = @_;
45         my $ctx = { env => $env, www => $self };
46
47         # we don't care about multi-value
48         %{$ctx->{qp}} = map {
49                 utf8::decode($_);
50                 tr/+/ /;
51                 my ($k, $v) = split(/=/, $_, 2);
52                 # none of the keys we care about will need escaping
53                 ($k // '', uri_unescape($v // ''))
54         } split(/[&;]+/, $env->{QUERY_STRING});
55
56         my $path_info = path_info_raw($env);
57         my $method = $env->{REQUEST_METHOD};
58
59         if ($method eq 'POST') {
60                 if ($path_info =~ m!$INBOX_RE/(?:(?:git/)?([0-9]+)(?:\.git)?/)?
61                                         (git-upload-pack)\z!x) {
62                         my ($epoch, $path) = ($2, $3);
63                         return invalid_inbox($ctx, $1) ||
64                                 serve_git($ctx, $epoch, $path);
65                 } elsif ($path_info =~ m!$INBOX_RE/(\w+)\.sql\.gz\z!o) {
66                         return get_altid_dump($ctx, $1, $2);
67                 } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$ATTACH_RE\z!o) {
68                         my ($idx, $fn) = ($3, $4);
69                         return invalid_inbox_mid($ctx, $1, $2) ||
70                                 get_attach($ctx, $idx, $fn);
71                 } elsif ($path_info =~ m!$INBOX_RE/!o) {
72                         return invalid_inbox($ctx, $1) || mbox_results($ctx);
73                 }
74         }
75         elsif ($method !~ /\A(?:GET|HEAD)\z/) {
76                 return r(405);
77         }
78
79         # top-level indices and feeds
80         if ($path_info eq '/') {
81                 require PublicInbox::WwwListing;
82                 PublicInbox::WwwListing->response($ctx);
83         } elsif ($path_info eq '/manifest.js.gz') {
84                 require PublicInbox::ManifestJsGz;
85                 PublicInbox::ManifestJsGz->response($ctx);
86         } elsif ($path_info =~ m!$INBOX_RE\z!o) {
87                 invalid_inbox($ctx, $1) || r301($ctx, $1);
88         } elsif ($path_info =~ m!$INBOX_RE(?:/|/index\.html)?\z!o) {
89                 invalid_inbox($ctx, $1) || get_index($ctx);
90         } elsif ($path_info =~ m!$INBOX_RE/(?:atom\.xml|new\.atom)\z!o) {
91                 invalid_inbox($ctx, $1) || get_atom($ctx);
92         } elsif ($path_info =~ m!$INBOX_RE/new\.html\z!o) {
93                 invalid_inbox($ctx, $1) || get_new($ctx);
94         } elsif ($path_info =~ m!$INBOX_RE/description\z!o) {
95                 get_description($ctx, $1);
96         } elsif ($path_info =~ m!$INBOX_RE/(?:(?:git/)?([0-9]+)(?:\.git)?/)?
97                                 ($PublicInbox::GitHTTPBackend::ANY)\z!ox) {
98                 my ($epoch, $path) = ($2, $3);
99                 invalid_inbox($ctx, $1) || serve_git($ctx, $epoch, $path);
100         } elsif ($path_info =~ m!$INBOX_RE/([a-zA-Z0-9_\-]+).mbox\.gz\z!o) {
101                 serve_mbox_range($ctx, $1, $2);
102         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$END_RE\z!o) {
103                 msg_page($ctx, $1, $2, $3);
104
105         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$ATTACH_RE\z!o) {
106                 my ($idx, $fn) = ($3, $4);
107                 invalid_inbox_mid($ctx, $1, $2) || get_attach($ctx, $idx, $fn);
108         # in case people leave off the trailing slash:
109         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/(T|t)\z!o) {
110                 my ($inbox, $mid_ue, $suffix) = ($1, $2, $3);
111                 $suffix .= $suffix =~ /\A[tT]\z/ ? '/#u' : '/';
112                 r301($ctx, $inbox, $mid_ue, $suffix);
113
114         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/R/?\z!o) {
115                 my ($inbox, $mid_ue) = ($1, $2);
116                 r301($ctx, $inbox, $mid_ue, '#R');
117
118         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/f/?\z!o) {
119                 r301($ctx, $1, $2);
120         } elsif ($path_info =~ m!$INBOX_RE/_/text(?:/(.*))?\z!o) {
121                 get_text($ctx, $1, $2);
122         } elsif ($path_info =~ m!$INBOX_RE/([a-zA-Z0-9_\-\.]+)\.css\z!o) {
123                 get_css($ctx, $1, $2);
124         } elsif ($path_info =~ m!$INBOX_RE/manifest\.js\.gz\z!o) {
125                 get_inbox_manifest($ctx, $1, $2);
126         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s/\z!o) {
127                 get_vcs_object($ctx, $1, $2);
128         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s/
129                                 ($PublicInbox::Hval::FN)\z!ox) {
130                 get_vcs_object($ctx, $1, $2, $3);
131         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s\z!o) {
132                 r301($ctx, $1, $2, 's/');
133         } elsif ($path_info =~ m!$INBOX_RE/(\w+)\.sql\.gz\z!o) {
134                 get_altid_dump($ctx, $1, $2);
135         # convenience redirects order matters
136         } elsif ($path_info =~ m!$INBOX_RE/([^/]{2,})\z!o) {
137                 r301($ctx, $1, $2);
138         } elsif ($path_info =~ m!\A/\+/([a-zA-Z0-9_\-\.]+)\.css\z!) {
139                 get_css($ctx, undef, $1); # for WwwListing
140         } else {
141                 legacy_redirects($ctx, $path_info);
142         }
143 }
144
145 # for CoW-friendliness, MOOOOO!  Even for single-process setups,
146 # we want to get all immortal allocations done early to avoid heap
147 # fragmentation since common allocators favor a large contiguous heap.
148 sub preload {
149         my ($self) = @_;
150
151         # populate caches used by Encode internally, since emails
152         # may show up with any encoding.
153         require Encode;
154         Encode::find_encoding($_) for Encode->encodings(':all');
155
156         require PublicInbox::ExtMsg;
157         require PublicInbox::Feed;
158         require PublicInbox::View;
159         require PublicInbox::SearchThread;
160         require PublicInbox::Eml;
161         require PublicInbox::Mbox;
162         require PublicInbox::ViewVCS;
163         require PublicInbox::WwwText;
164         require PublicInbox::WwwAttach;
165         eval {
166                 require PublicInbox::Search;
167                 PublicInbox::Search::load_xapian();
168         };
169         for (qw(SearchView MboxGz WwwAltId)) {
170                 eval "require PublicInbox::$_;";
171         }
172         if (ref($self)) {
173                 my $pi_cfg = $self->{pi_cfg};
174                 if (defined($pi_cfg->{'publicinbox.cgitrc'})) {
175                         $pi_cfg->limiter('-cgit');
176                 }
177                 $pi_cfg->ALL and require PublicInbox::Isearch;
178                 $self->cgit;
179                 $self->stylesheets_prepare($_) for ('', '../', '../../');
180                 $self->news_www;
181         }
182 }
183
184 # private functions below
185
186 sub r404 {
187         my ($ctx) = @_;
188         if ($ctx && $ctx->{mid}) {
189                 require PublicInbox::ExtMsg;
190                 return PublicInbox::ExtMsg::ext_msg($ctx);
191         }
192         r(404);
193 }
194
195 sub news_cgit_fallback ($) {
196         my ($ctx) = @_;
197         my $res = $ctx->{www}->news_www->call($ctx->{env});
198
199         $res->[0] == 404 and ($ctx->{www}->{cgit_fallback} //= do {
200                 my $c = $ctx->{www}->{pi_cfg}->{'publicinbox.cgit'} // 'first';
201                 $c ne 'first' # `fallback' and `rewrite' => true
202         } // 0) and $res = $ctx->{www}->coderepo->srv($ctx);
203
204         ref($res) eq 'ARRAY' && $res->[0] == 404 and
205                 $res = $ctx->{www}->cgit->call($ctx->{env}, $ctx);
206
207         ref($res) eq 'ARRAY' && $res->[0] == 404 &&
208                         !$ctx->{www}->{cgit_fallback} and
209                 $res = $ctx->{www}->coderepo->srv($ctx);
210         $res;
211 }
212
213 # returns undef if valid, array ref response if invalid
214 sub invalid_inbox ($$) {
215         my ($ctx, $inbox) = @_;
216         my $ibx = $ctx->{www}->{pi_cfg}->lookup_name($inbox) //
217                         $ctx->{www}->{pi_cfg}->lookup_ei($inbox);
218         if (defined $ibx) {
219                 $ctx->{ibx} = $ibx;
220                 return;
221         }
222
223         # sometimes linkifiers (not ours!) screw up automatic link
224         # generation and link things intended for nntp:// to https?://,
225         # so try to infer links and redirect them to the appropriate
226         # list URL.
227         news_cgit_fallback($ctx);
228 }
229
230 # returns undef if valid, array ref response if invalid
231 sub invalid_inbox_mid {
232         my ($ctx, $inbox, $mid_ue) = @_;
233         my $ret = invalid_inbox($ctx, $inbox);
234         return $ret if $ret;
235
236         my $mid = $ctx->{mid} = uri_unescape($mid_ue);
237         my $ibx = $ctx->{ibx};
238         if ($mid =~ m!\A([a-f0-9]{2})([a-f0-9]{38})\z!) {
239                 my ($x2, $x38) = ($1, $2);
240                 # this is horrifically wasteful for legacy URLs:
241                 my $str = $ctx->{ibx}->msg_by_path("$x2/$x38") or return;
242                 my $s = PublicInbox::Eml->new($str);
243                 $mid = PublicInbox::MID::mid_clean($s->header_raw('Message-ID'));
244                 return r301($ctx, $inbox, mid_escape($mid));
245         }
246         undef;
247 }
248
249 # /$INBOX/new.atom                     -> Atom feed, includes replies
250 sub get_atom {
251         my ($ctx) = @_;
252         require PublicInbox::Feed;
253         PublicInbox::Feed::generate($ctx);
254 }
255
256 # /$INBOX/new.html                      -> HTML only
257 sub get_new {
258         my ($ctx) = @_;
259         require PublicInbox::Feed;
260         PublicInbox::Feed::new_html($ctx);
261 }
262
263 # /$INBOX/?r=$GIT_COMMIT                 -> HTML only
264 sub get_index {
265         my ($ctx) = @_;
266         require PublicInbox::Feed;
267         if ($ctx->{env}->{QUERY_STRING} =~ /(?:\A|[&;])q=/) {
268                 require PublicInbox::SearchView;
269                 PublicInbox::SearchView::sres_top_html($ctx);
270         } else {
271                 PublicInbox::Feed::generate_html_index($ctx);
272         }
273 }
274
275 # /$INBOX/$MESSAGE_ID/raw                    -> raw mbox
276 sub get_mid_txt {
277         my ($ctx) = @_;
278         require PublicInbox::Mbox;
279         PublicInbox::Mbox::emit_raw($ctx) || r(404);
280 }
281
282 # /$INBOX/$MESSAGE_ID/                   -> HTML content (short quotes)
283 sub get_mid_html {
284         my ($ctx) = @_;
285         require PublicInbox::View;
286         PublicInbox::View::msg_page($ctx) || r404($ctx);
287 }
288
289 # /$INBOX/$MESSAGE_ID/t/
290 sub get_thread {
291         my ($ctx, $flat) = @_;
292         $ctx->{ibx}->over or return need($ctx, 'Overview');
293         $ctx->{flat} = $flat;
294         require PublicInbox::View;
295         PublicInbox::View::thread_html($ctx);
296 }
297
298 # /$INBOX/_/text/$KEY/
299 # /$INBOX/_/text/$KEY/raw
300 # KEY may contain slashes
301 sub get_text {
302         my ($ctx, $inbox, $key) = @_;
303         my $r404 = invalid_inbox($ctx, $inbox);
304         return $r404 if $r404;
305
306         require PublicInbox::WwwText;
307         PublicInbox::WwwText::get_text($ctx, $key);
308 }
309
310 # show git objects (blobs and commits)
311 # /$INBOX/$GIT_OBJECT_ID/s/
312 # /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
313 sub get_vcs_object ($$$;$) {
314         my ($ctx, $inbox, $oid, $filename) = @_;
315         my $r404 = invalid_inbox($ctx, $inbox);
316         return $r404 if $r404;
317         return r(404) if !$ctx->{www}->{pi_cfg}->repo_objs($ctx->{ibx});
318         require PublicInbox::ViewVCS;
319         PublicInbox::ViewVCS::show($ctx, $oid, $filename);
320 }
321
322 sub get_altid_dump {
323         my ($ctx, $inbox, $altid_pfx) =@_;
324         my $r404 = invalid_inbox($ctx, $inbox);
325         return $r404 if $r404;
326         eval { require PublicInbox::WwwAltId } or return need($ctx, 'sqlite3');
327         PublicInbox::WwwAltId::sqldump($ctx, $altid_pfx);
328 }
329
330 sub need {
331         my ($ctx, $extra) = @_;
332         require PublicInbox::WwwStream;
333         PublicInbox::WwwStream::html_oneshot($ctx, 501, <<EOF);
334 <pre>$extra is not available for this public-inbox
335 <a\nhref="../">Return to index</a></pre>
336 EOF
337 }
338
339 # /$INBOX/$MESSAGE_ID/t.mbox           -> thread as mbox
340 # /$INBOX/$MESSAGE_ID/t.mbox.gz        -> thread as gzipped mbox
341 # note: I'm not a big fan of other compression formats since they're
342 # significantly more expensive on CPU than gzip and less-widely available,
343 # especially on older systems.  Stick to zlib since that's what git uses.
344 sub get_thread_mbox {
345         my ($ctx, $sfx) = @_;
346         my $over = $ctx->{ibx}->over or return need($ctx, 'Overview');
347         require PublicInbox::Mbox;
348         PublicInbox::Mbox::thread_mbox($ctx, $over, $sfx);
349 }
350
351
352 # /$INBOX/$MESSAGE_ID/t.atom              -> thread as Atom feed
353 sub get_thread_atom {
354         my ($ctx) = @_;
355         $ctx->{ibx}->over or return need($ctx, 'Overview');
356         require PublicInbox::Feed;
357         PublicInbox::Feed::generate_thread_atom($ctx);
358 }
359
360 sub legacy_redirects {
361         my ($ctx, $path_info) = @_;
362
363         # single-message pages
364         if ($path_info =~ m!$INBOX_RE/m/(\S+)/\z!o) {
365                 r301($ctx, $1, $2);
366         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)/raw\z!o) {
367                 r301($ctx, $1, $2, 'raw');
368
369         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)/\z!o) {
370                 r301($ctx, $1, $2);
371
372         # thread display
373         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)/\z!o) {
374                 r301($ctx, $1, $2, 't/#u');
375
376         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)/mbox(\.gz)?\z!o) {
377                 r301($ctx, $1, $2, "t.mbox$3");
378
379         # even older legacy redirects
380         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)\.html\z!o) {
381                 r301($ctx, $1, $2);
382
383         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)\.html\z!o) {
384                 r301($ctx, $1, $2, 't/#u');
385
386         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)\.html\z!o) {
387                 r301($ctx, $1, $2);
388
389         } elsif ($path_info =~ m!$INBOX_RE/(?:m|f)/(\S+)\.txt\z!o) {
390                 r301($ctx, $1, $2, 'raw');
391
392         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)(\.mbox(?:\.gz)?)\z!o) {
393                 r301($ctx, $1, $2, "t$3");
394
395         # legacy convenience redirects, order still matters
396         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)\z!o) {
397                 r301($ctx, $1, $2);
398         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)\z!o) {
399                 r301($ctx, $1, $2, 't/#u');
400         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)\z!o) {
401                 r301($ctx, $1, $2);
402
403         # some Message-IDs have slashes in them and the HTTP server
404         # may try to be clever and unescape them :<
405         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/$END_RE\z!o) {
406                 msg_page($ctx, $1, $2, $3);
407
408         # in case people leave off the trailing slash:
409         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/(T|t)\z!o) {
410                 r301($ctx, $1, $2, $3 eq 't' ? 't/#u' : $3);
411         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/f\z!o) {
412                 r301($ctx, $1, $2);
413         } else {
414                 news_cgit_fallback($ctx);
415         }
416 }
417
418 sub r301 {
419         my ($ctx, $inbox, $mid_ue, $suffix) = @_;
420         my $ibx = $ctx->{ibx};
421         unless ($ibx) {
422                 my $r404 = invalid_inbox($ctx, $inbox);
423                 return $r404 if $r404;
424                 $ibx = $ctx->{ibx};
425         }
426         my $url = $ibx->base_url($ctx->{env});
427         my $qs = $ctx->{env}->{QUERY_STRING};
428         if (defined $mid_ue) {
429                 # common, and much nicer as '@' than '%40':
430                 $mid_ue =~ s/%40/@/g;
431                 $url .= $mid_ue . '/';
432         }
433         $url .= $suffix if (defined $suffix);
434         $url .= "?$qs" if $qs ne '';
435
436         [ 301,
437           [ Location => $url, 'Content-Type' => 'text/plain' ],
438           [ "Redirecting to $url\n" ] ]
439 }
440
441 sub msg_page {
442         my ($ctx, $inbox, $mid_ue, $e) = @_;
443         my $ret;
444         $ret = invalid_inbox_mid($ctx, $inbox, $mid_ue) and return $ret;
445         '' eq $e and return get_mid_html($ctx);
446         'T/' eq $e and return get_thread($ctx, 1);
447         't/' eq $e and return get_thread($ctx);
448         't.atom' eq $e and return get_thread_atom($ctx);
449         't.mbox' eq $e and return get_thread_mbox($ctx);
450         't.mbox.gz' eq $e and return get_thread_mbox($ctx, '.gz');
451         'raw' eq $e and return get_mid_txt($ctx);
452
453         # legacy, but no redirect for compatibility:
454         'f/' eq $e and return get_mid_html($ctx);
455         if ($e eq 'd/') {
456                 require PublicInbox::View;
457                 return PublicInbox::View::diff_msg($ctx);
458         }
459         r404($ctx);
460 }
461
462 sub serve_git {
463         my ($ctx, $epoch, $path) = @_;
464         my $env = $ctx->{env};
465         my $ibx = $ctx->{ibx};
466         my $git = defined $epoch ? $ibx->git_epoch($epoch) : $ibx->git;
467         $git ? PublicInbox::GitHTTPBackend::serve($env, $git, $path) : r404();
468 }
469
470 sub mbox_results {
471         my ($ctx) = @_;
472         if ($ctx->{env}->{QUERY_STRING} =~ /(?:\A|[&;])q=/) {
473                 $ctx->{ibx}->isrch or return need($ctx, 'search');
474                 require PublicInbox::SearchView;
475                 return PublicInbox::SearchView::mbox_results($ctx);
476         }
477         r404();
478 }
479
480 sub serve_mbox_range {
481         my ($ctx, $inbox, $range) = @_;
482         invalid_inbox($ctx, $inbox) || eval {
483                 require PublicInbox::Mbox;
484                 PublicInbox::Mbox::emit_range($ctx, $range);
485         }
486 }
487
488 sub news_www {
489         my ($self) = @_;
490         $self->{news_www} //= do {
491                 require PublicInbox::NewsWWW;
492                 PublicInbox::NewsWWW->new($self->{pi_cfg});
493         }
494 }
495
496 sub cgit {
497         my ($self) = @_;
498         $self->{cgit} //=
499                 (defined($self->{pi_cfg}->{'publicinbox.cgitrc'}) ? do {
500                         require PublicInbox::Cgit;
501                         PublicInbox::Cgit->new($self->{pi_cfg});
502                 } : undef) // do {
503                         require Plack::Util;
504                         Plack::Util::inline_object(call => sub { r404() });
505                 };
506 }
507
508 sub coderepo {
509         my ($self) = @_;
510         $self->{coderepo} //= do {
511                 require PublicInbox::WwwCoderepo;
512                 PublicInbox::WwwCoderepo->new($self->{pi_cfg});
513         }
514 }
515
516 # GET $INBOX/manifest.js.gz
517 sub get_inbox_manifest ($$$) {
518         my ($ctx, $inbox, $key) = @_;
519         my $r404 = invalid_inbox($ctx, $inbox);
520         return $r404 if $r404;
521         require PublicInbox::ManifestJsGz;
522         PublicInbox::ManifestJsGz::per_inbox($ctx);
523 }
524
525 sub get_attach {
526         my ($ctx, $idx, $fn) = @_;
527         require PublicInbox::WwwAttach;
528         PublicInbox::WwwAttach::get_attach($ctx, $idx, $fn);
529 }
530
531 # User-generated content (UGC) may have excessively long lines
532 # and screw up rendering on some browsers, so we use pre-wrap.
533 #
534 # We also force everything to the same scaled font-size because GUI
535 # browsers (tested both Firefox and surf (webkit)) uses a larger font
536 # for the Search <form> element than the rest of the page.  Font size
537 # uniformity is important to people who rely on gigantic fonts.
538 # Finally, we use monospace to ensure the Search field and button
539 # has the same size and spacing as everything else which is
540 # <pre>-formatted anyways.
541 our $STYLE = 'pre{white-space:pre-wrap}*{font-size:100%;font-family:monospace}';
542
543 sub stylesheets_prepare ($$) {
544         my ($self, $upfx) = @_;
545         my $mini = eval {
546                 require CSS::Minifier;
547                 sub { CSS::Minifier::minify(input => $_[0]) };
548         } || eval {
549                 require CSS::Minifier::XS;
550                 sub { CSS::Minifier::XS::minify($_[0]) };
551         } || sub { $_[0] };
552
553         my $css_map = {};
554         my $stylesheets = $self->{pi_cfg}->{css} || [];
555         my $links = [];
556         my $inline_ok = 1;
557
558         foreach my $s (@$stylesheets) {
559                 my $attr = {};
560                 local $_ = $s;
561                 foreach my $k (qw(media title href)) {
562                         if (s/\s*$k='([^']+)'// || s/\s*$k=(\S+)//) {
563                                 $attr->{$k} = $1;
564                         }
565                 }
566
567                 if (defined $attr->{href}) {
568                         $inline_ok = 0;
569                 } else {
570                         my $fn = $_;
571                         my ($key) = (m!([^/]+?)(?:\.css)?\z!i);
572                         if ($key !~ /\A[a-zA-Z0-9_\-\.]+\z/) {
573                                 warn "ignoring $fn, non-ASCII word character\n";
574                                 next;
575                         }
576                         open(my $fh, '<', $fn) or do {
577                                 warn "failed to open $fn: $!\n";
578                                 next;
579                         };
580                         my $ctime = 0;
581                         my $local = do { local $/; <$fh> };
582                         if ($local =~ /\S/) {
583                                 $ctime = sprintf('%x',(stat($fh))[10]);
584                                 $local = $mini->($local);
585                         }
586
587                         # do not let BOFHs override userContent.css:
588                         if ($local =~ /!\s*important\b/i) {
589                                 warn "ignoring $fn since it uses `!important'\n";
590                                 next;
591                         }
592
593                         $css_map->{$key} = $local;
594                         $attr->{href} = "$upfx$key.css?$ctime";
595                         if (defined($attr->{title})) {
596                                 $inline_ok = 0;
597                         } elsif (($attr->{media}||'screen') eq 'screen') {
598                                 $attr->{-inline} = $local;
599                         }
600                 }
601                 push @$links, $attr;
602         }
603
604         my $buf = "<style>$STYLE";
605         if ($inline_ok) {
606                 my @ext; # for media=print and whatnot
607                 foreach my $attr (@$links) {
608                         if (defined(my $str = delete $attr->{-inline})) {
609                                 $buf .= $str;
610                         } else {
611                                 push @ext, $attr;
612                         }
613                 }
614                 $links = \@ext;
615         }
616         $buf .= '</style>';
617
618         if (@$links) {
619                 foreach my $attr (@$links) {
620                         delete $attr->{-inline};
621                         $buf .= "<link\ntype=text/css\nrel=stylesheet";
622                         while (my ($k, $v) = each %$attr) {
623                                 $v = qq{"$v"} if $v =~ /[\s=]/;
624                                 $buf .= qq{\n$k=$v};
625                         }
626                         $buf .= ' />';
627                 }
628                 $self->{"-style-$upfx"} = $buf;
629         } else {
630                 $self->{-style_inline} = $buf;
631         }
632         $self->{-css_map} = $css_map;
633 }
634
635 # returns an HTML fragment with <style> or <link> tags in them
636 # Called by WwwStream by nearly every HTML page
637 sub style {
638         my ($self, $upfx) = @_;
639         $self->{-style_inline} || $self->{"-style-$upfx"} || do {
640                 stylesheets_prepare($self, $upfx);
641                 $self->{-style_inline} || $self->{"-style-$upfx"}
642         };
643 }
644
645 # /$INBOX/$KEY.css and /+/$KEY.css endpoints
646 # CSS is configured globally for all inboxes, but we access them on
647 # a per-inbox basis.  This allows administrators to setup per-inbox
648 # static routes to intercept the request before it hits PSGI
649 # inbox == undef => top-level WwwListing
650 sub get_css ($$$) {
651         my ($ctx, $inbox, $key) = @_;
652         my $r404 = defined($inbox) ? invalid_inbox($ctx, $inbox) : undef;
653         return $r404 if $r404;
654         my $self = $ctx->{www};
655         my $css_map = $self->{-css_map} ||
656                 stylesheets_prepare($self, defined($inbox) ? '' : '+/');
657         my $css = $css_map->{$key};
658         if (!defined($css) && defined($inbox) && $key eq 'userContent') {
659                 my $env = $ctx->{env};
660                 $css = PublicInbox::UserContent::sample($ctx->{ibx}, $env);
661         }
662         defined $css or return r404();
663         my $h = [ 'Content-Length', length($css), 'Content-Type', 'text/css' ];
664         PublicInbox::GitHTTPBackend::cache_one_year($h);
665         [ 200, $h, [ $css ] ];
666 }
667
668 sub get_description {
669         my ($ctx, $inbox) = @_;
670         invalid_inbox($ctx, $inbox) || do {
671                 my $d = $ctx->{ibx}->description . "\n";
672                 utf8::encode($d);
673                 [ 200, [ 'Content-Length', length($d),
674                         'Content-Type', 'text/plain' ], [ $d ] ];
675         };
676 }
677
678 sub event_step { # called via requeue
679         my ($self) = @_;
680         # gzf = PublicInbox::GzipFilter == $ctx
681         my $gzf = shift(@{$self->{-low_prio_q}}) // return;
682         PublicInbox::DS::requeue($self) if scalar(@{$self->{-low_prio_q}});
683         my $http = $gzf->{env}->{'psgix.io'}; # PublicInbox::HTTP
684         $http->next_step($gzf->can('async_next'));
685 }
686
687 1;