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