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