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