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