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