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