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