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