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