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