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