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