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