]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: move thread info near top of single view
[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 T_ANCHOR => '#u';
25 use constant INDENT => '  ';
26
27 *ascii_html = *PublicInbox::Hval::ascii_html;
28
29 my $enc_utf8 = find_encoding('UTF-8');
30
31 # public functions:
32 sub msg_html {
33         my ($ctx, $mime, $full_pfx, $footer) = @_;
34         if (defined $footer) {
35                 $footer = "\n" . $footer;
36         } else {
37                 $footer = '';
38         }
39         headers_to_html_header($mime, $full_pfx, $ctx) .
40                 multipart_text_as_html($mime, $full_pfx) .
41                 '</pre><hr />' . PublicInbox::Hval::PRE .
42                 html_footer($mime, 1, $full_pfx, $ctx) .
43                 $footer .
44                 '</pre></body></html>';
45 }
46
47 sub feed_entry {
48         my ($class, $mime, $full_pfx) = @_;
49
50         PublicInbox::Hval::PRE .
51                 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>" . PublicInbox::Hval::PRE;
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::Git;
187         my $git = $ctx->{git} ||= PublicInbox::Git->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 />" . PublicInbox::Hval::PRE . $next . "\n\n".
210                 $foot .  "</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                                 $rv .= "$h: <b\nid=t>";
432                                 $rv .= $v->as_html . "</b>\n";
433                                 next;
434                         }
435                 }
436                 $rv .= "$h: " . $v->as_html . "\n";
437
438         }
439         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
440         my $upfx = $full_pfx ? '' : '../';
441         $rv .= "(<a\nhref=\"${upfx}raw\">raw</a>)\n";
442         my $atom;
443         if ($srch) {
444                 thread_inline(\$rv, $ctx, $mime, $upfx);
445
446                 $atom = qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
447                         qq!href="${upfx}t.atom"\ntype="application/atom+xml"/>!;
448         } else {
449                 $rv .= _parent_headers_nosrch($header_obj);
450                 $atom = '';
451         }
452         $rv .= "\n";
453
454         ("<html><head><title>".  join(' - ', @title) .
455          "</title>$atom</head><body>" . PublicInbox::Hval::PRE . $rv);
456 }
457
458 sub thread_inline {
459         my ($dst, $ctx, $cur, $upfx) = @_;
460         my $srch = $ctx->{srch};
461         my $mid = mid_clean($cur->header('Message-ID'));
462         my $res = $srch->get_thread($mid);
463         my $nr = $res->{total};
464         my $expand = "<a\nhref=\"${upfx}t/#u\">expand</a> " .
465                         "/ <a\nhref=\"${upfx}t.mbox.gz\">mbox.gz</a>";
466
467         $$dst .= 'Thread: ';
468         my $parent = in_reply_to($cur);
469         if ($nr <= 1) {
470                 $$dst .= "[no followups, yet] ($expand)\n";
471                 $ctx->{next_msg} = undef;
472                 $ctx->{parent_msg} = $parent;
473                 return;
474         }
475
476         $$dst .= "~$nr messages (<a\nhref=\"#b\">skip</a> / " .
477                  $expand . ")\n";
478
479         my $subj = $srch->subject_path($cur->header('Subject'));
480         my $state = {
481                 seen => { $subj => 1 },
482                 srch => $srch,
483                 cur => $mid,
484                 parent_cmp => defined $parent ? $parent : '',
485                 parent => $parent,
486                 prev_attr => '',
487                 prev_level => 0,
488         };
489         for (thread_results(load_results($res))->rootset) {
490                 inline_dump($dst, $state, $upfx, $_, 0);
491         }
492         $$dst .= "<a\nid=b></a>"; # anchor for body start
493         $ctx->{next_msg} = $state->{next_msg};
494         $ctx->{parent_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>\n};
566         }
567         if ($idx && $srch) {
568                 my $p = $ctx->{parent_msg};
569                 my $next = $ctx->{next_msg};
570                 if ($p) {
571                         $p = PublicInbox::Hval->new_oneline($p);
572                         $p = $p->as_href;
573                         $irt = "<a\nhref=\"$upfx$p/\">parent</a> ";
574                 } else {
575                         $irt = ' ' x length('parent ');
576                 }
577                 if ($next) {
578                         $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
579                 } else {
580                         $irt .= ' ' x length('next ');
581                 }
582                 if ($p || $next) {
583                         $irt .= "<a\nhref=\"#r\">thread</a> ";
584                 } else {
585                         $irt .= ' ' x length('thread ');
586                 }
587         } else {
588                 $irt = '';
589         }
590
591         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
592 }
593
594 sub linkify_ref_nosrch {
595         my $v = PublicInbox::Hval->new_msgid($_[0], 1);
596         my $html = $v->as_html;
597         my $href = $v->as_href;
598         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
599 }
600
601 sub anchor_for {
602         my ($msgid) = @_;
603         my $id = $msgid;
604         if ($id !~ /\A[a-f0-9]{40}\z/) {
605                 $id = id_compress(mid_clean($id), 1);
606         }
607         'm' . $id;
608 }
609
610 sub thread_html_head {
611         my ($cb, $header, $state) = @_;
612         $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
613
614         my $s = PublicInbox::Hval->new_oneline($header->header('Subject'));
615         $s = $s->as_html;
616         $$cb->write("<html><head><title>$s</title>".
617                 qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
618                 qq!href="../t.atom"\ntype="application/atom+xml"/>! .
619                 "</head><body>");
620 }
621
622 sub pre_anchor_entry {
623         my ($seen, $mime) = @_;
624         my $id = anchor_for($mime->header('Message-ID'));
625         $seen->{$id} = "#$id"; # save the anchor for children, later
626 }
627
628 sub ghost_parent {
629         my ($upfx, $mid) = @_;
630         # 'subject dummy' is used internally by Mail::Thread
631         return '[no common parent]' if ($mid eq 'subject dummy');
632
633         $mid = PublicInbox::Hval->new_msgid($mid);
634         my $href = $mid->as_href;
635         my $html = $mid->as_html;
636         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
637 }
638
639 sub ghost_table {
640         my ($upfx, $mid, $level) = @_;
641         "<table\nsummary=ghost><tr><td>" .
642                 (INDENT x $level) . "</td><td>" .
643                 PublicInbox::Hval::PRE . ghost_parent($upfx, $mid) .
644                 '</pre></td></table>';
645 }
646
647 sub __thread_entry {
648         my ($cb, $git, $state, $mime, $level) = @_;
649
650         # lazy load the full message from mini_mime:
651         $mime = eval {
652                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
653                 Email::MIME->new($git->cat_file('HEAD:'.$path));
654         } or return;
655
656         if ($state->{anchor_idx} == 0) {
657                 thread_html_head($cb, $mime, $state);
658         }
659
660         if (my $ghost = delete $state->{ghost}) {
661                 # n.b. ghost messages may only be parents, not children
662                 foreach my $g (@$ghost) {
663                         $$cb->write(ghost_table('../../', @$g));
664                 }
665         }
666         index_entry($$cb, $mime, $level, $state);
667         1;
668 }
669
670 sub __ghost_entry {
671         my ($state, $node, $level) = @_;
672         my $ghost = $state->{ghost} ||= [];
673         push @$ghost, [ $node->messageid, $level ];
674 }
675
676 sub thread_entry {
677         my ($cb, $git, $state, $node, $level) = @_;
678         return unless $node;
679         if (my $mime = $node->message) {
680                 unless (__thread_entry($cb, $git, $state, $mime, $level)) {
681                         __ghost_entry($state, $node, $level);
682                 }
683         } else {
684                 __ghost_entry($state, $node, $level);
685         }
686
687         thread_entry($cb, $git, $state, $node->child, $level + 1);
688         thread_entry($cb, $git, $state, $node->next, $level);
689 }
690
691 sub load_results {
692         my ($res) = @_;
693
694         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
695 }
696
697 sub msg_timestamp {
698         my ($mime) = @_;
699         my $ts = eval { str2time($mime->header('Date')) };
700         defined($ts) ? $ts : 0;
701 }
702
703 sub thread_results {
704         my ($msgs, $nosubject) = @_;
705         require PublicInbox::Thread;
706         my $th = PublicInbox::Thread->new(@$msgs);
707         no warnings 'once';
708         $Mail::Thread::nosubject = $nosubject;
709         $th->thread;
710         $th->order(*sort_ts);
711         $th
712 }
713
714 sub missing_thread {
715         my ($cb, $ctx) = @_;
716         require PublicInbox::ExtMsg;
717
718         $cb->(PublicInbox::ExtMsg::ext_msg($ctx))
719 }
720
721 sub _msg_date {
722         my ($mime) = @_;
723         my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
724         fmt_ts($ts);
725 }
726
727 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
728
729 sub _inline_header {
730         my ($dst, $state, $upfx, $mime, $level) = @_;
731         my $dot = $level == 0 ? '' : '` ';
732
733         my $cur = $state->{cur};
734         my $mid = mid_clean($mime->header('Message-ID'));
735         my $f = $mime->header('X-PI-From');
736         my $d = _msg_date($mime);
737         $f = PublicInbox::Hval->new($f)->as_html;
738         $d = PublicInbox::Hval->new($d)->as_html;
739         my $pfx = ' ' . $d . ' ' . (INDENT x $level);
740         my $attr = $f;
741         $state->{first_level} ||= $level;
742
743         if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
744                 $state->{prev_attr} = $attr;
745         } else {
746                 $attr = '';
747         }
748         $state->{prev_level} = $level;
749
750         if ($cur) {
751                 if ($cur eq $mid) {
752                         delete $state->{cur};
753                         $$dst .= "$pfx$dot<b><a\nid=r\nhref=\"#b\">".
754                                  "$attr [this message]</a></b>\n";
755
756                         return;
757                 }
758         } else {
759                 $state->{next_msg} ||= $mid;
760         }
761
762         # Subject is never undef, this mail was loaded from
763         # our Xapian which would've resulted in '' if it were
764         # really missing (and Filter rejects empty subjects)
765         my $s = $mime->header('Subject');
766         my $h = $state->{srch}->subject_path($s);
767         if ($state->{seen}->{$h}) {
768                 $s = undef;
769         } else {
770                 $state->{seen}->{$h} = 1;
771                 $s = PublicInbox::Hval->new($s);
772                 $s = $s->as_html;
773         }
774         my $m = PublicInbox::Hval->new_msgid($mid);
775         $m = $upfx . '../' . $m->as_href . '/';
776         if (defined $s) {
777                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$s</a>$attr\n";
778         } else {
779                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$f</a>\n";
780         }
781 }
782
783 sub inline_dump {
784         my ($dst, $state, $upfx, $node, $level) = @_;
785         return unless $node;
786         if (my $mime = $node->message) {
787                 my $mid = mid_clean($mime->header('Message-ID'));
788                 if ($mid eq $state->{parent_cmp}) {
789                         $state->{parent} = $mid;
790                 }
791                 _inline_header($dst, $state, $upfx, $mime, $level);
792         } else {
793                 my $dot = $level == 0 ? '' : '` ';
794                 my $pfx = length(' 1970-01-01 13:37 ') .
795                         (INDENT x $level) . $dot;
796                 $$dst .= $pfx;
797                 $$dst .= ghost_parent("$upfx../", $node->messageid) . "\n";
798         }
799         inline_dump($dst, $state, $upfx, $node->child, $level+1);
800         inline_dump($dst, $state, $upfx, $node->next, $level);
801 }
802
803 sub sort_ts {
804         sort {
805                 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
806                 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
807         } @_;
808 }
809
810 sub rsort_ts {
811         sort {
812                 (eval { $b->topmost->message->header('X-PI-TS') } || 0) <=>
813                 (eval { $a->topmost->message->header('X-PI-TS') } || 0)
814         } @_;
815 }
816
817 # accumulate recent topics if search is supported
818 # returns 1 if done, undef if not
819 sub add_topic {
820         my ($state, $node, $level) = @_;
821         return unless $node;
822         my $child_adjust = 1;
823
824         if (my $x = $node->message) {
825                 $x = $x->header_obj;
826                 my ($topic, $subj);
827
828                 $subj = $x->header('Subject');
829                 $subj = $state->{srch}->subject_normalized($subj);
830                 $topic = $subj;
831
832                 # kill "[PATCH v2]" etc. for summarization
833                 unless ($level == 0) {
834                         $topic =~ s/\A\s*\[[^\]]+\]\s*//g;
835                 }
836
837                 if (++$state->{subjs}->{$topic} == 1) {
838                         push @{$state->{order}}, [ $level, $subj, $topic ];
839                 }
840
841                 my $mid = mid_clean($x->header('Message-ID'));
842
843                 my $ts = $x->header('X-PI-TS');
844                 my $exist = $state->{latest}->{$topic};
845                 if (!$exist || $exist->[1] < $ts) {
846                         $state->{latest}->{$topic} = [ $mid, $ts ];
847                 }
848         } else {
849                 # ghost message, do not bump level
850                 $child_adjust = 0;
851         }
852
853         add_topic($state, $node->child, $level + $child_adjust);
854         add_topic($state, $node->next, $level);
855 }
856
857 sub dump_topics {
858         my ($state) = @_;
859         my $order = $state->{order};
860         my $subjs = $state->{subjs};
861         my $latest = $state->{latest};
862         return "\n[No topics in range]</pre>" unless (scalar @$order);
863         my $dst = '';
864         my $pfx;
865         my $prev = 0;
866         my $prev_attr = '';
867         while (defined(my $info = shift @$order)) {
868                 my ($level, $subj, $topic) = @$info;
869                 my $n = delete $subjs->{$topic};
870                 my ($mid, $ts) = @{delete $latest->{$topic}};
871                 $mid = PublicInbox::Hval->new($mid)->as_href;
872                 $subj = PublicInbox::Hval->new($subj)->as_html;
873                 $pfx = INDENT x ($level - 1);
874                 my $nl = $level == $prev ? "\n" : '';
875                 my $dot = $level == 0 ? '' : '` ';
876                 $dst .= "$nl$pfx$dot<a\nhref=\"$mid/t/#u\"><b>$subj</b></a>\n";
877
878                 my $attr;
879                 $ts = fmt_ts($ts);
880                 if ($n == 1) {
881                         $attr = "@ $ts UTC";
882                         $n = "";
883                 } else {
884                         # $n isn't the total number of posts on the topic,
885                         # just the number of posts in the current results
886                         # window, so leave it unlabeled
887                         $attr = "@ $ts UTC";
888                         $n = " ($n)";
889                 }
890                 if ($level == 0 || $attr ne $prev_attr) {
891                         my $mbox = qq(<a\n$MBOX_TITLE\n) .
892                                    qq(href="$mid/t.mbox.gz">mbox.gz</a>);
893                         my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
894                         $pfx .= INDENT if $level > 0;
895                         $dst .= $pfx . $attr . $n . " - $mbox / $atom\n";
896                         $prev_attr = $attr;
897                 }
898         }
899         $dst .= '</pre>';
900 }
901
902 sub emit_index_topics {
903         my ($state, $fh) = @_;
904         my $off = $state->{ctx}->{cgi}->param('o');
905         $off = 0 unless defined $off;
906         $state->{order} = [];
907         $state->{subjs} = {};
908         $state->{latest} = {};
909         my $max = 25;
910         my %opts = ( offset => int $off, limit => $max * 4 );
911         while (scalar @{$state->{order}} < $max) {
912                 my $res = $state->{srch}->query('', \%opts);
913                 my $nr = scalar @{$res->{msgs}} or last;
914
915                 for (rsort_ts(thread_results(load_results($res), 1)->rootset)) {
916                         add_topic($state, $_, 0);
917                 }
918                 $opts{offset} += $nr;
919         }
920
921         $fh->write(dump_topics($state));
922         $opts{offset};
923 }
924
925 1;