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