]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
85dc3bd89d679d295ea0921e36d5acb69c515230
[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($eml, $ctx)) {
42                         $eml->each_part(\&add_text_body, $ctx, 1);
43                         $ctx->zadd('</pre><hr>');
44                 }
45                 html_footer($ctx, $ctx->{first_hdr}) if !$ctx->{smsg};
46                 ''; # XXX TODO cleanup
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($eml, $ctx)) { # sets {-title_html}
60                 $eml->each_part(\&add_text_body, $ctx, 1);
61                 $ctx->zadd('</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->zadd($rv); # XXX $rv is small, reuse below
249         $eml->each_part(\&add_text_body, $ctx, 1); # expensive
250
251         # add the footer
252         $rv = "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
253                 "<a\nhref=\"$mhref\">permalink</a>" .
254                 " <a\nhref=\"${mhref}raw\">raw</a>" .
255                 " <a\nhref=\"${mhref}#R\">reply</a>";
256
257         delete($ctx->{-qry}) and
258                 $rv .= qq[ <a\nhref="${mhref}#related">related</a>];
259
260         my $hr;
261         if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
262                 $rv .= "\t[relevance $pct%]";
263                 $hr = 1;
264         } elsif ($mapping) {
265                 my $nested = 'nested';
266                 my $flat = 'flat';
267                 if ($ctx->{flat}) {
268                         $hr = 1;
269                         $flat = "<b>$flat</b>";
270                 } else {
271                         $nested = "<b>$nested</b>";
272                 }
273                 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
274                 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
275                 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
276         } else {
277                 $hr = $ctx->{-hr};
278         }
279
280         # do we have more messages? start a new <pre> if so
281         $rv .= scalar(@{$ctx->{msgs}}) ? '</pre><hr><pre>' : '</pre>' if $hr;
282         $rv;
283 }
284
285 sub pad_link ($$;$) {
286         my ($mid, $level, $s) = @_;
287         $s ||= '...';
288         my $href = defined($mid) ?
289                 ("<a\nhref=#r".id_compress($mid, 1).">($s)</a>\n") :
290                 "($s)\n";
291         (' 'x19).indent_for($level).th_pfx($level).$href;
292 }
293
294 sub _skel_hdr {
295         # my ($mapping, $mid) = @_;
296         ($_[0]->{$_[1] // \'bogus'} // [ "(?)\n" ])->[0];
297 }
298
299 sub _th_index_lite {
300         my ($mid_raw, $irt, $id, $ctx) = @_;
301         my $rv = '';
302         my $mapping = $ctx->{mapping} or return $rv;
303         my $pad = '  ';
304         my $mid_map = $mapping->{$mid_raw} //
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         chop $attr; # remove "\n"
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</b>\n";
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         $ctx->zadd($beg.'<pre>');
390         eml_entry($ctx, $eml) . '</pre>' . $end;
391 }
392
393 sub next_in_queue ($$) {
394         my ($q, $ghost_ok) = @_;
395         while (@$q) {
396                 my ($level, $smsg) = splice(@$q, 0, 2);
397                 my $cl = $level + 1;
398                 unshift @$q, map { ($cl, $_) } @{$smsg->{children}};
399                 return ($level, $smsg) if $ghost_ok || exists($smsg->{blob});
400         }
401         undef;
402 }
403
404 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
405         my ($ctx, $eml) = @_;
406         return thread_eml_entry($ctx, $eml) if $eml;
407         return unless exists($ctx->{skel});
408         my $ghost_ok = $ctx->{nr}++;
409         while (1) {
410                 my ($lvl, $smsg) = next_in_queue($ctx->{-queue}, $ghost_ok);
411                 if ($smsg) {
412                         if (exists $smsg->{blob}) { # next message for cat-file
413                                 $ctx->{level} = $lvl;
414                                 if (!$ghost_ok) { # first non-ghost
415                                         $ctx->{-title_html} =
416                                                 ascii_html($smsg->{subject});
417                                         $ctx->zadd($ctx->html_top);
418                                 }
419                                 return $smsg;
420                         }
421                         # buffer the ghost entry and loop
422                         $ctx->zadd(ghost_index_entry($ctx, $lvl, $smsg));
423                 } else { # all done
424                         $ctx->zadd(join('', thread_adj_level($ctx, 0)));
425                         $ctx->zadd(${delete($ctx->{skel})});
426                         return;
427                 }
428         }
429 }
430
431 sub stream_thread ($$) {
432         my ($rootset, $ctx) = @_;
433         @{$ctx->{-queue}} = map { (0, $_) } @$rootset;
434         PublicInbox::WwwStream::aresponse($ctx, \&stream_thread_i);
435 }
436
437 # /$INBOX/$MSGID/t/ and /$INBOX/$MSGID/T/
438 sub thread_html {
439         my ($ctx) = @_;
440         $ctx->{-upfx} = '../../';
441         my $mid = $ctx->{mid};
442         my $ibx = $ctx->{ibx};
443         my ($nr, $msgs) = $ibx->over->get_thread($mid);
444         return missing_thread($ctx) if $nr == 0;
445
446         # link $INBOX_DIR/description text to "index_topics" view around
447         # the newest message in this thread
448         my $t = ts2str($ctx->{-t_max} = max(map { delete $_->{ts} } @$msgs));
449         my $t_fmt = fmt_ts($ctx->{-t_max});
450
451         my $skel = '<hr><pre>';
452         $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
453         $skel .= <<EOF;
454 , other threads:[<a
455 href="../../?t=$t">~$t_fmt UTC</a> | <a
456 href="../../">newest</a>]
457
458 EOF
459         $skel .= "<b\nid=t>Thread overview:</b> ";
460         $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
461         $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
462         $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
463         $skel .= "-- links below jump to the message on this page --\n";
464         $ctx->{cur_level} = 0;
465         $ctx->{skel} = \$skel;
466         $ctx->{prev_attr} = '';
467         $ctx->{prev_level} = 0;
468         $ctx->{root_anchor} = 'm' . id_compress($mid, 1);
469         $ctx->{mapping} = {}; # mid -> [ header_summary, node, idx, level ]
470         $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
471                        .' in thread';
472
473         my $rootset = thread_results($ctx, $msgs);
474
475         # reduce hash lookups in pre_thread->skel_dump
476         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
477         walk_thread($rootset, $ctx, \&pre_thread);
478
479         $skel .= '</pre>';
480         return stream_thread($rootset, $ctx) unless $ctx->{flat};
481
482         # flat display: lazy load the full message from smsg
483         $ctx->{msgs} = $msgs;
484         $ctx->{-html_tip} = '<pre>';
485         PublicInbox::WwwStream::aresponse($ctx, \&thread_html_i);
486 }
487
488 sub thread_html_i { # PublicInbox::WwwStream::getline callback
489         my ($ctx, $eml) = @_;
490         if ($eml) {
491                 my $smsg = $ctx->{smsg};
492                 if (exists $ctx->{-html_tip}) {
493                         $ctx->{-title_html} = ascii_html($smsg->{subject});
494                         $ctx->zadd($ctx->html_top);
495                 }
496                 return eml_entry($ctx, $eml);
497         } else {
498                 while (my $smsg = shift @{$ctx->{msgs}}) {
499                         return $smsg if exists($smsg->{blob});
500                 }
501                 my $skel = delete($ctx->{skel}) or return; # all done
502                 $ctx->zadd($$skel);
503                 undef;
504         }
505 }
506
507 sub submsg_hdr ($$) {
508         my ($ctx, $eml) = @_;
509         my $s = "\n";
510         for my $h (qw(From To Cc Subject Date Message-ID X-Alt-Message-ID)) {
511                 $s .= "$h: $_\n" for $eml->header($h);
512         }
513         obfuscate_addrs($ctx->{-obfs_ibx}, $s) if $ctx->{-obfs_ibx};
514         ascii_html($s);
515 }
516
517 sub attach_link ($$$$;$) {
518         my ($ctx, $ct, $p, $fn, $err) = @_;
519         my ($part, $depth, $idx) = @$p;
520
521         # Eml iteration clobbers multipart ->{bdy}, so do not offer
522         # downloads for 0-byte multipart attachments
523         return unless $part->{bdy};
524
525         my $size = length($part->body);
526         delete $part->{bdy}; # save memory
527
528         # hide attributes normally, unless we want to aid users in
529         # spotting MUA problems:
530         $ct =~ s/;.*// unless $err;
531         $ct = ascii_html($ct);
532         my $sfn;
533         if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
534                 $sfn = $fn;
535         } elsif ($ct eq 'text/plain') {
536                 $sfn = 'a.txt';
537         } else {
538                 $sfn = 'a.bin';
539         }
540         my $rv = $idx eq '1' ? '' : "\n"; # like join("\n", ...)
541         $rv .= qq(<a\nhref="$ctx->{mhref}$idx-$sfn">);
542         $rv .= <<EOF if $err;
543 [-- Warning: decoded text below may be mangled, UTF-8 assumed --]
544 EOF
545         $rv .= "[-- Attachment #$idx: ";
546         my $desc = $part->header('Content-Description') // $fn // '';
547         $rv .= ascii_html($desc)." --]\n[-- " if $desc ne '';
548         $rv .= "Type: $ct, Size: $size bytes --]</a>\n";
549         $rv .= submsg_hdr($ctx, $part) if $part->{is_submsg};
550         $rv;
551 }
552
553 sub add_text_body { # callback for each_part
554         my ($p, $ctx) = @_;
555         my $upfx = $ctx->{mhref};
556         my $ibx = $ctx->{ibx};
557         my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
558         # $p - from each_part: [ Email::MIME-like, depth, $idx ]
559         my ($part, $depth, $idx) = @$p;
560         my $ct = $part->content_type || 'text/plain';
561         my $fn = $part->filename;
562         my ($s, $err) = msg_part_text($part, $ct);
563         $s // return $ctx->zadd(attach_link($ctx, $ct, $p, $fn) // '');
564         my $buf = $part->{is_submsg} ? submsg_hdr($ctx, $part)."\n" : '';
565
566         # makes no difference to browsers, and don't screw up filename
567         # link generation in diffs with the extra '%0D'
568         $s =~ s/\r+\n/\n/sg;
569
570         # will be escaped to `&#8226;' in HTML
571         obfuscate_addrs($ibx, $s, "\x{2022}") if $ibx->{obfuscate};
572
573         # always support diff-highlighting, but we can't linkify hunk
574         # headers for solver unless some coderepo are configured:
575         my $diff;
576         if ($s =~ /^--- [^\n]+\n\+{3} [^\n]+\n@@ /ms) {
577                 # diffstat anchors do not link across attachments or messages,
578                 # -apfx is just a stable prefix for making diffstat anchors
579                 # linkable to the first diff hunk w/o crossing attachments
580                 $idx =~ tr!.!/!; # compatibility with previous versions
581                 $ctx->{-apfx} = $upfx . $idx;
582
583                 # do attr => filename mappings for diffstats in git diffs:
584                 $ctx->{-anchors} = {} if $s =~ /^diff --git /sm;
585                 $diff = 1;
586                 delete $ctx->{-long_path};
587                 my $spfx;
588                 # absolute URL (Atom feeds)
589                 if ($ibx->{coderepo}) {
590                         if (index($upfx, '//') >= 0) {
591                                 $spfx = $upfx;
592                                 $spfx =~ s!/([^/]*)/\z!/!;
593                         } else {
594                                 my $n_slash = $upfx =~ tr!/!/!;
595                                 if ($n_slash == 0) {
596                                         $spfx = '../';
597                                 } elsif ($n_slash == 1) {
598                                         $spfx = '';
599                                 } else { # nslash == 2
600                                         $spfx = '../../';
601                                 }
602                         }
603                 }
604                 $ctx->{-spfx} = $spfx;
605         };
606
607         # split off quoted and unquoted blocks:
608         my @sections = PublicInbox::MsgIter::split_quotes($s);
609         undef $s; # free memory
610         if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
611                 # badly-encoded message with $err? tell the world about it!
612                 $buf .= attach_link($ctx, $ct, $p, $fn, $err) . "\n";
613         }
614         delete $part->{bdy}; # save memory
615         $ctx->zadd($buf);
616         undef $buf;
617         for my $cur (@sections) { # $cur may be huge
618                 if ($cur =~ /\A>/) {
619                         # we use a <span> here to allow users to specify
620                         # their own color for quoted text
621                         $ctx->zadd(qq(<span\nclass="q">),
622                                         $l->to_html($cur), '</span>');
623                 } elsif ($diff) {
624                         flush_diff($ctx, \$cur);
625                 } else { # regular lines, OK
626                         $ctx->zadd($l->to_html($cur));
627                 }
628                 undef $cur; # free memory
629         }
630 }
631
632 sub _msg_page_prepare {
633         my ($eml, $ctx) = @_;
634         my $have_over = !!$ctx->{ibx}->over;
635         my $mids = mids_for_index($eml);
636         my $nr = $ctx->{nr}++;
637         if ($nr) { # unlikely
638                 if ($ctx->{chash} eq content_hash($eml)) {
639                         warn "W: BUG? @$mids not deduplicated properly\n";
640                         return;
641                 }
642                 $ctx->{-html_tip} =
643 "<pre>WARNING: multiple messages have this Message-ID\n</pre><pre>";
644         } else {
645                 $ctx->{first_hdr} = $eml->header_obj;
646                 $ctx->{chash} = content_hash($eml) if $ctx->{smsg}; # reused MID
647                 $ctx->{-html_tip} = "<pre\nid=b>"; # anchor for body start
648         }
649         $ctx->{-upfx} = '../';
650         my @title; # (Subject[0], From[0])
651         my $hbuf = '';
652         for my $v ($eml->header('From')) {
653                 my @n = PublicInbox::Address::names($v);
654                 $title[1] //= join(', ', @n);
655                 $hbuf .= "From: $v\n" if $v ne '';
656         }
657         for my $h (qw(To Cc)) {
658                 for my $v ($eml->header($h)) {
659                         fold_addresses($v);
660                         $hbuf .= "$h: $v\n" if $v ne '';
661                 }
662         }
663         my @subj = $eml->header('Subject');
664         $hbuf .= "Subject: $_\n" for @subj;
665         $title[0] = $subj[0] // '(no subject)';
666         $hbuf .= "Date: $_\n" for $eml->header('Date');
667         $hbuf = ascii_html($hbuf);
668         $ctx->{-title_html} = ascii_html(join(' - ', @title));
669         if (my $obfs_ibx = $ctx->{-obfs_ibx}) {
670                 obfuscate_addrs($obfs_ibx, $hbuf);
671                 obfuscate_addrs($obfs_ibx, $ctx->{-title_html});
672         }
673
674         # [thread overview] link is typically added after Date,
675         # but added after Subject, or even nothing.
676         if ($have_over) {
677                 chop $hbuf; # drop "\n", or noop if $rv eq ''
678                 $hbuf .= qq{\t<a\nhref="#r">[thread overview]</a>\n};
679                 $hbuf =~ s!^Subject:\x20(.*?)(\n[A-Z]|\z)
680                                 !Subject: <a\nhref="#r"\nid=t>$1</a>$2!msx or
681                         $hbuf .= qq(<a\nhref="#r\nid=t></a>);
682         }
683         if (scalar(@$mids) == 1) { # common case
684                 my $x = ascii_html($mids->[0]);
685                 $hbuf .= qq[Message-ID: &lt;$x&gt; (<a href="raw">raw</a>)\n];
686         }
687         if (!$nr) { # first (and only) message, common case
688                 $ctx->zadd($ctx->html_top, $hbuf);
689         } else {
690                 delete $ctx->{-title_html};
691                 $ctx->zadd($ctx->{-html_tip}, $hbuf);
692         }
693         $ctx->{-linkify} //= PublicInbox::Linkify->new;
694         $hbuf = '';
695         if (scalar(@$mids) != 1) { # unlikely, but it happens :<
696                 # X-Alt-Message-ID can happen if a message is injected from
697                 # public-inbox-nntpd because of multiple Message-ID headers.
698                 for my $h (qw(Message-ID X-Alt-Message-ID)) {
699                         $hbuf .= "$h: $_\n" for ($eml->header_raw($h));
700                 }
701                 $ctx->{-linkify}->linkify_mids('..', \$hbuf, 1); # escapes HTML
702                 $ctx->zadd($hbuf);
703                 $hbuf = '';
704         }
705         my @irt = $eml->header_raw('In-Reply-To');
706         my $refs;
707         if (!@irt) {
708                 $refs = references($eml);
709                 $irt[0] = pop(@$refs) if scalar @$refs;
710         }
711         $hbuf .= "In-Reply-To: $_\n" for @irt;
712
713         # do not display References: if search is present,
714         # we show the thread skeleton at the bottom, instead.
715         if (!$have_over) {
716                 $refs //= references($eml);
717                 $hbuf .= 'References: <'.join(">\n\t<", @$refs).">\n" if @$refs;
718         }
719         $ctx->{-linkify}->linkify_mids('..', \$hbuf); # escapes HTML
720         $ctx->zadd($hbuf .= "\n");
721         1;
722 }
723
724 sub SKEL_EXPAND () {
725         qq(expand[<a\nhref="T/#u">flat</a>) .
726                 qq(|<a\nhref="t/#u">nested</a>]  ) .
727                 qq(<a\nhref="t.mbox.gz">mbox.gz</a>  ) .
728                 qq(<a\nhref="t.atom">Atom feed</a>);
729 }
730
731 sub thread_skel ($$$) {
732         my ($skel, $ctx, $hdr) = @_;
733         my $mid = mids($hdr)->[0];
734         my $ibx = $ctx->{ibx};
735         my ($nr, $msgs) = $ibx->over->get_thread($mid);
736         my $parent = in_reply_to($hdr);
737         $$skel .= "\n<b>Thread overview: </b>";
738         if ($nr <= 1) {
739                 if (defined $parent) {
740                         $$skel .= SKEL_EXPAND."\n ";
741                         $$skel .= ghost_parent('../', $parent) . "\n";
742                 } else {
743                         $$skel .= "<a\nid=r>[no followups]</a> ".
744                                         SKEL_EXPAND."\n";
745                 }
746                 $ctx->{next_msg} = undef;
747                 $ctx->{parent_msg} = $parent;
748                 return;
749         }
750
751         $$skel .= $nr;
752         $$skel .= '+ messages / '.SKEL_EXPAND.qq!  <a\nhref="#b">top</a>\n!;
753
754         # nb: mutt only shows the first Subject in the index pane
755         # when multiple Subject: headers are present, so we follow suit:
756         my $subj = $hdr->header('Subject') // '';
757         $subj = '(no subject)' if $subj eq '';
758         $ctx->{cur} = $mid;
759         $ctx->{prev_attr} = '';
760         $ctx->{prev_level} = 0;
761         $ctx->{skel} = $skel;
762
763         # reduce hash lookups in skel_dump
764         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
765         walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
766
767         $ctx->{parent_msg} = $parent;
768 }
769
770 # writes to zbuf
771 sub html_footer {
772         my ($ctx, $hdr) = @_;
773         my $upfx = '../';
774         my ($related, $skel);
775         my $foot = '<pre>';
776         my $qry = delete $ctx->{-qry};
777         if ($qry && $ctx->{ibx}->isrch) {
778                 my $q = ''; # search for either ancestor or descendent patches
779                 for (@{$qry->{dfpre}}, @{$qry->{dfpost}}) {
780                         chop if length > 7; # include 1 abbrev "older" patches
781                         $q .= "dfblob:$_ ";
782                 }
783                 chop $q; # omit trailing SP
784                 local $Text::Wrap::columns = COLS;
785                 local $Text::Wrap::huge = 'overflow';
786                 $q = wrap('', '', $q);
787                 my $rows = ($q =~ tr/\n/\n/) + 1;
788                 $q = ascii_html($q);
789                 $related = <<EOM;
790 <form id=related
791 action=$upfx
792 ><pre>find likely ancestor, descendant, or conflicting patches for <a
793 href=#t>this message</a>:
794 <textarea name=q cols=${\COLS} rows=$rows>$q</textarea>
795 <input type=submit value=search
796 />\t(<a href=${upfx}_/text/help/#search>help</a>)</pre></form>
797 EOM
798         }
799         if ($ctx->{ibx}->over) {
800                 my $t = ts2str($ctx->{-t_max});
801                 my $t_fmt = fmt_ts($ctx->{-t_max});
802                 my $fallback = $related ? "\t" : "<a id=related>\t</a>";
803                 $skel = <<EOF;
804 ${fallback}other threads:[<a
805 href="$upfx?t=$t">~$t_fmt UTC</a>|<a
806 href="$upfx">newest</a>]
807 EOF
808                 thread_skel(\$skel, $ctx, $hdr);
809                 my ($next, $prev);
810                 my $parent = '       ';
811                 $next = $prev = '    ';
812
813                 if (my $n = $ctx->{next_msg}) {
814                         $n = mid_href($n);
815                         $next = qq(<a\nhref="$upfx$n/"\nrel=next>next</a>);
816                 }
817                 my $par = $ctx->{parent_msg};
818                 my $u = $par ? $upfx.mid_href($par).'/' : undef;
819                 if (my $p = $ctx->{prev_msg}) {
820                         $prev = mid_href($p);
821                         if ($p && $par && $p eq $par) {
822                                 $prev = qq(<a\nhref="$upfx$prev/"\n) .
823                                         'rel=prev>prev parent</a>';
824                                 $parent = '';
825                         } else {
826                                 $prev = qq(<a\nhref="$upfx$prev/"\n) .
827                                         'rel=prev>prev</a>';
828                                 $parent = qq( <a\nhref="$u">parent</a>) if $u;
829                         }
830                 } elsif ($u) { # unlikely
831                         $parent = qq( <a\nhref="$u"\nrel=prev>parent</a>);
832                 }
833                 $foot .= "$next $prev$parent ";
834         } else { # unindexed inboxes w/o over
835                 $skel = qq( <a\nhref="$upfx">latest</a>);
836         }
837         $foot .= qq(<a\nhref="#R">reply</a>);
838         # $skel may be big for big threads, don't append it to $foot
839         $skel .= '</pre>' . ($related // '');
840         $ctx->zadd($foot, $skel .= msg_reply($ctx, $hdr));
841 }
842
843 sub ghost_parent {
844         my ($upfx, $mid) = @_;
845
846         my $href = mid_href($mid);
847         my $html = ascii_html($mid);
848         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
849 }
850
851 sub indent_for {
852         my ($level) = @_;
853         $level ? INDENT x ($level - 1) : '';
854 }
855
856 sub find_mid_root {
857         my ($ctx, $level, $node, $idx) = @_;
858         ++$ctx->{root_idx} if $level == 0;
859         if ($node->{mid} eq $ctx->{mid}) {
860                 $ctx->{found_mid_at} = $ctx->{root_idx};
861                 return 0; # stop iterating
862         }
863         1;
864 }
865
866 sub strict_loose_note ($) {
867         my ($nr) = @_;
868         my $msg =
869 "  -- strict thread matches above, loose matches on Subject: below --\n";
870
871         if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
872                 $msg .=
873 "  -- use mbox.gz link to download all $nr messages --\n";
874         }
875         $msg;
876 }
877
878 sub thread_results {
879         my ($ctx, $msgs) = @_;
880         require PublicInbox::SearchThread;
881         my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
882
883         # FIXME: `tid' is broken on --reindex, so that needs to be fixed
884         # and preserved in the future.  This bug is hidden by `sid' matches
885         # in get_thread, so we never noticed it until now.  And even when
886         # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
887         # bump since reindexing is expensive and users may not do it
888
889         # loose threading could've returned too many results,
890         # put the root the message we care about at the top:
891         my $mid = $ctx->{mid};
892         if (defined($mid) && scalar(@$rootset) > 1) {
893                 $ctx->{root_idx} = -1;
894                 my $nr = scalar @$msgs;
895                 walk_thread($rootset, $ctx, \&find_mid_root);
896                 my $idx = $ctx->{found_mid_at};
897                 if (defined($idx) && $idx != 0) {
898                         my $tip = splice(@$rootset, $idx, 1);
899                         @$rootset = reverse @$rootset;
900                         unshift @$rootset, $tip;
901                         $ctx->{sl_note} = strict_loose_note($nr);
902                 }
903         }
904         $rootset
905 }
906
907 sub missing_thread {
908         my ($ctx) = @_;
909         require PublicInbox::ExtMsg;
910         PublicInbox::ExtMsg::ext_msg($ctx);
911 }
912
913 sub dedupe_subject {
914         my ($prev_subj, $subj, $val) = @_;
915
916         my $omit; # '"' denotes identical text omitted
917         my (@prev_pop, @curr_pop);
918         while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
919                 push(@prev_pop, pop(@$prev_subj));
920                 push(@curr_pop, pop(@$subj));
921                 $omit //= $val;
922         }
923         pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
924         if (scalar(@curr_pop) == 1) {
925                 $omit = undef;
926                 push @$prev_subj, @prev_pop;
927                 push @$subj, @curr_pop;
928         }
929         $omit // '';
930 }
931
932 sub skel_dump { # walk_thread callback
933         my ($ctx, $level, $smsg) = @_;
934         $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
935
936         my $skel = $ctx->{skel};
937         my $cur = $ctx->{cur};
938         my $mid = $smsg->{mid};
939
940         if ($level == 0 && $ctx->{skel_dump_roots}++) {
941                 $$skel .= delete($ctx->{sl_note}) || '';
942         }
943
944         my $f = ascii_html(delete $smsg->{from_name});
945         my $obfs_ibx = $ctx->{-obfs_ibx};
946         obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
947
948         my $d = fmt_ts($smsg->{ds});
949         my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
950         if (exists $ctx->{searchview}) {
951                 if (defined(my $pct = $smsg->{pct})) {
952                         $d .= (sprintf(' % 2u', $pct) . '%');
953                 } else {
954                         $unmatched = 1;
955                         $d .= '    ';
956                 }
957         }
958         $d .= ' ' . indent_for($level) . th_pfx($level);
959         my $attr = $f;
960         $ctx->{first_level} ||= $level;
961
962         if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
963                 $ctx->{prev_attr} = $attr;
964         }
965         $ctx->{prev_level} = $level;
966
967         if ($cur) {
968                 if ($cur eq $mid) {
969                         delete $ctx->{cur};
970                         $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
971                                  "$attr [this message]</a></b>\n";
972                         return 1;
973                 } else {
974                         $ctx->{prev_msg} = $mid;
975                 }
976         } else {
977                 $ctx->{next_msg} ||= $mid;
978         }
979
980         # Subject is never undef, this mail was loaded from
981         # our Xapian which would've resulted in '' if it were
982         # really missing (and Filter rejects empty subjects)
983         my @subj = split(/ /, subject_normalized($smsg->{subject}));
984         # remove common suffixes from the subject if it matches the previous,
985         # so we do not show redundant text at the end.
986         my $prev_subj = $ctx->{prev_subj} || [];
987         $ctx->{prev_subj} = [ @subj ];
988         my $omit = dedupe_subject($prev_subj, \@subj, '&#34; ');
989         my $end;
990         if (@subj) {
991                 my $subj = join(' ', @subj);
992                 $subj = ascii_html($subj);
993                 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
994                 $end = "$subj</a> $omit$f\n"
995         } else {
996                 $end = "$f</a>\n";
997         }
998         my $m;
999         my $id = '';
1000         my $mapping = $unmatched ? undef : $ctx->{mapping};
1001         if ($mapping) {
1002                 my $map = $mapping->{$mid};
1003                 $id = id_compress($mid, 1);
1004                 $m = '#m'.$id;
1005                 $map->[0] = "$d<a\nhref=\"$m\">$end";
1006                 $id = "\nid=r".$id;
1007         } else {
1008                 $m = $ctx->{-upfx}.mid_href($mid).'/';
1009         }
1010         $$skel .=  $d . "<a\nhref=\"$m\"$id>" . $end;
1011         1;
1012 }
1013
1014 sub _skel_ghost {
1015         my ($ctx, $level, $node) = @_;
1016
1017         my $mid = $node->{mid};
1018         my $d = '     [not found] ';
1019         $d .= '    '  if exists $ctx->{searchview};
1020         $d .= indent_for($level) . th_pfx($level);
1021         my $upfx = $ctx->{-upfx};
1022         my $href = $upfx . mid_href($mid) . '/';
1023         my $html = ascii_html($mid);
1024
1025         my $mapping = $ctx->{mapping};
1026         my $map = $mapping->{$mid} if $mapping;
1027         if ($map) {
1028                 my $id = id_compress($mid, 1);
1029                 $map->[0] = $d . qq{&lt;<a\nhref=#r$id>$html</a>&gt;\n};
1030                 $d .= qq{&lt;<a\nhref="$href"\nid=r$id>$html</a>&gt;\n};
1031         } else {
1032                 $d .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
1033         }
1034         ${$ctx->{skel}} .= $d;
1035         1;
1036 }
1037
1038 sub sort_ds {
1039         @{$_[0]} = sort {
1040                 (eval { $a->topmost->{ds} } || 0) <=>
1041                 (eval { $b->topmost->{ds} } || 0)
1042         } @{$_[0]};
1043 }
1044
1045 # accumulate recent topics if search is supported
1046 # returns 200 if done, 404 if not
1047 sub acc_topic { # walk_thread callback
1048         my ($ctx, $level, $smsg) = @_;
1049         my $mid = $smsg->{mid};
1050         my $has_blob = $smsg->{blob} // do {
1051                 if (my $by_mid = $ctx->{ibx}->smsg_by_mid($mid)) {
1052                         %$smsg = (%$smsg, %$by_mid);
1053                         1;
1054                 }
1055         };
1056         if ($has_blob) {
1057                 my $subj = subject_normalized($smsg->{subject});
1058                 $subj = '(no subject)' if $subj eq '';
1059                 my $ds = $smsg->{ds};
1060                 if ($level == 0) { # new, top-level topic
1061                         my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1062                         $ctx->{-cur_topic} = $topic;
1063                         push @{$ctx->{order}}, $topic;
1064                         return 1;
1065                 }
1066
1067                 # continue existing topic
1068                 my $topic = $ctx->{-cur_topic}; # should never be undef
1069                 $topic->[0] = $ds if $ds > $topic->[0];
1070                 $topic->[1]++; # bump N+ message counter
1071                 my $seen = $topic->[2];
1072                 if (scalar(@$topic) == 3) { # parent was a ghost
1073                         push @$topic, $subj;
1074                 } elsif (!defined($seen->{$subj})) {
1075                         push @$topic, $level, $subj; # @extra messages
1076                 }
1077                 $seen->{$subj} = $mid; # latest for subject
1078         } else { # ghost message
1079                 return 1 if $level != 0; # ignore child ghosts
1080                 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1081                 push @{$ctx->{order}}, $topic;
1082         }
1083         1;
1084 }
1085
1086 sub dump_topics {
1087         my ($ctx) = @_;
1088         my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1089         unless ($order) {
1090                 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1091                 return 404;
1092         }
1093
1094         my @out;
1095         my $obfs_ibx = $ctx->{ibx}->{obfuscate} ? $ctx->{ibx} : undef;
1096         if (my $note = delete $ctx->{t_note}) {
1097                 push @out, $note; # "messages from ... to ..."
1098         }
1099         # sort by recency, this allows new posts to "bump" old topics...
1100         foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1101                 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1102                 @$topic = ();
1103                 next unless defined $top_subj;  # ghost topic
1104                 my $mid = delete $seen->{$top_subj};
1105                 my $href = mid_href($mid);
1106                 my $prev_subj = [ split(/ /, $top_subj) ];
1107                 $top_subj = ascii_html($top_subj);
1108                 $ds = fmt_ts($ds);
1109
1110                 # $n isn't the total number of posts on the topic,
1111                 # just the number of posts in the current results window
1112                 my $anchor;
1113                 if ($n == 1) {
1114                         $n = '';
1115                         $anchor = '#u'; # top of only message
1116                 } else {
1117                         $n = " ($n+ messages)";
1118                         $anchor = '#t'; # thread skeleton
1119                 }
1120
1121                 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1122                         " $ds UTC $n\n";
1123                 while (@extra) {
1124                         my $level = shift @extra;
1125                         my $subj = shift @extra; # already normalized
1126                         $mid = delete $seen->{$subj};
1127                         my @subj = split(/ /, $subj);
1128                         my @next_prev = @subj; # full copy
1129                         my $omit = dedupe_subject($prev_subj, \@subj, ' &#34;');
1130                         $prev_subj = \@next_prev;
1131                         $subj = join(' ', @subj);
1132                         $subj = ascii_html($subj);
1133                         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1134                         $href = mid_href($mid);
1135                         $s .= indent_for($level) . TCHILD;
1136                         $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1137                 }
1138                 push @out, $s;
1139         }
1140         $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1141         200;
1142 }
1143
1144 sub str2ts ($) {
1145         my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1146         timegm($ss || 0, $mm || 0, $hh || 0, $dd, $mon - 1, $yyyy);
1147 }
1148
1149 sub pagination_footer ($$) {
1150         my ($ctx, $latest) = @_;
1151         my $next = $ctx->{next_page} || '';
1152         my $prev = $ctx->{prev_page} || '';
1153         if ($prev) {  # aligned padding for: 'next (older) | '
1154                 $next = $next ? "$next | " : '             | ';
1155                 $prev .= qq[ | <a\nhref="$latest">latest</a>];
1156         }
1157         ($next || $prev) ? "<hr><pre id=nav>page: $next$prev</pre>" : '';
1158 }
1159
1160 sub paginate_recent ($$) {
1161         my ($ctx, $lim) = @_;
1162         my $t = $ctx->{qp}->{t} || '';
1163         my $opts = { limit => $lim };
1164         my ($after, $before);
1165
1166         # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1167         # if only $after exists "YYYYMMDD.." because "." could be skipped
1168         # if interpreted as an end-of-sentence
1169         $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1170         $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1171
1172         my $msgs = $ctx->{ibx}->over->recent($opts, $after, $before);
1173         if (defined($after) && scalar(@$msgs) < $lim) {
1174                 $after = $before = undef;
1175                 $msgs = $ctx->{ibx}->over->recent($opts);
1176         }
1177         my $more = scalar(@$msgs) == $lim;
1178         my ($newest, $oldest);
1179         if (@$msgs) {
1180                 $newest = $msgs->[0]->{ts};
1181                 $oldest = $msgs->[-1]->{ts};
1182                 # if we only had $after, our SQL query in ->recent ordered
1183                 if ($newest < $oldest) {
1184                         ($oldest, $newest) = ($newest, $oldest);
1185                         $more = undef if defined($after) && $after < $oldest;
1186                 }
1187                 if (defined($after // $before)) {
1188                         my $n = strftime('%Y-%m-%d %H:%M:%S', gmtime($newest));
1189                         my $o = strftime('%Y-%m-%d %H:%M:%S', gmtime($oldest));
1190                         $ctx->{t_note} = <<EOM;
1191  messages from $o to $n UTC [<a href="#nav">more...</a>]
1192 EOM
1193                         my $s = ts2str($newest);
1194                         $ctx->{prev_page} = qq[<a\nhref="?t=$s-"\nrel=prev>] .
1195                                                 'prev (newer)</a>';
1196                 }
1197         }
1198         if (defined($oldest) && $more) {
1199                 my $s = ts2str($oldest);
1200                 $ctx->{next_page} = qq[<a\nhref="?t=$s"\nrel=next>] .
1201                                         'next (older)</a>';
1202         }
1203         $msgs;
1204 }
1205
1206 # GET /$INBOX - top-level inbox view for indexed inboxes
1207 sub index_topics {
1208         my ($ctx) = @_;
1209         my $msgs = paginate_recent($ctx, 200); # 200 is our window
1210         walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic) if @$msgs;
1211         html_oneshot($ctx, dump_topics($ctx), pagination_footer($ctx, '.'));
1212 }
1213
1214 sub thread_adj_level {
1215         my ($ctx, $level) = @_;
1216
1217         my $max = $ctx->{cur_level};
1218         if ($level <= 0) {
1219                 return ('', '') if $max == 0; # flat output
1220
1221                 # reset existing lists
1222                 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1223                 $ctx->{cur_level} = 0;
1224                 ("$beg</ul>", '');
1225         } elsif ($level == $max) { # continue existing list
1226                 qw(<li> </li>);
1227         } elsif ($level < $max) {
1228                 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1229                 $ctx->{cur_level} = $level;
1230                 ("$beg<li>", '</li>');
1231         } else { # ($level > $max) # start a new level
1232                 $ctx->{cur_level} = $level;
1233                 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1234                 ($beg, '</li>');
1235         }
1236 }
1237
1238 sub ghost_index_entry {
1239         my ($ctx, $level, $node) = @_;
1240         my ($beg, $end) = thread_adj_level($ctx,  $level);
1241         $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{mid} // '?')
1242                 . '</pre>' . $end;
1243 }
1244
1245 1;