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