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