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