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