]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: speed up homepage loading time with date clamp
[public-inbox.git] / lib / PublicInbox / View.pm
1 # Copyright (C) 2014-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Used for displaying the HTML web interface.
5 # See Documentation/design_www.txt for this.
6 package PublicInbox::View;
7 use strict;
8 use warnings;
9 use PublicInbox::MsgTime qw(msg_datestamp);
10 use PublicInbox::Hval qw/ascii_html obfuscate_addrs/;
11 use PublicInbox::Linkify;
12 use PublicInbox::MID qw/id_compress mid_escape mids references/;
13 use PublicInbox::MsgIter;
14 use PublicInbox::Address;
15 use PublicInbox::WwwStream;
16 use PublicInbox::Reply;
17 require POSIX;
18
19 use constant INDENT => '  ';
20 use constant TCHILD => '` ';
21 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
22
23 # public functions: (unstable)
24
25 sub msg_html {
26         my ($ctx, $mime, $more, $smsg) = @_;
27         my $hdr = $mime->header_obj;
28         my $ibx = $ctx->{-inbox};
29         my $obfs_ibx = $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
30         my $tip = _msg_html_prepare($hdr, $ctx, $more, 0);
31         my $end = 2;
32         PublicInbox::WwwStream->response($ctx, 200, sub {
33                 my ($nr, undef) = @_;
34                 if ($nr == 1) {
35                         # $more cannot be true w/o $smsg being defined:
36                         my $upfx = $more ? '../'.mid_escape($smsg->mid).'/' : '';
37                         $tip . multipart_text_as_html($mime, $upfx, $obfs_ibx) .
38                                 '</pre><hr>'
39                 } elsif ($more && @$more) {
40                         ++$end;
41                         msg_html_more($ctx, $more, $nr);
42                 } elsif ($nr == $end) {
43                         # fake an EOF if generating the footer fails;
44                         # we want to at least show the message if something
45                         # here crashes:
46                         eval {
47                                 '<pre>' . html_footer($hdr, 1, $ctx) .
48                                 '</pre>' . msg_reply($ctx, $hdr)
49                         };
50                 } else {
51                         undef
52                 }
53         });
54 }
55
56 sub msg_page {
57         my ($ctx) = @_;
58         my $mid = $ctx->{mid};
59         my $ibx = $ctx->{-inbox};
60         my ($first, $more, $head, $tail, $db);
61         my $smsg;
62         if (my $srch = $ibx->search) {
63                 $srch->retry_reopen(sub {
64                         ($head, $tail, $db) = $srch->each_smsg_by_mid($mid);
65                         for (; !defined($first) && $head != $tail; $head++) {
66                                 my @args = ($head, $db, $mid);
67                                 $smsg = PublicInbox::SearchMsg->get(@args);
68                                 $first = $ibx->msg_by_smsg($smsg);
69                         }
70                         if ($head != $tail) {
71                                 $more = [ $head, $tail, $db ];
72                         }
73                 });
74                 return unless $first;
75         } else {
76                 $first = $ibx->msg_by_mid($mid) or return;
77         }
78         msg_html($ctx, PublicInbox::MIME->new($first), $more, $smsg);
79 }
80
81 sub msg_html_more {
82         my ($ctx, $more, $nr) = @_;
83         my $str = eval {
84                 my $smsg;
85                 my ($head, $tail, $db) = @$more;
86                 my $mid = $ctx->{mid};
87                 for (; !defined($smsg) && $head != $tail; $head++) {
88                         my $m = PublicInbox::SearchMsg->get($head, $db, $mid);
89                         $smsg = $ctx->{-inbox}->smsg_mime($m);
90                 }
91                 if ($head == $tail) { # done
92                         @$more = ();
93                 } else {
94                         $more->[0] = $head;
95                 }
96                 if ($smsg) {
97                         my $mime = $smsg->{mime};
98                         my $upfx = '../' . mid_escape($smsg->mid) . '/';
99                         _msg_html_prepare($mime->header_obj, $ctx, $more, $nr) .
100                                 multipart_text_as_html($mime, $upfx,
101                                                         $ctx->{-obfs_ibx}) .
102                                 '</pre><hr>'
103                 } else {
104                         '';
105                 }
106         };
107         if ($@) {
108                 warn "Error lookup up additional messages: $@\n";
109                 $str = '<pre>Error looking up additional messages</pre>';
110         }
111         $str;
112 }
113
114 # /$INBOX/$MESSAGE_ID/#R
115 sub msg_reply {
116         my ($ctx, $hdr) = @_;
117         my $se_url =
118          'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
119         my $p_url =
120          'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
121
122         my $info = '';
123         my $ibx = $ctx->{-inbox};
124         if (my $url = $ibx->{infourl}) {
125                 $url = PublicInbox::Hval::prurl($ctx->{env}, $url);
126                 $info = qq(\n  List information: <a\nhref="$url">$url</a>\n);
127         }
128
129         my ($arg, $link, $reply_to_all) =
130                         PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
131
132         # mailto: link only works if address obfuscation is disabled
133         if ($link) {
134                 $link = <<EOF;
135
136 * If your mail client supports setting the <b>In-Reply-To</b> header
137   via mailto: links, try the <a
138 href="$link">mailto: link</a>
139 EOF
140         }
141
142         push @$arg, '/path/to/YOUR_REPLY';
143         $arg = ascii_html(join(" \\\n    ", '', @$arg));
144         <<EOF
145 <hr><pre
146 id=R><b>Reply instructions:</b>
147
148 You may reply publically to <a
149 href=#t>this message</a> via plain-text email
150 using any one of the following methods:
151
152 * Save the following mbox file, import it into your mail client,
153   and $reply_to_all from there: <a
154 href=raw>mbox</a>
155
156   Avoid top-posting and favor interleaved quoting:
157   <a
158 href="$p_url">$p_url</a>
159 $info
160 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
161   switches of git-send-email(1):
162
163   git send-email$arg
164
165   <a
166 href="$se_url">$se_url</a>
167 $link</pre>
168 EOF
169 }
170
171 sub in_reply_to {
172         my ($hdr) = @_;
173         my $refs = references($hdr);
174         $refs->[-1];
175 }
176
177 sub _hdr_names_html ($$) {
178         my ($hdr, $field) = @_;
179         my $val = $hdr->header($field) or return '';
180         ascii_html(join(', ', PublicInbox::Address::names($val)));
181 }
182
183 sub nr_to_s ($$$) {
184         my ($nr, $singular, $plural) = @_;
185         return "0 $plural" if $nr == 0;
186         $nr == 1 ? "$nr $singular" : "$nr $plural";
187 }
188
189 # this is already inside a <pre>
190 sub index_entry {
191         my ($smsg, $ctx, $more) = @_;
192         my $srch = $ctx->{srch};
193         my $subj = $smsg->subject;
194         my $mid_raw = $smsg->mid;
195         my $id = id_compress($mid_raw, 1);
196         my $id_m = 'm'.$id;
197
198         my $root_anchor = $ctx->{root_anchor} || '';
199         my $irt;
200         my $obfs_ibx = $ctx->{-obfs_ibx};
201
202         my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
203         $subj = '<b>'.ascii_html($subj).'</b>';
204         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
205         $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
206         $rv .= $subj . "\n";
207         $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
208         my @tocc;
209         my $mime = $smsg->{mime};
210         my $hdr = $mime->header_obj;
211         foreach my $f (qw(To Cc)) {
212                 my $dst = _hdr_names_html($hdr, $f);
213                 if ($dst ne '') {
214                         obfuscate_addrs($obfs_ibx, $dst) if $obfs_ibx;
215                         push @tocc, "$f: $dst";
216                 }
217         }
218         my $from = _hdr_names_html($hdr, 'From');
219         obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
220         $rv .= "From: $from @ ".fmt_ts($smsg->ds)." UTC";
221         my $upfx = $ctx->{-upfx};
222         my $mhref = $upfx . mid_escape($mid_raw) . '/';
223         $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
224         $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
225         $rv .= '  '.join('; +', @tocc) . "\n" if @tocc;
226
227         my $mapping = $ctx->{mapping};
228         if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
229                 my $mirt = PublicInbox::Hval->new_msgid($irt);
230                 my $href = $upfx . $mirt->{href}. '/';
231                 my $html = $mirt->as_html;
232                 $rv .= qq(In-Reply-To: &lt;<a\nhref="$href">$html</a>&gt;\n)
233         }
234         $rv .= "\n";
235
236         # scan through all parts, looking for displayable text
237         msg_iter($mime, sub { $rv .= add_text_body($mhref, $obfs_ibx, $_[0]) });
238
239         # add the footer
240         $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
241                 "<a\nhref=\"$mhref\">permalink</a>" .
242                 " <a\nhref=\"${mhref}raw\">raw</a>" .
243                 " <a\nhref=\"${mhref}#R\">reply</a>";
244
245         my $hr;
246         if (my $pct = $ctx->{pct}) { # used by SearchView.pm
247                 $rv .= "\t[relevance $pct->{$mid_raw}%]";
248                 $hr = 1;
249         } elsif ($mapping) {
250                 my $nested = 'nested';
251                 my $flat = 'flat';
252                 my $end = '';
253                 if ($ctx->{flat}) {
254                         $hr = 1;
255                         $flat = "<b>$flat</b>";
256                 } else {
257                         $nested = "<b>$nested</b>";
258                 }
259                 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
260                 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
261                 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
262         } else {
263                 $hr = $ctx->{-hr};
264         }
265
266         $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
267         $rv;
268 }
269
270 sub pad_link ($$;$) {
271         my ($mid, $level, $s) = @_;
272         $s ||= '...';
273         my $id = id_compress($mid, 1);
274         (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
275 }
276
277 sub _th_index_lite {
278         my ($mid_raw, $irt, $id, $ctx) = @_;
279         my $rv = '';
280         my $mapping = $ctx->{mapping} or return $rv;
281         my $pad = '  ';
282         my $mid_map = $mapping->{$mid_raw};
283         defined $mid_map or
284                 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
285         my ($attr, $node, $idx, $level) = @$mid_map;
286         my $children = $node->{children};
287         my $nr_c = scalar @$children;
288         my $nr_s = 0;
289         my $siblings;
290         if (my $smsg = $node->{smsg}) {
291                 ($$irt) = (($smsg->{references} || '') =~ m/<([^>]+)>\z/);
292         }
293         my $irt_map = $mapping->{$$irt} if defined $$irt;
294         if (defined $irt_map) {
295                 $siblings = $irt_map->[1]->{children};
296                 $nr_s = scalar(@$siblings) - 1;
297                 $rv .= $pad . $irt_map->[0];
298                 if ($idx > 0) {
299                         my $prev = $siblings->[$idx - 1];
300                         my $pmid = $prev->{id};
301                         if ($idx > 2) {
302                                 my $s = ($idx - 1). ' preceding siblings ...';
303                                 $rv .= pad_link($pmid, $level, $s);
304                         } elsif ($idx == 2) {
305                                 my $ppmid = $siblings->[0]->{id};
306                                 $rv .= $pad . $mapping->{$ppmid}->[0];
307                         }
308                         $rv .= $pad . $mapping->{$pmid}->[0];
309                 }
310         }
311         my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
312         my $s_c = nr_to_s($nr_c, 'reply', 'replies');
313         $attr =~ s!\n\z!</b>\n!s;
314         $attr =~ s!<a\nhref.*</a> !!s; # no point in duplicating subject
315         $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
316         $rv .= "<b>@ $attr";
317         if ($nr_c) {
318                 my $cmid = $children->[0]->{id};
319                 $rv .= $pad . $mapping->{$cmid}->[0];
320                 if ($nr_c > 2) {
321                         my $s = ($nr_c - 1). ' more replies';
322                         $rv .= pad_link($cmid, $level + 1, $s);
323                 } elsif (my $cn = $children->[1]) {
324                         $rv .= $pad . $mapping->{$cn->{id}}->[0];
325                 }
326         }
327
328         my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
329         if ($next) {
330                 my $nmid = $next->{id};
331                 $rv .= $pad . $mapping->{$nmid}->[0];
332                 my $nnext = $nr_s - $idx;
333                 if ($nnext > 2) {
334                         my $s = ($nnext - 1).' subsequent siblings';
335                         $rv .= pad_link($nmid, $level, $s);
336                 } elsif (my $nn = $siblings->[$idx + 2]) {
337                         $rv .= $pad . $mapping->{$nn->{id}}->[0];
338                 }
339         }
340         $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
341 }
342
343 sub walk_thread {
344         my ($rootset, $ctx, $cb) = @_;
345         my @q = map { (0, $_, -1) } @$rootset;
346         while (@q) {
347                 my ($level, $node, $i) = splice(@q, 0, 3);
348                 defined $node or next;
349                 $cb->($ctx, $level, $node, $i);
350                 ++$level;
351                 $i = 0;
352                 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
353         }
354 }
355
356 sub pre_thread  {
357         my ($ctx, $level, $node, $idx) = @_;
358         $ctx->{mapping}->{$node->{id}} = [ '', $node, $idx, $level ];
359         skel_dump($ctx, $level, $node);
360 }
361
362 sub thread_index_entry {
363         my ($ctx, $level, $smsg) = @_;
364         my ($beg, $end) = thread_adj_level($ctx, $level);
365         $beg . '<pre>' . index_entry($smsg, $ctx, 0) . '</pre>' . $end;
366 }
367
368 sub stream_thread ($$) {
369         my ($rootset, $ctx) = @_;
370         my $inbox = $ctx->{-inbox};
371         my @q = map { (0, $_) } @$rootset;
372         my $level;
373         my $smsg;
374         while (@q) {
375                 $level = shift @q;
376                 my $node = shift @q or next;
377                 my $cl = $level + 1;
378                 unshift @q, map { ($cl, $_) } @{$node->{children}};
379                 $smsg = $inbox->smsg_mime($node->{smsg}) and last;
380         }
381         return missing_thread($ctx) unless $smsg;
382
383         $ctx->{-obfs_ibx} = $inbox->{obfuscate} ? $inbox : undef;
384         $ctx->{-title_html} = ascii_html($smsg->subject);
385         $ctx->{-html_tip} = thread_index_entry($ctx, $level, $smsg);
386         $smsg = undef;
387         PublicInbox::WwwStream->response($ctx, 200, sub {
388                 return unless $ctx;
389                 while (@q) {
390                         $level = shift @q;
391                         my $node = shift @q or next;
392                         my $cl = $level + 1;
393                         unshift @q, map { ($cl, $_) } @{$node->{children}};
394                         if ($smsg = $inbox->smsg_mime($node->{smsg})) {
395                                 return thread_index_entry($ctx, $level, $smsg);
396                         } else {
397                                 return ghost_index_entry($ctx, $level, $node);
398                         }
399                 }
400                 my $ret = join('', thread_adj_level($ctx, 0));
401                 $ret .= ${$ctx->{dst}}; # skel
402                 $ctx = undef;
403                 $ret;
404         });
405 }
406
407 sub thread_html {
408         my ($ctx) = @_;
409         my $mid = $ctx->{mid};
410         my $srch = $ctx->{srch};
411         my $sres = $srch->get_thread($mid);
412         my $msgs = load_results($srch, $sres);
413         my $nr = $sres->{total};
414         return missing_thread($ctx) if $nr == 0;
415         my $skel = '<hr><pre>';
416         $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
417         $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
418         $skel .= "<b\nid=t>Thread overview:</b> ";
419         $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
420         $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
421         $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
422         $skel .= "-- links below jump to the message on this page --\n";
423         $ctx->{-upfx} = '../../';
424         $ctx->{cur_level} = 0;
425         $ctx->{dst} = \$skel;
426         $ctx->{prev_attr} = '';
427         $ctx->{prev_level} = 0;
428         $ctx->{root_anchor} = anchor_for($mid);
429         $ctx->{mapping} = {};
430         $ctx->{s_nr} = "$nr+ messages in thread";
431
432         my $rootset = thread_results($ctx, $msgs);
433
434         # reduce hash lookups in pre_thread->skel_dump
435         my $inbox = $ctx->{-inbox};
436         $ctx->{-obfs_ibx} = $inbox->{obfuscate} ? $inbox : undef;
437         walk_thread($rootset, $ctx, *pre_thread);
438
439         $skel .= '</pre>';
440         return stream_thread($rootset, $ctx) unless $ctx->{flat};
441
442         # flat display: lazy load the full message from smsg
443         my $smsg;
444         while (my $m = shift @$msgs) {
445                 $smsg = $inbox->smsg_mime($m) and last;
446         }
447         return missing_thread($ctx) unless $smsg;
448         $ctx->{-title_html} = ascii_html($smsg->subject);
449         $ctx->{-html_tip} = '<pre>'.index_entry($smsg, $ctx, scalar @$msgs);
450         $smsg = undef;
451         PublicInbox::WwwStream->response($ctx, 200, sub {
452                 return unless $msgs;
453                 $smsg = undef;
454                 while (my $m = shift @$msgs) {
455                         $smsg = $inbox->smsg_mime($m) and last;
456                 }
457                 return index_entry($smsg, $ctx, scalar @$msgs) if $smsg;
458                 $msgs = undef;
459                 $skel;
460         });
461 }
462
463 sub multipart_text_as_html {
464         my ($mime, $upfx, $obfs_ibx) = @_;
465         my $rv = "";
466
467         # scan through all parts, looking for displayable text
468         msg_iter($mime, sub { $rv .= add_text_body($upfx, $obfs_ibx, $_[0]) });
469         $rv;
470 }
471
472 sub flush_quote {
473         my ($s, $l, $quot) = @_;
474
475         # show everything in the full version with anchor from
476         # short version (see above)
477         my $rv = $l->linkify_1(join('', @$quot));
478         @$quot = ();
479
480         # we use a <span> here to allow users to specify their own
481         # color for quoted text
482         $rv = $l->linkify_2(ascii_html($rv));
483         $$s .= qq(<span\nclass="q">) . $rv . '</span>'
484 }
485
486 sub attach_link ($$$$;$) {
487         my ($upfx, $ct, $p, $fn, $err) = @_;
488         my ($part, $depth, @idx) = @$p;
489         my $nl = $idx[-1] > 1 ? "\n" : '';
490         my $idx = join('.', @idx);
491         my $size = bytes::length($part->body);
492
493         # hide attributes normally, unless we want to aid users in
494         # spotting MUA problems:
495         $ct =~ s/;.*// unless $err;
496         $ct = ascii_html($ct);
497         my $desc = $part->header('Content-Description');
498         $desc = $fn unless defined $desc;
499         $desc = '' unless defined $desc;
500         my $sfn;
501         if (defined $fn && $fn =~ /\A[[:alnum:]][\w\.-]+[[:alnum:]]\z/) {
502                 $sfn = $fn;
503         } elsif ($ct eq 'text/plain') {
504                 $sfn = 'a.txt';
505         } else {
506                 $sfn = 'a.bin';
507         }
508         my $ret = qq($nl<a\nhref="$upfx$idx-$sfn">);
509         if ($err) {
510                 $ret .=
511 "[-- Warning: decoded text below may be mangled --]\n";
512         }
513         $ret .= "[-- Attachment #$idx: ";
514         my $ts = "Type: $ct, Size: $size bytes";
515         $desc = ascii_html($desc);
516         $ret .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
517         $ret .= "</a>\n";
518 }
519
520 sub add_text_body {
521         my ($upfx, $obfs_ibx, $p) = @_;
522         # $p - from msg_iter: [ Email::MIME, depth, @idx ]
523         my ($part, $depth) = @$p; # attachment @idx is unused
524         my $ct = $part->content_type || 'text/plain';
525         my $fn = $part->filename;
526
527         if ($ct =~ m!\btext/x?html\b!i) {
528                 return attach_link($upfx, $ct, $p, $fn);
529         }
530
531         my $s = eval { $part->body_str };
532
533         # badly-encoded message? tell the world about it!
534         my $err = $@;
535         if ($err) {
536                 if ($ct =~ m!\btext/plain\b!i) {
537                         # Try to assume UTF-8 because Alpine seems to
538                         # do wacky things and set charset=X-UNKNOWN
539                         $part->charset_set('UTF-8');
540                         $s = eval { $part->body_str };
541
542                         # If forcing charset=UTF-8 failed,
543                         # attach_link will warn further down...
544                         $s = $part->body if $@;
545                 } else {
546                         return attach_link($upfx, $ct, $p, $fn);
547                 }
548         }
549
550         my @lines = split(/^/m, $s);
551         $s = '';
552         if (defined($fn) || $depth > 0 || $err) {
553                 $s .= attach_link($upfx, $ct, $p, $fn, $err);
554                 $s .= "\n";
555         }
556         my @quot;
557         my $l = PublicInbox::Linkify->new;
558         foreach my $cur (@lines) {
559                 if ($cur !~ /^>/) {
560                         # show the previously buffered quote inline
561                         flush_quote(\$s, $l, \@quot) if @quot;
562
563                         # regular line, OK
564                         $l->linkify_1($cur);
565                         $s .= $l->linkify_2(ascii_html($cur));
566                 } else {
567                         push @quot, $cur;
568                 }
569         }
570
571         if (@quot) { # ugh, top posted
572                 flush_quote(\$s, $l, \@quot);
573                 obfuscate_addrs($obfs_ibx, $s) if $obfs_ibx;
574                 $s;
575         } else {
576                 obfuscate_addrs($obfs_ibx, $s) if $obfs_ibx;
577                 if ($s =~ /\n\z/s) { # common, last line ends with a newline
578                         $s;
579                 } else { # some editors don't do newlines...
580                         $s .= "\n";
581                 }
582         }
583 }
584
585 sub _msg_html_prepare {
586         my ($hdr, $ctx, $more, $nr) = @_;
587         my $srch = $ctx->{srch} if $ctx;
588         my $atom = '';
589         my $obfs_ibx = $ctx->{-obfs_ibx};
590         my $rv = '';
591         my $mids = mids($hdr);
592         my $multiple = scalar(@$mids) > 1; # zero, one, infinity
593         if ($nr == 0) {
594                 if ($more) {
595                         $rv .=
596 "<pre>WARNING: multiple messages refer to this Message-ID\n</pre>";
597                 }
598                 $rv .= "<pre\nid=b>"; # anchor for body start
599         } else {
600                 $rv .= '<pre>';
601         }
602         if ($srch) {
603                 $ctx->{-upfx} = '../';
604         }
605         my @title;
606         foreach my $h (qw(From To Cc Subject Date)) {
607                 my $v = $hdr->header($h);
608                 defined($v) && ($v ne '') or next;
609                 $v = PublicInbox::Hval->new($v);
610
611                 if ($h eq 'From') {
612                         my @n = PublicInbox::Address::names($v->raw);
613                         $title[1] = ascii_html(join(', ', @n));
614                         obfuscate_addrs($obfs_ibx, $title[1]) if $obfs_ibx;
615                 } elsif ($h eq 'Subject') {
616                         $title[0] = $v->as_html;
617                         if ($srch) {
618                                 $rv .= qq($h: <a\nhref="#r"\nid=t>);
619                                 $rv .= $v->as_html . "</a>\n";
620                                 next;
621                         }
622                 }
623                 $v = $v->as_html;
624                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
625                 $rv .= "$h: $v\n";
626
627         }
628         $title[0] ||= '(no subject)';
629         $ctx->{-title_html} = join(' - ', @title);
630         foreach (@$mids) {
631                 my $mid = PublicInbox::Hval->new_msgid($_) ;
632                 my $mhtml = $mid->as_html;
633                 if ($multiple) {
634                         my $href = $mid->{href};
635                         $rv .= "Message-ID: ";
636                         $rv .= "<a\nhref=\"../$href/\">";
637                         $rv .= "&lt;$mhtml&gt;</a> ";
638                         $rv .= "(<a\nhref=\"../$href/raw\">raw</a>)\n";
639                 } else {
640                         $rv .= "Message-ID: &lt;$mhtml&gt; ";
641                         $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
642                 }
643         }
644         $rv .= _parent_headers($hdr, $srch);
645         $rv .= "\n";
646 }
647
648 sub thread_skel {
649         my ($dst, $ctx, $hdr, $tpfx) = @_;
650         my $srch = $ctx->{srch};
651         my $mid = mids($hdr)->[0];
652         my $sres = $srch->get_thread($mid);
653         my $nr = $sres->{total};
654         my $expand = qq(expand[<a\nhref="${tpfx}T/#u">flat</a>) .
655                         qq(|<a\nhref="${tpfx}t/#u">nested</a>]  ) .
656                         qq(<a\nhref="${tpfx}t.mbox.gz">mbox.gz</a>  ) .
657                         qq(<a\nhref="${tpfx}t.atom">Atom feed</a>);
658
659         my $parent = in_reply_to($hdr);
660         $$dst .= "\n<b>Thread overview: </b>";
661         if ($nr <= 1) {
662                 if (defined $parent) {
663                         $$dst .= "$expand\n ";
664                         $$dst .= ghost_parent("$tpfx../", $parent) . "\n";
665                 } else {
666                         $$dst .= "[no followups] $expand\n";
667                 }
668                 $ctx->{next_msg} = undef;
669                 $ctx->{parent_msg} = $parent;
670                 return;
671         }
672
673         $$dst .= "$nr+ messages / $expand";
674         $$dst .= qq!  <a\nhref="#b">top</a>\n!;
675
676         my $subj = $hdr->header('Subject');
677         defined $subj or $subj = '';
678         $ctx->{prev_subj} = [ split(/ /, $srch->subject_normalized($subj)) ];
679         $ctx->{cur} = $mid;
680         $ctx->{prev_attr} = '';
681         $ctx->{prev_level} = 0;
682         $ctx->{dst} = $dst;
683         $sres = load_results($srch, $sres);
684
685         # reduce hash lookups in skel_dump
686         my $ibx = $ctx->{-inbox};
687         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
688         walk_thread(thread_results($ctx, $sres), $ctx, *skel_dump);
689
690         $ctx->{parent_msg} = $parent;
691 }
692
693 sub _parent_headers {
694         my ($hdr, $srch) = @_;
695         my $rv = '';
696
697         my $irt = in_reply_to($hdr);
698         if (defined $irt) {
699                 my $v = PublicInbox::Hval->new_msgid($irt);
700                 my $html = $v->as_html;
701                 my $href = $v->{href};
702                 $rv .= "In-Reply-To: &lt;";
703                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
704         }
705
706         # do not display References: if search is present,
707         # we show the thread skeleton at the bottom, instead.
708         return $rv if $srch;
709
710         my $refs = $hdr->header_raw('References');
711         if ($refs) {
712                 # avoid redundant URLs wasting bandwidth
713                 my %seen;
714                 $seen{$irt} = 1 if defined $irt;
715                 my @refs;
716                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
717                 foreach my $ref (@raw_refs) {
718                         next if $seen{$ref};
719                         $seen{$ref} = 1;
720                         push @refs, linkify_ref_nosrch($ref);
721                 }
722
723                 if (@refs) {
724                         $rv .= 'References: '. join("\n\t", @refs) . "\n";
725                 }
726         }
727         $rv;
728 }
729
730 sub html_footer {
731         my ($hdr, $standalone, $ctx, $rhref) = @_;
732
733         my $srch = $ctx->{srch} if $ctx;
734         my $upfx = '../';
735         my $tpfx = '';
736         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
737         my $irt = '';
738         if ($idx && $srch) {
739                 $idx .= "\n";
740                 thread_skel(\$idx, $ctx, $hdr, $tpfx);
741                 my ($next, $prev);
742                 my $parent = '       ';
743                 $next = $prev = '    ';
744
745                 if (my $n = $ctx->{next_msg}) {
746                         $n = PublicInbox::Hval->new_msgid($n)->{href};
747                         $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
748                 }
749                 my $u;
750                 my $par = $ctx->{parent_msg};
751                 if ($par) {
752                         $u = PublicInbox::Hval->new_msgid($par)->{href};
753                         $u = "$upfx$u/";
754                 }
755                 if (my $p = $ctx->{prev_msg}) {
756                         $prev = PublicInbox::Hval->new_msgid($p)->{href};
757                         if ($p && $par && $p eq $par) {
758                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
759                                         'rel=prev>prev parent</a>';
760                                 $parent = '';
761                         } else {
762                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
763                                         'rel=prev>prev</a>';
764                                 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
765                         }
766                 } elsif ($u) { # unlikely
767                         $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
768                 }
769                 $irt = "$next $prev$parent ";
770         } else {
771                 $irt = '';
772         }
773         $rhref ||= '#R';
774         $irt .= qq(<a\nhref="$rhref">reply</a>);
775         $irt .= $idx;
776 }
777
778 sub linkify_ref_nosrch {
779         my $v = PublicInbox::Hval->new_msgid($_[0]);
780         my $html = $v->as_html;
781         my $href = $v->{href};
782         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
783 }
784
785 sub anchor_for {
786         my ($msgid) = @_;
787         'm' . id_compress($msgid, 1);
788 }
789
790 sub ghost_parent {
791         my ($upfx, $mid) = @_;
792
793         $mid = PublicInbox::Hval->new_msgid($mid);
794         my $href = $mid->{href};
795         my $html = $mid->as_html;
796         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
797 }
798
799 sub indent_for {
800         my ($level) = @_;
801         $level ? INDENT x ($level - 1) : '';
802 }
803
804 sub load_results {
805         my ($srch, $sres) = @_;
806         my $msgs = delete $sres->{msgs};
807         $srch->retry_reopen(sub { [ map { $_->mid; $_ } @$msgs ] });
808 }
809
810 sub thread_results {
811         my ($ctx, $msgs) = @_;
812         require PublicInbox::SearchThread;
813         PublicInbox::SearchThread::thread($msgs, *sort_ds, $ctx->{-inbox});
814 }
815
816 sub missing_thread {
817         my ($ctx) = @_;
818         require PublicInbox::ExtMsg;
819         PublicInbox::ExtMsg::ext_msg($ctx);
820 }
821
822 sub _msg_date {
823         my ($hdr) = @_;
824         fmt_ts(msg_datestamp($hdr));
825 }
826
827 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
828
829 sub dedupe_subject {
830         my ($prev_subj, $subj, $val) = @_;
831
832         my $omit = ''; # '"' denotes identical text omitted
833         my (@prev_pop, @curr_pop);
834         while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
835                 push(@prev_pop, pop(@$prev_subj));
836                 push(@curr_pop, pop(@$subj));
837                 $omit ||= $val;
838         }
839         pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
840         if (scalar(@curr_pop) == 1) {
841                 $omit = '';
842                 push @$prev_subj, @prev_pop;
843                 push @$subj, @curr_pop;
844         }
845         $omit;
846 }
847
848 sub skel_dump {
849         my ($ctx, $level, $node) = @_;
850         my $smsg = $node->{smsg} or return _skel_ghost($ctx, $level, $node);
851
852         my $dst = $ctx->{dst};
853         my $cur = $ctx->{cur};
854         my $mid = $smsg->{mid};
855
856         my $f = ascii_html($smsg->from_name);
857         my $obfs_ibx = $ctx->{-obfs_ibx};
858         obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
859
860         my $d = fmt_ts($smsg->{ds}) . ' ' . indent_for($level) . th_pfx($level);
861         my $attr = $f;
862         $ctx->{first_level} ||= $level;
863
864         if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
865                 $ctx->{prev_attr} = $attr;
866         }
867         $ctx->{prev_level} = $level;
868
869         if ($cur) {
870                 if ($cur eq $mid) {
871                         delete $ctx->{cur};
872                         $$dst .= "<b>$d<a\nid=r\nhref=\"#t\">".
873                                  "$attr [this message]</a></b>\n";
874                         return;
875                 } else {
876                         $ctx->{prev_msg} = $mid;
877                 }
878         } else {
879                 $ctx->{next_msg} ||= $mid;
880         }
881
882         # Subject is never undef, this mail was loaded from
883         # our Xapian which would've resulted in '' if it were
884         # really missing (and Filter rejects empty subjects)
885         my @subj = split(/ /, $ctx->{srch}->subject_normalized($smsg->subject));
886
887         # remove common suffixes from the subject if it matches the previous,
888         # so we do not show redundant text at the end.
889         my $prev_subj = $ctx->{prev_subj} || [];
890         $ctx->{prev_subj} = [ @subj ];
891         my $omit = dedupe_subject($prev_subj, \@subj, '&#34; ');
892         my $end;
893         if (@subj) {
894                 my $subj = join(' ', @subj);
895                 $subj = ascii_html($subj);
896                 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
897                 $end = "$subj</a> $omit$f\n"
898         } else {
899                 $end = "$f</a>\n";
900         }
901         my $m;
902         my $id = '';
903         my $mapping = $ctx->{mapping};
904         if ($mapping) {
905                 my $map = $mapping->{$mid};
906                 $id = id_compress($mid, 1);
907                 $m = '#m'.$id;
908                 $map->[0] = "$d<a\nhref=\"$m\">$end";
909                 $id = "\nid=r".$id;
910         } else {
911                 $m = $ctx->{-upfx}.mid_escape($mid).'/';
912         }
913         $$dst .=  $d . "<a\nhref=\"$m\"$id>" . $end;
914 }
915
916 sub _skel_ghost {
917         my ($ctx, $level, $node) = @_;
918
919         my $mid = $node->{id};
920         my $d = $ctx->{pct} ? '    [irrelevant] ' # search result
921                             : '     [not found] ';
922         $d .= indent_for($level) . th_pfx($level);
923         my $upfx = $ctx->{-upfx};
924         my $m = PublicInbox::Hval->new_msgid($mid);
925         my $href = $upfx . $m->{href} . '/';
926         my $html = $m->as_html;
927
928         my $mapping = $ctx->{mapping};
929         my $map = $mapping->{$mid} if $mapping;
930         if ($map) {
931                 my $id = id_compress($mid, 1);
932                 $map->[0] = $d . qq{&lt;<a\nhref=#r$id>$html</a>&gt;\n};
933                 $d .= qq{&lt;<a\nhref="$href"\nid=r$id>$html</a>&gt;\n};
934         } else {
935                 $d .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
936         }
937         my $dst = $ctx->{dst};
938         $$dst .= $d;
939 }
940
941 sub sort_ds {
942         [ sort {
943                 (eval { $a->topmost->{smsg}->ds } || 0) <=>
944                 (eval { $b->topmost->{smsg}->ds } || 0)
945         } @{$_[0]} ];
946 }
947
948 # accumulate recent topics if search is supported
949 # returns 200 if done, 404 if not
950 sub acc_topic {
951         my ($ctx, $level, $node) = @_;
952         my $srch = $ctx->{srch};
953         my $mid = $node->{id};
954         my $x = $node->{smsg} || $ctx->{-inbox}->smsg_by_mid($mid);
955         my ($subj, $ds);
956         my $topic;
957         if ($x) {
958                 $subj = $x->subject;
959                 $subj = $srch->subject_normalized($subj);
960                 $ds = $x->ds;
961                 if ($level == 0) {
962                         $topic = [ $ds, 1, { $subj => $mid }, $subj ];
963                         $ctx->{-cur_topic} = $topic;
964                         push @{$ctx->{order}}, $topic;
965                         return;
966                 }
967
968                 $topic = $ctx->{-cur_topic}; # should never be undef
969                 $topic->[0] = $ds if $ds > $topic->[0];
970                 $topic->[1]++;
971                 my $seen = $topic->[2];
972                 if (scalar(@$topic) == 3) { # parent was a ghost
973                         push @$topic, $subj;
974                 } elsif (!$seen->{$subj}) {
975                         push @$topic, $level, $subj;
976                 }
977                 $seen->{$subj} = $mid; # latest for subject
978         } else { # ghost message
979                 return if $level != 0; # ignore child ghosts
980                 $topic = [ -666, 0, {} ];
981                 $ctx->{-cur_topic} = $topic;
982                 push @{$ctx->{order}}, $topic;
983         }
984 }
985
986 sub dump_topics {
987         my ($ctx) = @_;
988         my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
989         if (!@$order) {
990                 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
991                 return 404;
992         }
993
994         my @out;
995         my $ibx = $ctx->{-inbox};
996         my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
997         my $srch = $ctx->{srch};
998
999         # sort by recency, this allows new posts to "bump" old topics...
1000         foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1001                 my ($ds, $n, $seen, $top, @ex) = @$topic;
1002                 @$topic = ();
1003                 next unless defined $top;  # ghost topic
1004                 my $mid = delete $seen->{$top};
1005                 my $href = mid_escape($mid);
1006                 my $prev_subj = [ split(/ /, $top) ];
1007                 $top = PublicInbox::Hval->new($top)->as_html;
1008                 $ds = fmt_ts($ds);
1009
1010                 # $n isn't the total number of posts on the topic,
1011                 # just the number of posts in the current results window
1012                 my $anchor;
1013                 if ($n == 1) {
1014                         $n = '';
1015                         $anchor = '#u'; # top of only message
1016                 } else {
1017                         $n = " ($n+ messages)";
1018                         $anchor = '#t'; # thread skeleton
1019                 }
1020
1021                 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1022                 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1023                 my $s = "<a\nhref=\"$href/T/$anchor\"><b>$top</b></a>\n" .
1024                         " $ds UTC $n - $mbox / $atom\n";
1025                 for (my $i = 0; $i < scalar(@ex); $i += 2) {
1026                         my $level = $ex[$i];
1027                         my $subj = $ex[$i + 1];
1028                         $mid = delete $seen->{$subj};
1029                         my @subj = split(/ /, $srch->subject_normalized($subj));
1030                         my @next_prev = @subj; # full copy
1031                         my $omit = dedupe_subject($prev_subj, \@subj, ' &#34;');
1032                         $prev_subj = \@next_prev;
1033                         $subj = ascii_html(join(' ', @subj));
1034                         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1035                         $href = mid_escape($mid);
1036                         $s .= indent_for($level) . TCHILD;
1037                         $s .= "<a\nhref=\"$href/T/#u\">$subj</a>$omit\n";
1038                 }
1039                 push @out, $s;
1040         }
1041         $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1042         200;
1043 }
1044
1045 sub index_nav { # callback for WwwStream
1046         my (undef, $ctx) = @_;
1047         delete $ctx->{qp} or return;
1048         my ($next, $prev);
1049         $next = $prev = '    ';
1050         my $latest = '';
1051
1052         my $next_o = $ctx->{-next_o};
1053         if ($next_o) {
1054                 $next = qq!<a\nhref="?o=$next_o"\nrel=next>next</a>!;
1055         }
1056         if (my $cur_o = $ctx->{-cur_o}) {
1057                 $latest = qq! <a\nhref=.>latest</a>!;
1058
1059                 my $o = $cur_o - ($next_o - $cur_o);
1060                 if ($o > 0) {
1061                         $prev = qq!<a\nhref="?o=$o"\nrel=prev>prev</a>!;
1062                 } elsif ($o == 0) {
1063                         $prev = qq!<a\nhref=.\nrel=prev>prev</a>!;
1064                 }
1065         }
1066         "<hr><pre>page: $next $prev$latest</pre>";
1067 }
1068
1069 sub index_topics {
1070         my ($ctx) = @_;
1071         my ($off) = (($ctx->{qp}->{o} || '0') =~ /(\d+)/);
1072         my $lim = 200;
1073         my $opts = { offset => $off, limit => $lim };
1074
1075         $ctx->{order} = [];
1076         my $srch = $ctx->{srch};
1077
1078         my $qs = '';
1079         # this complicated bit cuts loading time by over 400ms on my system:
1080         if ($off == 0) {
1081                 my ($min, $max) = $ctx->{-inbox}->mm->minmax;
1082                 my $n = $max - $lim;
1083                 $n = $min if $n < $min;
1084                 for (; $qs eq '' && $n >= $min; --$n) {
1085                         my $smsg = $srch->lookup_article($n) or next;
1086                         $qs = POSIX::strftime('d:%Y%m%d..', gmtime($smsg->ts));
1087                 }
1088         }
1089
1090         my $sres = $srch->query($qs, $opts);
1091         my $nr = scalar @{$sres->{msgs}};
1092         if ($nr) {
1093                 $sres = load_results($srch, $sres);
1094                 walk_thread(thread_results($ctx, $sres), $ctx, *acc_topic);
1095         }
1096         $ctx->{-next_o} = $off + $nr;
1097         $ctx->{-cur_o} = $off;
1098         PublicInbox::WwwStream->response($ctx, dump_topics($ctx), *index_nav);
1099 }
1100
1101 sub thread_adj_level {
1102         my ($ctx, $level) = @_;
1103
1104         my $max = $ctx->{cur_level};
1105         if ($level <= 0) {
1106                 return ('', '') if $max == 0; # flat output
1107
1108                 # reset existing lists
1109                 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1110                 $ctx->{cur_level} = 0;
1111                 ("$beg</ul>", '');
1112         } elsif ($level == $max) { # continue existing list
1113                 qw(<li> </li>);
1114         } elsif ($level < $max) {
1115                 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1116                 $ctx->{cur_level} = $level;
1117                 ("$beg<li>", '</li>');
1118         } else { # ($level > $max) # start a new level
1119                 $ctx->{cur_level} = $level;
1120                 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1121                 ($beg, '</li>');
1122         }
1123 }
1124
1125 sub ghost_index_entry {
1126         my ($ctx, $level, $node) = @_;
1127         my ($beg, $end) = thread_adj_level($ctx,  $level);
1128         $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{id})
1129                 . '</pre>' . $end;
1130 }
1131
1132 1;