]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: avoid excessive indentation in thread summary
[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}) {
144                 $rv .= " [$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                 max_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->{max_level}) {
191                         my $x = $max > 1 ? ('</ul></li>' x ($max-1)) : '';
192                         $cb->write($x . '</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         if ($full_pfx) {
319                 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
320                         # show quote inline
321                         my %l;
322                         my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
323                         @$quot = ();
324                         $rv = ascii_html($rv);
325                         return linkify_2(\%l, $rv);
326                 }
327
328                 # show a short snippet of quoted text and link to full version:
329                 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
330                 my $cur = join(' ', @$quot);
331                 @$quot = split(/\s+/, $cur);
332                 $cur = '';
333                 do {
334                         my $tmp = shift(@$quot);
335                         my $len = length($tmp) + length($cur);
336                         if ($len > MAX_TRUNC_LEN) {
337                                 @$quot = ();
338                         } else {
339                                 $cur .= $tmp . ' ';
340                         }
341                 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
342                 @$quot = ();
343                 $cur =~ s/ \z/ .../s;
344                 $cur = ascii_html($cur);
345                 my $nr = ++$$n;
346                 "&gt; [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
347         } else {
348                 # show everything in the full version with anchor from
349                 # short version (see above)
350                 my %l;
351                 my $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
352                 @$quot = ();
353                 $rv = ascii_html($rv);
354                 return linkify_2(\%l, $rv) unless $do_anchor;
355                 my $nr = ++$$n;
356                 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
357         }
358 }
359
360 sub add_text_body {
361         my ($enc_msg, $part, $part_nr, $full_pfx, $do_anchor) = @_;
362         return '' if $part->subparts;
363
364         my $ct = $part->content_type;
365         # account for filter bugs...
366         if (defined $ct && $ct =~ m!\btext/x?html\b!i) {
367                 $part->body_set('');
368                 return '';
369         }
370         my $enc = enc_for($ct, $enc_msg);
371         my $n = 0;
372         my $nr = 0;
373         my $s = $part->body;
374         $part->body_set('');
375         $s = $enc->decode($s);
376         my @lines = split(/^/m, $s);
377         $s = '';
378
379         if ($$part_nr > 0) {
380                 my $fn = $part->filename;
381                 defined($fn) or $fn = "part #" . ($$part_nr + 1);
382                 $s .= add_filename_line($enc, $fn);
383         }
384
385         my @quot;
386         while (defined(my $cur = shift @lines)) {
387                 if ($cur !~ /^>/) {
388                         # show the previously buffered quote inline
389                         if (scalar @quot) {
390                                 $s .= flush_quote(\@quot, \$n, $$part_nr,
391                                                   $full_pfx, 0, $do_anchor);
392                         }
393
394                         # regular line, OK
395                         my %l;
396                         $cur = linkify_1(\%l, $cur);
397                         $cur = ascii_html($cur);
398                         $s .= linkify_2(\%l, $cur);
399                 } else {
400                         push @quot, $cur;
401                 }
402         }
403         if (scalar @quot) {
404                 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1,
405                                   $do_anchor);
406         }
407         $s .= "\n" unless $s =~ /\n\z/s;
408         ++$$part_nr;
409         $s;
410 }
411
412 sub headers_to_html_header {
413         my ($mime, $full_pfx, $ctx) = @_;
414         my $srch = $ctx->{srch} if $ctx;
415         my $rv = "";
416         my @title;
417         my $header_obj = $mime->header_obj;
418         my $mid = $header_obj->header('Message-ID');
419         $mid = PublicInbox::Hval->new_msgid($mid);
420         foreach my $h (qw(From To Cc Subject Date)) {
421                 my $v = $header_obj->header($h);
422                 defined($v) && ($v ne '') or next;
423                 $v = PublicInbox::Hval->new_oneline($v);
424
425                 if ($h eq 'From') {
426                         my @from = Email::Address->parse($v->raw);
427                         $title[1] = ascii_html($from[0]->name);
428                 } elsif ($h eq 'Subject') {
429                         $title[0] = $v->as_html;
430                         if ($srch) {
431                                 $rv .= "$h: <b\nid=t>";
432                                 $rv .= $v->as_html . "</b>\n";
433                                 next;
434                         }
435                 }
436                 $rv .= "$h: " . $v->as_html . "\n";
437
438         }
439         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
440         my $upfx = $full_pfx ? '' : '../';
441         $rv .= "(<a\nhref=\"${upfx}raw\">raw</a>)\n";
442         my $atom;
443         if ($srch) {
444                 thread_inline(\$rv, $ctx, $mime, $upfx);
445
446                 $atom = qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
447                         qq!href="${upfx}t.atom"\ntype="application/atom+xml"/>!;
448         } else {
449                 $rv .= _parent_headers_nosrch($header_obj);
450                 $atom = '';
451         }
452         $rv .= "\n";
453
454         ("<html><head><title>".  join(' - ', @title) . "</title>$atom".
455          PublicInbox::Hval::STYLE . "</head><body><pre>" . $rv);
456 }
457
458 sub thread_inline {
459         my ($dst, $ctx, $cur, $upfx) = @_;
460         my $srch = $ctx->{srch};
461         my $mid = mid_clean($cur->header('Message-ID'));
462         my $res = $srch->get_thread($mid);
463         my $nr = $res->{total};
464         my $expand = "<a\nhref=\"${upfx}t/#u\">expand</a> " .
465                         "/ <a\nhref=\"${upfx}t.mbox.gz\">mbox.gz</a>";
466
467         $$dst .= 'Thread: ';
468         my $parent = in_reply_to($cur);
469         if ($nr <= 1) {
470                 $$dst .= "[no followups, yet] ($expand)\n";
471                 $ctx->{next_msg} = undef;
472                 $ctx->{parent_msg} = $parent;
473                 return;
474         }
475
476         $$dst .= "~$nr messages (<a\nhref=\"#b\">skip</a> / " .
477                  $expand . ")\n";
478
479         my $subj = $srch->subject_path($cur->header('Subject'));
480         my $state = {
481                 seen => { $subj => 1 },
482                 srch => $srch,
483                 cur => $mid,
484                 parent_cmp => defined $parent ? $parent : '',
485                 parent => $parent,
486                 prev_attr => '',
487                 prev_level => 0,
488         };
489         for (thread_results(load_results($res))->rootset) {
490                 inline_dump($dst, $state, $upfx, $_, 0);
491         }
492         $$dst .= "<a\nid=b></a>"; # anchor for body start
493         $ctx->{next_msg} = $state->{next_msg};
494         $ctx->{parent_msg} = $state->{parent};
495 }
496
497 sub _parent_headers_nosrch {
498         my ($header_obj) = @_;
499         my $rv = '';
500
501         my $irt = in_reply_to($header_obj);
502         if (defined $irt) {
503                 my $v = PublicInbox::Hval->new_msgid($irt, 1);
504                 my $html = $v->as_html;
505                 my $href = $v->as_href;
506                 $rv .= "In-Reply-To: &lt;";
507                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
508         }
509
510         my $refs = $header_obj->header('References');
511         if ($refs) {
512                 # avoid redundant URLs wasting bandwidth
513                 my %seen;
514                 $seen{$irt} = 1 if defined $irt;
515                 my @refs;
516                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
517                 foreach my $ref (@raw_refs) {
518                         next if $seen{$ref};
519                         $seen{$ref} = 1;
520                         push @refs, linkify_ref_nosrch($ref);
521                 }
522
523                 if (@refs) {
524                         $rv .= 'References: '. join(' ', @refs) . "\n";
525                 }
526         }
527         $rv;
528 }
529
530 sub html_footer {
531         my ($mime, $standalone, $full_pfx, $ctx) = @_;
532         my %cc; # everyone else
533         my $to; # this is the From address
534
535         foreach my $h (qw(From To Cc)) {
536                 my $v = $mime->header($h);
537                 defined($v) && ($v ne '') or next;
538                 my @addrs = Email::Address->parse($v);
539                 foreach my $recip (@addrs) {
540                         my $address = $recip->address;
541                         my $dst = lc($address);
542                         $cc{$dst} ||= $address;
543                         $to ||= $dst;
544                 }
545         }
546         Email::Address->purge_cache if $standalone;
547
548         my $subj = $mime->header('Subject') || '';
549         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
550         my $mid = $mime->header('Message-ID');
551         my $irt = uri_escape_utf8($mid);
552         delete $cc{$to};
553         $to = uri_escape_utf8($to);
554         $subj = uri_escape_utf8($subj);
555
556         my $cc = uri_escape_utf8(join(',', sort values %cc));
557         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
558         $href =~ s/%20/+/g;
559
560         my $srch = $ctx->{srch} if $ctx;
561         my $upfx = $full_pfx ? '../' : '../../';
562         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
563
564         if ($srch && $standalone) {
565                 $idx .= qq{ / follow: <a\nhref="t.atom">Atom feed</a>\n};
566         }
567         if ($idx && $srch) {
568                 my $p = $ctx->{parent_msg};
569                 my $next = $ctx->{next_msg};
570                 if ($p) {
571                         $p = PublicInbox::Hval->new_oneline($p);
572                         $p = $p->as_href;
573                         $irt = "<a\nhref=\"$upfx$p/\">parent</a> ";
574                 } else {
575                         $irt = ' ' x length('parent ');
576                 }
577                 if ($next) {
578                         $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
579                 } else {
580                         $irt .= ' ' x length('next ');
581                 }
582                 if ($p || $next) {
583                         $irt .= "<a\nhref=\"#r\">thread</a> ";
584                 } else {
585                         $irt .= ' ' x length('thread ');
586                 }
587         } else {
588                 $irt = '';
589         }
590
591         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
592 }
593
594 sub linkify_ref_nosrch {
595         my $v = PublicInbox::Hval->new_msgid($_[0], 1);
596         my $html = $v->as_html;
597         my $href = $v->as_href;
598         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
599 }
600
601 sub anchor_for {
602         my ($msgid) = @_;
603         my $id = $msgid;
604         if ($id !~ /\A[a-f0-9]{40}\z/) {
605                 $id = id_compress(mid_clean($id), 1);
606         }
607         'm' . $id;
608 }
609
610 sub thread_html_head {
611         my ($cb, $header, $state) = @_;
612         $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
613
614         my $s = PublicInbox::Hval->new_oneline($header->header('Subject'));
615         $s = $s->as_html;
616         $$cb->write("<html><head><title>$s</title>".
617                 qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
618                 qq!href="../t.atom"\ntype="application/atom+xml"/>! .
619                 PublicInbox::Hval::STYLE .
620                 "</head><body>");
621 }
622
623 sub pre_anchor_entry {
624         my ($seen, $mime) = @_;
625         my $id = anchor_for($mime->header('Message-ID'));
626         $seen->{$id} = "#$id"; # save the anchor for children, later
627 }
628
629 sub ghost_parent {
630         my ($upfx, $mid) = @_;
631         # 'subject dummy' is used internally by Mail::Thread
632         return '[no common parent]' if ($mid eq 'subject dummy');
633
634         $mid = PublicInbox::Hval->new_msgid($mid);
635         my $href = $mid->as_href;
636         my $html = $mid->as_html;
637         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
638 }
639
640 sub __thread_adj_level {
641         my ($cb, $state, $level) = @_;
642
643         return if $level <= 0; # flat output
644         my $max = $state->{max_level};
645         if ($level > $max) {
646                 $state->{max_level} = $level;
647                 $$cb->write(($max ? '<li>' : ''). '<ul><li>');
648         } else {
649                 $$cb->write('<li>');
650         }
651 }
652
653 sub __ghost_flush {
654         my ($cb, $state, $upfx, $mid, $level) = @_;
655
656         __thread_adj_level($cb, $state, $level);
657         $$cb->write('<pre>'. ghost_parent($upfx, $mid) .  '</pre>' .
658                         ($level > 0 ? '</li>' : ''));
659 }
660
661 sub __thread_entry {
662         my ($cb, $git, $state, $mime, $level) = @_;
663
664         # lazy load the full message from mini_mime:
665         $mime = eval {
666                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
667                 Email::MIME->new($git->cat_file('HEAD:'.$path));
668         } or return;
669
670         if ($state->{anchor_idx} == 0) {
671                 thread_html_head($cb, $mime, $state, $level);
672         }
673
674         if (my $ghost = delete $state->{ghost}) {
675                 # n.b. ghost messages may only be parents, not children
676                 foreach my $g (@$ghost) {
677                         __ghost_flush($cb, $state, '../../', @$g);
678                 }
679         }
680         __thread_adj_level($cb, $state, $level);
681         index_entry($$cb, $mime, $level, $state);
682         $$cb->write('</li>') if $level > 0;
683
684         1;
685 }
686
687 sub indent_for {
688         my ($level) = @_;
689         INDENT x ($level - 1);
690 }
691
692 sub __ghost_prepare {
693         my ($state, $node, $level) = @_;
694         my $ghost = $state->{ghost} ||= [];
695         push @$ghost, [ $node->messageid, $level ];
696 }
697
698 sub thread_entry {
699         my ($cb, $git, $state, $node, $level) = @_;
700         return unless $node;
701         if (my $mime = $node->message) {
702                 unless (__thread_entry($cb, $git, $state, $mime, $level)) {
703                         __ghost_prepare($state, $node, $level);
704                 }
705         } else {
706                 __ghost_prepare($state, $node, $level);
707         }
708
709         thread_entry($cb, $git, $state, $node->child, $level + 1);
710         thread_entry($cb, $git, $state, $node->next, $level);
711 }
712
713 sub load_results {
714         my ($res) = @_;
715
716         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
717 }
718
719 sub msg_timestamp {
720         my ($mime) = @_;
721         my $ts = eval { str2time($mime->header('Date')) };
722         defined($ts) ? $ts : 0;
723 }
724
725 sub thread_results {
726         my ($msgs, $nosubject) = @_;
727         require PublicInbox::Thread;
728         my $th = PublicInbox::Thread->new(@$msgs);
729         no warnings 'once';
730         $Mail::Thread::nosubject = $nosubject;
731         $th->thread;
732         $th->order(*sort_ts);
733         $th
734 }
735
736 sub missing_thread {
737         my ($cb, $ctx) = @_;
738         require PublicInbox::ExtMsg;
739
740         $cb->(PublicInbox::ExtMsg::ext_msg($ctx))
741 }
742
743 sub _msg_date {
744         my ($mime) = @_;
745         my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
746         fmt_ts($ts);
747 }
748
749 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
750
751 sub _inline_header {
752         my ($dst, $state, $upfx, $mime, $level) = @_;
753         my $dot = $level == 0 ? '' : '` ';
754
755         my $cur = $state->{cur};
756         my $mid = mid_clean($mime->header('Message-ID'));
757         my $f = $mime->header('X-PI-From');
758         my $d = _msg_date($mime);
759         $f = PublicInbox::Hval->new($f)->as_html;
760         $d = PublicInbox::Hval->new($d)->as_html;
761         my $pfx = ' ' . $d . ' ' . indent_for($level);
762         my $attr = $f;
763         $state->{first_level} ||= $level;
764
765         if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
766                 $state->{prev_attr} = $attr;
767         } else {
768                 $attr = '';
769         }
770         $state->{prev_level} = $level;
771
772         if ($cur) {
773                 if ($cur eq $mid) {
774                         delete $state->{cur};
775                         $$dst .= "$pfx$dot<b><a\nid=r\nhref=\"#b\">".
776                                  "$attr [this message]</a></b>\n";
777
778                         return;
779                 }
780         } else {
781                 $state->{next_msg} ||= $mid;
782         }
783
784         # Subject is never undef, this mail was loaded from
785         # our Xapian which would've resulted in '' if it were
786         # really missing (and Filter rejects empty subjects)
787         my $s = $mime->header('Subject');
788         my $h = $state->{srch}->subject_path($s);
789         if ($state->{seen}->{$h}) {
790                 $s = undef;
791         } else {
792                 $state->{seen}->{$h} = 1;
793                 $s = PublicInbox::Hval->new($s);
794                 $s = $s->as_html;
795         }
796         my $m = PublicInbox::Hval->new_msgid($mid);
797         $m = $upfx . '../' . $m->as_href . '/';
798         if (defined $s) {
799                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$s</a> $attr\n";
800         } else {
801                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$f</a>\n";
802         }
803 }
804
805 sub inline_dump {
806         my ($dst, $state, $upfx, $node, $level) = @_;
807         return unless $node;
808         if (my $mime = $node->message) {
809                 my $mid = mid_clean($mime->header('Message-ID'));
810                 if ($mid eq $state->{parent_cmp}) {
811                         $state->{parent} = $mid;
812                 }
813                 _inline_header($dst, $state, $upfx, $mime, $level);
814         } else {
815                 my $dot = $level == 0 ? '' : '` ';
816                 my $pfx = (' ' x length(' 1970-01-01 13:37 ')).
817                         indent_for($level) . $dot;
818                 $$dst .= $pfx;
819                 $$dst .= ghost_parent("$upfx../", $node->messageid) . "\n";
820         }
821         inline_dump($dst, $state, $upfx, $node->child, $level+1);
822         inline_dump($dst, $state, $upfx, $node->next, $level);
823 }
824
825 sub sort_ts {
826         sort {
827                 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
828                 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
829         } @_;
830 }
831
832 sub rsort_ts {
833         sort {
834                 (eval { $b->topmost->message->header('X-PI-TS') } || 0) <=>
835                 (eval { $a->topmost->message->header('X-PI-TS') } || 0)
836         } @_;
837 }
838
839 # accumulate recent topics if search is supported
840 # returns 1 if done, undef if not
841 sub add_topic {
842         my ($state, $node, $level) = @_;
843         return unless $node;
844         my $child_adjust = 1;
845
846         if (my $x = $node->message) {
847                 $x = $x->header_obj;
848                 my ($topic, $subj);
849
850                 $subj = $x->header('Subject');
851                 $subj = $state->{srch}->subject_normalized($subj);
852                 $topic = $subj;
853
854                 # kill "[PATCH v2]" etc. for summarization
855                 unless ($level == 0) {
856                         $topic =~ s/\A\s*\[[^\]]+\]\s*//g;
857                 }
858
859                 if (++$state->{subjs}->{$topic} == 1) {
860                         push @{$state->{order}}, [ $level, $subj, $topic ];
861                 }
862
863                 my $mid = mid_clean($x->header('Message-ID'));
864
865                 my $ts = $x->header('X-PI-TS');
866                 my $exist = $state->{latest}->{$topic};
867                 if (!$exist || $exist->[1] < $ts) {
868                         $state->{latest}->{$topic} = [ $mid, $ts ];
869                 }
870         } else {
871                 # ghost message, do not bump level
872                 $child_adjust = 0;
873         }
874
875         add_topic($state, $node->child, $level + $child_adjust);
876         add_topic($state, $node->next, $level);
877 }
878
879 sub dump_topics {
880         my ($state) = @_;
881         my $order = $state->{order};
882         my $subjs = $state->{subjs};
883         my $latest = $state->{latest};
884         return "\n[No topics in range]</pre>" unless (scalar @$order);
885         my $dst = '';
886         my $pfx;
887         my $prev = 0;
888         my $prev_attr = '';
889         while (defined(my $info = shift @$order)) {
890                 my ($level, $subj, $topic) = @$info;
891                 my $n = delete $subjs->{$topic};
892                 my ($mid, $ts) = @{delete $latest->{$topic}};
893                 $mid = PublicInbox::Hval->new($mid)->as_href;
894                 $subj = PublicInbox::Hval->new($subj)->as_html;
895                 $pfx = indent_for($level);
896                 my $nl = $level == $prev ? "\n" : '';
897                 my $dot = $level == 0 ? '' : '` ';
898                 $dst .= "$nl$pfx$dot<a\nhref=\"$mid/t/#u\"><b>$subj</b></a>\n";
899
900                 my $attr;
901                 $ts = fmt_ts($ts);
902                 $attr = " $ts UTC";
903
904                 # $n isn't the total number of posts on the topic,
905                 # just the number of posts in the current results
906                 # window, so leave it unlabeled
907                 $n = $n == 1 ? '' : " ($n+ messages)";
908
909                 if ($level == 0 || $attr ne $prev_attr) {
910                         my $mbox = qq(<a\nhref="$mid/t.mbox.gz">mbox.gz</a>);
911                         my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
912                         $pfx .= INDENT if $level > 0;
913                         $dst .= $pfx . $attr . $n . " - $mbox / $atom\n";
914                         $prev_attr = $attr;
915                 }
916         }
917         $dst .= '</pre>';
918 }
919
920 sub emit_index_topics {
921         my ($state, $fh) = @_;
922         my $off = $state->{ctx}->{cgi}->param('o');
923         $off = 0 unless defined $off;
924         $state->{order} = [];
925         $state->{subjs} = {};
926         $state->{latest} = {};
927         my $max = 25;
928         my %opts = ( offset => int $off, limit => $max * 4 );
929         while (scalar @{$state->{order}} < $max) {
930                 my $res = $state->{srch}->query('', \%opts);
931                 my $nr = scalar @{$res->{msgs}} or last;
932
933                 for (rsort_ts(thread_results(load_results($res), 1)->rootset)) {
934                         add_topic($state, $_, 0);
935                 }
936                 $opts{offset} += $nr;
937         }
938
939         $fh->write(dump_topics($state));
940         $opts{offset};
941 }
942
943 1;