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