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