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