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