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