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