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