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