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