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