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