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