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