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_html_more($ctx, $nr) };
39 } elsif ($nr == $ctx->{end_nr}) {
40 # fake an EOF if generating the footer fails;
41 # we want to at least show the message if something
43 eval { html_footer($ctx) };
49 # public functions: (unstable)
52 my ($ctx, $mime, $smsg) = @_;
53 my $ibx = $ctx->{-inbox};
54 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
55 my $hdr = $ctx->{hdr} = $mime->header_obj;
56 _msg_html_prepare_obuf($hdr, $ctx, 0);
60 PublicInbox::WwwStream->response($ctx, 200, \&msg_html_i);
65 my $mid = $ctx->{mid};
66 my $ibx = $ctx->{-inbox};
69 if (my $over = $ibx->over) {
71 $smsg = $over->next_by_mid($mid, \$id, \$prev);
72 $first = $ibx->msg_by_smsg($smsg) if $smsg;
74 my $next = $over->next_by_mid($mid, \$id, \$prev);
75 $ctx->{more} = [ $id, $prev, $next ] if $next;
79 $first = $ibx->msg_by_mid($mid) or return;
81 msg_html($ctx, PublicInbox::MIME->new($first), $smsg);
86 my ($id, $prev, $smsg) = @{$ctx->{more}};
87 my $ibx = $ctx->{-inbox};
88 $smsg = $ibx->smsg_mime($smsg);
89 my $next = $ibx->over->next_by_mid($ctx->{mid}, \$id, \$prev);
90 $ctx->{more} = $next ? [ $id, $prev, $next ] : undef;
91 return '' unless $smsg;
92 my $upfx = '../' . mid_escape($smsg->mid) . '/';
93 my $mime = delete $smsg->{mime};
94 _msg_html_prepare_obuf($mime->header_obj, $ctx, $nr);
95 multipart_text_as_html($mime, $upfx, $ctx);
96 ${delete $ctx->{obuf}} .= '</pre><hr>';
99 # /$INBOX/$MESSAGE_ID/#R
101 my ($ctx, $hdr) = @_;
103 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
105 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
108 my $ibx = $ctx->{-inbox};
109 if (my $url = $ibx->{infourl}) {
110 $url = prurl($ctx->{env}, $url);
111 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
114 my ($arg, $link, $reply_to_all) =
115 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
116 if (ref($arg) eq 'SCALAR') {
117 return '<pre id=R>'.ascii_html($$arg).'</pre>';
120 # mailto: link only works if address obfuscation is disabled
124 * If your mail client supports setting the <b>In-Reply-To</b> header
125 via mailto: links, try the <a
126 href="$link">mailto: link</a>
130 push @$arg, '/path/to/YOUR_REPLY';
131 $arg = ascii_html(join(" \\\n ", '', @$arg));
134 id=R><b>Reply instructions:</b>
136 You may reply publicly to <a
137 href=#t>this message</a> via plain-text email
138 using any one of the following methods:
140 * Save the following mbox file, import it into your mail client,
141 and $reply_to_all from there: <a
144 Avoid top-posting and favor interleaved quoting:
146 href="$p_url">$p_url</a>
148 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
149 switches of git-send-email(1):
154 href="$se_url">$se_url</a>
161 my $refs = references($hdr);
165 sub fold_addresses ($) {
166 return $_[0] if length($_[0]) <= COLS;
167 # try to fold on commas after non-word chars before $lim chars,
168 # Try to get the "," preceeded by ">" or ")", but avoid folding
169 # on the comma where somebody uses "Lastname, Firstname".
170 # We also try to keep the last and penultimate addresses in
171 # the list on the same line if possible, hence the extra \z
172 # Fall back to folding on spaces at $lim + 1 chars
173 my $lim = COLS - 8; # 8 = "\t" display width
174 my $too_long = $lim + 1;
175 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
177 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
180 .{$too_long,}?)(?:\s|\z)/xgo));
183 sub _hdr_names_html ($$) {
184 my ($hdr, $field) = @_;
185 my @vals = $hdr->header($field) or return '';
186 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
190 my ($nr, $singular, $plural) = @_;
191 return "0 $plural" if $nr == 0;
192 $nr == 1 ? "$nr $singular" : "$nr $plural";
195 # human-friendly format
196 sub fmt_ts ($) { strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
198 # this is already inside a <pre>
200 my ($smsg, $ctx, $more) = @_;
201 my $subj = $smsg->subject;
202 my $mid_raw = $smsg->mid;
203 my $id = id_compress($mid_raw, 1);
206 my $root_anchor = $ctx->{root_anchor} || '';
208 my $obfs_ibx = $ctx->{-obfs_ibx};
210 $subj = '(no subject)' if $subj eq '';
211 my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
212 $subj = '<b>'.ascii_html($subj).'</b>';
213 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
214 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
216 $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
218 my $ds = $smsg->ds; # for v1 non-Xapian/SQLite users
219 # deleting {mime} is critical to memory use,
220 # the rest of the fields saves about 400K as we iterate across 1K msgs
221 my ($mime) = delete @$smsg{qw(mime ds ts blob subject)};
223 my $hdr = $mime->header_obj;
224 my $from = _hdr_names_html($hdr, 'From');
225 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
226 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
227 my $upfx = $ctx->{-upfx};
228 my $mhref = $upfx . mid_escape($mid_raw) . '/';
229 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
230 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
231 my $to = fold_addresses(_hdr_names_html($hdr, 'To'));
232 my $cc = fold_addresses(_hdr_names_html($hdr, 'Cc'));
233 my ($tlen, $clen) = (length($to), length($cc));
235 if (($tlen + $clen) > COLS) {
236 $to_cc .= ' To: '.$to."\n" if $tlen;
237 $to_cc .= ' Cc: '.$cc."\n" if $clen;
240 $to_cc .= ' To: '.$to;
241 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
243 $to_cc .= ' Cc: '.$cc if $clen;
247 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
250 my $mapping = $ctx->{mapping};
251 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
252 my $mirt = PublicInbox::Hval->new_msgid($irt);
253 my $href = $upfx . $mirt->{href}. '/';
254 my $html = $mirt->as_html;
255 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
259 # scan through all parts, looking for displayable text
260 $ctx->{mhref} = $mhref;
262 msg_iter($mime, \&add_text_body, $ctx, 1);
266 $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
267 "<a\nhref=\"$mhref\">permalink</a>" .
268 " <a\nhref=\"${mhref}raw\">raw</a>" .
269 " <a\nhref=\"${mhref}#R\">reply</a>";
272 if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
273 $rv .= "\t[relevance $pct%]";
276 my $nested = 'nested';
281 $flat = "<b>$flat</b>";
283 $nested = "<b>$nested</b>";
285 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
286 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
287 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
292 $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
296 sub pad_link ($$;$) {
297 my ($mid, $level, $s) = @_;
299 my $id = id_compress($mid, 1);
300 (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
304 my ($mid_raw, $irt, $id, $ctx) = @_;
306 my $mapping = $ctx->{mapping} or return $rv;
308 my $mid_map = $mapping->{$mid_raw};
310 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
311 my ($attr, $node, $idx, $level) = @$mid_map;
312 my $children = $node->{children};
313 my $nr_c = scalar @$children;
316 if (my $smsg = $node->{smsg}) {
317 # delete saves about 200KB on a 1K message thread
318 if (my $refs = delete $smsg->{references}) {
319 ($$irt) = ($refs =~ m/<([^>]+)>\z/);
322 my $irt_map = $mapping->{$$irt} if defined $$irt;
323 if (defined $irt_map) {
324 $siblings = $irt_map->[1]->{children};
325 $nr_s = scalar(@$siblings) - 1;
326 $rv .= $pad . $irt_map->[0];
328 my $prev = $siblings->[$idx - 1];
329 my $pmid = $prev->{id};
331 my $s = ($idx - 1). ' preceding siblings ...';
332 $rv .= pad_link($pmid, $level, $s);
333 } elsif ($idx == 2) {
334 my $ppmid = $siblings->[0]->{id};
335 $rv .= $pad . $mapping->{$ppmid}->[0];
337 $rv .= $pad . $mapping->{$pmid}->[0];
340 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
341 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
342 $attr =~ s!\n\z!</b>\n!s;
343 $attr =~ s!<a\nhref.*</a> !!s; # no point in duplicating subject
344 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
347 my $cmid = $children->[0]->{id};
348 $rv .= $pad . $mapping->{$cmid}->[0];
350 my $s = ($nr_c - 1). ' more replies';
351 $rv .= pad_link($cmid, $level + 1, $s);
352 } elsif (my $cn = $children->[1]) {
353 $rv .= $pad . $mapping->{$cn->{id}}->[0];
357 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
359 my $nmid = $next->{id};
360 $rv .= $pad . $mapping->{$nmid}->[0];
361 my $nnext = $nr_s - $idx;
363 my $s = ($nnext - 1).' subsequent siblings';
364 $rv .= pad_link($nmid, $level, $s);
365 } elsif (my $nn = $siblings->[$idx + 2]) {
366 $rv .= $pad . $mapping->{$nn->{id}}->[0];
369 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
372 # non-recursive thread walker
373 sub walk_thread ($$$) {
374 my ($rootset, $ctx, $cb) = @_;
375 my @q = map { (0, $_, -1) } @$rootset;
377 my ($level, $node, $i) = splice(@q, 0, 3);
378 defined $node or next;
379 $cb->($ctx, $level, $node, $i) or return;
382 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
386 sub pre_thread { # walk_thread callback
387 my ($ctx, $level, $node, $idx) = @_;
388 $ctx->{mapping}->{$node->{id}} = [ '', $node, $idx, $level ];
389 skel_dump($ctx, $level, $node);
392 sub thread_index_entry {
393 my ($ctx, $level, $smsg) = @_;
394 my ($beg, $end) = thread_adj_level($ctx, $level);
395 $beg . '<pre>' . index_entry($smsg, $ctx, 0) . '</pre>' . $end;
398 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
400 return unless exists($ctx->{skel});
401 my $q = $ctx->{-queue};
403 my $level = shift @$q;
404 my $node = shift @$q or next;
406 unshift @$q, map { ($cl, $_) } @{$node->{children}};
407 if (my $smsg = $ctx->{-inbox}->smsg_mime($node->{smsg})) {
408 return thread_index_entry($ctx, $level, $smsg);
410 return ghost_index_entry($ctx, $level, $node);
413 join('', thread_adj_level($ctx, 0)) . ${delete $ctx->{skel}};
416 sub stream_thread ($$) {
417 my ($rootset, $ctx) = @_;
418 my $ibx = $ctx->{-inbox};
419 my @q = map { (0, $_) } @$rootset;
423 my $node = shift @q or next;
425 unshift @q, map { ($cl, $_) } @{$node->{children}};
426 $smsg = $ibx->smsg_mime($node->{smsg}) and last;
428 return missing_thread($ctx) unless $smsg;
430 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
431 $ctx->{-title_html} = ascii_html($smsg->subject);
432 $ctx->{-html_tip} = thread_index_entry($ctx, $level, $smsg);
433 $ctx->{-queue} = \@q;
434 PublicInbox::WwwStream->response($ctx, 200, \&stream_thread_i);
437 # /$INBOX/$MESSAGE_ID/t/
440 my $mid = $ctx->{mid};
441 my $ibx = $ctx->{-inbox};
442 my ($nr, $msgs) = $ibx->over->get_thread($mid);
443 return missing_thread($ctx) if $nr == 0;
444 my $skel = '<hr><pre>';
445 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
446 $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
447 $skel .= "<b\nid=t>Thread overview:</b> ";
448 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
449 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
450 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
451 $skel .= "-- links below jump to the message on this page --\n";
452 $ctx->{-upfx} = '../../';
453 $ctx->{cur_level} = 0;
454 $ctx->{skel} = \$skel;
455 $ctx->{prev_attr} = '';
456 $ctx->{prev_level} = 0;
457 $ctx->{root_anchor} = anchor_for($mid);
458 $ctx->{mapping} = {};
459 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
462 my $rootset = thread_results($ctx, $msgs);
464 # reduce hash lookups in pre_thread->skel_dump
465 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
466 walk_thread($rootset, $ctx, \&pre_thread);
469 return stream_thread($rootset, $ctx) unless $ctx->{flat};
471 # flat display: lazy load the full message from smsg
473 while (my $m = shift @$msgs) {
474 $smsg = $ibx->smsg_mime($m) and last;
476 return missing_thread($ctx) unless $smsg;
477 $ctx->{-title_html} = ascii_html($smsg->subject);
478 $ctx->{-html_tip} = '<pre>'.index_entry($smsg, $ctx, scalar @$msgs);
479 $ctx->{msgs} = $msgs;
480 PublicInbox::WwwStream->response($ctx, 200, \&thread_html_i);
483 sub thread_html_i { # PublicInbox::WwwStream::getline callback
485 my $msgs = $ctx->{msgs} or return;
486 while (my $smsg = shift @$msgs) {
487 $ctx->{-inbox}->smsg_mime($smsg) or next;
488 return index_entry($smsg, $ctx, scalar @$msgs);
490 my ($skel) = delete @$ctx{qw(skel msgs)};
494 sub multipart_text_as_html {
495 my (undef, $mhref, $ctx) = @_; # $mime = $_[0]
496 $ctx->{mhref} = $mhref;
498 # scan through all parts, looking for displayable text
499 msg_iter($_[0], \&add_text_body, $ctx, 1);
503 my ($s, $l, $quot) = @_;
505 # show everything in the full version with anchor from
506 # short version (see above)
507 my $rv = $l->linkify_1($$quot);
509 # we use a <span> here to allow users to specify their own
510 # color for quoted text
511 $rv = $l->linkify_2(ascii_html($rv));
513 $$s .= qq(<span\nclass="q">) . $rv . '</span>'
516 sub attach_link ($$$$;$) {
517 my ($ctx, $ct, $p, $fn, $err) = @_;
518 my ($part, $depth, @idx) = @$p;
519 my $nl = $idx[-1] > 1 ? "\n" : '';
520 my $idx = join('.', @idx);
521 my $size = bytes::length($part->body);
523 # hide attributes normally, unless we want to aid users in
524 # spotting MUA problems:
525 $ct =~ s/;.*// unless $err;
526 $ct = ascii_html($ct);
527 my $desc = $part->header('Content-Description');
528 $desc = $fn unless defined $desc;
529 $desc = '' unless defined $desc;
531 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
533 } elsif ($ct eq 'text/plain') {
538 my $rv = $ctx->{obuf};
539 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
541 $$rv .= "[-- Warning: decoded text below may be mangled --]\n";
543 $$rv .= "[-- Attachment #$idx: ";
544 my $ts = "Type: $ct, Size: $size bytes";
545 $desc = ascii_html($desc);
546 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
551 sub add_text_body { # callback for msg_iter
553 my $upfx = $ctx->{mhref};
554 my $ibx = $ctx->{-inbox};
555 # $p - from msg_iter: [ Email::MIME, depth, @idx ]
556 my ($part, $depth, @idx) = @$p;
557 my $ct = $part->content_type || 'text/plain';
558 my $fn = $part->filename;
559 my ($s, $err) = msg_part_text($part, $ct);
560 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
562 # makes no difference to browsers, and don't screw up filename
563 # link generation in diffs with the extra '%0D'
566 # always support diff-highlighting, but we can't linkify hunk
567 # headers for solver unless some coderepo are configured:
569 if ($s =~ /^(?:diff|---|\+{3}) /ms) {
570 # diffstat anchors do not link across attachments or messages:
571 $idx[0] = $upfx . $idx[0] if $upfx ne '';
572 $ctx->{-apfx} = join('/', @idx);
573 $ctx->{-anchors} = {}; # attr => filename
574 $ctx->{-diff} = $diff = [];
575 delete $ctx->{-long_path};
577 if ($ibx->{-repo_objs}) {
578 if (index($upfx, '//') >= 0) { # absolute URL (Atom feeds)
580 $spfx =~ s!/([^/]*)/\z!/!;
582 my $n_slash = $upfx =~ tr!/!/!;
585 } elsif ($n_slash == 1) {
587 } else { # nslash == 2
592 $ctx->{-spfx} = $spfx;
595 # some editors don't put trailing newlines at the end:
596 $s .= "\n" unless $s =~ /\n\z/s;
598 # split off quoted and unquoted blocks:
599 my @sections = split(/((?:^>[^\n]*\n)+)/sm, $s);
601 my $rv = $ctx->{obuf};
602 if (defined($fn) || $depth > 0 || $err) {
603 # badly-encoded message with $err? tell the world about it!
604 attach_link($ctx, $ct, $p, $fn, $err);
607 my $l = PublicInbox::Linkify->new;
608 foreach my $cur (@sections) {
610 flush_quote($rv, $l, \$cur);
612 @$diff = split(/^/m, $cur);
614 flush_diff($rv, $ctx, $l);
618 $$rv .= $l->linkify_2(ascii_html($cur));
623 obfuscate_addrs($ibx, $$rv) if $ibx->{obfuscate};
626 sub _msg_html_prepare_obuf {
627 my ($hdr, $ctx, $nr) = @_;
628 my $over = $ctx->{-inbox}->over;
629 my $obfs_ibx = $ctx->{-obfs_ibx};
631 my $mids = mids_for_index($hdr);
635 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
637 $rv .= "<pre\nid=b>"; # anchor for body start
642 $ctx->{-upfx} = '../';
644 my @title; # (Subject[0], From[0])
645 for my $v ($hdr->header('From')) {
646 $v = PublicInbox::Hval->new($v);
647 my @n = PublicInbox::Address::names($v->raw);
648 $title[1] //= ascii_html(join(', ', @n));
651 obfuscate_addrs($obfs_ibx, $v);
652 obfuscate_addrs($obfs_ibx, $title[1]);
654 $rv .= "From: $v\n" if $v ne '';
656 foreach my $h (qw(To Cc)) {
657 for my $v ($hdr->header($h)) {
660 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
661 $rv .= "$h: $v\n" if $v ne '';
664 my @subj = $hdr->header('Subject');
668 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
671 $rv .= qq(<a\nhref="#r"\nid=t>$v</a>\n);
677 } else { # dummy anchor for thread skeleton at bottom of page
678 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
679 $title[0] = '(no subject)';
681 for my $v ($hdr->header('Date')) {
683 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
686 $ctx->{-title_html} = join(' - ', @title);
687 if (scalar(@$mids) == 1) { # common case
688 my $mid = PublicInbox::Hval->new_msgid($mids->[0]);
689 my $mhtml = $mid->as_html;
690 $rv .= "Message-ID: <$mhtml> ";
691 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
693 # X-Alt-Message-ID can happen if a message is injected from
694 # public-inbox-nntpd because of multiple Message-ID headers.
695 my $lnk = PublicInbox::Linkify->new;
697 for my $h (qw(Message-ID X-Alt-Message-ID)) {
698 $s .= "$h: $_\n" for ($hdr->header_raw($h));
700 $lnk->linkify_mids('..', \$s, 1);
703 $rv .= _parent_headers($hdr, $over);
709 qq(expand[<a\nhref="T/#u">flat</a>) .
710 qq(|<a\nhref="t/#u">nested</a>] ) .
711 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
712 qq(<a\nhref="t.atom">Atom feed</a>);
715 sub thread_skel ($$$) {
716 my ($skel, $ctx, $hdr) = @_;
717 my $mid = mids($hdr)->[0];
718 my $ibx = $ctx->{-inbox};
719 my ($nr, $msgs) = $ibx->over->get_thread($mid);
720 my $parent = in_reply_to($hdr);
721 $$skel .= "\n<b>Thread overview: </b>";
723 if (defined $parent) {
724 $$skel .= SKEL_EXPAND."\n ";
725 $$skel .= ghost_parent('../', $parent) . "\n";
727 $$skel .= '[no followups] '.SKEL_EXPAND."\n";
729 $ctx->{next_msg} = undef;
730 $ctx->{parent_msg} = $parent;
735 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
737 # nb: mutt only shows the first Subject in the index pane
738 # when multiple Subject: headers are present, so we follow suit:
739 my $subj = $hdr->header('Subject') // '';
740 $subj = '(no subject)' if $subj eq '';
741 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
743 $ctx->{prev_attr} = '';
744 $ctx->{prev_level} = 0;
745 $ctx->{skel} = $skel;
747 # reduce hash lookups in skel_dump
748 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
749 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
751 $ctx->{parent_msg} = $parent;
754 sub _parent_headers {
755 my ($hdr, $over) = @_;
757 my @irt = $hdr->header_raw('In-Reply-To');
760 my $lnk = PublicInbox::Linkify->new;
761 $rv .= "In-Reply-To: $_\n" for @irt;
762 $lnk->linkify_mids('..', \$rv);
764 $refs = references($hdr);
765 my $irt = pop @$refs;
767 my $v = PublicInbox::Hval->new_msgid($irt);
768 my $html = $v->as_html;
769 my $href = $v->{href};
770 $rv .= "In-Reply-To: <";
771 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
775 # do not display References: if search is present,
776 # we show the thread skeleton at the bottom, instead.
779 $refs //= references($hdr);
781 @$refs = map { linkify_ref_no_over($_) } @$refs;
782 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
787 # returns a string buffer via ->getline
790 my $ibx = $ctx->{-inbox};
791 my $hdr = delete $ctx->{hdr};
793 my $skel = " <a\nhref=\"$upfx\">index</a>";
797 thread_skel(\$skel, $ctx, $hdr);
802 if (my $n = $ctx->{next_msg}) {
803 $n = PublicInbox::Hval->new_msgid($n)->{href};
804 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
807 my $par = $ctx->{parent_msg};
809 $u = PublicInbox::Hval->new_msgid($par)->{href};
812 if (my $p = $ctx->{prev_msg}) {
813 $prev = PublicInbox::Hval->new_msgid($p)->{href};
814 if ($p && $par && $p eq $par) {
815 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
816 'rel=prev>prev parent</a>';
819 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
821 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
823 } elsif ($u) { # unlikely
824 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
826 $rv .= "$next $prev$parent ";
828 $rv .= qq(<a\nhref="#R">reply</a>);
831 $rv .= msg_reply($ctx, $hdr);
834 sub linkify_ref_no_over {
835 my $v = PublicInbox::Hval->new_msgid($_[0]);
836 my $html = $v->as_html;
837 my $href = $v->{href};
838 "<<a\nhref=\"../$href/\">$html</a>>";
843 'm' . id_compress($msgid, 1);
847 my ($upfx, $mid) = @_;
849 $mid = PublicInbox::Hval->new_msgid($mid);
850 my $href = $mid->{href};
851 my $html = $mid->as_html;
852 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
857 $level ? INDENT x ($level - 1) : '';
861 my ($ctx, $level, $node, $idx) = @_;
862 ++$ctx->{root_idx} if $level == 0;
863 if ($node->{id} eq $ctx->{mid}) {
864 $ctx->{found_mid_at} = $ctx->{root_idx};
870 sub strict_loose_note ($) {
873 " -- strict thread matches above, loose matches on Subject: below --\n";
875 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
877 " -- use mbox.gz link to download all $nr messages --\n";
883 my ($ctx, $msgs) = @_;
884 require PublicInbox::SearchThread;
885 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
887 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
888 # and preserved in the future. This bug is hidden by `sid' matches
889 # in get_thread, so we never noticed it until now. And even when
890 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
891 # bump since reindexing is expensive and users may not do it
893 # loose threading could've returned too many results,
894 # put the root the message we care about at the top:
895 my $mid = $ctx->{mid};
896 if (defined($mid) && scalar(@$rootset) > 1) {
897 $ctx->{root_idx} = -1;
898 my $nr = scalar @$msgs;
899 walk_thread($rootset, $ctx, \&find_mid_root);
900 my $idx = $ctx->{found_mid_at};
901 if (defined($idx) && $idx != 0) {
902 my $tip = splice(@$rootset, $idx, 1);
903 @$rootset = reverse @$rootset;
904 unshift @$rootset, $tip;
905 $ctx->{sl_note} = strict_loose_note($nr);
913 require PublicInbox::ExtMsg;
914 PublicInbox::ExtMsg::ext_msg($ctx);
918 my ($prev_subj, $subj, $val) = @_;
920 my $omit = ''; # '"' denotes identical text omitted
921 my (@prev_pop, @curr_pop);
922 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
923 push(@prev_pop, pop(@$prev_subj));
924 push(@curr_pop, pop(@$subj));
927 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
928 if (scalar(@curr_pop) == 1) {
930 push @$prev_subj, @prev_pop;
931 push @$subj, @curr_pop;
936 sub skel_dump { # walk_thread callback
937 my ($ctx, $level, $node) = @_;
938 my $smsg = $node->{smsg} or return _skel_ghost($ctx, $level, $node);
940 my $skel = $ctx->{skel};
941 my $cur = $ctx->{cur};
942 my $mid = $smsg->{mid};
944 if ($level == 0 && $ctx->{skel_dump_roots}++) {
945 $$skel .= delete($ctx->{sl_note}) || '';
948 my $f = ascii_html($smsg->from_name);
949 my $obfs_ibx = $ctx->{-obfs_ibx};
950 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
952 my $d = fmt_ts($smsg->{ds});
953 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
954 if (exists $ctx->{searchview}) {
955 if (defined(my $pct = $smsg->{pct})) {
956 $d .= (sprintf(' % 2u', $pct) . '%');
962 $d .= ' ' . indent_for($level) . th_pfx($level);
964 $ctx->{first_level} ||= $level;
966 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
967 $ctx->{prev_attr} = $attr;
969 $ctx->{prev_level} = $level;
974 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
975 "$attr [this message]</a></b>\n";
978 $ctx->{prev_msg} = $mid;
981 $ctx->{next_msg} ||= $mid;
984 # Subject is never undef, this mail was loaded from
985 # our Xapian which would've resulted in '' if it were
986 # really missing (and Filter rejects empty subjects)
987 my @subj = split(/ /, subject_normalized($smsg->subject));
988 # remove common suffixes from the subject if it matches the previous,
989 # so we do not show redundant text at the end.
990 my $prev_subj = $ctx->{prev_subj} || [];
991 $ctx->{prev_subj} = [ @subj ];
992 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
995 my $subj = join(' ', @subj);
996 $subj = ascii_html($subj);
997 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
998 $end = "$subj</a> $omit$f\n"
1004 my $mapping = $unmatched ? undef : $ctx->{mapping};
1006 my $map = $mapping->{$mid};
1007 $id = id_compress($mid, 1);
1009 $map->[0] = "$d<a\nhref=\"$m\">$end";
1012 $m = $ctx->{-upfx}.mid_escape($mid).'/';
1014 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1019 my ($ctx, $level, $node) = @_;
1021 my $mid = $node->{id};
1022 my $d = ' [not found] ';
1023 $d .= ' ' if exists $ctx->{searchview};
1024 $d .= indent_for($level) . th_pfx($level);
1025 my $upfx = $ctx->{-upfx};
1026 my $m = PublicInbox::Hval->new_msgid($mid);
1027 my $href = $upfx . $m->{href} . '/';
1028 my $html = $m->as_html;
1030 my $mapping = $ctx->{mapping};
1031 my $map = $mapping->{$mid} if $mapping;
1033 my $id = id_compress($mid, 1);
1034 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1035 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1037 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1039 ${$ctx->{skel}} .= $d;
1045 (eval { $a->topmost->{smsg}->ds } || 0) <=>
1046 (eval { $b->topmost->{smsg}->ds } || 0)
1050 # accumulate recent topics if search is supported
1051 # returns 200 if done, 404 if not
1052 sub acc_topic { # walk_thread callback
1053 my ($ctx, $level, $node) = @_;
1054 my $mid = $node->{id};
1055 my $x = $node->{smsg} || $ctx->{-inbox}->smsg_by_mid($mid);
1059 $subj = $x->subject;
1060 $subj = subject_normalized($subj);
1061 $subj = '(no subject)' if $subj eq '';
1064 $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1065 $ctx->{-cur_topic} = $topic;
1066 push @{$ctx->{order}}, $topic;
1070 $topic = $ctx->{-cur_topic}; # should never be undef
1071 $topic->[0] = $ds if $ds > $topic->[0];
1073 my $seen = $topic->[2];
1074 if (scalar(@$topic) == 3) { # parent was a ghost
1075 push @$topic, $subj;
1076 } elsif (!$seen->{$subj}) {
1077 push @$topic, $level, $subj;
1079 $seen->{$subj} = $mid; # latest for subject
1080 } else { # ghost message
1081 return 1 if $level != 0; # ignore child ghosts
1082 $topic = [ -666, 0, {} ];
1083 $ctx->{-cur_topic} = $topic;
1084 push @{$ctx->{order}}, $topic;
1091 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1093 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1098 my $ibx = $ctx->{-inbox};
1099 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1101 # sort by recency, this allows new posts to "bump" old topics...
1102 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1103 my ($ds, $n, $seen, $top, @ex) = @$topic;
1105 next unless defined $top; # ghost topic
1106 my $mid = delete $seen->{$top};
1107 my $href = mid_escape($mid);
1108 my $prev_subj = [ split(/ /, $top) ];
1109 $top = PublicInbox::Hval->new($top)->as_html;
1112 # $n isn't the total number of posts on the topic,
1113 # just the number of posts in the current results window
1117 $anchor = '#u'; # top of only message
1119 $n = " ($n+ messages)";
1120 $anchor = '#t'; # thread skeleton
1123 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1124 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1125 my $s = "<a\nhref=\"$href/T/$anchor\">$top</a>\n" .
1126 " $ds UTC $n - $mbox / $atom\n";
1127 for (my $i = 0; $i < scalar(@ex); $i += 2) {
1128 my $level = $ex[$i];
1129 my $subj = $ex[$i + 1];
1130 $mid = delete $seen->{$subj};
1131 my @subj = split(/ /, subject_normalized($subj));
1132 my @next_prev = @subj; # full copy
1133 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1134 $prev_subj = \@next_prev;
1135 $subj = ascii_html(join(' ', @subj));
1136 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1137 $href = mid_escape($mid);
1138 $s .= indent_for($level) . TCHILD;
1139 $s .= "<a\nhref=\"$href/T/#u\">$subj</a>$omit\n";
1143 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1147 # only for the t= query parameter passed to overview DB
1148 sub ts2str ($) { strftime('%Y%m%d%H%M%S', gmtime($_[0])) };
1151 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1152 timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1155 sub pagination_footer ($$) {
1156 my ($ctx, $latest) = @_;
1157 delete $ctx->{qp} or return;
1158 my $next = $ctx->{next_page} || '';
1159 my $prev = $ctx->{prev_page} || '';
1161 $next = $next ? "$next " : ' ';
1162 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1164 "<hr><pre>page: $next$prev</pre>";
1167 sub index_nav { # callback for WwwStream
1168 my (undef, $ctx) = @_;
1169 pagination_footer($ctx, '.')
1172 sub paginate_recent ($$) {
1173 my ($ctx, $lim) = @_;
1174 my $t = $ctx->{qp}->{t} || '';
1175 my $opts = { limit => $lim };
1176 my ($after, $before);
1178 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1179 # if only $after exists "YYYYMMDD.." because "." could be skipped
1180 # if interpreted as an end-of-sentence
1181 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1182 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1184 my $ibx = $ctx->{-inbox};
1185 my $msgs = $ibx->recent($opts, $after, $before);
1186 my $nr = scalar @$msgs;
1187 if ($nr < $lim && defined($after)) {
1188 $after = $before = undef;
1189 $msgs = $ibx->recent($opts);
1190 $nr = scalar @$msgs;
1192 my $more = $nr == $lim;
1193 my ($newest, $oldest);
1195 $newest = $msgs->[0]->{ts};
1196 $oldest = $msgs->[-1]->{ts};
1197 # if we only had $after, our SQL query in ->recent ordered
1198 if ($newest < $oldest) {
1199 ($oldest, $newest) = ($newest, $oldest);
1200 $more = 0 if defined($after) && $after < $oldest;
1203 if (defined($oldest) && $more) {
1204 my $s = ts2str($oldest);
1205 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1207 if (defined($newest) && (defined($before) || defined($after))) {
1208 my $s = ts2str($newest);
1209 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1216 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1218 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1220 PublicInbox::WwwStream->response($ctx, dump_topics($ctx), \&index_nav);
1223 sub thread_adj_level {
1224 my ($ctx, $level) = @_;
1226 my $max = $ctx->{cur_level};
1228 return ('', '') if $max == 0; # flat output
1230 # reset existing lists
1231 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1232 $ctx->{cur_level} = 0;
1234 } elsif ($level == $max) { # continue existing list
1236 } elsif ($level < $max) {
1237 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1238 $ctx->{cur_level} = $level;
1239 ("$beg<li>", '</li>');
1240 } else { # ($level > $max) # start a new level
1241 $ctx->{cur_level} = $level;
1242 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1247 sub ghost_index_entry {
1248 my ($ctx, $level, $node) = @_;
1249 my ($beg, $end) = thread_adj_level($ctx, $level);
1250 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{id})