]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WWW.pm
5017f572c8947978e252463afe6df511ee4b9137
[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->cloneurl;
174         $ibx->description;
175         $ibx->base_url;
176 }
177
178 # private functions below
179
180 sub r404 {
181         my ($ctx) = @_;
182         if ($ctx && $ctx->{mid}) {
183                 require PublicInbox::ExtMsg;
184                 return PublicInbox::ExtMsg::ext_msg($ctx);
185         }
186         r(404);
187 }
188
189 sub news_cgit_fallback ($) {
190         my ($ctx) = @_;
191         my $www = $ctx->{www};
192         my $env = $ctx->{env};
193         my $res = $www->news_www->call($env);
194         $res->[0] == 404 ? $www->cgit->call($env) : $res;
195 }
196
197 # returns undef if valid, array ref response if invalid
198 sub invalid_inbox ($$) {
199         my ($ctx, $inbox) = @_;
200         my $ibx = $ctx->{www}->{pi_config}->lookup_name($inbox);
201         if (defined $ibx) {
202                 $ctx->{-inbox} = $ibx;
203                 return;
204         }
205
206         # sometimes linkifiers (not ours!) screw up automatic link
207         # generation and link things intended for nntp:// to https?://,
208         # so try to infer links and redirect them to the appropriate
209         # list URL.
210         news_cgit_fallback($ctx);
211 }
212
213 # returns undef if valid, array ref response if invalid
214 sub invalid_inbox_mid {
215         my ($ctx, $inbox, $mid_ue) = @_;
216         my $ret = invalid_inbox($ctx, $inbox);
217         return $ret if $ret;
218
219         my $mid = $ctx->{mid} = uri_unescape($mid_ue);
220         my $ibx = $ctx->{-inbox};
221         if ($mid =~ m!\A([a-f0-9]{2})([a-f0-9]{38})\z!) {
222                 my ($x2, $x38) = ($1, $2);
223                 # this is horrifically wasteful for legacy URLs:
224                 my $str = $ctx->{-inbox}->msg_by_path("$x2/$x38") or return;
225                 require Email::Simple;
226                 my $s = Email::Simple->new($str);
227                 $mid = PublicInbox::MID::mid_clean($s->header('Message-ID'));
228                 return r301($ctx, $inbox, mid_escape($mid));
229         }
230         undef;
231 }
232
233 # /$INBOX/new.atom                     -> Atom feed, includes replies
234 sub get_atom {
235         my ($ctx) = @_;
236         require PublicInbox::Feed;
237         PublicInbox::Feed::generate($ctx);
238 }
239
240 # /$INBOX/new.html                      -> HTML only
241 sub get_new {
242         my ($ctx) = @_;
243         require PublicInbox::Feed;
244         PublicInbox::Feed::new_html($ctx);
245 }
246
247 # /$INBOX/?r=$GIT_COMMIT                 -> HTML only
248 sub get_index {
249         my ($ctx) = @_;
250         require PublicInbox::Feed;
251         if ($ctx->{env}->{QUERY_STRING} =~ /(?:\A|[&;])q=/) {
252                 require PublicInbox::SearchView;
253                 PublicInbox::SearchView::sres_top_html($ctx);
254         } else {
255                 PublicInbox::Feed::generate_html_index($ctx);
256         }
257 }
258
259 # /$INBOX/$MESSAGE_ID/raw                    -> raw mbox
260 sub get_mid_txt {
261         my ($ctx) = @_;
262         require PublicInbox::Mbox;
263         PublicInbox::Mbox::emit_raw($ctx) || r404($ctx);
264 }
265
266 # /$INBOX/$MESSAGE_ID/                   -> HTML content (short quotes)
267 sub get_mid_html {
268         my ($ctx) = @_;
269         require PublicInbox::View;
270         PublicInbox::View::msg_page($ctx) || r404($ctx);
271 }
272
273 # /$INBOX/$MESSAGE_ID/t/
274 sub get_thread {
275         my ($ctx, $flat) = @_;
276         $ctx->{-inbox}->over or return need($ctx, 'Overview');
277         $ctx->{flat} = $flat;
278         require PublicInbox::View;
279         PublicInbox::View::thread_html($ctx);
280 }
281
282 # /$INBOX/_/text/$KEY/
283 # /$INBOX/_/text/$KEY/raw
284 # KEY may contain slashes
285 sub get_text {
286         my ($ctx, $inbox, $key) = @_;
287         my $r404 = invalid_inbox($ctx, $inbox);
288         return $r404 if $r404;
289
290         require PublicInbox::WwwText;
291         PublicInbox::WwwText::get_text($ctx, $key);
292 }
293
294 # show git objects (blobs and commits)
295 # /$INBOX/_/$OBJECT_ID/show
296 # /$INBOX/_/${OBJECT_ID}_${FILENAME}
297 # KEY may contain slashes
298 sub get_vcs_object ($$$;$) {
299         my ($ctx, $inbox, $oid, $filename) = @_;
300         my $r404 = invalid_inbox($ctx, $inbox);
301         return $r404 if $r404;
302         require PublicInbox::ViewVCS;
303         PublicInbox::ViewVCS::show($ctx, $oid, $filename);
304 }
305
306 sub get_altid_dump {
307         my ($ctx, $inbox, $altid_pfx) =@_;
308         my $r404 = invalid_inbox($ctx, $inbox);
309         return $r404 if $r404;
310         eval { require PublicInbox::WwwAltId } or return need($ctx, 'sqlite3');
311         PublicInbox::WwwAltId::sqldump($ctx, $altid_pfx);
312 }
313
314 sub need {
315         my ($ctx, $extra) = @_;
316         my $msg = <<EOF;
317 <html><head><title>$extra not available for this
318 public-inbox</title><body><pre>$extra 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 $over = $ctx->{-inbox}->over or return need($ctx, 'Overview');
332         require PublicInbox::Mbox;
333         PublicInbox::Mbox::thread_mbox($ctx, $over, $sfx);
334 }
335
336
337 # /$INBOX/$MESSAGE_ID/t.atom              -> thread as Atom feed
338 sub get_thread_atom {
339         my ($ctx) = @_;
340         $ctx->{-inbox}->over or return need($ctx, 'Overview');
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, $epoch, $path) = @_;
445         my $env = $ctx->{env};
446         my $ibx = $ctx->{-inbox};
447         my $git = defined $epoch ? $ibx->git_epoch($epoch) : $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                 $ctx->{-inbox}->search or return need($ctx, 'search');
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                 PublicInbox::Mbox::emit_range($ctx, $range);
466         }
467 }
468
469 sub news_www {
470         my ($self) = @_;
471         $self->{news_www} ||= do {
472                 require PublicInbox::NewsWWW;
473                 PublicInbox::NewsWWW->new($self->{pi_config});
474         }
475 }
476
477 sub cgit {
478         my ($self) = @_;
479         $self->{cgit} ||= do {
480                 my $pi_config = $self->{pi_config};
481
482                 if (defined($pi_config->{'publicinbox.cgitrc'})) {
483                         require PublicInbox::Cgit;
484                         PublicInbox::Cgit->new($pi_config);
485                 } else {
486                         require Plack::Util;
487                         Plack::Util::inline_object(call => sub { r404() });
488                 }
489         }
490 }
491
492 sub www_listing {
493         my ($self) = @_;
494         $self->{www_listing} ||= do {
495                 require PublicInbox::WwwListing;
496                 PublicInbox::WwwListing->new($self);
497         }
498 }
499
500 # GET $INBOX/manifest.js.gz
501 sub get_inbox_manifest ($$$) {
502         my ($ctx, $inbox, $key) = @_;
503         my $r404 = invalid_inbox($ctx, $inbox);
504         return $r404 if $r404;
505         require PublicInbox::WwwListing;
506         PublicInbox::WwwListing::js($ctx->{env}, [$ctx->{-inbox}]);
507 }
508
509 sub get_attach {
510         my ($ctx, $idx, $fn) = @_;
511         require PublicInbox::WwwAttach;
512         PublicInbox::WwwAttach::get_attach($ctx, $idx, $fn);
513 }
514
515 # User-generated content (UGC) may have excessively long lines
516 # and screw up rendering on some browsers, so we use pre-wrap.
517 #
518 # We also force everything to the same scaled font-size because GUI
519 # browsers (tested both Firefox and surf (webkit)) uses a larger font
520 # for the Search <form> element than the rest of the page.  Font size
521 # uniformity is important to people who rely on gigantic fonts.
522 # Finally, we use monospace to ensure the Search field and button
523 # has the same size and spacing as everything else which is
524 # <pre>-formatted anyways.
525 our $STYLE = 'pre{white-space:pre-wrap}*{font-size:100%;font-family:monospace}';
526
527 sub stylesheets_prepare ($$) {
528         my ($self, $upfx) = @_;
529         my $mini = eval {
530                 require CSS::Minifier;
531                 sub { CSS::Minifier::minify(input => $_[0]) };
532         } || eval {
533                 require CSS::Minifier::XS;
534                 sub { CSS::Minifier::XS::minify($_[0]) };
535         } || sub { $_[0] };
536
537         my $css_map = {};
538         my $stylesheets = $self->{pi_config}->{css} || [];
539         my $links = [];
540         my $inline_ok = 1;
541
542         foreach my $s (@$stylesheets) {
543                 my $attr = {};
544                 local $_ = $s;
545                 foreach my $k (qw(media title href)) {
546                         if (s/\s*$k='([^']+)'// || s/\s*$k=(\S+)//) {
547                                 $attr->{$k} = $1;
548                         }
549                 }
550
551                 if (defined $attr->{href}) {
552                         $inline_ok = 0;
553                 } else {
554                         my $fn = $_;
555                         my ($key) = (m!([^/]+?)(?:\.css)?\z!i);
556                         if ($key !~ /\A[a-zA-Z0-9_\-\.]+\z/) {
557                                 warn "ignoring $fn, non-ASCII word character\n";
558                                 next;
559                         }
560                         open(my $fh, '<', $fn) or do {
561                                 warn "failed to open $fn: $!\n";
562                                 next;
563                         };
564                         my $ctime = 0;
565                         my $local = do { local $/; <$fh> };
566                         if ($local =~ /\S/) {
567                                 $ctime = sprintf('%x',(stat($fh))[10]);
568                                 $local = $mini->($local);
569                         }
570
571                         # do not let BOFHs override userContent.css:
572                         if ($local =~ /!\s*important\b/i) {
573                                 warn "ignoring $fn since it uses `!important'\n";
574                                 next;
575                         }
576
577                         $css_map->{$key} = $local;
578                         $attr->{href} = "$upfx$key.css?$ctime";
579                         if (defined($attr->{title})) {
580                                 $inline_ok = 0;
581                         } elsif (($attr->{media}||'screen') eq 'screen') {
582                                 $attr->{-inline} = $local;
583                         }
584                 }
585                 push @$links, $attr;
586         }
587
588         my $buf = "<style>$STYLE";
589         if ($inline_ok) {
590                 my @ext; # for media=print and whatnot
591                 foreach my $attr (@$links) {
592                         if (defined(my $str = delete $attr->{-inline})) {
593                                 $buf .= $str;
594                         } else {
595                                 push @ext, $attr;
596                         }
597                 }
598                 $links = \@ext;
599         }
600         $buf .= '</style>';
601
602         if (@$links) {
603                 foreach my $attr (@$links) {
604                         delete $attr->{-inline};
605                         $buf .= "<link\ntype=text/css\nrel=stylesheet";
606                         while (my ($k, $v) = each %$attr) {
607                                 $v = qq{"$v"} if $v =~ /[\s=]/;
608                                 $buf .= qq{\n$k=$v};
609                         }
610                         $buf .= ' />';
611                 }
612                 $self->{"-style-$upfx"} = $buf;
613         } else {
614                 $self->{-style_inline} = $buf;
615         }
616         $self->{-css_map} = $css_map;
617 }
618
619 # returns an HTML fragment with <style> or <link> tags in them
620 # Called by WwwStream by nearly every HTML page
621 sub style {
622         my ($self, $upfx) = @_;
623         $self->{-style_inline} || $self->{"-style-$upfx"} || do {
624                 stylesheets_prepare($self, $upfx);
625                 $self->{-style_inline} || $self->{"-style-$upfx"}
626         };
627 }
628
629 # /$INBOX/$KEY.css endpoint
630 # CSS is configured globally for all inboxes, but we access them on
631 # a per-inbox basis.  This allows administrators to setup per-inbox
632 # static routes to intercept the request before it hits PSGI
633 sub get_css ($$$) {
634         my ($ctx, $inbox, $key) = @_;
635         my $r404 = invalid_inbox($ctx, $inbox);
636         return $r404 if $r404;
637         my $self = $ctx->{www};
638         my $css_map = $self->{-css_map} || stylesheets_prepare($self, '');
639         my $css = $css_map->{$key};
640         if (!defined($css) && $key eq 'userContent') {
641                 my $env = $ctx->{env};
642                 $css = PublicInbox::UserContent::sample($ctx->{-inbox}, $env);
643         }
644         defined $css or return r404();
645         my $h = [ 'Content-Length', bytes::length($css),
646                 'Content-Type', 'text/css' ];
647         PublicInbox::GitHTTPBackend::cache_one_year($h);
648         [ 200, $h, [ $css ] ];
649 }
650
651 sub get_description {
652         my ($ctx, $inbox) = @_;
653         invalid_inbox($ctx, $inbox) || do {
654                 my $d = $ctx->{-inbox}->description . "\n";
655                 [ 200, [ 'Content-Length', bytes::length($d),
656                         'Content-Type', 'text/plain' ], [ $d ] ];
657         };
658 }
659
660 1;