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