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