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