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