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