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