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