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