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