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