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