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