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