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