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