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