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