]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: do not hide patches or signatures
[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         # kill any leading or trailing whitespace lines
258         $s =~ s/^\s*$//sgm;
259         $s =~ s/\s+\z//s;
260
261         if ($s ne '') {
262                 # kill per-line trailing whitespace
263                 $s =~ s/[ \t]+$//sgm;
264                 $s .= "\n" unless $s =~ /\n\z/s;
265         }
266         $fh->write($s);
267 }
268
269 sub enc_for {
270         my ($ct, $default) = @_;
271         $default ||= $enc_utf8;
272         defined $ct or return $default;
273         my $ct_parsed = parse_content_type($ct);
274         if ($ct_parsed) {
275                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
276                         my $enc = find_encoding($charset);
277                         return $enc if $enc;
278                 }
279         }
280         $default;
281 }
282
283 sub multipart_text_as_html {
284         my ($mime, $full_pfx, $srch) = @_;
285         my $rv = "";
286         my $part_nr = 0;
287         my $enc = enc_for($mime->header("Content-Type"));
288
289         # scan through all parts, looking for displayable text
290         $mime->walk_parts(sub {
291                 my ($part) = @_;
292                 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx, 1);
293         });
294         $mime->body_set('');
295         $rv;
296 }
297
298 sub add_filename_line {
299         my ($enc, $fn) = @_;
300         my $len = 72;
301         my $pad = "-";
302         $fn = $enc->decode($fn);
303         $len -= length($fn);
304         $pad x= ($len/2) if ($len > 0);
305         "$pad " . ascii_html($fn) . " $pad\n";
306 }
307
308 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
309                  [\@:\w\.-]+/
310                  ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
311
312 sub linkify_1 {
313         my ($link_map, $s) = @_;
314         $s =~ s!$LINK_RE!
315                 my $url = $1;
316                 # salt this, as this could be exploited to show
317                 # links in the HTML which don't show up in the raw mail.
318                 my $key = sha1_hex($url . $SALT);
319                 $link_map->{$key} = $url;
320                 'PI-LINK-'. $key;
321         !ge;
322         $s;
323 }
324
325 sub linkify_2 {
326         my ($link_map, $s) = @_;
327
328         # Added "PI-LINK-" prefix to avoid false-positives on git commits
329         $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
330                 my $key = $1;
331                 my $url = $link_map->{$key};
332                 if (defined $url) {
333                         $url = ascii_html($url);
334                         "<a\nhref=\"$url\">$url</a>";
335                 } else {
336                         # false positive or somebody tried to mess with us
337                         $key;
338                 }
339         !ge;
340         $s;
341 }
342
343 sub flush_quote {
344         my ($quot, $n, $part_nr, $full_pfx, $final, $do_anchor) = @_;
345
346         # n.b.: do not use <blockquote> since it screws up alignment
347         # w.r.t. unquoted text.  Repliers may rely on pre-formatted
348         # alignment to point out a certain word in quoted text.
349         if ($full_pfx) {
350                 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
351                         # show quote inline
352                         my %l;
353                         my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
354                         @$quot = ();
355                         $rv = ascii_html($rv);
356                         return linkify_2(\%l, $rv);
357                 }
358
359                 # show a short snippet of quoted text and link to full version:
360                 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
361                 my $cur = join(' ', @$quot);
362                 @$quot = split(/\s+/, $cur);
363                 $cur = '';
364                 do {
365                         my $tmp = shift(@$quot);
366                         my $len = length($tmp) + length($cur);
367                         if ($len > MAX_TRUNC_LEN) {
368                                 @$quot = ();
369                         } else {
370                                 $cur .= $tmp . ' ';
371                         }
372                 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
373                 @$quot = ();
374                 $cur =~ s/ \z/ .../s;
375                 $cur = ascii_html($cur);
376                 my $nr = ++$$n;
377                 "&gt; [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
378         } else {
379                 # show everything in the full version with anchor from
380                 # short version (see above)
381                 my %l;
382                 my $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
383                 @$quot = ();
384                 $rv = ascii_html($rv);
385                 return linkify_2(\%l, $rv) unless $do_anchor;
386                 my $nr = ++$$n;
387                 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
388         }
389 }
390
391 sub add_text_body {
392         my ($enc_msg, $part, $part_nr, $full_pfx, $do_anchor) = @_;
393         return '' if $part->subparts;
394
395         my $ct = $part->content_type;
396         # account for filter bugs...
397         if (defined $ct && $ct =~ m!\btext/x?html\b!i) {
398                 $part->body_set('');
399                 return '';
400         }
401         my $enc = enc_for($ct, $enc_msg);
402         my $n = 0;
403         my $nr = 0;
404         my $s = $part->body;
405         $part->body_set('');
406         $s = $enc->decode($s);
407         my @lines = split(/^/m, $s);
408         $s = '';
409
410         if ($$part_nr > 0) {
411                 my $fn = $part->filename;
412                 defined($fn) or $fn = "part #" . ($$part_nr + 1);
413                 $s .= add_filename_line($enc, $fn);
414         }
415
416         my @quot;
417         while (defined(my $cur = shift @lines)) {
418                 if ($cur !~ /^>/) {
419                         # show the previously buffered quote inline
420                         if (scalar @quot) {
421                                 $s .= flush_quote(\@quot, \$n, $$part_nr,
422                                                   $full_pfx, 0, $do_anchor);
423                         }
424
425                         # regular line, OK
426                         my %l;
427                         $cur = linkify_1(\%l, $cur);
428                         $cur = ascii_html($cur);
429                         $s .= linkify_2(\%l, $cur);
430                 } else {
431                         push @quot, $cur;
432                 }
433         }
434         if (scalar @quot) {
435                 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1,
436                                   $do_anchor);
437         }
438         $s .= "\n" unless $s =~ /\n\z/s;
439         ++$$part_nr;
440         $s;
441 }
442
443 sub headers_to_html_header {
444         my ($hdr, $full_pfx, $ctx) = @_;
445         my $srch = $ctx->{srch} if $ctx;
446         my $rv = "";
447         my @title;
448         my $mid = $hdr->header('Message-ID');
449         $mid = PublicInbox::Hval->new_msgid($mid);
450         foreach my $h (qw(From To Cc Subject Date)) {
451                 my $v = $hdr->header($h);
452                 defined($v) && ($v ne '') or next;
453                 $v = PublicInbox::Hval->new_oneline($v);
454
455                 if ($h eq 'From') {
456                         my @from = Email::Address->parse($v->raw);
457                         $title[1] = ascii_html($from[0]->name);
458                 } elsif ($h eq 'Subject') {
459                         $title[0] = $v->as_html;
460                         if ($srch) {
461                                 $rv .= "$h: <b\nid=t>";
462                                 $rv .= $v->as_html . "</b>\n";
463                                 next;
464                         }
465                 }
466                 $rv .= "$h: " . $v->as_html . "\n";
467
468         }
469         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
470         my $upfx = $full_pfx ? '' : '../';
471         $rv .= "(<a\nhref=\"${upfx}raw\">raw</a>)\n";
472         my $atom;
473         if ($srch) {
474                 thread_inline(\$rv, $ctx, $hdr, $upfx);
475
476                 $atom = qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
477                         qq!href="${upfx}t.atom"\ntype="application/atom+xml"/>!;
478         } else {
479                 $rv .= _parent_headers_nosrch($hdr);
480                 $atom = '';
481         }
482         $rv .= "\n";
483
484         ("<html><head><title>".  join(' - ', @title) . "</title>$atom".
485          PublicInbox::Hval::STYLE . "</head><body><pre>" . $rv);
486 }
487
488 sub thread_inline {
489         my ($dst, $ctx, $hdr, $upfx) = @_;
490         my $srch = $ctx->{srch};
491         my $mid = mid_clean($hdr->header('Message-ID'));
492         my $res = $srch->get_thread($mid);
493         my $nr = $res->{total};
494         my $expand = "<a\nhref=\"${upfx}t/#u\">expand</a> " .
495                         "/ <a\nhref=\"${upfx}t.mbox.gz\">mbox.gz</a>";
496
497         $$dst .= 'Thread: ';
498         my $parent = in_reply_to($hdr);
499         if ($nr <= 1) {
500                 if (defined $parent) {
501                         $$dst .= "($expand)\n ";
502                         $$dst .= ghost_parent("$upfx../", $parent) . "\n";
503                 } else {
504                         $$dst .= "[no followups, yet] ($expand)\n";
505                 }
506                 $ctx->{next_msg} = undef;
507                 $ctx->{parent_msg} = $parent;
508                 return;
509         }
510
511         $$dst .= "~$nr messages ($expand";
512         if ($nr > MAX_INLINE_QUOTED) {
513                 $$dst .= qq! / <a\nhref="#b">[scroll down]</a>!;
514         }
515         $$dst .= ")\n";
516
517         my $subj = $srch->subject_path($hdr->header('Subject'));
518         my $state = {
519                 seen => { $subj => 1 },
520                 srch => $srch,
521                 cur => $mid,
522                 parent_cmp => defined $parent ? $parent : '',
523                 parent => $parent,
524                 prev_attr => '',
525                 prev_level => 0,
526         };
527         for (thread_results(load_results($res))->rootset) {
528                 inline_dump($dst, $state, $upfx, $_, 0);
529         }
530         $$dst .= "<a\nid=b></a>"; # anchor for body start
531         $ctx->{next_msg} = $state->{next_msg};
532         $ctx->{parent_msg} = $state->{parent};
533 }
534
535 sub _parent_headers_nosrch {
536         my ($hdr) = @_;
537         my $rv = '';
538
539         my $irt = in_reply_to($hdr);
540         if (defined $irt) {
541                 my $v = PublicInbox::Hval->new_msgid($irt, 1);
542                 my $html = $v->as_html;
543                 my $href = $v->as_href;
544                 $rv .= "In-Reply-To: &lt;";
545                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
546         }
547
548         my $refs = $hdr->header('References');
549         if ($refs) {
550                 # avoid redundant URLs wasting bandwidth
551                 my %seen;
552                 $seen{$irt} = 1 if defined $irt;
553                 my @refs;
554                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
555                 foreach my $ref (@raw_refs) {
556                         next if $seen{$ref};
557                         $seen{$ref} = 1;
558                         push @refs, linkify_ref_nosrch($ref);
559                 }
560
561                 if (@refs) {
562                         $rv .= 'References: '. join(' ', @refs) . "\n";
563                 }
564         }
565         $rv;
566 }
567
568 sub mailto_arg_link {
569         my ($hdr) = @_;
570         my %cc; # everyone else
571         my $to; # this is the From address
572
573         foreach my $h (qw(From To Cc)) {
574                 my $v = $hdr->header($h);
575                 defined($v) && ($v ne '') or next;
576                 my @addrs = Email::Address->parse($v);
577                 foreach my $recip (@addrs) {
578                         my $address = $recip->address;
579                         my $dst = lc($address);
580                         $cc{$dst} ||= $address;
581                         $to ||= $dst;
582                 }
583         }
584         Email::Address->purge_cache;
585         my @arg;
586
587         my $subj = $hdr->header('Subject') || '';
588         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
589         my $mid = $hdr->header('Message-ID');
590         push @arg, "--in-reply-to='" . ascii_html($mid) . "'";
591         my $irt = uri_escape_utf8($mid);
592         delete $cc{$to};
593         push @arg, '--to=' . ascii_html($to);
594         $to = uri_escape_utf8($to);
595         $subj = uri_escape_utf8($subj);
596         my $cc = join(',', sort values %cc);
597         push @arg, '--cc=' . ascii_html($cc);
598         $cc = uri_escape_utf8($cc);
599         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
600         $href =~ s/%20/+/g;
601
602         (\@arg, $href);
603 }
604
605 sub html_footer {
606         my ($mime, $standalone, $full_pfx, $ctx, $mhref) = @_;
607
608         my $srch = $ctx->{srch} if $ctx;
609         my $upfx = $full_pfx ? '../' : '../../';
610         my $tpfx = $full_pfx ? '' : '../';
611         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
612         my $irt = '';
613
614         if ($srch && $standalone) {
615                 $idx .= qq{ / follow: <a\nhref="${tpfx}t.atom">Atom feed</a>\n};
616         }
617         if ($idx && $srch) {
618                 my $p = $ctx->{parent_msg};
619                 my $next = $ctx->{next_msg};
620                 if ($p) {
621                         $p = PublicInbox::Hval->new_oneline($p);
622                         $p = $p->as_href;
623                         $irt = "<a\nhref=\"$upfx$p/\">parent</a> ";
624                 } else {
625                         $irt = ' ' x length('parent ');
626                 }
627                 if ($next) {
628                         $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
629                 } else {
630                         $irt .= ' ' x length('next ');
631                 }
632                 if ($p || $next) {
633                         $irt .= "<a\nhref=\"${tpfx}t/#u\">thread</a> ";
634                 } else {
635                         $irt .= ' ' x length('thread ');
636                 }
637         } else {
638                 $irt = '';
639         }
640
641         $mhref = './' unless defined $mhref;
642         $irt . qq(<a\nhref="${mhref}R/">reply</a>) . $idx;
643 }
644
645 sub linkify_ref_nosrch {
646         my $v = PublicInbox::Hval->new_msgid($_[0], 1);
647         my $html = $v->as_html;
648         my $href = $v->as_href;
649         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
650 }
651
652 sub anchor_for {
653         my ($msgid) = @_;
654         my $id = $msgid;
655         if ($id !~ /\A[a-f0-9]{40}\z/) {
656                 $id = id_compress(mid_clean($id), 1);
657         }
658         'm' . $id;
659 }
660
661 sub thread_html_head {
662         my ($cb, $header, $state) = @_;
663         $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
664
665         my $s = PublicInbox::Hval->new_oneline($header->header('Subject'));
666         $s = $s->as_html;
667         $$cb->write("<html><head><title>$s</title>".
668                 qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
669                 qq!href="../t.atom"\ntype="application/atom+xml"/>! .
670                 PublicInbox::Hval::STYLE .
671                 "</head><body>");
672 }
673
674 sub pre_anchor_entry {
675         my ($seen, $mime) = @_;
676         my $id = anchor_for($mime->header('Message-ID'));
677         $seen->{$id} = "#$id"; # save the anchor for children, later
678 }
679
680 sub ghost_parent {
681         my ($upfx, $mid) = @_;
682         # 'subject dummy' is used internally by Mail::Thread
683         return '[no common parent]' if ($mid eq 'subject dummy');
684
685         $mid = PublicInbox::Hval->new_msgid($mid);
686         my $href = $mid->as_href;
687         my $html = $mid->as_html;
688         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
689 }
690
691 sub thread_adj_level {
692         my ($fh, $state, $level) = @_;
693
694         my $max = $state->{cur_level};
695         if ($level <= 0) {
696                 return '' if $max == 0; # flat output
697
698                 # reset existing lists
699                 my $x = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
700                 $fh->write($x . '</ul>');
701                 $state->{cur_level} = 0;
702                 return '';
703         }
704         if ($level == $max) { # continue existing list
705                 $fh->write('<li>');
706         } elsif ($level < $max) {
707                 my $x = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
708                 $fh->write($x .= '<li>');
709                 $state->{cur_level} = $level;
710         } else { # ($level > $max) # start a new level
711                 $state->{cur_level} = $level;
712                 $fh->write(($max ? '<li>' : '') . '<ul><li>');
713         }
714         '</li>';
715 }
716
717 sub ghost_flush {
718         my ($fh, $state, $upfx, $mid, $level) = @_;
719
720         my $end = thread_adj_level($fh, $state, $level);
721         $fh->write('<pre>'. ghost_parent($upfx, $mid) .  '</pre>' . $end);
722 }
723
724 sub __thread_entry {
725         my ($cb, $git, $state, $mime, $level) = @_;
726
727         # lazy load the full message from mini_mime:
728         $mime = eval {
729                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
730                 Email::MIME->new($git->cat_file('HEAD:'.$path));
731         } or return;
732
733         if ($state->{anchor_idx} == 0) {
734                 thread_html_head($cb, $mime, $state, $level);
735         }
736         my $fh = $$cb;
737         if (my $ghost = delete $state->{ghost}) {
738                 # n.b. ghost messages may only be parents, not children
739                 foreach my $g (@$ghost) {
740                         ghost_flush($fh, $state, '../../', @$g);
741                 }
742         }
743         my $end = thread_adj_level($fh, $state, $level);
744         index_entry($fh, $mime, $level, $state);
745         $fh->write($end) if $end;
746
747         1;
748 }
749
750 sub indent_for {
751         my ($level) = @_;
752         INDENT x ($level - 1);
753 }
754
755 sub __ghost_prepare {
756         my ($state, $node, $level) = @_;
757         my $ghost = $state->{ghost} ||= [];
758         push @$ghost, [ $node->messageid, $level ];
759 }
760
761 sub thread_entry {
762         my ($cb, $git, $state, $node, $level) = @_;
763         return unless $node;
764         if (my $mime = $node->message) {
765                 unless (__thread_entry($cb, $git, $state, $mime, $level)) {
766                         __ghost_prepare($state, $node, $level);
767                 }
768         } else {
769                 __ghost_prepare($state, $node, $level);
770         }
771
772         thread_entry($cb, $git, $state, $node->child, $level + 1);
773         thread_entry($cb, $git, $state, $node->next, $level);
774 }
775
776 sub load_results {
777         my ($res) = @_;
778
779         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
780 }
781
782 sub msg_timestamp {
783         my ($hdr) = @_;
784         my $ts = eval { str2time($hdr->header('Date')) };
785         defined($ts) ? $ts : 0;
786 }
787
788 sub thread_results {
789         my ($msgs, $nosubject) = @_;
790         require PublicInbox::Thread;
791         my $th = PublicInbox::Thread->new(@$msgs);
792         no warnings 'once';
793         $Mail::Thread::nosubject = $nosubject;
794         $th->thread;
795         $th->order(*sort_ts);
796         $th
797 }
798
799 sub missing_thread {
800         my ($cb, $ctx) = @_;
801         require PublicInbox::ExtMsg;
802
803         $cb->(PublicInbox::ExtMsg::ext_msg($ctx))
804 }
805
806 sub _msg_date {
807         my ($hdr) = @_;
808         my $ts = $hdr->header('X-PI-TS') || msg_timestamp($hdr);
809         fmt_ts($ts);
810 }
811
812 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
813
814 sub _inline_header {
815         my ($dst, $state, $upfx, $hdr, $level) = @_;
816         my $dot = $level == 0 ? '' : '` ';
817
818         my $cur = $state->{cur};
819         my $mid = mid_clean($hdr->header('Message-ID'));
820         my $f = $hdr->header('X-PI-From');
821         my $d = _msg_date($hdr);
822         $f = PublicInbox::Hval->new_oneline($f)->as_html;
823         my $pfx = ' ' . $d . ' ' . indent_for($level);
824         my $attr = $f;
825         $state->{first_level} ||= $level;
826
827         if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
828                 $state->{prev_attr} = $attr;
829         } else {
830                 $attr = '';
831         }
832         $state->{prev_level} = $level;
833
834         if ($cur) {
835                 if ($cur eq $mid) {
836                         delete $state->{cur};
837                         $$dst .= "$pfx$dot<b><a\nid=r\nhref=\"#b\">".
838                                  "$attr [this message]</a></b>\n";
839
840                         return;
841                 }
842         } else {
843                 $state->{next_msg} ||= $mid;
844         }
845
846         # Subject is never undef, this mail was loaded from
847         # our Xapian which would've resulted in '' if it were
848         # really missing (and Filter rejects empty subjects)
849         my $s = $hdr->header('Subject');
850         my $h = $state->{srch}->subject_path($s);
851         if ($state->{seen}->{$h}) {
852                 $s = undef;
853         } else {
854                 $state->{seen}->{$h} = 1;
855                 $s = PublicInbox::Hval->new($s);
856                 $s = $s->as_html;
857         }
858         my $m = PublicInbox::Hval->new_msgid($mid);
859         $m = $upfx . '../' . $m->as_href . '/';
860         if (defined $s) {
861                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$s</a> $attr\n";
862         } else {
863                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$f</a>\n";
864         }
865 }
866
867 sub inline_dump {
868         my ($dst, $state, $upfx, $node, $level) = @_;
869         return unless $node;
870         if (my $mime = $node->message) {
871                 my $hdr = $mime->header_obj;
872                 my $mid = mid_clean($hdr->header('Message-ID'));
873                 if ($mid eq $state->{parent_cmp}) {
874                         $state->{parent} = $mid;
875                 }
876                 _inline_header($dst, $state, $upfx, $hdr, $level);
877         } else {
878                 my $dot = $level == 0 ? '' : '` ';
879                 my $pfx = (' ' x length(' 1970-01-01 13:37 ')).
880                         indent_for($level) . $dot;
881                 $$dst .= $pfx;
882                 $$dst .= ghost_parent("$upfx../", $node->messageid) . "\n";
883         }
884         inline_dump($dst, $state, $upfx, $node->child, $level+1);
885         inline_dump($dst, $state, $upfx, $node->next, $level);
886 }
887
888 sub sort_ts {
889         sort {
890                 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
891                 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
892         } @_;
893 }
894
895 sub rsort_ts {
896         sort {
897                 (eval { $b->topmost->message->header('X-PI-TS') } || 0) <=>
898                 (eval { $a->topmost->message->header('X-PI-TS') } || 0)
899         } @_;
900 }
901
902 # accumulate recent topics if search is supported
903 # returns 1 if done, undef if not
904 sub add_topic {
905         my ($state, $node, $level) = @_;
906         return unless $node;
907         my $child_adjust = 1;
908
909         if (my $x = $node->message) {
910                 $x = $x->header_obj;
911                 my $subj;
912
913                 $subj = $x->header('Subject');
914                 $subj = $state->{srch}->subject_normalized($subj);
915
916                 if (++$state->{subjs}->{$subj} == 1) {
917                         push @{$state->{order}}, [ $level, $subj ];
918                 }
919
920                 my $mid = mid_clean($x->header('Message-ID'));
921
922                 my $ts = $x->header('X-PI-TS');
923                 my $exist = $state->{latest}->{$subj};
924                 if (!$exist || $exist->[1] < $ts) {
925                         $state->{latest}->{$subj} = [ $mid, $ts ];
926                 }
927         } else {
928                 # ghost message, do not bump level
929                 $child_adjust = 0;
930         }
931
932         add_topic($state, $node->child, $level + $child_adjust);
933         add_topic($state, $node->next, $level);
934 }
935
936 sub dump_topics {
937         my ($state) = @_;
938         my $order = $state->{order};
939         my $subjs = $state->{subjs};
940         my $latest = $state->{latest};
941         return "\n[No topics in range]</pre>" unless (scalar @$order);
942         my $dst = '';
943         my $pfx;
944         my $prev = 0;
945         my $prev_attr = '';
946         while (defined(my $info = shift @$order)) {
947                 my ($level, $subj) = @$info;
948                 my $n = delete $subjs->{$subj};
949                 my ($mid, $ts) = @{delete $latest->{$subj}};
950                 $mid = PublicInbox::Hval->new_msgid($mid)->as_href;
951                 $subj = PublicInbox::Hval->new($subj)->as_html;
952                 $pfx = indent_for($level);
953                 my $nl = $level == $prev ? "\n" : '';
954                 my $dot = $level == 0 ? '' : '` ';
955                 $dst .= "$nl$pfx$dot<a\nhref=\"$mid/t/#u\"><b>$subj</b></a>\n";
956
957                 my $attr;
958                 $ts = fmt_ts($ts);
959                 $attr = " $ts UTC";
960
961                 # $n isn't the total number of posts on the topic,
962                 # just the number of posts in the current results
963                 # window, so leave it unlabeled
964                 $n = $n == 1 ? '' : " ($n+ messages)";
965
966                 if ($level == 0 || $attr ne $prev_attr) {
967                         my $mbox = qq(<a\nhref="$mid/t.mbox.gz">mbox.gz</a>);
968                         my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
969                         $pfx .= INDENT if $level > 0;
970                         $dst .= $pfx . $attr . $n . " - $mbox / $atom\n";
971                         $prev_attr = $attr;
972                 }
973         }
974         $dst .= '</pre>';
975 }
976
977 sub emit_index_topics {
978         my ($state, $fh) = @_;
979         my $off = $state->{ctx}->{cgi}->param('o');
980         $off = 0 unless defined $off;
981         $state->{order} = [];
982         $state->{subjs} = {};
983         $state->{latest} = {};
984         my $max = 25;
985         my %opts = ( offset => int $off, limit => $max * 4 );
986         while (scalar @{$state->{order}} < $max) {
987                 my $res = $state->{srch}->query('', \%opts);
988                 my $nr = scalar @{$res->{msgs}} or last;
989
990                 for (rsort_ts(thread_results(load_results($res), 1)->rootset)) {
991                         add_topic($state, $_, 0);
992                 }
993                 $opts{offset} += $nr;
994         }
995
996         $fh->write(dump_topics($state));
997         $opts{offset};
998 }
999
1000 1;