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