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