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