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