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