]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: add [thread overview] anchor next to Date:
[public-inbox.git] / lib / PublicInbox / View.pm
1 # Copyright (C) 2014-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Used for displaying the HTML web interface.
5 # See Documentation/design_www.txt for this.
6 package PublicInbox::View;
7 use strict;
8 use 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->{ibx}->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->{ibx};
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->{ibx};
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         return thread_eml_entry($ctx, $eml) if $eml;
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->{ibx};
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->{ibx};
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                 # absolute URL (Atom feeds)
595                 if ($ibx->{coderepo}) {
596                         if (index($upfx, '//') >= 0) {
597                                 $spfx = $upfx;
598                                 $spfx =~ s!/([^/]*)/\z!/!;
599                         } else {
600                                 my $n_slash = $upfx =~ tr!/!/!;
601                                 if ($n_slash == 0) {
602                                         $spfx = '../';
603                                 } elsif ($n_slash == 1) {
604                                         $spfx = '';
605                                 } else { # nslash == 2
606                                         $spfx = '../../';
607                                 }
608                         }
609                 }
610                 $ctx->{-spfx} = $spfx;
611         };
612
613         # some editors don't put trailing newlines at the end:
614         $s .= "\n" unless $s =~ /\n\z/s;
615
616         # split off quoted and unquoted blocks:
617         my @sections = PublicInbox::MsgIter::split_quotes($s);
618         undef $s; # free memory
619         if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
620                 # badly-encoded message with $err? tell the world about it!
621                 attach_link($ctx, $ct, $p, $fn, $err);
622                 $$rv .= "\n";
623         }
624         foreach my $cur (@sections) {
625                 if ($cur =~ /\A>/) {
626                         # we use a <span> here to allow users to specify
627                         # their own color for quoted text
628                         $$rv .= qq(<span\nclass="q">);
629                         $$rv .= $l->to_html($cur);
630                         $$rv .= '</span>';
631                 } elsif ($diff) {
632                         flush_diff($ctx, \$cur);
633                 } else {
634                         # regular lines, OK
635                         $$rv .= $l->to_html($cur);
636                 }
637                 undef $cur; # free memory
638         }
639 }
640
641 sub _msg_page_prepare_obuf {
642         my ($eml, $ctx) = @_;
643         my $over = $ctx->{ibx}->over;
644         my $obfs_ibx = $ctx->{-obfs_ibx};
645         my $rv = '';
646         my $mids = mids_for_index($eml);
647         my $nr = $ctx->{nr}++;
648         if ($nr) { # unlikely
649                 $rv .= '<pre>';
650         } else {
651                 $ctx->{first_hdr} = $eml->header_obj;
652                 if ($ctx->{smsg}) {
653                         $rv .=
654 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
655                 }
656                 $rv .= "<pre\nid=b>"; # anchor for body start
657         }
658         $ctx->{-upfx} = '../' if $over;
659         my @title; # (Subject[0], From[0])
660         for my $v ($eml->header('From')) {
661                 my @n = PublicInbox::Address::names($v);
662                 $v = ascii_html($v);
663                 $title[1] //= ascii_html(join(', ', @n));
664                 if ($obfs_ibx) {
665                         obfuscate_addrs($obfs_ibx, $v);
666                         obfuscate_addrs($obfs_ibx, $title[1]);
667                 }
668                 $rv .= "From: $v\n" if $v ne '';
669         }
670         foreach my $h (qw(To Cc)) {
671                 for my $v ($eml->header($h)) {
672                         fold_addresses($v);
673                         $v = ascii_html($v);
674                         obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
675                         $rv .= "$h: $v\n" if $v ne '';
676                 }
677         }
678         my @subj = $eml->header('Subject');
679         if (@subj) {
680                 my $v = ascii_html(shift @subj);
681                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
682                 $rv .= 'Subject: ';
683                 $rv .= $over ? qq(<a\nhref="#r"\nid=t>$v</a>\n) : "$v\n";
684                 $title[0] = $v;
685                 for $v (@subj) { # multi-Subject message :<
686                         $v = ascii_html($v);
687                         obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
688                         $rv .= "Subject: $v\n";
689                 }
690         } else { # dummy anchor for thread skeleton at bottom of page
691                 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
692                 $title[0] = '(no subject)';
693         }
694         for my $v ($eml->header('Date')) {
695                 $v = ascii_html($v);
696                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
697                 $rv .= qq{Date: $v\t<a\nhref="#r">[thread overview]</a>\n};
698         }
699         if (!$nr) { # first (and only) message, common case
700                 $ctx->{-title_html} = join(' - ', @title);
701                 $rv = $ctx->html_top . $rv;
702         }
703         if (scalar(@$mids) == 1) { # common case
704                 my $mhtml = ascii_html($mids->[0]);
705                 $rv .= "Message-ID: &lt;$mhtml&gt; ";
706                 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
707         } else {
708                 # X-Alt-Message-ID can happen if a message is injected from
709                 # public-inbox-nntpd because of multiple Message-ID headers.
710                 my $lnk = PublicInbox::Linkify->new;
711                 my $s = '';
712                 for my $h (qw(Message-ID X-Alt-Message-ID)) {
713                         $s .= "$h: $_\n" for ($eml->header_raw($h));
714                 }
715                 $lnk->linkify_mids('..', \$s, 1);
716                 $rv .= $s;
717         }
718         $rv .= _parent_headers($eml, $over);
719         $rv .= "\n";
720         \$rv;
721 }
722
723 sub SKEL_EXPAND () {
724         qq(expand[<a\nhref="T/#u">flat</a>) .
725                 qq(|<a\nhref="t/#u">nested</a>]  ) .
726                 qq(<a\nhref="t.mbox.gz">mbox.gz</a>  ) .
727                 qq(<a\nhref="t.atom">Atom feed</a>);
728 }
729
730 sub thread_skel ($$$) {
731         my ($skel, $ctx, $hdr) = @_;
732         my $mid = mids($hdr)->[0];
733         my $ibx = $ctx->{ibx};
734         my ($nr, $msgs) = $ibx->over->get_thread($mid);
735         my $parent = in_reply_to($hdr);
736         $$skel .= "\n<b>Thread overview: </b>";
737         if ($nr <= 1) {
738                 if (defined $parent) {
739                         $$skel .= SKEL_EXPAND."\n ";
740                         $$skel .= ghost_parent('../', $parent) . "\n";
741                 } else {
742                         $$skel .= "<a\nid=r>[no followups]</a> ".
743                                         SKEL_EXPAND."\n";
744                 }
745                 $ctx->{next_msg} = undef;
746                 $ctx->{parent_msg} = $parent;
747                 return;
748         }
749
750         $$skel .= $nr;
751         $$skel .= '+ messages / '.SKEL_EXPAND.qq!  <a\nhref="#b">top</a>\n!;
752
753         # nb: mutt only shows the first Subject in the index pane
754         # when multiple Subject: headers are present, so we follow suit:
755         my $subj = $hdr->header('Subject') // '';
756         $subj = '(no subject)' if $subj eq '';
757         $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
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 sub _parent_headers {
771         my ($hdr, $over) = @_;
772         my $rv = '';
773         my @irt = $hdr->header_raw('In-Reply-To');
774         my $refs;
775         if (@irt) {
776                 my $lnk = PublicInbox::Linkify->new;
777                 $rv .= "In-Reply-To: $_\n" for @irt;
778                 $lnk->linkify_mids('..', \$rv);
779         } else {
780                 $refs = references($hdr);
781                 my $irt = pop @$refs;
782                 if (defined $irt) {
783                         my $html = ascii_html($irt);
784                         my $href = mid_href($irt);
785                         $rv .= "In-Reply-To: &lt;";
786                         $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
787                 }
788         }
789
790         # do not display References: if search is present,
791         # we show the thread skeleton at the bottom, instead.
792         return $rv if $over;
793
794         $refs //= references($hdr);
795         if (@$refs) {
796                 @$refs = map { linkify_ref_no_over($_) } @$refs;
797                 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
798         }
799         $rv;
800 }
801
802 # returns a string buffer
803 sub html_footer {
804         my ($ctx, $hdr) = @_;
805         my $ibx = $ctx->{ibx};
806         my $upfx = '../';
807         my $skel;
808         my $rv = '<pre>';
809         if ($ibx->over) {
810                 my $t = ts2str($ctx->{-t_max});
811                 my $t_fmt = fmt_ts($ctx->{-t_max});
812                 $skel .= <<EOF;
813         other threads:[<a
814 href="$upfx?t=$t">~$t_fmt UTC</a>|<a
815 href="$upfx">newest</a>]
816 EOF
817
818                 thread_skel(\$skel, $ctx, $hdr);
819                 my ($next, $prev);
820                 my $parent = '       ';
821                 $next = $prev = '    ';
822
823                 if (my $n = $ctx->{next_msg}) {
824                         $n = mid_href($n);
825                         $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
826                 }
827                 my $u;
828                 my $par = $ctx->{parent_msg};
829                 if ($par) {
830                         $u = mid_href($par);
831                         $u = "$upfx$u/";
832                 }
833                 if (my $p = $ctx->{prev_msg}) {
834                         $prev = mid_href($p);
835                         if ($p && $par && $p eq $par) {
836                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
837                                         'rel=prev>prev parent</a>';
838                                 $parent = '';
839                         } else {
840                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
841                                         'rel=prev>prev</a>';
842                                 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
843                         }
844                 } elsif ($u) { # unlikely
845                         $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
846                 }
847                 $rv .= "$next $prev$parent ";
848         } else { # unindexed inboxes w/o over
849                 $skel = qq( <a\nhref="$upfx">latest</a>);
850         }
851         $rv .= qq(<a\nhref="#R">reply</a>);
852         $rv .= $skel;
853         $rv .= '</pre>';
854         $rv .= msg_reply($ctx, $hdr);
855 }
856
857 sub linkify_ref_no_over {
858         my ($mid) = @_;
859         my $href = mid_href($mid);
860         my $html = ascii_html($mid);
861         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
862 }
863
864 sub anchor_for {
865         my ($msgid) = @_;
866         'm' . id_compress($msgid, 1);
867 }
868
869 sub ghost_parent {
870         my ($upfx, $mid) = @_;
871
872         my $href = mid_href($mid);
873         my $html = ascii_html($mid);
874         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
875 }
876
877 sub indent_for {
878         my ($level) = @_;
879         $level ? INDENT x ($level - 1) : '';
880 }
881
882 sub find_mid_root {
883         my ($ctx, $level, $node, $idx) = @_;
884         ++$ctx->{root_idx} if $level == 0;
885         if ($node->{mid} eq $ctx->{mid}) {
886                 $ctx->{found_mid_at} = $ctx->{root_idx};
887                 return 0; # stop iterating
888         }
889         1;
890 }
891
892 sub strict_loose_note ($) {
893         my ($nr) = @_;
894         my $msg =
895 "  -- strict thread matches above, loose matches on Subject: below --\n";
896
897         if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
898                 $msg .=
899 "  -- use mbox.gz link to download all $nr messages --\n";
900         }
901         $msg;
902 }
903
904 sub thread_results {
905         my ($ctx, $msgs) = @_;
906         require PublicInbox::SearchThread;
907         my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
908
909         # FIXME: `tid' is broken on --reindex, so that needs to be fixed
910         # and preserved in the future.  This bug is hidden by `sid' matches
911         # in get_thread, so we never noticed it until now.  And even when
912         # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
913         # bump since reindexing is expensive and users may not do it
914
915         # loose threading could've returned too many results,
916         # put the root the message we care about at the top:
917         my $mid = $ctx->{mid};
918         if (defined($mid) && scalar(@$rootset) > 1) {
919                 $ctx->{root_idx} = -1;
920                 my $nr = scalar @$msgs;
921                 walk_thread($rootset, $ctx, \&find_mid_root);
922                 my $idx = $ctx->{found_mid_at};
923                 if (defined($idx) && $idx != 0) {
924                         my $tip = splice(@$rootset, $idx, 1);
925                         @$rootset = reverse @$rootset;
926                         unshift @$rootset, $tip;
927                         $ctx->{sl_note} = strict_loose_note($nr);
928                 }
929         }
930         $rootset
931 }
932
933 sub missing_thread {
934         my ($ctx) = @_;
935         require PublicInbox::ExtMsg;
936         PublicInbox::ExtMsg::ext_msg($ctx);
937 }
938
939 sub dedupe_subject {
940         my ($prev_subj, $subj, $val) = @_;
941
942         my $omit; # '"' denotes identical text omitted
943         my (@prev_pop, @curr_pop);
944         while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
945                 push(@prev_pop, pop(@$prev_subj));
946                 push(@curr_pop, pop(@$subj));
947                 $omit //= $val;
948         }
949         pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
950         if (scalar(@curr_pop) == 1) {
951                 $omit = undef;
952                 push @$prev_subj, @prev_pop;
953                 push @$subj, @curr_pop;
954         }
955         $omit // '';
956 }
957
958 sub skel_dump { # walk_thread callback
959         my ($ctx, $level, $smsg) = @_;
960         $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
961
962         my $skel = $ctx->{skel};
963         my $cur = $ctx->{cur};
964         my $mid = $smsg->{mid};
965
966         if ($level == 0 && $ctx->{skel_dump_roots}++) {
967                 $$skel .= delete($ctx->{sl_note}) || '';
968         }
969
970         my $f = ascii_html($smsg->{from_name});
971         my $obfs_ibx = $ctx->{-obfs_ibx};
972         obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
973
974         my $d = fmt_ts($smsg->{ds});
975         my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
976         if (exists $ctx->{searchview}) {
977                 if (defined(my $pct = $smsg->{pct})) {
978                         $d .= (sprintf(' % 2u', $pct) . '%');
979                 } else {
980                         $unmatched = 1;
981                         $d .= '    ';
982                 }
983         }
984         $d .= ' ' . indent_for($level) . th_pfx($level);
985         my $attr = $f;
986         $ctx->{first_level} ||= $level;
987
988         if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
989                 $ctx->{prev_attr} = $attr;
990         }
991         $ctx->{prev_level} = $level;
992
993         if ($cur) {
994                 if ($cur eq $mid) {
995                         delete $ctx->{cur};
996                         $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
997                                  "$attr [this message]</a></b>\n";
998                         return 1;
999                 } else {
1000                         $ctx->{prev_msg} = $mid;
1001                 }
1002         } else {
1003                 $ctx->{next_msg} ||= $mid;
1004         }
1005
1006         # Subject is never undef, this mail was loaded from
1007         # our Xapian which would've resulted in '' if it were
1008         # really missing (and Filter rejects empty subjects)
1009         my @subj = split(/ /, subject_normalized($smsg->{subject}));
1010         # remove common suffixes from the subject if it matches the previous,
1011         # so we do not show redundant text at the end.
1012         my $prev_subj = $ctx->{prev_subj} || [];
1013         $ctx->{prev_subj} = [ @subj ];
1014         my $omit = dedupe_subject($prev_subj, \@subj, '&#34; ');
1015         my $end;
1016         if (@subj) {
1017                 my $subj = join(' ', @subj);
1018                 $subj = ascii_html($subj);
1019                 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1020                 $end = "$subj</a> $omit$f\n"
1021         } else {
1022                 $end = "$f</a>\n";
1023         }
1024         my $m;
1025         my $id = '';
1026         my $mapping = $unmatched ? undef : $ctx->{mapping};
1027         if ($mapping) {
1028                 my $map = $mapping->{$mid};
1029                 $id = id_compress($mid, 1);
1030                 $m = '#m'.$id;
1031                 $map->[0] = "$d<a\nhref=\"$m\">$end";
1032                 $id = "\nid=r".$id;
1033         } else {
1034                 $m = $ctx->{-upfx}.mid_href($mid).'/';
1035         }
1036         $$skel .=  $d . "<a\nhref=\"$m\"$id>" . $end;
1037         1;
1038 }
1039
1040 sub _skel_ghost {
1041         my ($ctx, $level, $node) = @_;
1042
1043         my $mid = $node->{mid};
1044         my $d = '     [not found] ';
1045         $d .= '    '  if exists $ctx->{searchview};
1046         $d .= indent_for($level) . th_pfx($level);
1047         my $upfx = $ctx->{-upfx};
1048         my $href = $upfx . mid_href($mid) . '/';
1049         my $html = ascii_html($mid);
1050
1051         my $mapping = $ctx->{mapping};
1052         my $map = $mapping->{$mid} if $mapping;
1053         if ($map) {
1054                 my $id = id_compress($mid, 1);
1055                 $map->[0] = $d . qq{&lt;<a\nhref=#r$id>$html</a>&gt;\n};
1056                 $d .= qq{&lt;<a\nhref="$href"\nid=r$id>$html</a>&gt;\n};
1057         } else {
1058                 $d .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
1059         }
1060         ${$ctx->{skel}} .= $d;
1061         1;
1062 }
1063
1064 sub sort_ds {
1065         [ sort {
1066                 (eval { $a->topmost->{ds} } || 0) <=>
1067                 (eval { $b->topmost->{ds} } || 0)
1068         } @{$_[0]} ];
1069 }
1070
1071 # accumulate recent topics if search is supported
1072 # returns 200 if done, 404 if not
1073 sub acc_topic { # walk_thread callback
1074         my ($ctx, $level, $smsg) = @_;
1075         my $mid = $smsg->{mid};
1076         my $has_blob = $smsg->{blob} // do {
1077                 if (my $by_mid = $ctx->{ibx}->smsg_by_mid($mid)) {
1078                         %$smsg = (%$smsg, %$by_mid);
1079                         1;
1080                 }
1081         };
1082         if ($has_blob) {
1083                 my $subj = subject_normalized($smsg->{subject});
1084                 $subj = '(no subject)' if $subj eq '';
1085                 my $ds = $smsg->{ds};
1086                 if ($level == 0) { # new, top-level topic
1087                         my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1088                         $ctx->{-cur_topic} = $topic;
1089                         push @{$ctx->{order}}, $topic;
1090                         return 1;
1091                 }
1092
1093                 # continue existing topic
1094                 my $topic = $ctx->{-cur_topic}; # should never be undef
1095                 $topic->[0] = $ds if $ds > $topic->[0];
1096                 $topic->[1]++; # bump N+ message counter
1097                 my $seen = $topic->[2];
1098                 if (scalar(@$topic) == 3) { # parent was a ghost
1099                         push @$topic, $subj;
1100                 } elsif (!defined($seen->{$subj})) {
1101                         push @$topic, $level, $subj; # @extra messages
1102                 }
1103                 $seen->{$subj} = $mid; # latest for subject
1104         } else { # ghost message
1105                 return 1 if $level != 0; # ignore child ghosts
1106                 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1107                 push @{$ctx->{order}}, $topic;
1108         }
1109         1;
1110 }
1111
1112 sub dump_topics {
1113         my ($ctx) = @_;
1114         my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1115         unless ($order) {
1116                 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1117                 return 404;
1118         }
1119
1120         my @out;
1121         my $ibx = $ctx->{ibx};
1122         my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1123
1124         # sort by recency, this allows new posts to "bump" old topics...
1125         foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1126                 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1127                 @$topic = ();
1128                 next unless defined $top_subj;  # ghost topic
1129                 my $mid = delete $seen->{$top_subj};
1130                 my $href = mid_href($mid);
1131                 my $prev_subj = [ split(/ /, $top_subj) ];
1132                 $top_subj = ascii_html($top_subj);
1133                 $ds = fmt_ts($ds);
1134
1135                 # $n isn't the total number of posts on the topic,
1136                 # just the number of posts in the current results window
1137                 my $anchor;
1138                 if ($n == 1) {
1139                         $n = '';
1140                         $anchor = '#u'; # top of only message
1141                 } else {
1142                         $n = " ($n+ messages)";
1143                         $anchor = '#t'; # thread skeleton
1144                 }
1145
1146                 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1147                 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1148                 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1149                         " $ds UTC $n - $mbox / $atom\n";
1150                 for (my $i = 0; $i < scalar(@extra); $i += 2) {
1151                         my $level = $extra[$i];
1152                         my $subj = $extra[$i + 1]; # already normalized
1153                         $mid = delete $seen->{$subj};
1154                         my @subj = split(/ /, $subj);
1155                         my @next_prev = @subj; # full copy
1156                         my $omit = dedupe_subject($prev_subj, \@subj, ' &#34;');
1157                         $prev_subj = \@next_prev;
1158                         $subj = join(' ', @subj);
1159                         $subj = ascii_html($subj);
1160                         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1161                         $href = mid_href($mid);
1162                         $s .= indent_for($level) . TCHILD;
1163                         $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1164                 }
1165                 push @out, $s;
1166         }
1167         $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1168         200;
1169 }
1170
1171 sub str2ts ($) {
1172         my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1173         timegm($ss || 0, $mm || 0, $hh || 0, $dd, $mon - 1, $yyyy);
1174 }
1175
1176 sub pagination_footer ($$) {
1177         my ($ctx, $latest) = @_;
1178         my $next = $ctx->{next_page} || '';
1179         my $prev = $ctx->{prev_page} || '';
1180         if ($prev) {  # aligned padding for: 'next (older) | '
1181                 $next = $next ? "$next | " : '             | ';
1182                 $prev .= qq[ | <a\nhref="$latest">latest</a>];
1183         }
1184         "<hr><pre>page: $next$prev</pre>";
1185 }
1186
1187 sub paginate_recent ($$) {
1188         my ($ctx, $lim) = @_;
1189         my $t = $ctx->{qp}->{t} || '';
1190         my $opts = { limit => $lim };
1191         my ($after, $before);
1192
1193         # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1194         # if only $after exists "YYYYMMDD.." because "." could be skipped
1195         # if interpreted as an end-of-sentence
1196         $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1197         $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1198
1199         my $ibx = $ctx->{ibx};
1200         my $msgs = $ibx->recent($opts, $after, $before);
1201         my $nr = scalar @$msgs;
1202         if ($nr < $lim && defined($after)) {
1203                 $after = $before = undef;
1204                 $msgs = $ibx->recent($opts);
1205                 $nr = scalar @$msgs;
1206         }
1207         my $more = $nr == $lim;
1208         my ($newest, $oldest);
1209         if ($nr) {
1210                 $newest = $msgs->[0]->{ts};
1211                 $oldest = $msgs->[-1]->{ts};
1212                 # if we only had $after, our SQL query in ->recent ordered
1213                 if ($newest < $oldest) {
1214                         ($oldest, $newest) = ($newest, $oldest);
1215                         $more = 0 if defined($after) && $after < $oldest;
1216                 }
1217         }
1218         if (defined($oldest) && $more) {
1219                 my $s = ts2str($oldest);
1220                 $ctx->{next_page} = qq[<a\nhref="?t=$s"\nrel=next>] .
1221                                         'next (older)</a>';
1222         }
1223         if (defined($newest) && (defined($before) || defined($after))) {
1224                 my $s = ts2str($newest);
1225                 $ctx->{prev_page} = qq[<a\nhref="?t=$s-"\nrel=prev>] .
1226                                         'prev (newer)</a>';
1227         }
1228         $msgs;
1229 }
1230
1231 # GET /$INBOX - top-level inbox view for indexed inboxes
1232 sub index_topics {
1233         my ($ctx) = @_;
1234         my $msgs = paginate_recent($ctx, 200); # 200 is our window
1235         if (@$msgs) {
1236                 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1237         }
1238         html_oneshot($ctx, dump_topics($ctx), \pagination_footer($ctx, '.'));
1239
1240 }
1241
1242 sub thread_adj_level {
1243         my ($ctx, $level) = @_;
1244
1245         my $max = $ctx->{cur_level};
1246         if ($level <= 0) {
1247                 return ('', '') if $max == 0; # flat output
1248
1249                 # reset existing lists
1250                 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1251                 $ctx->{cur_level} = 0;
1252                 ("$beg</ul>", '');
1253         } elsif ($level == $max) { # continue existing list
1254                 qw(<li> </li>);
1255         } elsif ($level < $max) {
1256                 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1257                 $ctx->{cur_level} = $level;
1258                 ("$beg<li>", '</li>');
1259         } else { # ($level > $max) # start a new level
1260                 $ctx->{cur_level} = $level;
1261                 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1262                 ($beg, '</li>');
1263         }
1264 }
1265
1266 sub ghost_index_entry {
1267         my ($ctx, $level, $node) = @_;
1268         my ($beg, $end) = thread_adj_level($ctx,  $level);
1269         $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{mid})
1270                 . '</pre>' . $end;
1271 }
1272
1273 1;