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