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