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