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