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