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