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