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