]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: s/threaded/nested/ in view
[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 $ibx = $ctx->{-inbox};
28         my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
29         my $tip = _msg_html_prepare($hdr, $ctx, $obfs_ibx);
30         PublicInbox::WwwStream->response($ctx, 200, sub {
31                 my ($nr, undef) = @_;
32                 if ($nr == 1) {
33                         $tip . multipart_text_as_html($mime, '', $obfs_ibx) .
34                                 '</pre><hr>'
35                 } elsif ($nr == 2) {
36                         # fake an EOF if generating the footer fails;
37                         # we want to at least show the message if something
38                         # here crashes:
39                         eval {
40                                 '<pre>' . html_footer($hdr, 1, $ctx) .
41                                 '</pre>' . msg_reply($ctx, $hdr)
42                         };
43                 } else {
44                         undef
45                 }
46         });
47 }
48
49 # /$INBOX/$MESSAGE_ID/#R
50 sub msg_reply {
51         my ($ctx, $hdr) = @_;
52         my $se_url =
53          'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
54         my $p_url =
55          'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
56
57         my $info = '';
58         my $ibx = $ctx->{-inbox};
59         if (my $url = $ibx->{infourl}) {
60                 $url = PublicInbox::Hval::prurl($ctx->{env}, $url);
61                 $info = qq(\n  List information: <a\nhref="$url">$url</a>\n);
62         }
63
64         my ($arg, $link) = PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
65
66         # mailto: link only works if address obfuscation is disabled
67         if ($link) {
68                 $link = <<EOF;
69
70 * If your mail client supports setting the <b>In-Reply-To</b> header
71   via mailto: links, try the <a
72 href="$link">mailto: link</a></pre>
73 EOF
74         }
75         push @$arg, '/path/to/YOUR_REPLY';
76         $arg = ascii_html(join(" \\\n    ", '', @$arg));
77         <<EOF
78 <hr><pre
79 id=R><b>Reply instructions:</b>
80
81 You may reply publically to <a
82 href=#t>this message</a> via plain-text email
83 using any one of the following methods:
84
85 * Save the following mbox file, import it into your mail client,
86   and reply-to-all from there: <a
87 href=raw>mbox</a>
88
89   Avoid top-posting and favor interleaved quoting:
90   <a
91 href="$p_url">$p_url</a>
92 $info
93 * Reply to all the recipients using the <b>--to</b>, <b>--cc</b>,
94   and <b>--in-reply-to</b> switches of git-send-email(1):
95
96   git send-email$arg
97
98   <a
99 href="$se_url">$se_url</a>
100 $link
101 EOF
102 }
103
104 sub in_reply_to {
105         my ($hdr) = @_;
106         my %mid = map { $_ => 1 } $hdr->header_raw('Message-ID');
107         my @refs = (($hdr->header_raw('References') || '') =~ /<([^>]+)>/g);
108         push(@refs, (($hdr->header_raw('In-Reply-To') || '') =~ /<([^>]+)>/g));
109         while (defined(my $irt = pop @refs)) {
110                 next if $mid{"<$irt>"};
111                 return $irt;
112         }
113         undef;
114 }
115
116 sub _hdr_names_html ($$) {
117         my ($hdr, $field) = @_;
118         my $val = $hdr->header($field) or return '';
119         ascii_html(join(', ', PublicInbox::Address::names($val)));
120 }
121
122 sub nr_to_s ($$$) {
123         my ($nr, $singular, $plural) = @_;
124         return "0 $plural" if $nr == 0;
125         $nr == 1 ? "$nr $singular" : "$nr $plural";
126 }
127
128 # this is already inside a <pre>
129 sub index_entry {
130         my ($mime, $ctx, $more) = @_;
131         my $srch = $ctx->{srch};
132         my $hdr = $mime->header_obj;
133         my $subj = $hdr->header('Subject');
134
135         my $mid_raw = mid_clean(mid_mime($mime));
136         my $id = id_compress($mid_raw, 1);
137         my $id_m = 'm'.$id;
138
139         my $root_anchor = $ctx->{root_anchor} || '';
140         my $irt;
141         my $obfs_ibx = $ctx->{-obfs_ibx};
142
143         my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
144         $subj = '<b>'.ascii_html($subj).'</b>';
145         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
146         $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
147         $rv .= $subj . "\n";
148         $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
149         my @tocc;
150         foreach my $f (qw(To Cc)) {
151                 my $dst = _hdr_names_html($hdr, $f);
152                 if ($dst ne '') {
153                         obfuscate_addrs($obfs_ibx, $dst) if $obfs_ibx;
154                         push @tocc, "$f: $dst";
155                 }
156         }
157         my $from = _hdr_names_html($hdr, 'From');
158         obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
159         $rv .= "From: $from @ "._msg_date($hdr)." UTC";
160         my $upfx = $ctx->{-upfx};
161         my $mhref = $upfx . mid_escape($mid_raw) . '/';
162         $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
163         $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
164         $rv .= '  '.join('; +', @tocc) . "\n" if @tocc;
165
166         my $mapping = $ctx->{mapping};
167         if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
168                 my $mirt = PublicInbox::Hval->new_msgid($irt);
169                 my $href = $upfx . $mirt->{href}. '/';
170                 my $html = $mirt->as_html;
171                 $rv .= qq(In-Reply-To: &lt;<a\nhref="$href">$html</a>&gt;\n)
172         }
173         $rv .= "\n";
174
175         # scan through all parts, looking for displayable text
176         msg_iter($mime, sub { $rv .= add_text_body($mhref, $obfs_ibx, $_[0]) });
177
178         # add the footer
179         $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
180                 "<a\nhref=\"$mhref\">permalink</a>" .
181                 " <a\nhref=\"${mhref}raw\">raw</a>" .
182                 " <a\nhref=\"${mhref}#R\">reply</a>";
183
184         my $hr;
185         if (my $pct = $ctx->{pct}) { # used by SearchView.pm
186                 $rv .= "\t[relevance $pct->{$mid_raw}%]";
187                 $hr = 1;
188         } elsif ($mapping) {
189                 my $nested = 'nested';
190                 my $flat = 'flat';
191                 my $end = '';
192                 if ($ctx->{flat}) {
193                         $hr = 1;
194                         $flat = "<b>$flat</b>";
195                 } else {
196                         $nested = "<b>$nested</b>";
197                 }
198                 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
199                 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
200                 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
201         } else {
202                 $hr = $ctx->{-hr};
203         }
204
205         $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
206         $rv;
207 }
208
209 sub pad_link ($$;$) {
210         my ($mid, $level, $s) = @_;
211         $s ||= '...';
212         my $id = id_compress($mid, 1);
213         (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
214 }
215
216 sub _th_index_lite {
217         my ($mid_raw, $irt, $id, $ctx) = @_;
218         my $rv = '';
219         my $mapping = $ctx->{mapping} or return $rv;
220         my $pad = '  ';
221         my $mid_map = $mapping->{$mid_raw};
222         defined $mid_map or
223                 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
224         my ($attr, $node, $idx, $level) = @$mid_map;
225         my $children = $node->{children};
226         my $nr_c = scalar @$children;
227         my $nr_s = 0;
228         my $siblings;
229         if (my $smsg = $node->{smsg}) {
230                 ($$irt) = (($smsg->{references} || '') =~ m/<([^>]+)>\z/);
231         }
232         my $irt_map = $mapping->{$$irt} if defined $$irt;
233         if (defined $irt_map) {
234                 $siblings = $irt_map->[1]->{children};
235                 $nr_s = scalar(@$siblings) - 1;
236                 $rv .= $pad . $irt_map->[0];
237                 if ($idx > 0) {
238                         my $prev = $siblings->[$idx - 1];
239                         my $pmid = $prev->{id};
240                         if ($idx > 2) {
241                                 my $s = ($idx - 1). ' preceding siblings ...';
242                                 $rv .= pad_link($pmid, $level, $s);
243                         } elsif ($idx == 2) {
244                                 my $ppmid = $siblings->[0]->{id};
245                                 $rv .= $pad . $mapping->{$ppmid}->[0];
246                         }
247                         $rv .= $pad . $mapping->{$pmid}->[0];
248                 }
249         }
250         my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
251         my $s_c = nr_to_s($nr_c, 'reply', 'replies');
252         $attr =~ s!\n\z!</b>\n!s;
253         $attr =~ s!<a\nhref.*</a> !!s; # no point in duplicating subject
254         $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
255         $rv .= "<b>@ $attr";
256         if ($nr_c) {
257                 my $cmid = $children->[0]->{id};
258                 $rv .= $pad . $mapping->{$cmid}->[0];
259                 if ($nr_c > 2) {
260                         my $s = ($nr_c - 1). ' more replies';
261                         $rv .= pad_link($cmid, $level + 1, $s);
262                 } elsif (my $cn = $children->[1]) {
263                         $rv .= $pad . $mapping->{$cn->{id}}->[0];
264                 }
265         }
266
267         my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
268         if ($next) {
269                 my $nmid = $next->{id};
270                 $rv .= $pad . $mapping->{$nmid}->[0];
271                 my $nnext = $nr_s - $idx;
272                 if ($nnext > 2) {
273                         my $s = ($nnext - 1).' subsequent siblings';
274                         $rv .= pad_link($nmid, $level, $s);
275                 } elsif (my $nn = $siblings->[$idx + 2]) {
276                         $rv .= $pad . $mapping->{$nn->{id}}->[0];
277                 }
278         }
279         $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
280 }
281
282 sub walk_thread {
283         my ($rootset, $ctx, $cb) = @_;
284         my @q = map { (0, $_, -1) } @$rootset;
285         while (@q) {
286                 my ($level, $node, $i) = splice(@q, 0, 3);
287                 defined $node or next;
288                 $cb->($ctx, $level, $node, $i);
289                 ++$level;
290                 $i = 0;
291                 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
292         }
293 }
294
295 sub pre_thread  {
296         my ($ctx, $level, $node, $idx) = @_;
297         $ctx->{mapping}->{$node->{id}} = [ '', $node, $idx, $level ];
298         skel_dump($ctx, $level, $node);
299 }
300
301 sub thread_index_entry {
302         my ($ctx, $level, $mime) = @_;
303         my ($beg, $end) = thread_adj_level($ctx, $level);
304         $beg . '<pre>' . index_entry($mime, $ctx, 0) . '</pre>' . $end;
305 }
306
307 sub stream_thread ($$) {
308         my ($rootset, $ctx) = @_;
309         my $inbox = $ctx->{-inbox};
310         my $mime;
311         my @q = map { (0, $_) } @$rootset;
312         my $level;
313         while (@q) {
314                 $level = shift @q;
315                 my $node = shift @q or next;
316                 my $cl = $level + 1;
317                 unshift @q, map { ($cl, $_) } @{$node->{children}};
318                 $mime = $inbox->msg_by_smsg($node->{smsg}) and last;
319         }
320         return missing_thread($ctx) unless $mime;
321
322         $ctx->{-obfs_ibx} = $inbox->{obfuscate} ? $inbox : undef;
323         $mime = PublicInbox::MIME->new($mime);
324         $ctx->{-title_html} = ascii_html($mime->header('Subject'));
325         $ctx->{-html_tip} = thread_index_entry($ctx, $level, $mime);
326         PublicInbox::WwwStream->response($ctx, 200, sub {
327                 return unless $ctx;
328                 while (@q) {
329                         $level = shift @q;
330                         my $node = shift @q or next;
331                         my $cl = $level + 1;
332                         unshift @q, map { ($cl, $_) } @{$node->{children}};
333                         my $mid = $node->{id};
334                         if ($mime = $inbox->msg_by_smsg($node->{smsg})) {
335                                 $mime = PublicInbox::MIME->new($mime);
336                                 return thread_index_entry($ctx, $level, $mime);
337                         } else {
338                                 return ghost_index_entry($ctx, $level, $node);
339                         }
340                 }
341                 my $ret = join('', thread_adj_level($ctx, 0));
342                 $ret .= ${$ctx->{dst}}; # skel
343                 $ctx = undef;
344                 $ret;
345         });
346 }
347
348 sub thread_html {
349         my ($ctx) = @_;
350         my $mid = $ctx->{mid};
351         my $srch = $ctx->{srch};
352         my $sres = $srch->get_thread($mid);
353         my $msgs = load_results($srch, $sres);
354         my $nr = $sres->{total};
355         return missing_thread($ctx) if $nr == 0;
356         my $skel = '<hr><pre>';
357         $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
358         $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
359         $skel .= "<b\nid=t>Thread overview:</b> ";
360         $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
361         $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
362         $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
363         $skel .= "-- links below jump to the message on this page --\n";
364         $ctx->{-upfx} = '../../';
365         $ctx->{cur_level} = 0;
366         $ctx->{dst} = \$skel;
367         $ctx->{prev_attr} = '';
368         $ctx->{prev_level} = 0;
369         $ctx->{root_anchor} = anchor_for($mid);
370         $ctx->{mapping} = {};
371         $ctx->{s_nr} = "$nr+ messages in thread";
372
373         my $rootset = thread_results($msgs, $srch);
374
375         # reduce hash lookups in pre_thread->skel_dump
376         my $inbox = $ctx->{-inbox};
377         $ctx->{-obfs_ibx} = $inbox->{obfuscate} ? $inbox : undef;
378         walk_thread($rootset, $ctx, *pre_thread);
379
380         $skel .= '</pre>';
381         return stream_thread($rootset, $ctx) unless $ctx->{flat};
382
383         # flat display: lazy load the full message from smsg
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_ibx) = @_;
409         my $rv = "";
410
411         # scan through all parts, looking for displayable text
412         msg_iter($mime, sub { $rv .= add_text_body($upfx, $obfs_ibx, $_[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_ibx, $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($obfs_ibx, $s) if $obfs_ibx;
518                 $s;
519         } else {
520                 obfuscate_addrs($obfs_ibx, $s) if $obfs_ibx;
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_ibx) = @_;
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($obfs_ibx, $title[1]) if $obfs_ibx;
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($obfs_ibx, $v) if $obfs_ibx;
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 = $hdr->header('Subject');
599         defined $subj or $subj = '';
600         $ctx->{prev_subj} = [ split(/ /, $srch->subject_normalized($subj)) ];
601         $ctx->{cur} = $mid;
602         $ctx->{prev_attr} = '';
603         $ctx->{prev_level} = 0;
604         $ctx->{dst} = $dst;
605         $sres = load_results($srch, $sres);
606
607         # reduce hash lookups in skel_dump
608         my $ibx = $ctx->{-inbox};
609         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
610         walk_thread(thread_results($sres, $srch), $ctx, *skel_dump);
611
612         $ctx->{parent_msg} = $parent;
613 }
614
615 sub _parent_headers {
616         my ($hdr, $srch) = @_;
617         my $rv = '';
618
619         my $irt = in_reply_to($hdr);
620         if (defined $irt) {
621                 my $v = PublicInbox::Hval->new_msgid($irt);
622                 my $html = $v->as_html;
623                 my $href = $v->{href};
624                 $rv .= "In-Reply-To: &lt;";
625                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
626         }
627
628         # do not display References: if search is present,
629         # we show the thread skeleton at the bottom, instead.
630         return $rv if $srch;
631
632         my $refs = $hdr->header_raw('References');
633         if ($refs) {
634                 # avoid redundant URLs wasting bandwidth
635                 my %seen;
636                 $seen{$irt} = 1 if defined $irt;
637                 my @refs;
638                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
639                 foreach my $ref (@raw_refs) {
640                         next if $seen{$ref};
641                         $seen{$ref} = 1;
642                         push @refs, linkify_ref_nosrch($ref);
643                 }
644
645                 if (@refs) {
646                         $rv .= 'References: '. join("\n\t", @refs) . "\n";
647                 }
648         }
649         $rv;
650 }
651
652 sub html_footer {
653         my ($hdr, $standalone, $ctx, $rhref) = @_;
654
655         my $srch = $ctx->{srch} if $ctx;
656         my $upfx = '../';
657         my $tpfx = '';
658         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
659         my $irt = '';
660         if ($idx && $srch) {
661                 $idx .= "\n";
662                 thread_skel(\$idx, $ctx, $hdr, $tpfx);
663                 my ($next, $prev);
664                 my $parent = '       ';
665                 $next = $prev = '    ';
666
667                 if (my $n = $ctx->{next_msg}) {
668                         $n = PublicInbox::Hval->new_msgid($n)->{href};
669                         $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
670                 }
671                 my $u;
672                 my $par = $ctx->{parent_msg};
673                 if ($par) {
674                         $u = PublicInbox::Hval->new_msgid($par)->{href};
675                         $u = "$upfx$u/";
676                 }
677                 if (my $p = $ctx->{prev_msg}) {
678                         $prev = PublicInbox::Hval->new_msgid($p)->{href};
679                         if ($p && $par && $p eq $par) {
680                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
681                                         'rel=prev>prev parent</a>';
682                                 $parent = '';
683                         } else {
684                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
685                                         'rel=prev>prev</a>';
686                                 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
687                         }
688                 } elsif ($u) { # unlikely
689                         $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
690                 }
691                 $irt = "$next $prev$parent ";
692         } else {
693                 $irt = '';
694         }
695         $rhref ||= '#R';
696         $irt .= qq(<a\nhref="$rhref">reply</a>);
697         $irt .= $idx;
698 }
699
700 sub linkify_ref_nosrch {
701         my $v = PublicInbox::Hval->new_msgid($_[0]);
702         my $html = $v->as_html;
703         my $href = $v->{href};
704         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
705 }
706
707 sub anchor_for {
708         my ($msgid) = @_;
709         'm' . id_compress($msgid, 1);
710 }
711
712 sub ghost_parent {
713         my ($upfx, $mid) = @_;
714
715         $mid = PublicInbox::Hval->new_msgid($mid);
716         my $href = $mid->{href};
717         my $html = $mid->as_html;
718         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
719 }
720
721 sub indent_for {
722         my ($level) = @_;
723         INDENT x ($level - 1);
724 }
725
726 sub load_results {
727         my ($srch, $sres) = @_;
728         my $msgs = delete $sres->{msgs};
729         $srch->retry_reopen(sub { [ map { $_->mid; $_ } @$msgs ] });
730 }
731
732 sub msg_timestamp {
733         my ($hdr) = @_;
734         my $ts = eval { str2time($hdr->header('Date')) };
735         defined($ts) ? $ts : 0;
736 }
737
738 sub thread_results {
739         my ($msgs, $srch) = @_;
740         require PublicInbox::SearchThread;
741         PublicInbox::SearchThread::thread($msgs, *sort_ts, $srch);
742 }
743
744 sub missing_thread {
745         my ($ctx) = @_;
746         require PublicInbox::ExtMsg;
747         PublicInbox::ExtMsg::ext_msg($ctx);
748 }
749
750 sub _msg_date {
751         my ($hdr) = @_;
752         my $ts = $hdr->header('X-PI-TS') || msg_timestamp($hdr);
753         fmt_ts($ts);
754 }
755
756 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
757
758 sub skel_dump {
759         my ($ctx, $level, $node) = @_;
760         my $smsg = $node->{smsg} or return _skel_ghost($ctx, $level, $node);
761
762         my $dst = $ctx->{dst};
763         my $cur = $ctx->{cur};
764         my $mid = $smsg->{mid};
765
766         my $f = ascii_html($smsg->from_name);
767         my $obfs_ibx = $ctx->{-obfs_ibx};
768         obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
769
770         my $d = fmt_ts($smsg->{ts}) . ' ' . indent_for($level) . th_pfx($level);
771         my $attr = $f;
772         $ctx->{first_level} ||= $level;
773
774         if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
775                 $ctx->{prev_attr} = $attr;
776         }
777         $ctx->{prev_level} = $level;
778
779         if ($cur) {
780                 if ($cur eq $mid) {
781                         delete $ctx->{cur};
782                         $$dst .= "<b>$d<a\nid=r\nhref=\"#t\">".
783                                  "$attr [this message]</a></b>\n";
784                         return;
785                 } else {
786                         $ctx->{prev_msg} = $mid;
787                 }
788         } else {
789                 $ctx->{next_msg} ||= $mid;
790         }
791
792         # Subject is never undef, this mail was loaded from
793         # our Xapian which would've resulted in '' if it were
794         # really missing (and Filter rejects empty subjects)
795         my @subj = split(/ /, $ctx->{srch}->subject_normalized($smsg->subject));
796
797         # remove common suffixes from the subject if it matches the previous,
798         # so we do not show redundant text at the end.
799         my $prev_subj = $ctx->{prev_subj} || [];
800         $ctx->{prev_subj} = [ @subj ];
801         my $omit = ''; # '"' denotes identical text omitted
802         while (@$prev_subj && @subj && $subj[-1] eq $prev_subj->[-1]) {
803                 pop @$prev_subj;
804                 pop @subj;
805                 $omit ||= '&#34; ';
806         }
807         pop @subj if @subj && $subj[-1] =~ /^re:\s*/i;
808         my $end;
809         if (@subj) {
810                 my $subj = join(' ', @subj);
811                 $subj = ascii_html($subj);
812                 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
813                 $end = "$subj</a> $omit$f\n"
814         } else {
815                 $end = "$f</a>\n";
816         }
817         my $m;
818         my $id = '';
819         my $mapping = $ctx->{mapping};
820         if ($mapping) {
821                 my $map = $mapping->{$mid};
822                 $id = id_compress($mid, 1);
823                 $m = '#m'.$id;
824                 $map->[0] = "$d<a\nhref=\"$m\">$end";
825                 $id = "\nid=r".$id;
826         } else {
827                 $m = $ctx->{-upfx}.mid_escape($mid).'/';
828         }
829         $$dst .=  $d . "<a\nhref=\"$m\"$id>" . $end;
830 }
831
832 sub _skel_ghost {
833         my ($ctx, $level, $node) = @_;
834
835         my $mid = $node->{id};
836         my $d = $ctx->{pct} ? '    [irrelevant] ' # search result
837                             : '     [not found] ';
838         $d .= indent_for($level) . th_pfx($level);
839         my $upfx = $ctx->{-upfx};
840         my $m = PublicInbox::Hval->new_msgid($mid);
841         my $href = $upfx . $m->{href} . '/';
842         my $html = $m->as_html;
843
844         my $mapping = $ctx->{mapping};
845         my $map = $mapping->{$mid} if $mapping;
846         if ($map) {
847                 my $id = id_compress($mid, 1);
848                 $map->[0] = $d . qq{&lt;<a\nhref=#r$id>$html</a>&gt;\n};
849                 $d .= qq{&lt;<a\nhref="$href"\nid=r$id>$html</a>&gt;\n};
850         } else {
851                 $d .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
852         }
853         my $dst = $ctx->{dst};
854         $$dst .= $d;
855 }
856
857 sub sort_ts {
858         [ sort {
859                 (eval { $a->topmost->{smsg}->ts } || 0) <=>
860                 (eval { $b->topmost->{smsg}->ts } || 0)
861         } @{$_[0]} ];
862 }
863
864 # accumulate recent topics if search is supported
865 # returns 200 if done, 404 if not
866 sub acc_topic {
867         my ($ctx, $level, $node) = @_;
868         my $srch = $ctx->{srch};
869         my $mid = $node->{id};
870         my $x = $node->{smsg} || $srch->lookup_mail($mid);
871         my ($subj, $ts);
872         my $topic;
873         if ($x) {
874                 $subj = $x->subject;
875                 $subj = $srch->subject_normalized($subj);
876                 $ts = $x->ts;
877                 if ($level == 0) {
878                         $topic = [ $ts, 1, { $subj => $mid }, $subj ];
879                         $ctx->{-cur_topic} = $topic;
880                         push @{$ctx->{order}}, $topic;
881                         return;
882                 }
883
884                 $topic = $ctx->{-cur_topic}; # should never be undef
885                 $topic->[0] = $ts if $ts > $topic->[0];
886                 $topic->[1]++;
887                 my $seen = $topic->[2];
888                 if (scalar(@$topic) == 3) { # parent was a ghost
889                         push @$topic, $subj;
890                 } elsif (!$seen->{$subj}) {
891                         push @$topic, $level, $subj;
892                 }
893                 $seen->{$subj} = $mid; # latest for subject
894         } else { # ghost message
895                 return if $level != 0; # ignore child ghosts
896                 $topic = [ -666, 0, {} ];
897                 $ctx->{-cur_topic} = $topic;
898                 push @{$ctx->{order}}, $topic;
899         }
900 }
901
902 sub dump_topics {
903         my ($ctx) = @_;
904         my $order = delete $ctx->{order}; # [ ts, subj1, subj2, subj3, ... ]
905         if (!@$order) {
906                 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
907                 return 404;
908         }
909
910         my @out;
911         my $ibx = $ctx->{-inbox};
912         my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
913         my $srch = $ctx->{srch};
914
915         # sort by recency, this allows new posts to "bump" old topics...
916         foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
917                 my ($ts, $n, $seen, $top, @ex) = @$topic;
918                 @$topic = ();
919                 next unless defined $top;  # ghost topic
920                 my $mid = delete $seen->{$top};
921                 my $href = mid_escape($mid);
922                 my $prev_subj = [ split(/ /, $top) ];
923                 $top = PublicInbox::Hval->new($top)->as_html;
924                 $ts = fmt_ts($ts);
925
926                 # $n isn't the total number of posts on the topic,
927                 # just the number of posts in the current results window
928                 my $anchor;
929                 if ($n == 1) {
930                         $n = '';
931                         $anchor = '#u'; # top of only message
932                 } else {
933                         $n = " ($n+ messages)";
934                         $anchor = '#t'; # thread skeleton
935                 }
936
937                 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
938                 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
939                 my $s = "<a\nhref=\"$href/T/$anchor\"><b>$top</b></a>\n" .
940                         " $ts UTC $n - $mbox / $atom\n";
941                 for (my $i = 0; $i < scalar(@ex); $i += 2) {
942                         my $level = $ex[$i];
943                         my $subj = $ex[$i + 1];
944                         $mid = delete $seen->{$subj};
945                         my @subj = split(/ /, $srch->subject_normalized($subj));
946                         my @next_prev = @subj; # full copy
947                         my $omit = ''; # '"' denotes identical text omitted
948                         while (@$prev_subj && @subj &&
949                                         $subj[-1] eq $prev_subj->[-1]) {
950                                 pop @$prev_subj;
951                                 pop @subj;
952                                 $omit ||= ' &#34;';
953                         }
954                         pop @subj if @subj && $subj[-1] =~ /^re:\s*/i;
955                         $prev_subj = \@next_prev;
956                         $subj = ascii_html(join(' ', @subj));
957                         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
958                         $href = mid_escape($mid);
959                         $s .= indent_for($level) . TCHILD;
960                         $s .= "<a\nhref=\"$href/T/#u\">$subj</a>$omit\n";
961                 }
962                 push @out, $s;
963         }
964         $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
965         200;
966 }
967
968 sub index_nav { # callback for WwwStream
969         my (undef, $ctx) = @_;
970         delete $ctx->{qp} or return;
971         my ($next, $prev);
972         $next = $prev = '    ';
973         my $latest = '';
974
975         my $next_o = $ctx->{-next_o};
976         if ($next_o) {
977                 $next = qq!<a\nhref="?o=$next_o"\nrel=next>next</a>!;
978         }
979         if (my $cur_o = $ctx->{-cur_o}) {
980                 $latest = qq! <a\nhref=.>latest</a>!;
981
982                 my $o = $cur_o - ($next_o - $cur_o);
983                 if ($o > 0) {
984                         $prev = qq!<a\nhref="?o=$o"\nrel=prev>prev</a>!;
985                 } elsif ($o == 0) {
986                         $prev = qq!<a\nhref=.\nrel=prev>prev</a>!;
987                 }
988         }
989         "<hr><pre>page: $next $prev$latest</pre>";
990 }
991
992 sub index_topics {
993         my ($ctx) = @_;
994         my ($off) = (($ctx->{qp}->{o} || '0') =~ /(\d+)/);
995         my $opts = { offset => $off, limit => 200 };
996
997         $ctx->{order} = [];
998         my $srch = $ctx->{srch};
999         my $sres = $srch->query('', $opts);
1000         my $nr = scalar @{$sres->{msgs}};
1001         if ($nr) {
1002                 $sres = load_results($srch, $sres);
1003                 walk_thread(thread_results($sres, $srch), $ctx, *acc_topic);
1004         }
1005         $ctx->{-next_o} = $off+ $nr;
1006         $ctx->{-cur_o} = $off;
1007         PublicInbox::WwwStream->response($ctx, dump_topics($ctx), *index_nav);
1008 }
1009
1010 sub thread_adj_level {
1011         my ($ctx, $level) = @_;
1012
1013         my $max = $ctx->{cur_level};
1014         if ($level <= 0) {
1015                 return ('', '') if $max == 0; # flat output
1016
1017                 # reset existing lists
1018                 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1019                 $ctx->{cur_level} = 0;
1020                 ("$beg</ul>", '');
1021         } elsif ($level == $max) { # continue existing list
1022                 qw(<li> </li>);
1023         } elsif ($level < $max) {
1024                 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1025                 $ctx->{cur_level} = $level;
1026                 ("$beg<li>", '</li>');
1027         } else { # ($level > $max) # start a new level
1028                 $ctx->{cur_level} = $level;
1029                 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1030                 ($beg, '</li>');
1031         }
1032 }
1033
1034 sub ghost_index_entry {
1035         my ($ctx, $level, $node) = @_;
1036         my ($beg, $end) = thread_adj_level($ctx,  $level);
1037         $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{id})
1038                 . '</pre>' . $end;
1039 }
1040
1041 1;