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