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