1 # Copyright (C) 2014-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Used for displaying the HTML web interface.
5 # See Documentation/design_www.txt for this.
6 package PublicInbox::View;
9 use bytes (); # only for bytes::length
10 use PublicInbox::MsgTime qw(msg_datestamp);
11 use PublicInbox::Hval qw(ascii_html obfuscate_addrs prurl);
12 use PublicInbox::Linkify;
13 use PublicInbox::MID qw/id_compress mid_escape mids mids_for_index references/;
14 use PublicInbox::MsgIter;
15 use PublicInbox::Address;
16 use PublicInbox::WwwStream;
17 use PublicInbox::Reply;
18 use PublicInbox::ViewDiff qw(flush_diff);
19 use POSIX qw(strftime);
20 use Time::Local qw(timegm);
21 use PublicInbox::SearchMsg qw(subject_normalized);
22 use constant COLS => 72;
23 use constant INDENT => ' ';
24 use constant TCHILD => '` ';
25 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
29 my $more = $ctx->{more};
31 # $more cannot be true w/o $smsg being defined:
32 my $upfx = $more ? '../'.mid_escape($ctx->{smsg}->mid).'/' : '';
33 multipart_text_as_html(delete $ctx->{mime}, $upfx, $ctx);
34 ${delete $ctx->{obuf}} .= '</pre><hr>';
37 # fake an EOF if {more} retrieval fails fails;
38 eval { msg_page_more($ctx, $nr) };
39 } elsif ($nr == $ctx->{end_nr}) {
40 # fake an EOF if generating the footer fails;
41 # we want to at least show the message if something
43 eval { html_footer($ctx) };
49 # public functions: (unstable)
53 my $mid = $ctx->{mid};
54 my $ibx = $ctx->{-inbox};
57 if (my $over = $ibx->over) {
59 $smsg = $over->next_by_mid($mid, \$id, \$prev);
60 $first = $ibx->msg_by_smsg($smsg) if $smsg;
62 my $next = $over->next_by_mid($mid, \$id, \$prev);
63 $ctx->{more} = [ $id, $prev, $next ] if $next;
67 $first = $ibx->msg_by_mid($mid) or return;
69 my $mime = $ctx->{mime} = PublicInbox::MIME->new($first);
70 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
71 my $hdr = $ctx->{hdr} = $mime->header_obj;
72 _msg_page_prepare_obuf($hdr, $ctx, 0);
75 PublicInbox::WwwStream->response($ctx, 200, \&msg_page_i);
80 my ($id, $prev, $smsg) = @{$ctx->{more}};
81 my $ibx = $ctx->{-inbox};
82 $smsg = $ibx->smsg_mime($smsg);
83 my $next = $ibx->over->next_by_mid($ctx->{mid}, \$id, \$prev);
84 $ctx->{more} = $next ? [ $id, $prev, $next ] : undef;
85 return '' unless $smsg;
86 my $upfx = '../' . mid_escape($smsg->mid) . '/';
87 my $mime = delete $smsg->{mime};
88 _msg_page_prepare_obuf($mime->header_obj, $ctx, $nr);
89 multipart_text_as_html($mime, $upfx, $ctx);
90 ${delete $ctx->{obuf}} .= '</pre><hr>';
93 # /$INBOX/$MESSAGE_ID/#R
97 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
99 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
102 my $ibx = $ctx->{-inbox};
103 if (my $url = $ibx->{infourl}) {
104 $url = prurl($ctx->{env}, $url);
105 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
108 my ($arg, $link, $reply_to_all) =
109 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
110 if (ref($arg) eq 'SCALAR') {
111 return '<pre id=R>'.ascii_html($$arg).'</pre>';
114 # mailto: link only works if address obfuscation is disabled
118 * If your mail client supports setting the <b>In-Reply-To</b> header
119 via mailto: links, try the <a
120 href="$link">mailto: link</a>
124 push @$arg, '/path/to/YOUR_REPLY';
125 $arg = ascii_html(join(" \\\n ", '', @$arg));
128 id=R><b>Reply instructions:</b>
130 You may reply publicly to <a
131 href=#t>this message</a> via plain-text email
132 using any one of the following methods:
134 * Save the following mbox file, import it into your mail client,
135 and $reply_to_all from there: <a
138 Avoid top-posting and favor interleaved quoting:
140 href="$p_url">$p_url</a>
142 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
143 switches of git-send-email(1):
148 href="$se_url">$se_url</a>
155 my $refs = references($hdr);
159 sub fold_addresses ($) {
160 return $_[0] if length($_[0]) <= COLS;
161 # try to fold on commas after non-word chars before $lim chars,
162 # Try to get the "," preceeded by ">" or ")", but avoid folding
163 # on the comma where somebody uses "Lastname, Firstname".
164 # We also try to keep the last and penultimate addresses in
165 # the list on the same line if possible, hence the extra \z
166 # Fall back to folding on spaces at $lim + 1 chars
167 my $lim = COLS - 8; # 8 = "\t" display width
168 my $too_long = $lim + 1;
169 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
171 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
174 .{$too_long,}?)(?:\s|\z)/xgo));
177 sub _hdr_names_html ($$) {
178 my ($hdr, $field) = @_;
179 my @vals = $hdr->header($field) or return '';
180 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
184 my ($nr, $singular, $plural) = @_;
185 return "0 $plural" if $nr == 0;
186 $nr == 1 ? "$nr $singular" : "$nr $plural";
189 # human-friendly format
190 sub fmt_ts ($) { strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
192 # this is already inside a <pre>
194 my ($smsg, $ctx, $more) = @_;
195 my $subj = $smsg->subject;
196 my $mid_raw = $smsg->mid;
197 my $id = id_compress($mid_raw, 1);
200 my $root_anchor = $ctx->{root_anchor} || '';
202 my $obfs_ibx = $ctx->{-obfs_ibx};
204 $subj = '(no subject)' if $subj eq '';
205 my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
206 $subj = '<b>'.ascii_html($subj).'</b>';
207 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
208 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
210 $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
212 my $ds = $smsg->ds; # for v1 non-Xapian/SQLite users
213 # deleting {mime} is critical to memory use,
214 # the rest of the fields saves about 400K as we iterate across 1K msgs
215 my ($mime) = delete @$smsg{qw(mime ds ts blob subject)};
217 my $hdr = $mime->header_obj;
218 my $from = _hdr_names_html($hdr, 'From');
219 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
220 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
221 my $upfx = $ctx->{-upfx};
222 my $mhref = $upfx . mid_escape($mid_raw) . '/';
223 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
224 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
225 my $to = fold_addresses(_hdr_names_html($hdr, 'To'));
226 my $cc = fold_addresses(_hdr_names_html($hdr, 'Cc'));
227 my ($tlen, $clen) = (length($to), length($cc));
229 if (($tlen + $clen) > COLS) {
230 $to_cc .= ' To: '.$to."\n" if $tlen;
231 $to_cc .= ' Cc: '.$cc."\n" if $clen;
234 $to_cc .= ' To: '.$to;
235 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
237 $to_cc .= ' Cc: '.$cc if $clen;
241 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
244 my $mapping = $ctx->{mapping};
245 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
246 my $mirt = PublicInbox::Hval->new_msgid($irt);
247 my $href = $upfx . $mirt->{href}. '/';
248 my $html = $mirt->as_html;
249 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
253 # scan through all parts, looking for displayable text
254 $ctx->{mhref} = $mhref;
256 msg_iter($mime, \&add_text_body, $ctx, 1);
260 $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
261 "<a\nhref=\"$mhref\">permalink</a>" .
262 " <a\nhref=\"${mhref}raw\">raw</a>" .
263 " <a\nhref=\"${mhref}#R\">reply</a>";
266 if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
267 $rv .= "\t[relevance $pct%]";
270 my $nested = 'nested';
275 $flat = "<b>$flat</b>";
277 $nested = "<b>$nested</b>";
279 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
280 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
281 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
286 $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
290 sub pad_link ($$;$) {
291 my ($mid, $level, $s) = @_;
293 my $id = id_compress($mid, 1);
294 (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
298 my ($mid_raw, $irt, $id, $ctx) = @_;
300 my $mapping = $ctx->{mapping} or return $rv;
302 my $mid_map = $mapping->{$mid_raw};
304 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
305 my ($attr, $node, $idx, $level) = @$mid_map;
306 my $children = $node->{children};
307 my $nr_c = scalar @$children;
310 if (my $smsg = $node->{smsg}) {
311 # delete saves about 200KB on a 1K message thread
312 if (my $refs = delete $smsg->{references}) {
313 ($$irt) = ($refs =~ m/<([^>]+)>\z/);
316 my $irt_map = $mapping->{$$irt} if defined $$irt;
317 if (defined $irt_map) {
318 $siblings = $irt_map->[1]->{children};
319 $nr_s = scalar(@$siblings) - 1;
320 $rv .= $pad . $irt_map->[0];
322 my $prev = $siblings->[$idx - 1];
323 my $pmid = $prev->{id};
325 my $s = ($idx - 1). ' preceding siblings ...';
326 $rv .= pad_link($pmid, $level, $s);
327 } elsif ($idx == 2) {
328 my $ppmid = $siblings->[0]->{id};
329 $rv .= $pad . $mapping->{$ppmid}->[0];
331 $rv .= $pad . $mapping->{$pmid}->[0];
334 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
335 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
336 $attr =~ s!\n\z!</b>\n!s;
337 $attr =~ s!<a\nhref.*</a> !!s; # no point in duplicating subject
338 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
341 my $cmid = $children->[0]->{id};
342 $rv .= $pad . $mapping->{$cmid}->[0];
344 my $s = ($nr_c - 1). ' more replies';
345 $rv .= pad_link($cmid, $level + 1, $s);
346 } elsif (my $cn = $children->[1]) {
347 $rv .= $pad . $mapping->{$cn->{id}}->[0];
351 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
353 my $nmid = $next->{id};
354 $rv .= $pad . $mapping->{$nmid}->[0];
355 my $nnext = $nr_s - $idx;
357 my $s = ($nnext - 1).' subsequent siblings';
358 $rv .= pad_link($nmid, $level, $s);
359 } elsif (my $nn = $siblings->[$idx + 2]) {
360 $rv .= $pad . $mapping->{$nn->{id}}->[0];
363 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
366 # non-recursive thread walker
367 sub walk_thread ($$$) {
368 my ($rootset, $ctx, $cb) = @_;
369 my @q = map { (0, $_, -1) } @$rootset;
371 my ($level, $node, $i) = splice(@q, 0, 3);
372 defined $node or next;
373 $cb->($ctx, $level, $node, $i) or return;
376 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
380 sub pre_thread { # walk_thread callback
381 my ($ctx, $level, $node, $idx) = @_;
382 $ctx->{mapping}->{$node->{id}} = [ '', $node, $idx, $level ];
383 skel_dump($ctx, $level, $node);
386 sub thread_index_entry {
387 my ($ctx, $level, $smsg) = @_;
388 my ($beg, $end) = thread_adj_level($ctx, $level);
389 $beg . '<pre>' . index_entry($smsg, $ctx, 0) . '</pre>' . $end;
392 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
394 return unless exists($ctx->{skel});
395 my $q = $ctx->{-queue};
397 my $level = shift @$q;
398 my $node = shift @$q or next;
400 unshift @$q, map { ($cl, $_) } @{$node->{children}};
401 if (my $smsg = $ctx->{-inbox}->smsg_mime($node->{smsg})) {
402 return thread_index_entry($ctx, $level, $smsg);
404 return ghost_index_entry($ctx, $level, $node);
407 join('', thread_adj_level($ctx, 0)) . ${delete $ctx->{skel}};
410 sub stream_thread ($$) {
411 my ($rootset, $ctx) = @_;
412 my $ibx = $ctx->{-inbox};
413 my @q = map { (0, $_) } @$rootset;
417 my $node = shift @q or next;
419 unshift @q, map { ($cl, $_) } @{$node->{children}};
420 $smsg = $ibx->smsg_mime($node->{smsg}) and last;
422 return missing_thread($ctx) unless $smsg;
424 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
425 $ctx->{-title_html} = ascii_html($smsg->subject);
426 $ctx->{-html_tip} = thread_index_entry($ctx, $level, $smsg);
427 $ctx->{-queue} = \@q;
428 PublicInbox::WwwStream->response($ctx, 200, \&stream_thread_i);
431 # /$INBOX/$MESSAGE_ID/t/
434 my $mid = $ctx->{mid};
435 my $ibx = $ctx->{-inbox};
436 my ($nr, $msgs) = $ibx->over->get_thread($mid);
437 return missing_thread($ctx) if $nr == 0;
438 my $skel = '<hr><pre>';
439 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
440 $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
441 $skel .= "<b\nid=t>Thread overview:</b> ";
442 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
443 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
444 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
445 $skel .= "-- links below jump to the message on this page --\n";
446 $ctx->{-upfx} = '../../';
447 $ctx->{cur_level} = 0;
448 $ctx->{skel} = \$skel;
449 $ctx->{prev_attr} = '';
450 $ctx->{prev_level} = 0;
451 $ctx->{root_anchor} = anchor_for($mid);
452 $ctx->{mapping} = {};
453 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
456 my $rootset = thread_results($ctx, $msgs);
458 # reduce hash lookups in pre_thread->skel_dump
459 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
460 walk_thread($rootset, $ctx, \&pre_thread);
463 return stream_thread($rootset, $ctx) unless $ctx->{flat};
465 # flat display: lazy load the full message from smsg
467 while (my $m = shift @$msgs) {
468 $smsg = $ibx->smsg_mime($m) and last;
470 return missing_thread($ctx) unless $smsg;
471 $ctx->{-title_html} = ascii_html($smsg->subject);
472 $ctx->{-html_tip} = '<pre>'.index_entry($smsg, $ctx, scalar @$msgs);
473 $ctx->{msgs} = $msgs;
474 PublicInbox::WwwStream->response($ctx, 200, \&thread_html_i);
477 sub thread_html_i { # PublicInbox::WwwStream::getline callback
479 my $msgs = $ctx->{msgs} or return;
480 while (my $smsg = shift @$msgs) {
481 $ctx->{-inbox}->smsg_mime($smsg) or next;
482 return index_entry($smsg, $ctx, scalar @$msgs);
484 my ($skel) = delete @$ctx{qw(skel msgs)};
488 sub multipart_text_as_html {
489 my (undef, $mhref, $ctx) = @_; # $mime = $_[0]
490 $ctx->{mhref} = $mhref;
492 # scan through all parts, looking for displayable text
493 msg_iter($_[0], \&add_text_body, $ctx, 1);
497 my ($s, $l, $quot) = @_;
499 my $rv = $l->to_html($$quot);
501 # we use a <span> here to allow users to specify their own
502 # color for quoted text
504 $$s .= qq(<span\nclass="q">) . $rv . '</span>'
507 sub attach_link ($$$$;$) {
508 my ($ctx, $ct, $p, $fn, $err) = @_;
509 my ($part, $depth, @idx) = @$p;
510 my $nl = $idx[-1] > 1 ? "\n" : '';
511 my $idx = join('.', @idx);
512 my $size = bytes::length($part->body);
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 $desc = $part->header('Content-Description');
519 $desc = $fn unless defined $desc;
520 $desc = '' unless defined $desc;
522 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
524 } elsif ($ct eq 'text/plain') {
529 my $rv = $ctx->{obuf};
530 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
532 $$rv .= "[-- Warning: decoded text below may be mangled --]\n";
534 $$rv .= "[-- Attachment #$idx: ";
535 my $ts = "Type: $ct, Size: $size bytes";
536 $desc = ascii_html($desc);
537 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
542 sub add_text_body { # callback for msg_iter
544 my $upfx = $ctx->{mhref};
545 my $ibx = $ctx->{-inbox};
546 # $p - from msg_iter: [ Email::MIME, depth, @idx ]
547 my ($part, $depth, @idx) = @$p;
548 my $ct = $part->content_type || 'text/plain';
549 my $fn = $part->filename;
550 my ($s, $err) = msg_part_text($part, $ct);
551 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
553 # makes no difference to browsers, and don't screw up filename
554 # link generation in diffs with the extra '%0D'
557 # always support diff-highlighting, but we can't linkify hunk
558 # headers for solver unless some coderepo are configured:
560 if ($s =~ /^(?:diff|---|\+{3}) /ms) {
561 # diffstat anchors do not link across attachments or messages:
562 $idx[0] = $upfx . $idx[0] if $upfx ne '';
563 $ctx->{-apfx} = join('/', @idx);
564 $ctx->{-anchors} = {}; # attr => filename
566 delete $ctx->{-long_path};
568 if ($ibx->{-repo_objs}) {
569 if (index($upfx, '//') >= 0) { # absolute URL (Atom feeds)
571 $spfx =~ s!/([^/]*)/\z!/!;
573 my $n_slash = $upfx =~ tr!/!/!;
576 } elsif ($n_slash == 1) {
578 } else { # nslash == 2
583 $ctx->{-spfx} = $spfx;
586 # some editors don't put trailing newlines at the end:
587 $s .= "\n" unless $s =~ /\n\z/s;
589 # split off quoted and unquoted blocks:
590 my @sections = split(/((?:^>[^\n]*\n)+)/sm, $s);
592 my $rv = $ctx->{obuf};
593 if (defined($fn) || $depth > 0 || $err) {
594 # badly-encoded message with $err? tell the world about it!
595 attach_link($ctx, $ct, $p, $fn, $err);
598 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
599 foreach my $cur (@sections) {
601 flush_quote($rv, $l, \$cur);
603 flush_diff($rv, $ctx, \$cur);
606 $$rv .= $l->to_html($cur);
611 obfuscate_addrs($ibx, $$rv) if $ibx->{obfuscate};
614 sub _msg_page_prepare_obuf {
615 my ($hdr, $ctx, $nr) = @_;
616 my $over = $ctx->{-inbox}->over;
617 my $obfs_ibx = $ctx->{-obfs_ibx};
619 my $mids = mids_for_index($hdr);
623 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
625 $rv .= "<pre\nid=b>"; # anchor for body start
630 $ctx->{-upfx} = '../';
632 my @title; # (Subject[0], From[0])
633 for my $v ($hdr->header('From')) {
634 $v = PublicInbox::Hval->new($v);
635 my @n = PublicInbox::Address::names($v->raw);
636 $title[1] //= ascii_html(join(', ', @n));
639 obfuscate_addrs($obfs_ibx, $v);
640 obfuscate_addrs($obfs_ibx, $title[1]);
642 $rv .= "From: $v\n" if $v ne '';
644 foreach my $h (qw(To Cc)) {
645 for my $v ($hdr->header($h)) {
648 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
649 $rv .= "$h: $v\n" if $v ne '';
652 my @subj = $hdr->header('Subject');
656 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
659 $rv .= qq(<a\nhref="#r"\nid=t>$v</a>\n);
665 } else { # dummy anchor for thread skeleton at bottom of page
666 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
667 $title[0] = '(no subject)';
669 for my $v ($hdr->header('Date')) {
671 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
674 $ctx->{-title_html} = join(' - ', @title);
675 if (scalar(@$mids) == 1) { # common case
676 my $mid = PublicInbox::Hval->new_msgid($mids->[0]);
677 my $mhtml = $mid->as_html;
678 $rv .= "Message-ID: <$mhtml> ";
679 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
681 # X-Alt-Message-ID can happen if a message is injected from
682 # public-inbox-nntpd because of multiple Message-ID headers.
683 my $lnk = PublicInbox::Linkify->new;
685 for my $h (qw(Message-ID X-Alt-Message-ID)) {
686 $s .= "$h: $_\n" for ($hdr->header_raw($h));
688 $lnk->linkify_mids('..', \$s, 1);
691 $rv .= _parent_headers($hdr, $over);
697 qq(expand[<a\nhref="T/#u">flat</a>) .
698 qq(|<a\nhref="t/#u">nested</a>] ) .
699 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
700 qq(<a\nhref="t.atom">Atom feed</a>);
703 sub thread_skel ($$$) {
704 my ($skel, $ctx, $hdr) = @_;
705 my $mid = mids($hdr)->[0];
706 my $ibx = $ctx->{-inbox};
707 my ($nr, $msgs) = $ibx->over->get_thread($mid);
708 my $parent = in_reply_to($hdr);
709 $$skel .= "\n<b>Thread overview: </b>";
711 if (defined $parent) {
712 $$skel .= SKEL_EXPAND."\n ";
713 $$skel .= ghost_parent('../', $parent) . "\n";
715 $$skel .= '[no followups] '.SKEL_EXPAND."\n";
717 $ctx->{next_msg} = undef;
718 $ctx->{parent_msg} = $parent;
723 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
725 # nb: mutt only shows the first Subject in the index pane
726 # when multiple Subject: headers are present, so we follow suit:
727 my $subj = $hdr->header('Subject') // '';
728 $subj = '(no subject)' if $subj eq '';
729 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
731 $ctx->{prev_attr} = '';
732 $ctx->{prev_level} = 0;
733 $ctx->{skel} = $skel;
735 # reduce hash lookups in skel_dump
736 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
737 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
739 $ctx->{parent_msg} = $parent;
742 sub _parent_headers {
743 my ($hdr, $over) = @_;
745 my @irt = $hdr->header_raw('In-Reply-To');
748 my $lnk = PublicInbox::Linkify->new;
749 $rv .= "In-Reply-To: $_\n" for @irt;
750 $lnk->linkify_mids('..', \$rv);
752 $refs = references($hdr);
753 my $irt = pop @$refs;
755 my $v = PublicInbox::Hval->new_msgid($irt);
756 my $html = $v->as_html;
757 my $href = $v->{href};
758 $rv .= "In-Reply-To: <";
759 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
763 # do not display References: if search is present,
764 # we show the thread skeleton at the bottom, instead.
767 $refs //= references($hdr);
769 @$refs = map { linkify_ref_no_over($_) } @$refs;
770 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
775 # returns a string buffer via ->getline
778 my $ibx = $ctx->{-inbox};
779 my $hdr = delete $ctx->{hdr};
781 my $skel = " <a\nhref=\"$upfx\">index</a>";
785 thread_skel(\$skel, $ctx, $hdr);
790 if (my $n = $ctx->{next_msg}) {
791 $n = PublicInbox::Hval->new_msgid($n)->{href};
792 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
795 my $par = $ctx->{parent_msg};
797 $u = PublicInbox::Hval->new_msgid($par)->{href};
800 if (my $p = $ctx->{prev_msg}) {
801 $prev = PublicInbox::Hval->new_msgid($p)->{href};
802 if ($p && $par && $p eq $par) {
803 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
804 'rel=prev>prev parent</a>';
807 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
809 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
811 } elsif ($u) { # unlikely
812 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
814 $rv .= "$next $prev$parent ";
816 $rv .= qq(<a\nhref="#R">reply</a>);
819 $rv .= msg_reply($ctx, $hdr);
822 sub linkify_ref_no_over {
823 my $v = PublicInbox::Hval->new_msgid($_[0]);
824 my $html = $v->as_html;
825 my $href = $v->{href};
826 "<<a\nhref=\"../$href/\">$html</a>>";
831 'm' . id_compress($msgid, 1);
835 my ($upfx, $mid) = @_;
837 $mid = PublicInbox::Hval->new_msgid($mid);
838 my $href = $mid->{href};
839 my $html = $mid->as_html;
840 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
845 $level ? INDENT x ($level - 1) : '';
849 my ($ctx, $level, $node, $idx) = @_;
850 ++$ctx->{root_idx} if $level == 0;
851 if ($node->{id} eq $ctx->{mid}) {
852 $ctx->{found_mid_at} = $ctx->{root_idx};
858 sub strict_loose_note ($) {
861 " -- strict thread matches above, loose matches on Subject: below --\n";
863 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
865 " -- use mbox.gz link to download all $nr messages --\n";
871 my ($ctx, $msgs) = @_;
872 require PublicInbox::SearchThread;
873 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
875 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
876 # and preserved in the future. This bug is hidden by `sid' matches
877 # in get_thread, so we never noticed it until now. And even when
878 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
879 # bump since reindexing is expensive and users may not do it
881 # loose threading could've returned too many results,
882 # put the root the message we care about at the top:
883 my $mid = $ctx->{mid};
884 if (defined($mid) && scalar(@$rootset) > 1) {
885 $ctx->{root_idx} = -1;
886 my $nr = scalar @$msgs;
887 walk_thread($rootset, $ctx, \&find_mid_root);
888 my $idx = $ctx->{found_mid_at};
889 if (defined($idx) && $idx != 0) {
890 my $tip = splice(@$rootset, $idx, 1);
891 @$rootset = reverse @$rootset;
892 unshift @$rootset, $tip;
893 $ctx->{sl_note} = strict_loose_note($nr);
901 require PublicInbox::ExtMsg;
902 PublicInbox::ExtMsg::ext_msg($ctx);
906 my ($prev_subj, $subj, $val) = @_;
908 my $omit = ''; # '"' denotes identical text omitted
909 my (@prev_pop, @curr_pop);
910 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
911 push(@prev_pop, pop(@$prev_subj));
912 push(@curr_pop, pop(@$subj));
915 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
916 if (scalar(@curr_pop) == 1) {
918 push @$prev_subj, @prev_pop;
919 push @$subj, @curr_pop;
924 sub skel_dump { # walk_thread callback
925 my ($ctx, $level, $node) = @_;
926 my $smsg = $node->{smsg} or return _skel_ghost($ctx, $level, $node);
928 my $skel = $ctx->{skel};
929 my $cur = $ctx->{cur};
930 my $mid = $smsg->{mid};
932 if ($level == 0 && $ctx->{skel_dump_roots}++) {
933 $$skel .= delete($ctx->{sl_note}) || '';
936 my $f = ascii_html($smsg->from_name);
937 my $obfs_ibx = $ctx->{-obfs_ibx};
938 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
940 my $d = fmt_ts($smsg->{ds});
941 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
942 if (exists $ctx->{searchview}) {
943 if (defined(my $pct = $smsg->{pct})) {
944 $d .= (sprintf(' % 2u', $pct) . '%');
950 $d .= ' ' . indent_for($level) . th_pfx($level);
952 $ctx->{first_level} ||= $level;
954 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
955 $ctx->{prev_attr} = $attr;
957 $ctx->{prev_level} = $level;
962 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
963 "$attr [this message]</a></b>\n";
966 $ctx->{prev_msg} = $mid;
969 $ctx->{next_msg} ||= $mid;
972 # Subject is never undef, this mail was loaded from
973 # our Xapian which would've resulted in '' if it were
974 # really missing (and Filter rejects empty subjects)
975 my @subj = split(/ /, subject_normalized($smsg->subject));
976 # remove common suffixes from the subject if it matches the previous,
977 # so we do not show redundant text at the end.
978 my $prev_subj = $ctx->{prev_subj} || [];
979 $ctx->{prev_subj} = [ @subj ];
980 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
983 my $subj = join(' ', @subj);
984 $subj = ascii_html($subj);
985 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
986 $end = "$subj</a> $omit$f\n"
992 my $mapping = $unmatched ? undef : $ctx->{mapping};
994 my $map = $mapping->{$mid};
995 $id = id_compress($mid, 1);
997 $map->[0] = "$d<a\nhref=\"$m\">$end";
1000 $m = $ctx->{-upfx}.mid_escape($mid).'/';
1002 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1007 my ($ctx, $level, $node) = @_;
1009 my $mid = $node->{id};
1010 my $d = ' [not found] ';
1011 $d .= ' ' if exists $ctx->{searchview};
1012 $d .= indent_for($level) . th_pfx($level);
1013 my $upfx = $ctx->{-upfx};
1014 my $m = PublicInbox::Hval->new_msgid($mid);
1015 my $href = $upfx . $m->{href} . '/';
1016 my $html = $m->as_html;
1018 my $mapping = $ctx->{mapping};
1019 my $map = $mapping->{$mid} if $mapping;
1021 my $id = id_compress($mid, 1);
1022 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1023 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1025 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1027 ${$ctx->{skel}} .= $d;
1033 (eval { $a->topmost->{smsg}->ds } || 0) <=>
1034 (eval { $b->topmost->{smsg}->ds } || 0)
1038 # accumulate recent topics if search is supported
1039 # returns 200 if done, 404 if not
1040 sub acc_topic { # walk_thread callback
1041 my ($ctx, $level, $node) = @_;
1042 my $mid = $node->{id};
1043 my $x = $node->{smsg} || $ctx->{-inbox}->smsg_by_mid($mid);
1047 $subj = $x->subject;
1048 $subj = subject_normalized($subj);
1049 $subj = '(no subject)' if $subj eq '';
1052 $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1053 $ctx->{-cur_topic} = $topic;
1054 push @{$ctx->{order}}, $topic;
1058 $topic = $ctx->{-cur_topic}; # should never be undef
1059 $topic->[0] = $ds if $ds > $topic->[0];
1061 my $seen = $topic->[2];
1062 if (scalar(@$topic) == 3) { # parent was a ghost
1063 push @$topic, $subj;
1064 } elsif (!$seen->{$subj}) {
1065 push @$topic, $level, $subj;
1067 $seen->{$subj} = $mid; # latest for subject
1068 } else { # ghost message
1069 return 1 if $level != 0; # ignore child ghosts
1070 $topic = [ -666, 0, {} ];
1071 $ctx->{-cur_topic} = $topic;
1072 push @{$ctx->{order}}, $topic;
1079 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1081 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1086 my $ibx = $ctx->{-inbox};
1087 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1089 # sort by recency, this allows new posts to "bump" old topics...
1090 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1091 my ($ds, $n, $seen, $top, @ex) = @$topic;
1093 next unless defined $top; # ghost topic
1094 my $mid = delete $seen->{$top};
1095 my $href = mid_escape($mid);
1096 my $prev_subj = [ split(/ /, $top) ];
1097 $top = PublicInbox::Hval->new($top)->as_html;
1100 # $n isn't the total number of posts on the topic,
1101 # just the number of posts in the current results window
1105 $anchor = '#u'; # top of only message
1107 $n = " ($n+ messages)";
1108 $anchor = '#t'; # thread skeleton
1111 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1112 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1113 my $s = "<a\nhref=\"$href/T/$anchor\">$top</a>\n" .
1114 " $ds UTC $n - $mbox / $atom\n";
1115 for (my $i = 0; $i < scalar(@ex); $i += 2) {
1116 my $level = $ex[$i];
1117 my $subj = $ex[$i + 1];
1118 $mid = delete $seen->{$subj};
1119 my @subj = split(/ /, subject_normalized($subj));
1120 my @next_prev = @subj; # full copy
1121 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1122 $prev_subj = \@next_prev;
1123 $subj = ascii_html(join(' ', @subj));
1124 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1125 $href = mid_escape($mid);
1126 $s .= indent_for($level) . TCHILD;
1127 $s .= "<a\nhref=\"$href/T/#u\">$subj</a>$omit\n";
1131 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1135 # only for the t= query parameter passed to overview DB
1136 sub ts2str ($) { strftime('%Y%m%d%H%M%S', gmtime($_[0])) };
1139 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1140 timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1143 sub pagination_footer ($$) {
1144 my ($ctx, $latest) = @_;
1145 delete $ctx->{qp} or return;
1146 my $next = $ctx->{next_page} || '';
1147 my $prev = $ctx->{prev_page} || '';
1149 $next = $next ? "$next " : ' ';
1150 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1152 "<hr><pre>page: $next$prev</pre>";
1155 sub index_nav { # callback for WwwStream
1156 my (undef, $ctx) = @_;
1157 pagination_footer($ctx, '.')
1160 sub paginate_recent ($$) {
1161 my ($ctx, $lim) = @_;
1162 my $t = $ctx->{qp}->{t} || '';
1163 my $opts = { limit => $lim };
1164 my ($after, $before);
1166 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1167 # if only $after exists "YYYYMMDD.." because "." could be skipped
1168 # if interpreted as an end-of-sentence
1169 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1170 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1172 my $ibx = $ctx->{-inbox};
1173 my $msgs = $ibx->recent($opts, $after, $before);
1174 my $nr = scalar @$msgs;
1175 if ($nr < $lim && defined($after)) {
1176 $after = $before = undef;
1177 $msgs = $ibx->recent($opts);
1178 $nr = scalar @$msgs;
1180 my $more = $nr == $lim;
1181 my ($newest, $oldest);
1183 $newest = $msgs->[0]->{ts};
1184 $oldest = $msgs->[-1]->{ts};
1185 # if we only had $after, our SQL query in ->recent ordered
1186 if ($newest < $oldest) {
1187 ($oldest, $newest) = ($newest, $oldest);
1188 $more = 0 if defined($after) && $after < $oldest;
1191 if (defined($oldest) && $more) {
1192 my $s = ts2str($oldest);
1193 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1195 if (defined($newest) && (defined($before) || defined($after))) {
1196 my $s = ts2str($newest);
1197 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1204 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1206 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1208 PublicInbox::WwwStream->response($ctx, dump_topics($ctx), \&index_nav);
1211 sub thread_adj_level {
1212 my ($ctx, $level) = @_;
1214 my $max = $ctx->{cur_level};
1216 return ('', '') if $max == 0; # flat output
1218 # reset existing lists
1219 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1220 $ctx->{cur_level} = 0;
1222 } elsif ($level == $max) { # continue existing list
1224 } elsif ($level < $max) {
1225 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1226 $ctx->{cur_level} = $level;
1227 ("$beg<li>", '</li>');
1228 } else { # ($level > $max) # start a new level
1229 $ctx->{cur_level} = $level;
1230 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1235 sub ghost_index_entry {
1236 my ($ctx, $level, $node) = @_;
1237 my ($beg, $end) = thread_adj_level($ctx, $level);
1238 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{id})