]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WWW.pm
isearch: emulate per-inbox search with ->ALL
[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 use PublicInbox::Eml;
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,}!;
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/(\w+)\.sql\.gz\z!o) {
70                         return get_altid_dump($ctx, $1, $2);
71                 } elsif ($path_info =~ m!$INBOX_RE/!o) {
72                         return invalid_inbox($ctx, $1) || mbox_results($ctx);
73                 }
74         }
75         elsif ($method !~ /\A(?:GET|HEAD)\z/) {
76                 return r(405);
77         }
78
79         # top-level indices and feeds
80         if ($path_info eq '/') {
81                 require PublicInbox::WwwListing;
82                 PublicInbox::WwwListing->response($ctx);
83         } elsif ($path_info eq '/manifest.js.gz') {
84                 require PublicInbox::ManifestJsGz;
85                 PublicInbox::ManifestJsGz->response($ctx);
86         } elsif ($path_info =~ m!$INBOX_RE\z!o) {
87                 invalid_inbox($ctx, $1) || r301($ctx, $1);
88         } elsif ($path_info =~ m!$INBOX_RE(?:/|/index\.html)?\z!o) {
89                 invalid_inbox($ctx, $1) || get_index($ctx);
90         } elsif ($path_info =~ m!$INBOX_RE/(?:atom\.xml|new\.atom)\z!o) {
91                 invalid_inbox($ctx, $1) || get_atom($ctx);
92         } elsif ($path_info =~ m!$INBOX_RE/new\.html\z!o) {
93                 invalid_inbox($ctx, $1) || get_new($ctx);
94         } elsif ($path_info =~ m!$INBOX_RE/description\z!o) {
95                 get_description($ctx, $1);
96         } elsif ($path_info =~ m!$INBOX_RE/(?:(?:git/)?([0-9]+)(?:\.git)?/)?
97                                 ($PublicInbox::GitHTTPBackend::ANY)\z!ox) {
98                 my ($epoch, $path) = ($2, $3);
99                 invalid_inbox($ctx, $1) || serve_git($ctx, $epoch, $path);
100         } elsif ($path_info =~ m!$INBOX_RE/([a-zA-Z0-9_\-]+).mbox\.gz\z!o) {
101                 serve_mbox_range($ctx, $1, $2);
102         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$END_RE\z!o) {
103                 msg_page($ctx, $1, $2, $3);
104
105         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$ATTACH_RE\z!o) {
106                 my ($idx, $fn) = ($3, $4);
107                 invalid_inbox_mid($ctx, $1, $2) || get_attach($ctx, $idx, $fn);
108         # in case people leave off the trailing slash:
109         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/(T|t)\z!o) {
110                 my ($inbox, $mid_ue, $suffix) = ($1, $2, $3);
111                 $suffix .= $suffix =~ /\A[tT]\z/ ? '/#u' : '/';
112                 r301($ctx, $inbox, $mid_ue, $suffix);
113
114         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/R/?\z!o) {
115                 my ($inbox, $mid_ue) = ($1, $2);
116                 r301($ctx, $inbox, $mid_ue, '#R');
117
118         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/f/?\z!o) {
119                 r301($ctx, $1, $2);
120         } elsif ($path_info =~ m!$INBOX_RE/_/text(?:/(.*))?\z!o) {
121                 get_text($ctx, $1, $2);
122         } elsif ($path_info =~ m!$INBOX_RE/([a-zA-Z0-9_\-\.]+)\.css\z!o) {
123                 get_css($ctx, $1, $2);
124         } elsif ($path_info =~ m!$INBOX_RE/manifest\.js\.gz\z!o) {
125                 get_inbox_manifest($ctx, $1, $2);
126         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s/\z!o) {
127                 get_vcs_object($ctx, $1, $2);
128         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s/
129                                 ($PublicInbox::Hval::FN)\z!ox) {
130                 get_vcs_object($ctx, $1, $2, $3);
131         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s\z!o) {
132                 r301($ctx, $1, $2, 's/');
133         } elsif ($path_info =~ m!$INBOX_RE/(\w+)\.sql\.gz\z!o) {
134                 get_altid_dump($ctx, $1, $2);
135         # convenience redirects order matters
136         } elsif ($path_info =~ m!$INBOX_RE/([^/]{2,})\z!o) {
137                 r301($ctx, $1, $2);
138
139         } else {
140                 legacy_redirects($ctx, $path_info);
141         }
142 }
143
144 # for CoW-friendliness, MOOOOO!  Even for single-process setups,
145 # we want to get all immortal allocations done early to avoid heap
146 # fragmentation since common allocators favor a large contiguous heap.
147 sub preload {
148         my ($self) = @_;
149
150         # populate caches used by Encode internally, since emails
151         # may show up with any encoding.
152         require Encode;
153         Encode::find_encoding($_) for Encode->encodings(':all');
154
155         require PublicInbox::ExtMsg;
156         require PublicInbox::Feed;
157         require PublicInbox::View;
158         require PublicInbox::SearchThread;
159         require PublicInbox::Eml;
160         require PublicInbox::Mbox;
161         require PublicInbox::ViewVCS;
162         require PublicInbox::WwwText;
163         require PublicInbox::WwwAttach;
164         eval {
165                 require PublicInbox::Search;
166                 PublicInbox::Search::load_xapian();
167         };
168         for (qw(SearchView MboxGz WwwAltId)) {
169                 eval "require PublicInbox::$_;";
170         }
171         if (ref($self)) {
172                 my $pi_config = $self->{pi_config};
173                 if (defined($pi_config->{'publicinbox.cgitrc'})) {
174                         $pi_config->limiter('-cgit');
175                 }
176                 $self->cgit;
177                 $self->stylesheets_prepare($_) for ('', '../', '../../');
178                 $self->news_www;
179                 $pi_config->each_inbox(\&preload_inbox);
180         }
181 }
182
183 sub preload_inbox {
184         my $ibx = shift;
185         $ibx->altid_map;
186         $ibx->cloneurl;
187         $ibx->description;
188         $ibx->base_url;
189 }
190
191 # private functions below
192
193 sub r404 {
194         my ($ctx) = @_;
195         if ($ctx && $ctx->{mid}) {
196                 require PublicInbox::ExtMsg;
197                 return PublicInbox::ExtMsg::ext_msg($ctx);
198         }
199         r(404);
200 }
201
202 sub news_cgit_fallback ($) {
203         my ($ctx) = @_;
204         my $www = $ctx->{www};
205         my $env = $ctx->{env};
206         my $res = $www->news_www->call($env);
207         $res->[0] == 404 ? $www->cgit->call($env) : $res;
208 }
209
210 # returns undef if valid, array ref response if invalid
211 sub invalid_inbox ($$) {
212         my ($ctx, $inbox) = @_;
213         my $ibx = $ctx->{www}->{pi_config}->lookup_name($inbox) //
214                         $ctx->{www}->{pi_config}->lookup_ei($inbox);
215         if (defined $ibx) {
216                 $ctx->{-inbox} = $ibx;
217                 return;
218         }
219
220         # sometimes linkifiers (not ours!) screw up automatic link
221         # generation and link things intended for nntp:// to https?://,
222         # so try to infer links and redirect them to the appropriate
223         # list URL.
224         news_cgit_fallback($ctx);
225 }
226
227 # returns undef if valid, array ref response if invalid
228 sub invalid_inbox_mid {
229         my ($ctx, $inbox, $mid_ue) = @_;
230         my $ret = invalid_inbox($ctx, $inbox);
231         return $ret if $ret;
232
233         my $mid = $ctx->{mid} = uri_unescape($mid_ue);
234         my $ibx = $ctx->{-inbox};
235         if ($mid =~ m!\A([a-f0-9]{2})([a-f0-9]{38})\z!) {
236                 my ($x2, $x38) = ($1, $2);
237                 # this is horrifically wasteful for legacy URLs:
238                 my $str = $ctx->{-inbox}->msg_by_path("$x2/$x38") or return;
239                 my $s = PublicInbox::Eml->new($str);
240                 $mid = PublicInbox::MID::mid_clean($s->header_raw('Message-ID'));
241                 return r301($ctx, $inbox, mid_escape($mid));
242         }
243         undef;
244 }
245
246 # /$INBOX/new.atom                     -> Atom feed, includes replies
247 sub get_atom {
248         my ($ctx) = @_;
249         require PublicInbox::Feed;
250         PublicInbox::Feed::generate($ctx);
251 }
252
253 # /$INBOX/new.html                      -> HTML only
254 sub get_new {
255         my ($ctx) = @_;
256         require PublicInbox::Feed;
257         PublicInbox::Feed::new_html($ctx);
258 }
259
260 # /$INBOX/?r=$GIT_COMMIT                 -> HTML only
261 sub get_index {
262         my ($ctx) = @_;
263         require PublicInbox::Feed;
264         if ($ctx->{env}->{QUERY_STRING} =~ /(?:\A|[&;])q=/) {
265                 require PublicInbox::SearchView;
266                 PublicInbox::SearchView::sres_top_html($ctx);
267         } else {
268                 PublicInbox::Feed::generate_html_index($ctx);
269         }
270 }
271
272 # /$INBOX/$MESSAGE_ID/raw                    -> raw mbox
273 sub get_mid_txt {
274         my ($ctx) = @_;
275         require PublicInbox::Mbox;
276         PublicInbox::Mbox::emit_raw($ctx) || r404($ctx);
277 }
278
279 # /$INBOX/$MESSAGE_ID/                   -> HTML content (short quotes)
280 sub get_mid_html {
281         my ($ctx) = @_;
282         require PublicInbox::View;
283         PublicInbox::View::msg_page($ctx) || r404($ctx);
284 }
285
286 # /$INBOX/$MESSAGE_ID/t/
287 sub get_thread {
288         my ($ctx, $flat) = @_;
289         $ctx->{-inbox}->over or return need($ctx, 'Overview');
290         $ctx->{flat} = $flat;
291         require PublicInbox::View;
292         PublicInbox::View::thread_html($ctx);
293 }
294
295 # /$INBOX/_/text/$KEY/
296 # /$INBOX/_/text/$KEY/raw
297 # KEY may contain slashes
298 sub get_text {
299         my ($ctx, $inbox, $key) = @_;
300         my $r404 = invalid_inbox($ctx, $inbox);
301         return $r404 if $r404;
302
303         require PublicInbox::WwwText;
304         PublicInbox::WwwText::get_text($ctx, $key);
305 }
306
307 # show git objects (blobs and commits)
308 # /$INBOX/$GIT_OBJECT_ID/s/
309 # /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
310 sub get_vcs_object ($$$;$) {
311         my ($ctx, $inbox, $oid, $filename) = @_;
312         my $r404 = invalid_inbox($ctx, $inbox);
313         return $r404 if $r404;
314         require PublicInbox::ViewVCS;
315         PublicInbox::ViewVCS::show($ctx, $oid, $filename);
316 }
317
318 sub get_altid_dump {
319         my ($ctx, $inbox, $altid_pfx) =@_;
320         my $r404 = invalid_inbox($ctx, $inbox);
321         return $r404 if $r404;
322         eval { require PublicInbox::WwwAltId } or return need($ctx, 'sqlite3');
323         PublicInbox::WwwAltId::sqldump($ctx, $altid_pfx);
324 }
325
326 sub need {
327         my ($ctx, $extra) = @_;
328         require PublicInbox::WwwStream;
329         PublicInbox::WwwStream::html_oneshot($ctx, 501, \<<EOF);
330 <pre>$extra is not available for this public-inbox
331 <a\nhref="../">Return to index</a></pre>
332 EOF
333 }
334
335 # /$INBOX/$MESSAGE_ID/t.mbox           -> thread as mbox
336 # /$INBOX/$MESSAGE_ID/t.mbox.gz        -> thread as gzipped mbox
337 # note: I'm not a big fan of other compression formats since they're
338 # significantly more expensive on CPU than gzip and less-widely available,
339 # especially on older systems.  Stick to zlib since that's what git uses.
340 sub get_thread_mbox {
341         my ($ctx, $sfx) = @_;
342         my $over = $ctx->{-inbox}->over or return need($ctx, 'Overview');
343         require PublicInbox::Mbox;
344         PublicInbox::Mbox::thread_mbox($ctx, $over, $sfx);
345 }
346
347
348 # /$INBOX/$MESSAGE_ID/t.atom              -> thread as Atom feed
349 sub get_thread_atom {
350         my ($ctx) = @_;
351         $ctx->{-inbox}->over or return need($ctx, 'Overview');
352         require PublicInbox::Feed;
353         PublicInbox::Feed::generate_thread_atom($ctx);
354 }
355
356 sub legacy_redirects {
357         my ($ctx, $path_info) = @_;
358
359         # single-message pages
360         if ($path_info =~ m!$INBOX_RE/m/(\S+)/\z!o) {
361                 r301($ctx, $1, $2);
362         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)/raw\z!o) {
363                 r301($ctx, $1, $2, 'raw');
364
365         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)/\z!o) {
366                 r301($ctx, $1, $2);
367
368         # thread display
369         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)/\z!o) {
370                 r301($ctx, $1, $2, 't/#u');
371
372         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)/mbox(\.gz)?\z!o) {
373                 r301($ctx, $1, $2, "t.mbox$3");
374
375         # even older legacy redirects
376         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)\.html\z!o) {
377                 r301($ctx, $1, $2);
378
379         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)\.html\z!o) {
380                 r301($ctx, $1, $2, 't/#u');
381
382         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)\.html\z!o) {
383                 r301($ctx, $1, $2);
384
385         } elsif ($path_info =~ m!$INBOX_RE/(?:m|f)/(\S+)\.txt\z!o) {
386                 r301($ctx, $1, $2, 'raw');
387
388         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)(\.mbox(?:\.gz)?)\z!o) {
389                 r301($ctx, $1, $2, "t$3");
390
391         # legacy convenience redirects, order still matters
392         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)\z!o) {
393                 r301($ctx, $1, $2);
394         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)\z!o) {
395                 r301($ctx, $1, $2, 't/#u');
396         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)\z!o) {
397                 r301($ctx, $1, $2);
398
399         # some Message-IDs have slashes in them and the HTTP server
400         # may try to be clever and unescape them :<
401         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/$END_RE\z!o) {
402                 msg_page($ctx, $1, $2, $3);
403
404         # in case people leave off the trailing slash:
405         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/(T|t)\z!o) {
406                 r301($ctx, $1, $2, $3 eq 't' ? 't/#u' : $3);
407         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/f\z!o) {
408                 r301($ctx, $1, $2);
409         } else {
410                 news_cgit_fallback($ctx);
411         }
412 }
413
414 sub r301 {
415         my ($ctx, $inbox, $mid_ue, $suffix) = @_;
416         my $ibx = $ctx->{-inbox};
417         unless ($ibx) {
418                 my $r404 = invalid_inbox($ctx, $inbox);
419                 return $r404 if $r404;
420                 $ibx = $ctx->{-inbox};
421         }
422         my $url = $ibx->base_url($ctx->{env});
423         my $qs = $ctx->{env}->{QUERY_STRING};
424         if (defined $mid_ue) {
425                 # common, and much nicer as '@' than '%40':
426                 $mid_ue =~ s/%40/@/g;
427                 $url .= $mid_ue . '/';
428         }
429         $url .= $suffix if (defined $suffix);
430         $url .= "?$qs" if $qs ne '';
431
432         [ 301,
433           [ Location => $url, 'Content-Type' => 'text/plain' ],
434           [ "Redirecting to $url\n" ] ]
435 }
436
437 sub msg_page {
438         my ($ctx, $inbox, $mid_ue, $e) = @_;
439         my $ret;
440         $ret = invalid_inbox_mid($ctx, $inbox, $mid_ue) and return $ret;
441         '' eq $e and return get_mid_html($ctx);
442         'T/' eq $e and return get_thread($ctx, 1);
443         't/' eq $e and return get_thread($ctx);
444         't.atom' eq $e and return get_thread_atom($ctx);
445         't.mbox' eq $e and return get_thread_mbox($ctx);
446         't.mbox.gz' eq $e and return get_thread_mbox($ctx, '.gz');
447         'raw' eq $e and return get_mid_txt($ctx);
448
449         # legacy, but no redirect for compatibility:
450         'f/' eq $e and return get_mid_html($ctx);
451         r404($ctx);
452 }
453
454 sub serve_git {
455         my ($ctx, $epoch, $path) = @_;
456         my $env = $ctx->{env};
457         my $ibx = $ctx->{-inbox};
458         my $git = defined $epoch ? $ibx->git_epoch($epoch) : $ibx->git;
459         $git ? PublicInbox::GitHTTPBackend::serve($env, $git, $path) : r404();
460 }
461
462 sub mbox_results {
463         my ($ctx) = @_;
464         if ($ctx->{env}->{QUERY_STRING} =~ /(?:\A|[&;])q=/) {
465                 $ctx->{-inbox}->isrch or return need($ctx, 'search');
466                 require PublicInbox::SearchView;
467                 return PublicInbox::SearchView::mbox_results($ctx);
468         }
469         r404();
470 }
471
472 sub serve_mbox_range {
473         my ($ctx, $inbox, $range) = @_;
474         invalid_inbox($ctx, $inbox) || eval {
475                 require PublicInbox::Mbox;
476                 PublicInbox::Mbox::emit_range($ctx, $range);
477         }
478 }
479
480 sub news_www {
481         my ($self) = @_;
482         $self->{news_www} ||= do {
483                 require PublicInbox::NewsWWW;
484                 PublicInbox::NewsWWW->new($self->{pi_config});
485         }
486 }
487
488 sub cgit {
489         my ($self) = @_;
490         $self->{cgit} ||= do {
491                 my $pi_config = $self->{pi_config};
492
493                 if (defined($pi_config->{'publicinbox.cgitrc'})) {
494                         require PublicInbox::Cgit;
495                         PublicInbox::Cgit->new($pi_config);
496                 } else {
497                         require Plack::Util;
498                         Plack::Util::inline_object(call => sub { r404() });
499                 }
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::ManifestJsGz;
509         PublicInbox::ManifestJsGz->response($ctx);
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;