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