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