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