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