]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: fix message truncation logic
[public-inbox.git] / lib / PublicInbox / View.pm
1 # Copyright (C) 2014-2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (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 URI::Escape qw/uri_escape_utf8/;
10 use Date::Parse qw/str2time/;
11 use Encode qw/find_encoding/;
12 use Encode::MIME::Header;
13 use Email::MIME::ContentType qw/parse_content_type/;
14 use PublicInbox::Hval;
15 use PublicInbox::MID qw/mid_clean id_compress mid2path/;
16 use Digest::SHA qw/sha1_hex/;
17 my $SALT = rand;
18 my $MBOX_TITLE = 'title="download thread as gzipped mbox"';
19 require POSIX;
20
21 # TODO: make these constants tunable
22 use constant MAX_INLINE_QUOTED => 12; # half an 80x24 terminal
23 use constant MAX_TRUNC_LEN => 72;
24 use constant PRE_WRAP => "<pre\nstyle=\"white-space:pre-wrap\">";
25 use constant T_ANCHOR => '#u';
26 use constant INDENT => '  ';
27
28 *ascii_html = *PublicInbox::Hval::ascii_html;
29
30 my $enc_utf8 = find_encoding('UTF-8');
31
32 # public functions:
33 sub msg_html {
34         my ($ctx, $mime, $full_pfx, $footer) = @_;
35         if (defined $footer) {
36                 $footer = "\n" . $footer;
37         } else {
38                 $footer = '';
39         }
40         headers_to_html_header($mime, $full_pfx, $ctx) .
41                 multipart_text_as_html($mime, $full_pfx) .
42                 '</pre><hr />' . PRE_WRAP .
43                 html_footer($mime, 1, $full_pfx, $ctx) .
44                 $footer .
45                 '</pre></body></html>';
46 }
47
48 sub feed_entry {
49         my ($class, $mime, $full_pfx) = @_;
50
51         PRE_WRAP . multipart_text_as_html($mime, $full_pfx) . '</pre>';
52 }
53
54 sub in_reply_to {
55         my ($header_obj) = @_;
56         my $irt = $header_obj->header('In-Reply-To');
57
58         return mid_clean($irt) if (defined $irt);
59
60         my $refs = $header_obj->header('References');
61         if ($refs && $refs =~ /<([^>]+)>\s*\z/s) {
62                 return $1;
63         }
64         undef;
65 }
66
67 # this is already inside a <pre>
68 sub index_entry {
69         my ($fh, $mime, $level, $state) = @_;
70         my $midx = $state->{anchor_idx}++;
71         my $ctx = $state->{ctx};
72         my $srch = $ctx->{srch};
73         my ($prev, $next) = ($midx - 1, $midx + 1);
74         my $part_nr = 0;
75         my $enc = enc_for($mime->header("Content-Type"));
76         my $subj = $mime->header('Subject');
77         my $header_obj = $mime->header_obj;
78
79         my $mid_raw = mid_clean($header_obj->header('Message-ID'));
80         my $id = anchor_for($mid_raw);
81         my $seen = $state->{seen};
82         $seen->{$id} = "#$id"; # save the anchor for children, later
83
84         my $mid = PublicInbox::Hval->new_msgid($mid_raw);
85         my $from = PublicInbox::Hval->new_oneline($mime->header('From'))->raw;
86         my @from = Email::Address->parse($from);
87         $from = $from[0]->name;
88
89         $from = PublicInbox::Hval->new_oneline($from)->as_html;
90         $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
91         my $root_anchor = $state->{root_anchor} || '';
92         my $path = $root_anchor ? '../../' : '';
93         my $href = $mid->as_href;
94         my $irt = in_reply_to($header_obj);
95         my $parent_anchor = $seen->{anchor_for($irt)} if defined $irt;
96
97         if ($srch) {
98                 my $t = $ctx->{flat} ? 'T' : 't';
99                 $subj = "<a\nhref=\"${path}$href/$t/#u\">$subj</a>";
100         }
101         if ($root_anchor eq $id) {
102                 $subj = "<u\nid=\"u\">$subj</u>";
103         }
104
105         my $ts = _msg_date($mime);
106         my $rv = "<table\nsummary=l$level><tr>";
107         if ($level) {
108                 $rv .= '<td><pre>' . (INDENT x $level) . '</pre></td>';
109         }
110         $rv .= "<td\nid=s$midx>" . PRE_WRAP;
111         $rv .= "<b\nid=\"$id\">$subj</b>\n";
112         $rv .= "- $from @ $ts UTC - ";
113         $rv .= "<a\nhref=\"#s$next\">next</a>";
114         if ($prev >= 0) {
115                 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
116         }
117         $fh->write($rv .= "\n\n");
118
119         my ($fhref, $more_ref);
120         my $mhref = "${path}$href/";
121         my $more = 'permalink';
122
123         # show full message if it's our root message
124         my $neq = $root_anchor ne $id;
125         if ($neq || ($neq && $level != 0 && !$ctx->{flat})) {
126                 $fhref = "${path}$href/f/";
127                 $more_ref = \$more;
128         }
129         # scan through all parts, looking for displayable text
130         $mime->walk_parts(sub {
131                 index_walk($fh, $_[0], $enc, \$part_nr, $fhref, $more_ref);
132         });
133         $mime->body_set('');
134
135         my $txt = "${path}$href/raw";
136         $rv = "\n<a\nhref=\"$mhref\">$more</a> <a\nhref=\"$txt\">raw</a> ";
137         $rv .= html_footer($mime, 0, undef, $ctx);
138
139         if (defined $irt) {
140                 unless (defined $parent_anchor) {
141                         my $v = PublicInbox::Hval->new_msgid($irt, 1);
142                         $v = $v->as_href;
143                         $parent_anchor = "${path}$v/";
144                 }
145                 $rv .= " <a\nhref=\"$parent_anchor\">parent</a>";
146         }
147         if (my $pct = $state->{pct}) {
148                 $rv .= " [$pct->{$mid_raw}%]";
149         } elsif ($srch) {
150                 if ($ctx->{flat}) {
151                         $rv .= " [<a\nhref=\"${path}$href/t/#u\">threaded</a>" .
152                                 "|<b>flat</b>]";
153                 } else {
154                         $rv .= " [<b>threaded</b>|" .
155                                 "<a\nhref=\"${path}$href/T/#u\">flat</a>]";
156                 }
157         }
158
159         $fh->write($rv .= '</pre></td></tr></table>');
160 }
161
162 sub thread_html {
163         my ($ctx, $foot, $srch) = @_;
164         sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
165 }
166
167 # only private functions below.
168
169 sub emit_thread_html {
170         my ($cb, $ctx, $foot, $srch) = @_;
171         my $mid = $ctx->{mid};
172         my $res = $srch->get_thread($mid);
173         my $msgs = load_results($res);
174         my $nr = scalar @$msgs;
175         return missing_thread($cb, $ctx) if $nr == 0;
176         my $flat = $ctx->{flat};
177         my $orig_cb = $cb;
178         my $seen = {};
179         my $state = {
180                 ctx => $ctx,
181                 seen => $seen,
182                 root_anchor => anchor_for($mid),
183                 anchor_idx => 0,
184         };
185
186         require PublicInbox::GitCatFile;
187         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
188         if ($flat) {
189                 pre_anchor_entry($seen, $_) for (@$msgs);
190                 __thread_entry(\$cb, $git, $state, $_, 0) for (@$msgs);
191         } else {
192                 my $th = thread_results($msgs);
193                 thread_entry(\$cb, $git, $state, $_, 0) for $th->rootset;
194         }
195         $git = undef;
196         Email::Address->purge_cache;
197
198         # there could be a race due to a message being deleted in git
199         # but still being in the Xapian index:
200         return missing_thread($cb, $ctx) if ($orig_cb eq $cb);
201
202         my $final_anchor = $state->{anchor_idx};
203         my $next = "<a\nid=\"s$final_anchor\">";
204         $next .= $final_anchor == 1 ? 'only message in' : 'end of';
205         $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>";
206         $next .= "\ndownload thread: ";
207         $next .= "<a\n$MBOX_TITLE\nhref=\"../t.mbox.gz\">mbox.gz</a>";
208         $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>";
209         $cb->write("<hr />" . PRE_WRAP . $next . "\n\n". $foot .
210                    "</pre></body></html>");
211         $cb->close;
212 }
213
214 sub index_walk {
215         my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
216         my $s = add_text_body($enc, $part, $part_nr, $fhref);
217
218         if ($more) {
219                 my $m = 0;
220                 # drop the remainder of git patches, they're usually better
221                 # to review when the full message is viewed
222                 $s =~ s!^---+\n.*\z!!ms and $m = 1;
223
224                 # Drop signatures
225                 $s =~ s/^-- \n.*\z//ms and $m = 1;
226                 $$more = "<b>More...</b>\n\n$$more" if $m;
227         }
228
229         # kill any leading or trailing whitespace lines
230         $s =~ s/^\s*$//sgm;
231         $s =~ s/\s+\z//s;
232
233         if ($s ne '') {
234                 # kill per-line trailing whitespace
235                 $s =~ s/[ \t]+$//sgm;
236                 $s .= "\n" unless $s =~ /\n\z/s;
237         }
238         $fh->write($s);
239 }
240
241 sub enc_for {
242         my ($ct, $default) = @_;
243         $default ||= $enc_utf8;
244         defined $ct or return $default;
245         my $ct_parsed = parse_content_type($ct);
246         if ($ct_parsed) {
247                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
248                         my $enc = find_encoding($charset);
249                         return $enc if $enc;
250                 }
251         }
252         $default;
253 }
254
255 sub multipart_text_as_html {
256         my ($mime, $full_pfx, $srch) = @_;
257         my $rv = "";
258         my $part_nr = 0;
259         my $enc = enc_for($mime->header("Content-Type"));
260
261         # scan through all parts, looking for displayable text
262         $mime->walk_parts(sub {
263                 my ($part) = @_;
264                 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx, 1);
265         });
266         $mime->body_set('');
267         $rv;
268 }
269
270 sub add_filename_line {
271         my ($enc, $fn) = @_;
272         my $len = 72;
273         my $pad = "-";
274         $fn = $enc->decode($fn);
275         $len -= length($fn);
276         $pad x= ($len/2) if ($len > 0);
277         "$pad " . ascii_html($fn) . " $pad\n";
278 }
279
280 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
281                  [\@:\w\.-]+/
282                  ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
283
284 sub linkify_1 {
285         my ($link_map, $s) = @_;
286         $s =~ s!$LINK_RE!
287                 my $url = $1;
288                 # salt this, as this could be exploited to show
289                 # links in the HTML which don't show up in the raw mail.
290                 my $key = sha1_hex($url . $SALT);
291                 $link_map->{$key} = $url;
292                 'PI-LINK-'. $key;
293         !ge;
294         $s;
295 }
296
297 sub linkify_2 {
298         my ($link_map, $s) = @_;
299
300         # Added "PI-LINK-" prefix to avoid false-positives on git commits
301         $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
302                 my $key = $1;
303                 my $url = $link_map->{$key};
304                 if (defined $url) {
305                         $url = ascii_html($url);
306                         "<a\nhref=\"$url\">$url</a>";
307                 } else {
308                         # false positive or somebody tried to mess with us
309                         $key;
310                 }
311         !ge;
312         $s;
313 }
314
315 sub flush_quote {
316         my ($quot, $n, $part_nr, $full_pfx, $final, $do_anchor) = @_;
317
318         if ($full_pfx) {
319                 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
320                         # show quote inline
321                         my %l;
322                         my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
323                         @$quot = ();
324                         $rv = ascii_html($rv);
325                         return linkify_2(\%l, $rv);
326                 }
327
328                 # show a short snippet of quoted text and link to full version:
329                 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
330                 my $cur = join(' ', @$quot);
331                 @$quot = split(/\s+/, $cur);
332                 $cur = '';
333                 do {
334                         my $tmp = shift(@$quot);
335                         my $len = length($tmp) + length($cur);
336                         if ($len > MAX_TRUNC_LEN) {
337                                 @$quot = ();
338                         } else {
339                                 $cur .= $tmp . ' ';
340                         }
341                 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
342                 @$quot = ();
343                 $cur =~ s/ \z/ .../s;
344                 $cur = ascii_html($cur);
345                 my $nr = ++$$n;
346                 "&gt; [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
347         } else {
348                 # show everything in the full version with anchor from
349                 # short version (see above)
350                 my %l;
351                 my $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
352                 @$quot = ();
353                 $rv = ascii_html($rv);
354                 return linkify_2(\%l, $rv) unless $do_anchor;
355                 my $nr = ++$$n;
356                 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
357         }
358 }
359
360 sub add_text_body {
361         my ($enc_msg, $part, $part_nr, $full_pfx, $do_anchor) = @_;
362         return '' if $part->subparts;
363
364         my $ct = $part->content_type;
365         # account for filter bugs...
366         if (defined $ct && $ct =~ m!\btext/x?html\b!i) {
367                 $part->body_set('');
368                 return '';
369         }
370         my $enc = enc_for($ct, $enc_msg);
371         my $n = 0;
372         my $nr = 0;
373         my $s = $part->body;
374         $part->body_set('');
375         $s = $enc->decode($s);
376         my @lines = split(/^/m, $s);
377         $s = '';
378
379         if ($$part_nr > 0) {
380                 my $fn = $part->filename;
381                 defined($fn) or $fn = "part #" . ($$part_nr + 1);
382                 $s .= add_filename_line($enc, $fn);
383         }
384
385         my @quot;
386         while (defined(my $cur = shift @lines)) {
387                 if ($cur !~ /^>/) {
388                         # show the previously buffered quote inline
389                         if (scalar @quot) {
390                                 $s .= flush_quote(\@quot, \$n, $$part_nr,
391                                                   $full_pfx, 0, $do_anchor);
392                         }
393
394                         # regular line, OK
395                         my %l;
396                         $cur = linkify_1(\%l, $cur);
397                         $cur = ascii_html($cur);
398                         $s .= linkify_2(\%l, $cur);
399                 } else {
400                         push @quot, $cur;
401                 }
402         }
403         if (scalar @quot) {
404                 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1,
405                                   $do_anchor);
406         }
407         $s .= "\n" unless $s =~ /\n\z/s;
408         ++$$part_nr;
409         $s;
410 }
411
412 sub headers_to_html_header {
413         my ($mime, $full_pfx, $ctx) = @_;
414         my $srch = $ctx->{srch} if $ctx;
415         my $rv = "";
416         my @title;
417         my $header_obj = $mime->header_obj;
418         my $mid = $header_obj->header('Message-ID');
419         $mid = PublicInbox::Hval->new_msgid($mid);
420         foreach my $h (qw(From To Cc Subject Date)) {
421                 my $v = $header_obj->header($h);
422                 defined($v) && ($v ne '') or next;
423                 $v = PublicInbox::Hval->new_oneline($v);
424
425                 if ($h eq 'From') {
426                         my @from = Email::Address->parse($v->raw);
427                         $title[1] = ascii_html($from[0]->name);
428                 } elsif ($h eq 'Subject') {
429                         $title[0] = $v->as_html;
430                         if ($srch) {
431                                 my $p = $full_pfx ? '' : '../';
432                                 $rv .= "$h: <a\nid=\"t\"\nhref=\"${p}t/#u\">";
433                                 $rv .= $v->as_html . "</a>\n";
434                                 next;
435                         }
436                 }
437                 $rv .= "$h: " . $v->as_html . "\n";
438
439         }
440         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
441         my $upfx = $full_pfx ? '' : '../';
442         $rv .= "(<a\nhref=\"${upfx}raw\">raw</a>)\n";
443         my $atom;
444         if ($srch) {
445                 if ($header_obj->header('In-Reply-To') ||
446                     $header_obj->header('References')) {
447                         $rv .= "<a\nhref=\"${upfx}t/#u\">" .
448                                 "References: [expand]</a>\n";
449                 }
450
451                 $atom = qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
452                         qq!href="${upfx}t.atom"\ntype="application/atom+xml"/>!;
453         } else {
454                 $rv .= _parent_headers_nosrch($header_obj);
455                 $atom = '';
456         }
457         $rv .= "\n";
458
459         ("<html><head><title>".  join(' - ', @title) .
460          "</title>$atom</head><body>" . PRE_WRAP . $rv);
461 }
462
463 sub thread_inline {
464         my ($dst, $ctx, $cur, $full_pfx) = @_;
465         my $srch = $ctx->{srch};
466         my $mid = mid_clean($cur->header('Message-ID'));
467         my $res = $srch->get_thread($mid);
468         my $nr = $res->{total};
469         my $upfx = $full_pfx ? '' : '../';
470         my $expand = "(<a\nhref=\"${upfx}t/#u\">expand</a> " .
471                         "/ <a\nhref=\"${upfx}t.mbox.gz\">mbox.gz</a>)";
472
473         if ($nr <= 1) {
474                 $$dst .= "\n[no followups, yet] $expand\n";
475                 return (undef, in_reply_to($cur));
476         }
477
478         $$dst .= "\n\n~$nr messages in thread: $expand\n";
479
480         my $subj = $srch->subject_path($cur->header('Subject'));
481         my $parent = in_reply_to($cur);
482         my $state = {
483                 seen => { $subj => 1 },
484                 srch => $srch,
485                 cur => $mid,
486                 parent_cmp => defined $parent ? $parent : '',
487                 parent => $parent,
488                 prev_attr => '',
489                 prev_level => 0,
490         };
491         for (thread_results(load_results($res))->rootset) {
492                 inline_dump($dst, $state, $upfx, $_, 0);
493         }
494         ($state->{next_msg}, $state->{parent});
495 }
496
497 sub _parent_headers_nosrch {
498         my ($header_obj) = @_;
499         my $rv = '';
500
501         my $irt = in_reply_to($header_obj);
502         if (defined $irt) {
503                 my $v = PublicInbox::Hval->new_msgid($irt, 1);
504                 my $html = $v->as_html;
505                 my $href = $v->as_href;
506                 $rv .= "In-Reply-To: &lt;";
507                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
508         }
509
510         my $refs = $header_obj->header('References');
511         if ($refs) {
512                 # avoid redundant URLs wasting bandwidth
513                 my %seen;
514                 $seen{$irt} = 1 if defined $irt;
515                 my @refs;
516                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
517                 foreach my $ref (@raw_refs) {
518                         next if $seen{$ref};
519                         $seen{$ref} = 1;
520                         push @refs, linkify_ref_nosrch($ref);
521                 }
522
523                 if (@refs) {
524                         $rv .= 'References: '. join(' ', @refs) . "\n";
525                 }
526         }
527         $rv;
528 }
529
530 sub html_footer {
531         my ($mime, $standalone, $full_pfx, $ctx) = @_;
532         my %cc; # everyone else
533         my $to; # this is the From address
534
535         foreach my $h (qw(From To Cc)) {
536                 my $v = $mime->header($h);
537                 defined($v) && ($v ne '') or next;
538                 my @addrs = Email::Address->parse($v);
539                 foreach my $recip (@addrs) {
540                         my $address = $recip->address;
541                         my $dst = lc($address);
542                         $cc{$dst} ||= $address;
543                         $to ||= $dst;
544                 }
545         }
546         Email::Address->purge_cache if $standalone;
547
548         my $subj = $mime->header('Subject') || '';
549         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
550         my $mid = $mime->header('Message-ID');
551         my $irt = uri_escape_utf8($mid);
552         delete $cc{$to};
553         $to = uri_escape_utf8($to);
554         $subj = uri_escape_utf8($subj);
555
556         my $cc = uri_escape_utf8(join(',', sort values %cc));
557         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
558         $href =~ s/%20/+/g;
559
560         my $srch = $ctx->{srch} if $ctx;
561         my $upfx = $full_pfx ? '../' : '../../';
562         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
563
564         if ($srch && $standalone) {
565                 $idx .= qq{ / follow: <a\nhref="t.atom">Atom feed</a>};
566         }
567         if ($idx && $srch) {
568                 my ($next, $p) = thread_inline(\$idx, $ctx, $mime, $full_pfx);
569                 if (defined $p) {
570                         $p = PublicInbox::Hval->new_oneline($p);
571                         $p = $p->as_href;
572                         $irt = "<a\nhref=\"$upfx$p/\">parent</a> ";
573                 } else {
574                         $irt = ' ' x length('parent ');
575                 }
576                 if ($next) {
577                         $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
578                 } else {
579                         $irt .= '     ';
580                 }
581         } else {
582                 $irt = '';
583         }
584
585         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
586 }
587
588 sub linkify_ref_nosrch {
589         my $v = PublicInbox::Hval->new_msgid($_[0], 1);
590         my $html = $v->as_html;
591         my $href = $v->as_href;
592         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
593 }
594
595 sub anchor_for {
596         my ($msgid) = @_;
597         my $id = $msgid;
598         if ($id !~ /\A[a-f0-9]{40}\z/) {
599                 $id = id_compress(mid_clean($id), 1);
600         }
601         'm' . $id;
602 }
603
604 sub thread_html_head {
605         my ($cb, $header, $state) = @_;
606         $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
607
608         my $s = PublicInbox::Hval->new_oneline($header->header('Subject'));
609         $s = $s->as_html;
610         $$cb->write("<html><head><title>$s</title>".
611                 qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
612                 qq!href="../t.atom"\ntype="application/atom+xml"/>! .
613                 "</head><body>");
614 }
615
616 sub pre_anchor_entry {
617         my ($seen, $mime) = @_;
618         my $id = anchor_for($mime->header('Message-ID'));
619         $seen->{$id} = "#$id"; # save the anchor for children, later
620 }
621
622 sub ghost_parent {
623         my ($upfx, $mid) = @_;
624         # 'subject dummy' is used internally by Mail::Thread
625         return '[no common parent]' if ($mid eq 'subject dummy');
626
627         $mid = PublicInbox::Hval->new_msgid($mid);
628         my $href = $mid->as_href;
629         my $html = $mid->as_html;
630         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
631 }
632
633 sub ghost_table {
634         my ($upfx, $mid, $level) = @_;
635         "<table\nsummary=ghost><tr><td>" .
636                 (INDENT x $level) . "</td><td>" .
637                 PRE_WRAP . ghost_parent($upfx, $mid) .
638                 '</pre></td></table>';
639 }
640
641 sub __thread_entry {
642         my ($cb, $git, $state, $mime, $level) = @_;
643
644         # lazy load the full message from mini_mime:
645         $mime = eval {
646                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
647                 Email::MIME->new($git->cat_file('HEAD:'.$path));
648         } or return;
649
650         if ($state->{anchor_idx} == 0) {
651                 thread_html_head($cb, $mime, $state);
652         }
653
654         if (my $ghost = delete $state->{ghost}) {
655                 # n.b. ghost messages may only be parents, not children
656                 foreach my $g (@$ghost) {
657                         $$cb->write(ghost_table('../../', @$g));
658                 }
659         }
660         index_entry($$cb, $mime, $level, $state);
661         1;
662 }
663
664 sub __ghost_entry {
665         my ($state, $node, $level) = @_;
666         my $ghost = $state->{ghost} ||= [];
667         push @$ghost, [ $node->messageid, $level ];
668 }
669
670 sub thread_entry {
671         my ($cb, $git, $state, $node, $level) = @_;
672         return unless $node;
673         if (my $mime = $node->message) {
674                 unless (__thread_entry($cb, $git, $state, $mime, $level)) {
675                         __ghost_entry($state, $node, $level);
676                 }
677         } else {
678                 __ghost_entry($state, $node, $level);
679         }
680
681         thread_entry($cb, $git, $state, $node->child, $level + 1);
682         thread_entry($cb, $git, $state, $node->next, $level);
683 }
684
685 sub load_results {
686         my ($res) = @_;
687
688         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
689 }
690
691 sub msg_timestamp {
692         my ($mime) = @_;
693         my $ts = eval { str2time($mime->header('Date')) };
694         defined($ts) ? $ts : 0;
695 }
696
697 sub thread_results {
698         my ($msgs, $nosubject) = @_;
699         require PublicInbox::Thread;
700         my $th = PublicInbox::Thread->new(@$msgs);
701         no warnings 'once';
702         $Mail::Thread::nosubject = $nosubject;
703         $th->thread;
704         $th->order(*sort_ts);
705         $th
706 }
707
708 sub missing_thread {
709         my ($cb, $ctx) = @_;
710         require PublicInbox::ExtMsg;
711
712         $cb->(PublicInbox::ExtMsg::ext_msg($ctx))
713 }
714
715 sub _msg_date {
716         my ($mime) = @_;
717         my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
718         fmt_ts($ts);
719 }
720
721 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
722
723 sub _inline_header {
724         my ($dst, $state, $upfx, $mime, $level) = @_;
725         my $pfx = INDENT x ($level - 1);
726         my $dot = $level == 0 ? '' : '` ';
727
728         my $cur = $state->{cur};
729         my $mid = mid_clean($mime->header('Message-ID'));
730         my $f = $mime->header('X-PI-From');
731         my $d = _msg_date($mime);
732         $f = PublicInbox::Hval->new($f)->as_html;
733         $d = PublicInbox::Hval->new($d)->as_html;
734         my $attr = "$f @ $d";
735         $state->{first_level} ||= $level;
736         if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
737                 $state->{prev_attr} = $attr;
738                 $attr = ' - ' . $attr;
739                 $attr .= ' UTC' if $level >= $state->{first_level};
740         } else {
741                 $attr = '';
742         }
743         $state->{prev_level} = $level;
744
745         if ($cur) {
746                 if ($cur eq $mid) {
747                         delete $state->{cur};
748                         $$dst .= "$pfx$dot<b><a\nid=\"r\"\nhref=\"#t\">".
749                                  "[this message]</a></b>$attr\n";
750
751                         return;
752                 }
753         } else {
754                 $state->{next_msg} ||= $mid;
755         }
756
757         # Subject is never undef, this mail was loaded from
758         # our Xapian which would've resulted in '' if it were
759         # really missing (and Filter rejects empty subjects)
760         my $s = $mime->header('Subject');
761         my $h = $state->{srch}->subject_path($s);
762         if ($state->{seen}->{$h}) {
763                 $s = undef;
764         } else {
765                 $state->{seen}->{$h} = 1;
766                 $s = PublicInbox::Hval->new($s);
767                 $s = $s->as_html;
768         }
769         my $m = PublicInbox::Hval->new_msgid($mid);
770         $m = $upfx . '../' . $m->as_href . '/';
771         if (defined $s) {
772                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$s</a>$attr\n";
773         } else {
774                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$f @ $d</a>\n";
775         }
776 }
777
778 sub inline_dump {
779         my ($dst, $state, $upfx, $node, $level) = @_;
780         return unless $node;
781         if (my $mime = $node->message) {
782                 my $mid = mid_clean($mime->header('Message-ID'));
783                 if ($mid eq $state->{parent_cmp}) {
784                         $state->{parent} = $mid;
785                 }
786                 _inline_header($dst, $state, $upfx, $mime, $level);
787         } else {
788                 my $dot = $level == 0 ? '' : '` ';
789                 my $pfx = (INDENT x $level) . $dot;
790                 $$dst .= $pfx;
791                 $$dst .= ghost_parent("$upfx../", $node->messageid) . "\n";
792         }
793         inline_dump($dst, $state, $upfx, $node->child, $level+1);
794         inline_dump($dst, $state, $upfx, $node->next, $level);
795 }
796
797 sub sort_ts {
798         sort {
799                 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
800                 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
801         } @_;
802 }
803
804 sub rsort_ts {
805         sort {
806                 (eval { $b->topmost->message->header('X-PI-TS') } || 0) <=>
807                 (eval { $a->topmost->message->header('X-PI-TS') } || 0)
808         } @_;
809 }
810
811 # accumulate recent topics if search is supported
812 # returns 1 if done, undef if not
813 sub add_topic {
814         my ($state, $node, $level) = @_;
815         return unless $node;
816         my $child_adjust = 1;
817
818         if (my $x = $node->message) {
819                 $x = $x->header_obj;
820                 my ($topic, $subj);
821
822                 $subj = $x->header('Subject');
823                 $subj = $state->{srch}->subject_normalized($subj);
824                 $topic = $subj;
825
826                 # kill "[PATCH v2]" etc. for summarization
827                 unless ($level == 0) {
828                         $topic =~ s/\A\s*\[[^\]]+\]\s*//g;
829                 }
830
831                 if (++$state->{subjs}->{$topic} == 1) {
832                         push @{$state->{order}}, [ $level, $subj, $topic ];
833                 }
834
835                 my $mid = mid_clean($x->header('Message-ID'));
836
837                 my $ts = $x->header('X-PI-TS');
838                 my $exist = $state->{latest}->{$topic};
839                 if (!$exist || $exist->[1] < $ts) {
840                         $state->{latest}->{$topic} = [ $mid, $ts ];
841                 }
842         } else {
843                 # ghost message, do not bump level
844                 $child_adjust = 0;
845         }
846
847         add_topic($state, $node->child, $level + $child_adjust);
848         add_topic($state, $node->next, $level);
849 }
850
851 sub dump_topics {
852         my ($state) = @_;
853         my $order = $state->{order};
854         my $subjs = $state->{subjs};
855         my $latest = $state->{latest};
856         return "\n[No recent topics]</pre>" unless (scalar @$order);
857         my $dst = '';
858         my $pfx;
859         my $prev = 0;
860         my $prev_attr = '';
861         while (defined(my $info = shift @$order)) {
862                 my ($level, $subj, $topic) = @$info;
863                 my $n = delete $subjs->{$topic};
864                 my ($mid, $ts) = @{delete $latest->{$topic}};
865                 $mid = PublicInbox::Hval->new($mid)->as_href;
866                 $subj = PublicInbox::Hval->new($subj)->as_html;
867                 $pfx = INDENT x ($level - 1);
868                 my $nl = $level == $prev ? "\n" : '';
869                 my $dot = $level == 0 ? '' : '` ';
870                 $dst .= "$nl$pfx$dot<a\nhref=\"$mid/t/#u\"><b>$subj</b></a>\n";
871
872                 my $attr;
873                 $ts = fmt_ts($ts);
874                 if ($n == 1) {
875                         $attr = "@ $ts UTC";
876                         $n = "";
877                 } else {
878                         # $n isn't the total number of posts on the topic,
879                         # just the number of posts in the current results
880                         # window, so leave it unlabeled
881                         $attr = "@ $ts UTC";
882                         $n = " ($n)";
883                 }
884                 if ($level == 0 || $attr ne $prev_attr) {
885                         my $mbox = qq(<a\n$MBOX_TITLE\n) .
886                                    qq(href="$mid/t.mbox.gz">mbox.gz</a>);
887                         my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
888                         $pfx .= INDENT if $level > 0;
889                         $dst .= $pfx . $attr . $n . " - $mbox / $atom\n";
890                         $prev_attr = $attr;
891                 }
892         }
893         $dst .= '</pre>';
894 }
895
896 sub emit_index_topics {
897         my ($state, $fh) = @_;
898         my $off = $state->{ctx}->{cgi}->param('o');
899         $off = 0 unless defined $off;
900         $state->{order} = [];
901         $state->{subjs} = {};
902         $state->{latest} = {};
903         my $max = 25;
904         my %opts = ( offset => int $off, limit => $max * 4 );
905         while (scalar @{$state->{order}} < $max) {
906                 my $res = $state->{srch}->query('', \%opts);
907                 my $nr = scalar @{$res->{msgs}} or last;
908
909                 for (rsort_ts(thread_results(load_results($res), 1)->rootset)) {
910                         add_topic($state, $_, 0);
911                 }
912                 $opts{offset} += $nr;
913         }
914
915         $fh->write(dump_topics($state));
916         $opts{offset};
917 }
918
919 1;