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