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