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