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