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