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