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