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