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