]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: note we assume UTF-8 on unknown encodings
[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 POSIX qw(strftime);
21 use Time::Local qw(timegm);
22 use PublicInbox::Smsg qw(subject_normalized);
23 use constant COLS => 72;
24 use constant INDENT => '  ';
25 use constant TCHILD => '` ';
26 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
27
28 sub msg_page_i {
29         my ($nr, $ctx) = @_;
30         if (my $more = delete $ctx->{more}) { # unlikely
31                 # fake an EOF if $more retrieval fails;
32                 eval { msg_page_more($ctx, $nr, @$more) };
33         } elsif (my $hdr = delete $ctx->{hdr}) {
34                 # fake an EOF if generating the footer fails;
35                 # we want to at least show the message if something
36                 # here crashes:
37                 eval { html_footer($ctx, $hdr) };
38         } else {
39                 undef
40         }
41 }
42
43 # public functions: (unstable)
44
45 sub msg_page {
46         my ($ctx) = @_;
47         my $mid = $ctx->{mid};
48         my $ibx = $ctx->{-inbox};
49         my ($smsg, $first, $next);
50         if (my $over = $ibx->over) {
51                 my ($id, $prev);
52                 $smsg = $over->next_by_mid($mid, \$id, \$prev) or return;
53                 $first = $ibx->msg_by_smsg($smsg) or return;
54                 $next = $over->next_by_mid($mid, \$id, \$prev);
55                 $ctx->{more} = [ $id, $prev, $next ] if $next;
56         } else {
57                 $first = $ibx->msg_by_mid($mid) or return;
58         }
59         my $mime = PublicInbox::MIME->new($first);
60         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
61         my $hdr = $ctx->{hdr} = $mime->header_obj;
62         $ctx->{obuf} = _msg_page_prepare_obuf($hdr, $ctx, 0);
63         $ctx->{smsg} = $smsg;
64         # $next cannot be true w/o $smsg being defined:
65         $ctx->{mhref} = $next ? '../'.mid_href($smsg->{mid}).'/' : '';
66         multipart_text_as_html($mime, $ctx);
67         $ctx->{-html_tip} = (${delete $ctx->{obuf}} .= '</pre><hr>');
68         PublicInbox::WwwStream->response($ctx, 200, \&msg_page_i);
69 }
70
71 sub msg_page_more { # cold
72         my ($ctx, $nr, $id, $prev, $smsg) = @_;
73         my $ibx = $ctx->{-inbox};
74         my $next = $ibx->over->next_by_mid($ctx->{mid}, \$id, \$prev);
75         $ctx->{more} = [ $id, $prev, $next ] if $next;
76         $smsg = $ibx->smsg_mime($smsg) or return '';
77         $ctx->{mhref} = '../' . mid_href($smsg->{mid}) . '/';
78         my $mime = delete $smsg->{mime};
79         $ctx->{obuf} = _msg_page_prepare_obuf($mime->header_obj, $ctx, $nr);
80         multipart_text_as_html($mime, $ctx);
81         ${delete $ctx->{obuf}} .= '</pre><hr>';
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 "," preceeded 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 # this is already inside a <pre>
184 sub index_entry {
185         my ($smsg, $ctx, $more) = @_;
186         my $subj = $smsg->subject;
187         my $mid_raw = $smsg->mid;
188         my $id = id_compress($mid_raw, 1);
189         my $id_m = 'm'.$id;
190
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 = $smsg->ds; # for v1 non-Xapian/SQLite users
204         # deleting {mime} is critical to memory use,
205         # the rest of the fields saves about 400K as we iterate across 1K msgs
206         my ($mime) = delete @$smsg{qw(mime ds ts blob subject)};
207
208         my $hdr = $mime->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         msg_iter($mime, \&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         if (my $smsg = $node->{smsg}) {
301                 # delete saves about 200KB on a 1K message thread
302                 if (my $refs = delete $smsg->{references}) {
303                         ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
304                 }
305         }
306         my $irt_map = $mapping->{$$irt} if defined $$irt;
307         if (defined $irt_map) {
308                 $siblings = $irt_map->[1]->{children};
309                 $nr_s = scalar(@$siblings) - 1;
310                 $rv .= $pad . $irt_map->[0];
311                 if ($idx > 0) {
312                         my $prev = $siblings->[$idx - 1];
313                         my $pmid = $prev->{id};
314                         if ($idx > 2) {
315                                 my $s = ($idx - 1). ' preceding siblings ...';
316                                 $rv .= pad_link($pmid, $level, $s);
317                         } elsif ($idx == 2) {
318                                 my $ppmid = $siblings->[0]->{id};
319                                 $rv .= $pad . $mapping->{$ppmid}->[0];
320                         }
321                         $rv .= $pad . $mapping->{$pmid}->[0];
322                 }
323         }
324         my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
325         my $s_c = nr_to_s($nr_c, 'reply', 'replies');
326         $attr =~ s!\n\z!</b>\n!s;
327         $attr =~ s!<a\nhref.*</a> !!s; # no point in duplicating subject
328         $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
329         $rv .= "<b>@ $attr";
330         if ($nr_c) {
331                 my $cmid = $children->[0]->{id};
332                 $rv .= $pad . $mapping->{$cmid}->[0];
333                 if ($nr_c > 2) {
334                         my $s = ($nr_c - 1). ' more replies';
335                         $rv .= pad_link($cmid, $level + 1, $s);
336                 } elsif (my $cn = $children->[1]) {
337                         $rv .= $pad . $mapping->{$cn->{id}}->[0];
338                 }
339         }
340
341         my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
342         if ($next) {
343                 my $nmid = $next->{id};
344                 $rv .= $pad . $mapping->{$nmid}->[0];
345                 my $nnext = $nr_s - $idx;
346                 if ($nnext > 2) {
347                         my $s = ($nnext - 1).' subsequent siblings';
348                         $rv .= pad_link($nmid, $level, $s);
349                 } elsif (my $nn = $siblings->[$idx + 2]) {
350                         $rv .= $pad . $mapping->{$nn->{id}}->[0];
351                 }
352         }
353         $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
354 }
355
356 # non-recursive thread walker
357 sub walk_thread ($$$) {
358         my ($rootset, $ctx, $cb) = @_;
359         my @q = map { (0, $_, -1) } @$rootset;
360         while (@q) {
361                 my ($level, $node, $i) = splice(@q, 0, 3);
362                 defined $node or next;
363                 $cb->($ctx, $level, $node, $i) or return;
364                 ++$level;
365                 $i = 0;
366                 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
367         }
368 }
369
370 sub pre_thread  { # walk_thread callback
371         my ($ctx, $level, $node, $idx) = @_;
372         $ctx->{mapping}->{$node->{id}} = [ '', $node, $idx, $level ];
373         skel_dump($ctx, $level, $node);
374 }
375
376 sub thread_index_entry {
377         my ($ctx, $level, $smsg) = @_;
378         my ($beg, $end) = thread_adj_level($ctx, $level);
379         $beg . '<pre>' . index_entry($smsg, $ctx, 0) . '</pre>' . $end;
380 }
381
382 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
383         my ($nr, $ctx) = @_;
384         return unless exists($ctx->{skel});
385         my $q = $ctx->{-queue};
386         while (@$q) {
387                 my $level = shift @$q;
388                 my $node = shift @$q or next;
389                 my $cl = $level + 1;
390                 unshift @$q, map { ($cl, $_) } @{$node->{children}};
391                 if (my $smsg = $ctx->{-inbox}->smsg_mime($node->{smsg})) {
392                         return thread_index_entry($ctx, $level, $smsg);
393                 } else {
394                         return ghost_index_entry($ctx, $level, $node);
395                 }
396         }
397         join('', thread_adj_level($ctx, 0)) . ${delete $ctx->{skel}};
398 }
399
400 sub stream_thread ($$) {
401         my ($rootset, $ctx) = @_;
402         my $ibx = $ctx->{-inbox};
403         my @q = map { (0, $_) } @$rootset;
404         my ($smsg, $level);
405         while (@q) {
406                 $level = shift @q;
407                 my $node = shift @q or next;
408                 my $cl = $level + 1;
409                 unshift @q, map { ($cl, $_) } @{$node->{children}};
410                 $smsg = $ibx->smsg_mime($node->{smsg}) and last;
411         }
412         return missing_thread($ctx) unless $smsg;
413
414         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
415         $ctx->{-title_html} = ascii_html($smsg->{subject});
416         $ctx->{-html_tip} = thread_index_entry($ctx, $level, $smsg);
417         $ctx->{-queue} = \@q;
418         PublicInbox::WwwStream->response($ctx, 200, \&stream_thread_i);
419 }
420
421 # /$INBOX/$MESSAGE_ID/t/
422 sub thread_html {
423         my ($ctx) = @_;
424         my $mid = $ctx->{mid};
425         my $ibx = $ctx->{-inbox};
426         my ($nr, $msgs) = $ibx->over->get_thread($mid);
427         return missing_thread($ctx) if $nr == 0;
428         my $skel = '<hr><pre>';
429         $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
430         $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
431         $skel .= "<b\nid=t>Thread overview:</b> ";
432         $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
433         $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
434         $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
435         $skel .= "-- links below jump to the message on this page --\n";
436         $ctx->{-upfx} = '../../';
437         $ctx->{cur_level} = 0;
438         $ctx->{skel} = \$skel;
439         $ctx->{prev_attr} = '';
440         $ctx->{prev_level} = 0;
441         $ctx->{root_anchor} = anchor_for($mid);
442         $ctx->{mapping} = {};
443         $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
444                        .' in thread';
445
446         my $rootset = thread_results($ctx, $msgs);
447
448         # reduce hash lookups in pre_thread->skel_dump
449         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
450         walk_thread($rootset, $ctx, \&pre_thread);
451
452         $skel .= '</pre>';
453         return stream_thread($rootset, $ctx) unless $ctx->{flat};
454
455         # flat display: lazy load the full message from smsg
456         my $smsg;
457         while (my $m = shift @$msgs) {
458                 $smsg = $ibx->smsg_mime($m) and last;
459         }
460         return missing_thread($ctx) unless $smsg;
461         $ctx->{-title_html} = ascii_html($smsg->{subject});
462         $ctx->{-html_tip} = '<pre>'.index_entry($smsg, $ctx, scalar @$msgs);
463         $ctx->{msgs} = $msgs;
464         PublicInbox::WwwStream->response($ctx, 200, \&thread_html_i);
465 }
466
467 sub thread_html_i { # PublicInbox::WwwStream::getline callback
468         my ($nr, $ctx) = @_;
469         my $msgs = $ctx->{msgs} or return;
470         while (my $smsg = shift @$msgs) {
471                 $ctx->{-inbox}->smsg_mime($smsg) or next;
472                 return index_entry($smsg, $ctx, scalar @$msgs);
473         }
474         my ($skel) = delete @$ctx{qw(skel msgs)};
475         $$skel;
476 }
477
478 sub multipart_text_as_html {
479         # ($mime, $ctx) = @_; # msg_iter will do "$_[0] = undef"
480
481         # scan through all parts, looking for displayable text
482         msg_iter($_[0], \&add_text_body, $_[1], 1);
483 }
484
485 sub flush_quote {
486         my ($s, $l, $quot) = @_;
487
488         my $rv = $l->to_html($$quot);
489
490         # we use a <span> here to allow users to specify their own
491         # color for quoted text
492         $$quot = undef;
493         $$s .= qq(<span\nclass="q">) . $rv . '</span>'
494 }
495
496 sub attach_link ($$$$;$) {
497         my ($ctx, $ct, $p, $fn, $err) = @_;
498         my ($part, $depth, @idx) = @$p;
499         my $nl = $idx[-1] > 1 ? "\n" : '';
500         my $idx = join('.', @idx);
501         my $size = bytes::length($part->body);
502
503         # hide attributes normally, unless we want to aid users in
504         # spotting MUA problems:
505         $ct =~ s/;.*// unless $err;
506         $ct = ascii_html($ct);
507         my $desc = $part->header('Content-Description');
508         $desc = $fn unless defined $desc;
509         $desc = '' unless defined $desc;
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         $desc = ascii_html($desc);
528         $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
529         $$rv .= "</a>\n";
530         undef;
531 }
532
533 sub add_text_body { # callback for msg_iter
534         my ($p, $ctx) = @_;
535         my $upfx = $ctx->{mhref};
536         my $ibx = $ctx->{-inbox};
537         # $p - from msg_iter: [ Email::MIME, depth, @idx ]
538         my ($part, $depth, @idx) = @$p;
539         my $ct = $part->content_type || 'text/plain';
540         my $fn = $part->filename;
541         my ($s, $err) = msg_part_text($part, $ct);
542         return attach_link($ctx, $ct, $p, $fn) unless defined $s;
543
544         # makes no difference to browsers, and don't screw up filename
545         # link generation in diffs with the extra '%0D'
546         $s =~ s/\r\n/\n/sg;
547
548         # always support diff-highlighting, but we can't linkify hunk
549         # headers for solver unless some coderepo are configured:
550         my $diff;
551         if ($s =~ /^(?:diff|---|\+{3}) /ms) {
552                 # diffstat anchors do not link across attachments or messages:
553                 $idx[0] = $upfx . $idx[0] if $upfx ne '';
554                 $ctx->{-apfx} = join('/', @idx);
555                 $ctx->{-anchors} = {}; # attr => filename
556                 $diff = 1;
557                 delete $ctx->{-long_path};
558                 my $spfx;
559                 if ($ibx->{-repo_objs}) {
560                         if (index($upfx, '//') >= 0) { # absolute URL (Atom feeds)
561                                 $spfx = $upfx;
562                                 $spfx =~ s!/([^/]*)/\z!/!;
563                         } else {
564                                 my $n_slash = $upfx =~ tr!/!/!;
565                                 if ($n_slash == 0) {
566                                         $spfx = '../';
567                                 } elsif ($n_slash == 1) {
568                                         $spfx = '';
569                                 } else { # nslash == 2
570                                         $spfx = '../../';
571                                 }
572                         }
573                 }
574                 $ctx->{-spfx} = $spfx;
575         };
576
577         # some editors don't put trailing newlines at the end:
578         $s .= "\n" unless $s =~ /\n\z/s;
579
580         # split off quoted and unquoted blocks:
581         my @sections = PublicInbox::MsgIter::split_quotes($s);
582         $s = '';
583         my $rv = $ctx->{obuf};
584         if (defined($fn) || $depth > 0 || $err) {
585                 # badly-encoded message with $err? tell the world about it!
586                 attach_link($ctx, $ct, $p, $fn, $err);
587                 $$rv .= "\n";
588         }
589         my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
590         foreach my $cur (@sections) {
591                 if ($cur =~ /\A>/) {
592                         flush_quote($rv, $l, \$cur);
593                 } elsif ($diff) {
594                         flush_diff($rv, $ctx, \$cur);
595                 } else {
596                         # regular lines, OK
597                         $$rv .= $l->to_html($cur);
598                         $cur = undef;
599                 }
600         }
601
602         obfuscate_addrs($ibx, $$rv) if $ibx->{obfuscate};
603 }
604
605 sub _msg_page_prepare_obuf {
606         my ($hdr, $ctx, $nr) = @_;
607         my $over = $ctx->{-inbox}->over;
608         my $obfs_ibx = $ctx->{-obfs_ibx};
609         my $rv = '';
610         my $mids = mids_for_index($hdr);
611         if ($nr == 0) {
612                 if ($ctx->{more}) {
613                         $rv .=
614 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
615                 }
616                 $rv .= "<pre\nid=b>"; # anchor for body start
617         } else {
618                 $rv .= '<pre>';
619         }
620         if ($over) {
621                 $ctx->{-upfx} = '../';
622         }
623         my @title; # (Subject[0], From[0])
624         for my $v ($hdr->header('From')) {
625                 my @n = PublicInbox::Address::names($v);
626                 $v = ascii_html($v);
627                 $title[1] //= ascii_html(join(', ', @n));
628                 if ($obfs_ibx) {
629                         obfuscate_addrs($obfs_ibx, $v);
630                         obfuscate_addrs($obfs_ibx, $title[1]);
631                 }
632                 $rv .= "From: $v\n" if $v ne '';
633         }
634         foreach my $h (qw(To Cc)) {
635                 for my $v ($hdr->header($h)) {
636                         fold_addresses($v);
637                         $v = ascii_html($v);
638                         obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
639                         $rv .= "$h: $v\n" if $v ne '';
640                 }
641         }
642         my @subj = $hdr->header('Subject');
643         if (@subj) {
644                 my $v = ascii_html(shift @subj);
645                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
646                 $rv .= 'Subject: ';
647                 $rv .= $over ? qq(<a\nhref="#r"\nid=t>$v</a>\n) : "$v\n";
648                 $title[0] = $v;
649                 for $v (@subj) { # multi-Subject message :<
650                         $v = ascii_html($v);
651                         obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
652                         $rv .= "Subject: $v\n";
653                 }
654         } else { # dummy anchor for thread skeleton at bottom of page
655                 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
656                 $title[0] = '(no subject)';
657         }
658         for my $v ($hdr->header('Date')) {
659                 $v = ascii_html($v);
660                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
661                 $rv .= "Date: $v\n";
662         }
663         $ctx->{-title_html} = join(' - ', @title);
664         if (scalar(@$mids) == 1) { # common case
665                 my $mhtml = ascii_html($mids->[0]);
666                 $rv .= "Message-ID: &lt;$mhtml&gt; ";
667                 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
668         } else {
669                 # X-Alt-Message-ID can happen if a message is injected from
670                 # public-inbox-nntpd because of multiple Message-ID headers.
671                 my $lnk = PublicInbox::Linkify->new;
672                 my $s = '';
673                 for my $h (qw(Message-ID X-Alt-Message-ID)) {
674                         $s .= "$h: $_\n" for ($hdr->header_raw($h));
675                 }
676                 $lnk->linkify_mids('..', \$s, 1);
677                 $rv .= $s;
678         }
679         $rv .= _parent_headers($hdr, $over);
680         $rv .= "\n";
681         \$rv;
682 }
683
684 sub SKEL_EXPAND () {
685         qq(expand[<a\nhref="T/#u">flat</a>) .
686                 qq(|<a\nhref="t/#u">nested</a>]  ) .
687                 qq(<a\nhref="t.mbox.gz">mbox.gz</a>  ) .
688                 qq(<a\nhref="t.atom">Atom feed</a>);
689 }
690
691 sub thread_skel ($$$) {
692         my ($skel, $ctx, $hdr) = @_;
693         my $mid = mids($hdr)->[0];
694         my $ibx = $ctx->{-inbox};
695         my ($nr, $msgs) = $ibx->over->get_thread($mid);
696         my $parent = in_reply_to($hdr);
697         $$skel .= "\n<b>Thread overview: </b>";
698         if ($nr <= 1) {
699                 if (defined $parent) {
700                         $$skel .= SKEL_EXPAND."\n ";
701                         $$skel .= ghost_parent('../', $parent) . "\n";
702                 } else {
703                         $$skel .= '[no followups] '.SKEL_EXPAND."\n";
704                 }
705                 $ctx->{next_msg} = undef;
706                 $ctx->{parent_msg} = $parent;
707                 return;
708         }
709
710         $$skel .= $nr;
711         $$skel .= '+ messages / '.SKEL_EXPAND.qq!  <a\nhref="#b">top</a>\n!;
712
713         # nb: mutt only shows the first Subject in the index pane
714         # when multiple Subject: headers are present, so we follow suit:
715         my $subj = $hdr->header('Subject') // '';
716         $subj = '(no subject)' if $subj eq '';
717         $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
718         $ctx->{cur} = $mid;
719         $ctx->{prev_attr} = '';
720         $ctx->{prev_level} = 0;
721         $ctx->{skel} = $skel;
722
723         # reduce hash lookups in skel_dump
724         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
725         walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
726
727         $ctx->{parent_msg} = $parent;
728 }
729
730 sub _parent_headers {
731         my ($hdr, $over) = @_;
732         my $rv = '';
733         my @irt = $hdr->header_raw('In-Reply-To');
734         my $refs;
735         if (@irt) {
736                 my $lnk = PublicInbox::Linkify->new;
737                 $rv .= "In-Reply-To: $_\n" for @irt;
738                 $lnk->linkify_mids('..', \$rv);
739         } else {
740                 $refs = references($hdr);
741                 my $irt = pop @$refs;
742                 if (defined $irt) {
743                         my $html = ascii_html($irt);
744                         my $href = mid_href($irt);
745                         $rv .= "In-Reply-To: &lt;";
746                         $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
747                 }
748         }
749
750         # do not display References: if search is present,
751         # we show the thread skeleton at the bottom, instead.
752         return $rv if $over;
753
754         $refs //= references($hdr);
755         if (@$refs) {
756                 @$refs = map { linkify_ref_no_over($_) } @$refs;
757                 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
758         }
759         $rv;
760 }
761
762 # returns a string buffer via ->getline
763 sub html_footer {
764         my ($ctx, $hdr) = @_;
765         my $ibx = $ctx->{-inbox};
766         my $upfx = '../';
767         my $skel = " <a\nhref=\"$upfx\">index</a>";
768         my $rv = '<pre>';
769         if ($ibx->over) {
770                 $skel .= "\n";
771                 thread_skel(\$skel, $ctx, $hdr);
772                 my ($next, $prev);
773                 my $parent = '       ';
774                 $next = $prev = '    ';
775
776                 if (my $n = $ctx->{next_msg}) {
777                         $n = mid_href($n);
778                         $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
779                 }
780                 my $u;
781                 my $par = $ctx->{parent_msg};
782                 if ($par) {
783                         $u = mid_href($par);
784                         $u = "$upfx$u/";
785                 }
786                 if (my $p = $ctx->{prev_msg}) {
787                         $prev = mid_href($p);
788                         if ($p && $par && $p eq $par) {
789                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
790                                         'rel=prev>prev parent</a>';
791                                 $parent = '';
792                         } else {
793                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
794                                         'rel=prev>prev</a>';
795                                 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
796                         }
797                 } elsif ($u) { # unlikely
798                         $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
799                 }
800                 $rv .= "$next $prev$parent ";
801         }
802         $rv .= qq(<a\nhref="#R">reply</a>);
803         $rv .= $skel;
804         $rv .= '</pre>';
805         $rv .= msg_reply($ctx, $hdr);
806 }
807
808 sub linkify_ref_no_over {
809         my ($mid) = @_;
810         my $href = mid_href($mid);
811         my $html = ascii_html($mid);
812         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
813 }
814
815 sub anchor_for {
816         my ($msgid) = @_;
817         'm' . id_compress($msgid, 1);
818 }
819
820 sub ghost_parent {
821         my ($upfx, $mid) = @_;
822
823         my $href = mid_href($mid);
824         my $html = ascii_html($mid);
825         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
826 }
827
828 sub indent_for {
829         my ($level) = @_;
830         $level ? INDENT x ($level - 1) : '';
831 }
832
833 sub find_mid_root {
834         my ($ctx, $level, $node, $idx) = @_;
835         ++$ctx->{root_idx} if $level == 0;
836         if ($node->{id} eq $ctx->{mid}) {
837                 $ctx->{found_mid_at} = $ctx->{root_idx};
838                 return 0;
839         }
840         1;
841 }
842
843 sub strict_loose_note ($) {
844         my ($nr) = @_;
845         my $msg =
846 "  -- strict thread matches above, loose matches on Subject: below --\n";
847
848         if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
849                 $msg .=
850 "  -- use mbox.gz link to download all $nr messages --\n";
851         }
852         $msg;
853 }
854
855 sub thread_results {
856         my ($ctx, $msgs) = @_;
857         require PublicInbox::SearchThread;
858         my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
859
860         # FIXME: `tid' is broken on --reindex, so that needs to be fixed
861         # and preserved in the future.  This bug is hidden by `sid' matches
862         # in get_thread, so we never noticed it until now.  And even when
863         # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
864         # bump since reindexing is expensive and users may not do it
865
866         # loose threading could've returned too many results,
867         # put the root the message we care about at the top:
868         my $mid = $ctx->{mid};
869         if (defined($mid) && scalar(@$rootset) > 1) {
870                 $ctx->{root_idx} = -1;
871                 my $nr = scalar @$msgs;
872                 walk_thread($rootset, $ctx, \&find_mid_root);
873                 my $idx = $ctx->{found_mid_at};
874                 if (defined($idx) && $idx != 0) {
875                         my $tip = splice(@$rootset, $idx, 1);
876                         @$rootset = reverse @$rootset;
877                         unshift @$rootset, $tip;
878                         $ctx->{sl_note} = strict_loose_note($nr);
879                 }
880         }
881         $rootset
882 }
883
884 sub missing_thread {
885         my ($ctx) = @_;
886         require PublicInbox::ExtMsg;
887         PublicInbox::ExtMsg::ext_msg($ctx);
888 }
889
890 sub dedupe_subject {
891         my ($prev_subj, $subj, $val) = @_;
892
893         my $omit = ''; # '"' denotes identical text omitted
894         my (@prev_pop, @curr_pop);
895         while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
896                 push(@prev_pop, pop(@$prev_subj));
897                 push(@curr_pop, pop(@$subj));
898                 $omit ||= $val;
899         }
900         pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
901         if (scalar(@curr_pop) == 1) {
902                 $omit = '';
903                 push @$prev_subj, @prev_pop;
904                 push @$subj, @curr_pop;
905         }
906         $omit;
907 }
908
909 sub skel_dump { # walk_thread callback
910         my ($ctx, $level, $node) = @_;
911         my $smsg = $node->{smsg} or return _skel_ghost($ctx, $level, $node);
912
913         my $skel = $ctx->{skel};
914         my $cur = $ctx->{cur};
915         my $mid = $smsg->{mid};
916
917         if ($level == 0 && $ctx->{skel_dump_roots}++) {
918                 $$skel .= delete($ctx->{sl_note}) || '';
919         }
920
921         my $f = ascii_html($smsg->{from_name});
922         my $obfs_ibx = $ctx->{-obfs_ibx};
923         obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
924
925         my $d = fmt_ts($smsg->{ds});
926         my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
927         if (exists $ctx->{searchview}) {
928                 if (defined(my $pct = $smsg->{pct})) {
929                         $d .= (sprintf(' % 2u', $pct) . '%');
930                 } else {
931                         $unmatched = 1;
932                         $d .= '    ';
933                 }
934         }
935         $d .= ' ' . indent_for($level) . th_pfx($level);
936         my $attr = $f;
937         $ctx->{first_level} ||= $level;
938
939         if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
940                 $ctx->{prev_attr} = $attr;
941         }
942         $ctx->{prev_level} = $level;
943
944         if ($cur) {
945                 if ($cur eq $mid) {
946                         delete $ctx->{cur};
947                         $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
948                                  "$attr [this message]</a></b>\n";
949                         return 1;
950                 } else {
951                         $ctx->{prev_msg} = $mid;
952                 }
953         } else {
954                 $ctx->{next_msg} ||= $mid;
955         }
956
957         # Subject is never undef, this mail was loaded from
958         # our Xapian which would've resulted in '' if it were
959         # really missing (and Filter rejects empty subjects)
960         my @subj = split(/ /, subject_normalized($smsg->{subject}));
961         # remove common suffixes from the subject if it matches the previous,
962         # so we do not show redundant text at the end.
963         my $prev_subj = $ctx->{prev_subj} || [];
964         $ctx->{prev_subj} = [ @subj ];
965         my $omit = dedupe_subject($prev_subj, \@subj, '&#34; ');
966         my $end;
967         if (@subj) {
968                 my $subj = join(' ', @subj);
969                 $subj = ascii_html($subj);
970                 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
971                 $end = "$subj</a> $omit$f\n"
972         } else {
973                 $end = "$f</a>\n";
974         }
975         my $m;
976         my $id = '';
977         my $mapping = $unmatched ? undef : $ctx->{mapping};
978         if ($mapping) {
979                 my $map = $mapping->{$mid};
980                 $id = id_compress($mid, 1);
981                 $m = '#m'.$id;
982                 $map->[0] = "$d<a\nhref=\"$m\">$end";
983                 $id = "\nid=r".$id;
984         } else {
985                 $m = $ctx->{-upfx}.mid_href($mid).'/';
986         }
987         $$skel .=  $d . "<a\nhref=\"$m\"$id>" . $end;
988         1;
989 }
990
991 sub _skel_ghost {
992         my ($ctx, $level, $node) = @_;
993
994         my $mid = $node->{id};
995         my $d = '     [not found] ';
996         $d .= '    '  if exists $ctx->{searchview};
997         $d .= indent_for($level) . th_pfx($level);
998         my $upfx = $ctx->{-upfx};
999         my $href = $upfx . mid_href($mid) . '/';
1000         my $html = ascii_html($mid);
1001
1002         my $mapping = $ctx->{mapping};
1003         my $map = $mapping->{$mid} if $mapping;
1004         if ($map) {
1005                 my $id = id_compress($mid, 1);
1006                 $map->[0] = $d . qq{&lt;<a\nhref=#r$id>$html</a>&gt;\n};
1007                 $d .= qq{&lt;<a\nhref="$href"\nid=r$id>$html</a>&gt;\n};
1008         } else {
1009                 $d .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
1010         }
1011         ${$ctx->{skel}} .= $d;
1012         1;
1013 }
1014
1015 sub sort_ds {
1016         [ sort {
1017                 (eval { $a->topmost->{smsg}->{ds} } || 0) <=>
1018                 (eval { $b->topmost->{smsg}->{ds} } || 0)
1019         } @{$_[0]} ];
1020 }
1021
1022 # accumulate recent topics if search is supported
1023 # returns 200 if done, 404 if not
1024 sub acc_topic { # walk_thread callback
1025         my ($ctx, $level, $node) = @_;
1026         my $mid = $node->{id};
1027         my $smsg = $node->{smsg} // $ctx->{-inbox}->smsg_by_mid($mid);
1028         if ($smsg) {
1029                 my $subj = subject_normalized($smsg->{subject});
1030                 $subj = '(no subject)' if $subj eq '';
1031                 my $ds = $smsg->{ds};
1032                 if ($level == 0) { # new, top-level topic
1033                         my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1034                         $ctx->{-cur_topic} = $topic;
1035                         push @{$ctx->{order}}, $topic;
1036                         return 1;
1037                 }
1038
1039                 # continue existing topic
1040                 my $topic = $ctx->{-cur_topic}; # should never be undef
1041                 $topic->[0] = $ds if $ds > $topic->[0];
1042                 $topic->[1]++; # bump N+ message counter
1043                 my $seen = $topic->[2];
1044                 if (scalar(@$topic) == 3) { # parent was a ghost
1045                         push @$topic, $subj;
1046                 } elsif (!defined($seen->{$subj})) {
1047                         push @$topic, $level, $subj; # @extra messages
1048                 }
1049                 $seen->{$subj} = $mid; # latest for subject
1050         } else { # ghost message
1051                 return 1 if $level != 0; # ignore child ghosts
1052                 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1053                 push @{$ctx->{order}}, $topic;
1054         }
1055         1;
1056 }
1057
1058 sub dump_topics {
1059         my ($ctx) = @_;
1060         my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1061         unless ($order) {
1062                 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1063                 return 404;
1064         }
1065
1066         my @out;
1067         my $ibx = $ctx->{-inbox};
1068         my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1069
1070         # sort by recency, this allows new posts to "bump" old topics...
1071         foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1072                 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1073                 @$topic = ();
1074                 next unless defined $top_subj;  # ghost topic
1075                 my $mid = delete $seen->{$top_subj};
1076                 my $href = mid_href($mid);
1077                 my $prev_subj = [ split(/ /, $top_subj) ];
1078                 $top_subj = ascii_html($top_subj);
1079                 $ds = fmt_ts($ds);
1080
1081                 # $n isn't the total number of posts on the topic,
1082                 # just the number of posts in the current results window
1083                 my $anchor;
1084                 if ($n == 1) {
1085                         $n = '';
1086                         $anchor = '#u'; # top of only message
1087                 } else {
1088                         $n = " ($n+ messages)";
1089                         $anchor = '#t'; # thread skeleton
1090                 }
1091
1092                 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1093                 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1094                 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1095                         " $ds UTC $n - $mbox / $atom\n";
1096                 for (my $i = 0; $i < scalar(@extra); $i += 2) {
1097                         my $level = $extra[$i];
1098                         my $subj = $extra[$i + 1]; # already normalized
1099                         $mid = delete $seen->{$subj};
1100                         my @subj = split(/ /, $subj);
1101                         my @next_prev = @subj; # full copy
1102                         my $omit = dedupe_subject($prev_subj, \@subj, ' &#34;');
1103                         $prev_subj = \@next_prev;
1104                         $subj = ascii_html($subj);
1105                         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1106                         $href = mid_href($mid);
1107                         $s .= indent_for($level) . TCHILD;
1108                         $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1109                 }
1110                 push @out, $s;
1111         }
1112         $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1113         200;
1114 }
1115
1116 # only for the t= query parameter passed to overview DB
1117 sub ts2str ($) { strftime('%Y%m%d%H%M%S', gmtime($_[0])) };
1118
1119 sub str2ts ($) {
1120         my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1121         timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1122 }
1123
1124 sub pagination_footer ($$) {
1125         my ($ctx, $latest) = @_;
1126         delete $ctx->{qp} or return;
1127         my $next = $ctx->{next_page} || '';
1128         my $prev = $ctx->{prev_page} || '';
1129         if ($prev) {
1130                 $next = $next ? "$next " : '     ';
1131                 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1132         }
1133         "<hr><pre>page: $next$prev</pre>";
1134 }
1135
1136 sub index_nav { # callback for WwwStream
1137         my (undef, $ctx) = @_;
1138         pagination_footer($ctx, '.')
1139 }
1140
1141 sub paginate_recent ($$) {
1142         my ($ctx, $lim) = @_;
1143         my $t = $ctx->{qp}->{t} || '';
1144         my $opts = { limit => $lim };
1145         my ($after, $before);
1146
1147         # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1148         # if only $after exists "YYYYMMDD.." because "." could be skipped
1149         # if interpreted as an end-of-sentence
1150         $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1151         $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1152
1153         my $ibx = $ctx->{-inbox};
1154         my $msgs = $ibx->recent($opts, $after, $before);
1155         my $nr = scalar @$msgs;
1156         if ($nr < $lim && defined($after)) {
1157                 $after = $before = undef;
1158                 $msgs = $ibx->recent($opts);
1159                 $nr = scalar @$msgs;
1160         }
1161         my $more = $nr == $lim;
1162         my ($newest, $oldest);
1163         if ($nr) {
1164                 $newest = $msgs->[0]->{ts};
1165                 $oldest = $msgs->[-1]->{ts};
1166                 # if we only had $after, our SQL query in ->recent ordered
1167                 if ($newest < $oldest) {
1168                         ($oldest, $newest) = ($newest, $oldest);
1169                         $more = 0 if defined($after) && $after < $oldest;
1170                 }
1171         }
1172         if (defined($oldest) && $more) {
1173                 my $s = ts2str($oldest);
1174                 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1175         }
1176         if (defined($newest) && (defined($before) || defined($after))) {
1177                 my $s = ts2str($newest);
1178                 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1179         }
1180         $msgs;
1181 }
1182
1183 sub index_topics {
1184         my ($ctx) = @_;
1185         my $msgs = paginate_recent($ctx, 200); # 200 is our window
1186         if (@$msgs) {
1187                 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1188         }
1189         PublicInbox::WwwStream->response($ctx, dump_topics($ctx), \&index_nav);
1190 }
1191
1192 sub thread_adj_level {
1193         my ($ctx, $level) = @_;
1194
1195         my $max = $ctx->{cur_level};
1196         if ($level <= 0) {
1197                 return ('', '') if $max == 0; # flat output
1198
1199                 # reset existing lists
1200                 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1201                 $ctx->{cur_level} = 0;
1202                 ("$beg</ul>", '');
1203         } elsif ($level == $max) { # continue existing list
1204                 qw(<li> </li>);
1205         } elsif ($level < $max) {
1206                 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1207                 $ctx->{cur_level} = $level;
1208                 ("$beg<li>", '</li>');
1209         } else { # ($level > $max) # start a new level
1210                 $ctx->{cur_level} = $level;
1211                 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1212                 ($beg, '</li>');
1213         }
1214 }
1215
1216 sub ghost_index_entry {
1217         my ($ctx, $level, $node) = @_;
1218         my ($beg, $end) = thread_adj_level($ctx,  $level);
1219         $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{id})
1220                 . '</pre>' . $end;
1221 }
1222
1223 1;