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