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