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