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