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