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