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