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