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