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