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).'/' : '';
34 multipart_text_as_html(delete $ctx->{mime}, $upfx,
38 # fake an EOF if {more} retrieval fails fails;
39 eval { msg_html_more($ctx, $nr) };
40 } elsif ($nr == $ctx->{end_nr}) {
41 # fake an EOF if generating the footer fails;
42 # we want to at least show the message if something
44 eval { html_footer($ctx) };
50 # public functions: (unstable)
53 my ($ctx, $mime, $smsg) = @_;
54 my $ibx = $ctx->{-inbox};
55 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
56 my $hdr = $ctx->{hdr} = $mime->header_obj;
57 $ctx->{tip} = _msg_html_prepare($hdr, $ctx, 0);
61 PublicInbox::WwwStream->response($ctx, 200, \&msg_html_i);
66 my $mid = $ctx->{mid};
67 my $ibx = $ctx->{-inbox};
70 if (my $over = $ibx->over) {
72 $smsg = $over->next_by_mid($mid, \$id, \$prev);
73 $first = $ibx->msg_by_smsg($smsg) if $smsg;
75 my $next = $over->next_by_mid($mid, \$id, \$prev);
76 $ctx->{more} = [ $id, $prev, $next ] if $next;
80 $first = $ibx->msg_by_mid($mid) or return;
82 msg_html($ctx, PublicInbox::MIME->new($first), $smsg);
87 my ($id, $prev, $smsg) = @{$ctx->{more}};
88 my $ibx = $ctx->{-inbox};
89 $smsg = $ibx->smsg_mime($smsg);
90 my $next = $ibx->over->next_by_mid($ctx->{mid}, \$id, \$prev);
91 $ctx->{more} = $next ? [ $id, $prev, $next ] : undef;
92 return '' unless $smsg;
93 my $upfx = '../' . mid_escape($smsg->mid) . '/';
94 my $mime = delete $smsg->{mime};
95 _msg_html_prepare($mime->header_obj, $ctx, $nr) .
96 multipart_text_as_html($mime, $upfx, $ctx) .
100 # /$INBOX/$MESSAGE_ID/#R
102 my ($ctx, $hdr) = @_;
104 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
106 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
109 my $ibx = $ctx->{-inbox};
110 if (my $url = $ibx->{infourl}) {
111 $url = prurl($ctx->{env}, $url);
112 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
115 my ($arg, $link, $reply_to_all) =
116 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
117 if (ref($arg) eq 'SCALAR') {
118 return '<pre id=R>'.ascii_html($$arg).'</pre>';
121 # mailto: link only works if address obfuscation is disabled
125 * If your mail client supports setting the <b>In-Reply-To</b> header
126 via mailto: links, try the <a
127 href="$link">mailto: link</a>
131 push @$arg, '/path/to/YOUR_REPLY';
132 $arg = ascii_html(join(" \\\n ", '', @$arg));
135 id=R><b>Reply instructions:</b>
137 You may reply publicly to <a
138 href=#t>this message</a> via plain-text email
139 using any one of the following methods:
141 * Save the following mbox file, import it into your mail client,
142 and $reply_to_all from there: <a
145 Avoid top-posting and favor interleaved quoting:
147 href="$p_url">$p_url</a>
149 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
150 switches of git-send-email(1):
155 href="$se_url">$se_url</a>
162 my $refs = references($hdr);
166 sub fold_addresses ($) {
167 return $_[0] if length($_[0]) <= COLS;
168 # try to fold on commas after non-word chars before $lim chars,
169 # Try to get the "," preceeded by ">" or ")", but avoid folding
170 # on the comma where somebody uses "Lastname, Firstname".
171 # We also try to keep the last and penultimate addresses in
172 # the list on the same line if possible, hence the extra \z
173 # Fall back to folding on spaces at $lim + 1 chars
174 my $lim = COLS - 8; # 8 = "\t" display width
175 my $too_long = $lim + 1;
176 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
178 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
181 .{$too_long,}?)(?:\s|\z)/xgo));
184 sub _hdr_names_html ($$) {
185 my ($hdr, $field) = @_;
186 my @vals = $hdr->header($field) or return '';
187 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
191 my ($nr, $singular, $plural) = @_;
192 return "0 $plural" if $nr == 0;
193 $nr == 1 ? "$nr $singular" : "$nr $plural";
196 # human-friendly format
197 sub fmt_ts ($) { strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
199 # this is already inside a <pre>
201 my ($smsg, $ctx, $more) = @_;
202 my $subj = $smsg->subject;
203 my $mid_raw = $smsg->mid;
204 my $id = id_compress($mid_raw, 1);
207 my $root_anchor = $ctx->{root_anchor} || '';
209 my $obfs_ibx = $ctx->{-obfs_ibx};
211 $subj = '(no subject)' if $subj eq '';
212 my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
213 $subj = '<b>'.ascii_html($subj).'</b>';
214 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
215 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
217 $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
219 my $ds = $smsg->ds; # for v1 non-Xapian/SQLite users
220 # deleting {mime} is critical to memory use,
221 # the rest of the fields saves about 400K as we iterate across 1K msgs
222 my ($mime) = delete @$smsg{qw(mime ds ts blob subject)};
224 my $hdr = $mime->header_obj;
225 my $from = _hdr_names_html($hdr, 'From');
226 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
227 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
228 my $upfx = $ctx->{-upfx};
229 my $mhref = $upfx . mid_escape($mid_raw) . '/';
230 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
231 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
232 my $to = fold_addresses(_hdr_names_html($hdr, 'To'));
233 my $cc = fold_addresses(_hdr_names_html($hdr, 'Cc'));
234 my ($tlen, $clen) = (length($to), length($cc));
236 if (($tlen + $clen) > COLS) {
237 $to_cc .= ' To: '.$to."\n" if $tlen;
238 $to_cc .= ' Cc: '.$cc."\n" if $clen;
241 $to_cc .= ' To: '.$to;
242 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
244 $to_cc .= ' Cc: '.$cc if $clen;
248 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
251 my $mapping = $ctx->{mapping};
252 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
253 my $mirt = PublicInbox::Hval->new_msgid($irt);
254 my $href = $upfx . $mirt->{href}. '/';
255 my $html = $mirt->as_html;
256 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
260 # scan through all parts, looking for displayable text
261 $ctx->{mhref} = $mhref;
263 msg_iter($mime, \&add_text_body, $ctx, 1);
267 $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
268 "<a\nhref=\"$mhref\">permalink</a>" .
269 " <a\nhref=\"${mhref}raw\">raw</a>" .
270 " <a\nhref=\"${mhref}#R\">reply</a>";
273 if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
274 $rv .= "\t[relevance $pct%]";
277 my $nested = 'nested';
282 $flat = "<b>$flat</b>";
284 $nested = "<b>$nested</b>";
286 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
287 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
288 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
293 $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
297 sub pad_link ($$;$) {
298 my ($mid, $level, $s) = @_;
300 my $id = id_compress($mid, 1);
301 (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
305 my ($mid_raw, $irt, $id, $ctx) = @_;
307 my $mapping = $ctx->{mapping} or return $rv;
309 my $mid_map = $mapping->{$mid_raw};
311 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
312 my ($attr, $node, $idx, $level) = @$mid_map;
313 my $children = $node->{children};
314 my $nr_c = scalar @$children;
317 if (my $smsg = $node->{smsg}) {
318 # delete saves about 200KB on a 1K message thread
319 if (my $refs = delete $smsg->{references}) {
320 ($$irt) = ($refs =~ m/<([^>]+)>\z/);
323 my $irt_map = $mapping->{$$irt} if defined $$irt;
324 if (defined $irt_map) {
325 $siblings = $irt_map->[1]->{children};
326 $nr_s = scalar(@$siblings) - 1;
327 $rv .= $pad . $irt_map->[0];
329 my $prev = $siblings->[$idx - 1];
330 my $pmid = $prev->{id};
332 my $s = ($idx - 1). ' preceding siblings ...';
333 $rv .= pad_link($pmid, $level, $s);
334 } elsif ($idx == 2) {
335 my $ppmid = $siblings->[0]->{id};
336 $rv .= $pad . $mapping->{$ppmid}->[0];
338 $rv .= $pad . $mapping->{$pmid}->[0];
341 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
342 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
343 $attr =~ s!\n\z!</b>\n!s;
344 $attr =~ s!<a\nhref.*</a> !!s; # no point in duplicating subject
345 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
348 my $cmid = $children->[0]->{id};
349 $rv .= $pad . $mapping->{$cmid}->[0];
351 my $s = ($nr_c - 1). ' more replies';
352 $rv .= pad_link($cmid, $level + 1, $s);
353 } elsif (my $cn = $children->[1]) {
354 $rv .= $pad . $mapping->{$cn->{id}}->[0];
358 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
360 my $nmid = $next->{id};
361 $rv .= $pad . $mapping->{$nmid}->[0];
362 my $nnext = $nr_s - $idx;
364 my $s = ($nnext - 1).' subsequent siblings';
365 $rv .= pad_link($nmid, $level, $s);
366 } elsif (my $nn = $siblings->[$idx + 2]) {
367 $rv .= $pad . $mapping->{$nn->{id}}->[0];
370 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
373 # non-recursive thread walker
374 sub walk_thread ($$$) {
375 my ($rootset, $ctx, $cb) = @_;
376 my @q = map { (0, $_, -1) } @$rootset;
378 my ($level, $node, $i) = splice(@q, 0, 3);
379 defined $node or next;
380 $cb->($ctx, $level, $node, $i) or return;
383 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
387 sub pre_thread { # walk_thread callback
388 my ($ctx, $level, $node, $idx) = @_;
389 $ctx->{mapping}->{$node->{id}} = [ '', $node, $idx, $level ];
390 skel_dump($ctx, $level, $node);
393 sub thread_index_entry {
394 my ($ctx, $level, $smsg) = @_;
395 my ($beg, $end) = thread_adj_level($ctx, $level);
396 $beg . '<pre>' . index_entry($smsg, $ctx, 0) . '</pre>' . $end;
399 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
401 return unless exists($ctx->{skel});
402 my $q = $ctx->{-queue};
404 my $level = shift @$q;
405 my $node = shift @$q or next;
407 unshift @$q, map { ($cl, $_) } @{$node->{children}};
408 if (my $smsg = $ctx->{-inbox}->smsg_mime($node->{smsg})) {
409 return thread_index_entry($ctx, $level, $smsg);
411 return ghost_index_entry($ctx, $level, $node);
414 join('', thread_adj_level($ctx, 0)) . ${delete $ctx->{skel}};
417 sub stream_thread ($$) {
418 my ($rootset, $ctx) = @_;
419 my $ibx = $ctx->{-inbox};
420 my @q = map { (0, $_) } @$rootset;
424 my $node = shift @q or next;
426 unshift @q, map { ($cl, $_) } @{$node->{children}};
427 $smsg = $ibx->smsg_mime($node->{smsg}) and last;
429 return missing_thread($ctx) unless $smsg;
431 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
432 $ctx->{-title_html} = ascii_html($smsg->subject);
433 $ctx->{-html_tip} = thread_index_entry($ctx, $level, $smsg);
434 $ctx->{-queue} = \@q;
435 PublicInbox::WwwStream->response($ctx, 200, \&stream_thread_i);
438 # /$INBOX/$MESSAGE_ID/t/
441 my $mid = $ctx->{mid};
442 my $ibx = $ctx->{-inbox};
443 my ($nr, $msgs) = $ibx->over->get_thread($mid);
444 return missing_thread($ctx) if $nr == 0;
445 my $skel = '<hr><pre>';
446 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
447 $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
448 $skel .= "<b\nid=t>Thread overview:</b> ";
449 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
450 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
451 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
452 $skel .= "-- links below jump to the message on this page --\n";
453 $ctx->{-upfx} = '../../';
454 $ctx->{cur_level} = 0;
455 $ctx->{skel} = \$skel;
456 $ctx->{prev_attr} = '';
457 $ctx->{prev_level} = 0;
458 $ctx->{root_anchor} = anchor_for($mid);
459 $ctx->{mapping} = {};
460 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
463 my $rootset = thread_results($ctx, $msgs);
465 # reduce hash lookups in pre_thread->skel_dump
466 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
467 walk_thread($rootset, $ctx, \&pre_thread);
470 return stream_thread($rootset, $ctx) unless $ctx->{flat};
472 # flat display: lazy load the full message from smsg
474 while (my $m = shift @$msgs) {
475 $smsg = $ibx->smsg_mime($m) and last;
477 return missing_thread($ctx) unless $smsg;
478 $ctx->{-title_html} = ascii_html($smsg->subject);
479 $ctx->{-html_tip} = '<pre>'.index_entry($smsg, $ctx, scalar @$msgs);
480 $ctx->{msgs} = $msgs;
481 PublicInbox::WwwStream->response($ctx, 200, \&thread_html_i);
484 sub thread_html_i { # PublicInbox::WwwStream::getline callback
486 my $msgs = $ctx->{msgs} or return;
487 while (my $smsg = shift @$msgs) {
488 $ctx->{-inbox}->smsg_mime($smsg) or next;
489 return index_entry($smsg, $ctx, scalar @$msgs);
491 my ($skel) = delete @$ctx{qw(skel msgs)};
495 sub multipart_text_as_html {
496 my (undef, $mhref, $ctx) = @_; # $mime = $_[0]
497 $ctx->{mhref} = $mhref;
498 $ctx->{rv} = \(my $rv = '');
500 # scan through all parts, looking for displayable text
501 msg_iter($_[0], \&add_text_body, $ctx, 1);
502 ${delete $ctx->{rv}};
506 my ($s, $l, $quot) = @_;
508 # show everything in the full version with anchor from
509 # short version (see above)
510 my $rv = $l->linkify_1($$quot);
512 # we use a <span> here to allow users to specify their own
513 # color for quoted text
514 $rv = $l->linkify_2(ascii_html($rv));
516 $$s .= qq(<span\nclass="q">) . $rv . '</span>'
519 sub attach_link ($$$$;$) {
520 my ($ctx, $ct, $p, $fn, $err) = @_;
521 my ($part, $depth, @idx) = @$p;
522 my $nl = $idx[-1] > 1 ? "\n" : '';
523 my $idx = join('.', @idx);
524 my $size = bytes::length($part->body);
526 # hide attributes normally, unless we want to aid users in
527 # spotting MUA problems:
528 $ct =~ s/;.*// unless $err;
529 $ct = ascii_html($ct);
530 my $desc = $part->header('Content-Description');
531 $desc = $fn unless defined $desc;
532 $desc = '' unless defined $desc;
534 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
536 } elsif ($ct eq 'text/plain') {
542 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
544 $$rv .= "[-- Warning: decoded text below may be mangled --]\n";
546 $$rv .= "[-- Attachment #$idx: ";
547 my $ts = "Type: $ct, Size: $size bytes";
548 $desc = ascii_html($desc);
549 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
554 sub add_text_body { # callback for msg_iter
556 my $upfx = $ctx->{mhref};
557 my $ibx = $ctx->{-inbox};
558 # $p - from msg_iter: [ Email::MIME, depth, @idx ]
559 my ($part, $depth, @idx) = @$p;
560 my $ct = $part->content_type || 'text/plain';
561 my $fn = $part->filename;
562 my ($s, $err) = msg_part_text($part, $ct);
563 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
565 # makes no difference to browsers, and don't screw up filename
566 # link generation in diffs with the extra '%0D'
569 # always support diff-highlighting, but we can't linkify hunk
570 # headers for solver unless some coderepo are configured:
572 if ($s =~ /^(?:diff|---|\+{3}) /ms) {
573 # diffstat anchors do not link across attachments or messages:
574 $idx[0] = $upfx . $idx[0] if $upfx ne '';
575 $ctx->{-apfx} = join('/', @idx);
576 $ctx->{-anchors} = {}; # attr => filename
577 $ctx->{-diff} = $diff = [];
578 delete $ctx->{-long_path};
580 if ($ibx->{-repo_objs}) {
581 if (index($upfx, '//') >= 0) { # absolute URL (Atom feeds)
583 $spfx =~ s!/([^/]*)/\z!/!;
585 my $n_slash = $upfx =~ tr!/!/!;
588 } elsif ($n_slash == 1) {
590 } else { # nslash == 2
595 $ctx->{-spfx} = $spfx;
598 # some editors don't put trailing newlines at the end:
599 $s .= "\n" unless $s =~ /\n\z/s;
601 # split off quoted and unquoted blocks:
602 my @sections = split(/((?:^>[^\n]*\n)+)/sm, $s);
605 if (defined($fn) || $depth > 0 || $err) {
606 # badly-encoded message with $err? tell the world about it!
607 attach_link($ctx, $ct, $p, $fn, $err);
610 my $l = PublicInbox::Linkify->new;
611 foreach my $cur (@sections) {
613 flush_quote($rv, $l, \$cur);
615 @$diff = split(/^/m, $cur);
617 flush_diff($rv, $ctx, $l);
621 $$rv .= $l->linkify_2(ascii_html($cur));
626 obfuscate_addrs($ibx, $$rv) if $ibx->{obfuscate};
629 sub _msg_html_prepare {
630 my ($hdr, $ctx, $nr) = @_;
632 my $over = $ctx->{-inbox}->over;
633 my $obfs_ibx = $ctx->{-obfs_ibx};
635 my $mids = mids_for_index($hdr);
639 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
641 $rv .= "<pre\nid=b>"; # anchor for body start
646 $ctx->{-upfx} = '../';
648 my @title; # (Subject[0], From[0])
649 for my $v ($hdr->header('From')) {
650 $v = PublicInbox::Hval->new($v);
651 my @n = PublicInbox::Address::names($v->raw);
652 $title[1] //= ascii_html(join(', ', @n));
655 obfuscate_addrs($obfs_ibx, $v);
656 obfuscate_addrs($obfs_ibx, $title[1]);
658 $rv .= "From: $v\n" if $v ne '';
660 foreach my $h (qw(To Cc)) {
661 for my $v ($hdr->header($h)) {
664 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
665 $rv .= "$h: $v\n" if $v ne '';
668 my @subj = $hdr->header('Subject');
672 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
675 $rv .= qq(<a\nhref="#r"\nid=t>$v</a>\n);
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)';
685 for my $v ($hdr->header('Date')) {
687 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
690 $ctx->{-title_html} = join(' - ', @title);
691 if (scalar(@$mids) == 1) { # common case
692 my $mid = PublicInbox::Hval->new_msgid($mids->[0]);
693 my $mhtml = $mid->as_html;
694 $rv .= "Message-ID: <$mhtml> ";
695 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
697 # X-Alt-Message-ID can happen if a message is injected from
698 # public-inbox-nntpd because of multiple Message-ID headers.
699 my $lnk = PublicInbox::Linkify->new;
701 for my $h (qw(Message-ID X-Alt-Message-ID)) {
702 $s .= "$h: $_\n" for ($hdr->header_raw($h));
704 $lnk->linkify_mids('..', \$s, 1);
707 $rv .= _parent_headers($hdr, $over);
712 qq(expand[<a\nhref="T/#u">flat</a>) .
713 qq(|<a\nhref="t/#u">nested</a>] ) .
714 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
715 qq(<a\nhref="t.atom">Atom feed</a>);
718 sub thread_skel ($$$) {
719 my ($skel, $ctx, $hdr) = @_;
720 my $mid = mids($hdr)->[0];
721 my $ibx = $ctx->{-inbox};
722 my ($nr, $msgs) = $ibx->over->get_thread($mid);
723 my $parent = in_reply_to($hdr);
724 $$skel .= "\n<b>Thread overview: </b>";
726 if (defined $parent) {
727 $$skel .= SKEL_EXPAND."\n ";
728 $$skel .= ghost_parent('../', $parent) . "\n";
730 $$skel .= '[no followups] '.SKEL_EXPAND."\n";
732 $ctx->{next_msg} = undef;
733 $ctx->{parent_msg} = $parent;
738 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
740 # nb: mutt only shows the first Subject in the index pane
741 # when multiple Subject: headers are present, so we follow suit:
742 my $subj = $hdr->header('Subject') // '';
743 $subj = '(no subject)' if $subj eq '';
744 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
746 $ctx->{prev_attr} = '';
747 $ctx->{prev_level} = 0;
748 $ctx->{skel} = $skel;
750 # reduce hash lookups in skel_dump
751 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
752 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
754 $ctx->{parent_msg} = $parent;
757 sub _parent_headers {
758 my ($hdr, $over) = @_;
760 my @irt = $hdr->header_raw('In-Reply-To');
763 my $lnk = PublicInbox::Linkify->new;
764 $rv .= "In-Reply-To: $_\n" for @irt;
765 $lnk->linkify_mids('..', \$rv);
767 $refs = references($hdr);
768 my $irt = pop @$refs;
770 my $v = PublicInbox::Hval->new_msgid($irt);
771 my $html = $v->as_html;
772 my $href = $v->{href};
773 $rv .= "In-Reply-To: <";
774 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
778 # do not display References: if search is present,
779 # we show the thread skeleton at the bottom, instead.
782 $refs //= references($hdr);
784 @$refs = map { linkify_ref_no_over($_) } @$refs;
785 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
790 # returns a string buffer via ->getline
793 my $ibx = $ctx->{-inbox};
794 my $hdr = delete $ctx->{hdr};
796 my $skel = " <a\nhref=\"$upfx\">index</a>";
800 thread_skel(\$skel, $ctx, $hdr);
805 if (my $n = $ctx->{next_msg}) {
806 $n = PublicInbox::Hval->new_msgid($n)->{href};
807 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
810 my $par = $ctx->{parent_msg};
812 $u = PublicInbox::Hval->new_msgid($par)->{href};
815 if (my $p = $ctx->{prev_msg}) {
816 $prev = PublicInbox::Hval->new_msgid($p)->{href};
817 if ($p && $par && $p eq $par) {
818 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
819 'rel=prev>prev parent</a>';
822 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
824 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
826 } elsif ($u) { # unlikely
827 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
829 $rv .= "$next $prev$parent ";
831 $rv .= qq(<a\nhref="#R">reply</a>);
834 $rv .= msg_reply($ctx, $hdr);
837 sub linkify_ref_no_over {
838 my $v = PublicInbox::Hval->new_msgid($_[0]);
839 my $html = $v->as_html;
840 my $href = $v->{href};
841 "<<a\nhref=\"../$href/\">$html</a>>";
846 'm' . id_compress($msgid, 1);
850 my ($upfx, $mid) = @_;
852 $mid = PublicInbox::Hval->new_msgid($mid);
853 my $href = $mid->{href};
854 my $html = $mid->as_html;
855 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
860 $level ? INDENT x ($level - 1) : '';
864 my ($ctx, $level, $node, $idx) = @_;
865 ++$ctx->{root_idx} if $level == 0;
866 if ($node->{id} eq $ctx->{mid}) {
867 $ctx->{found_mid_at} = $ctx->{root_idx};
873 sub strict_loose_note ($) {
876 " -- strict thread matches above, loose matches on Subject: below --\n";
878 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
880 " -- use mbox.gz link to download all $nr messages --\n";
886 my ($ctx, $msgs) = @_;
887 require PublicInbox::SearchThread;
888 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
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
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);
916 require PublicInbox::ExtMsg;
917 PublicInbox::ExtMsg::ext_msg($ctx);
921 my ($prev_subj, $subj, $val) = @_;
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));
930 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
931 if (scalar(@curr_pop) == 1) {
933 push @$prev_subj, @prev_pop;
934 push @$subj, @curr_pop;
939 sub skel_dump { # walk_thread callback
940 my ($ctx, $level, $node) = @_;
941 my $smsg = $node->{smsg} or return _skel_ghost($ctx, $level, $node);
943 my $skel = $ctx->{skel};
944 my $cur = $ctx->{cur};
945 my $mid = $smsg->{mid};
947 if ($level == 0 && $ctx->{skel_dump_roots}++) {
948 $$skel .= delete($ctx->{sl_note}) || '';
951 my $f = ascii_html($smsg->from_name);
952 my $obfs_ibx = $ctx->{-obfs_ibx};
953 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
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) . '%');
965 $d .= ' ' . indent_for($level) . th_pfx($level);
967 $ctx->{first_level} ||= $level;
969 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
970 $ctx->{prev_attr} = $attr;
972 $ctx->{prev_level} = $level;
977 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
978 "$attr [this message]</a></b>\n";
981 $ctx->{prev_msg} = $mid;
984 $ctx->{next_msg} ||= $mid;
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, '" ');
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"
1007 my $mapping = $unmatched ? undef : $ctx->{mapping};
1009 my $map = $mapping->{$mid};
1010 $id = id_compress($mid, 1);
1012 $map->[0] = "$d<a\nhref=\"$m\">$end";
1015 $m = $ctx->{-upfx}.mid_escape($mid).'/';
1017 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1022 my ($ctx, $level, $node) = @_;
1024 my $mid = $node->{id};
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 $m = PublicInbox::Hval->new_msgid($mid);
1030 my $href = $upfx . $m->{href} . '/';
1031 my $html = $m->as_html;
1033 my $mapping = $ctx->{mapping};
1034 my $map = $mapping->{$mid} if $mapping;
1036 my $id = id_compress($mid, 1);
1037 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1038 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1040 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1042 ${$ctx->{skel}} .= $d;
1048 (eval { $a->topmost->{smsg}->ds } || 0) <=>
1049 (eval { $b->topmost->{smsg}->ds } || 0)
1053 # accumulate recent topics if search is supported
1054 # returns 200 if done, 404 if not
1055 sub acc_topic { # walk_thread callback
1056 my ($ctx, $level, $node) = @_;
1057 my $mid = $node->{id};
1058 my $x = $node->{smsg} || $ctx->{-inbox}->smsg_by_mid($mid);
1062 $subj = $x->subject;
1063 $subj = subject_normalized($subj);
1064 $subj = '(no subject)' if $subj eq '';
1067 $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1068 $ctx->{-cur_topic} = $topic;
1069 push @{$ctx->{order}}, $topic;
1073 $topic = $ctx->{-cur_topic}; # should never be undef
1074 $topic->[0] = $ds if $ds > $topic->[0];
1076 my $seen = $topic->[2];
1077 if (scalar(@$topic) == 3) { # parent was a ghost
1078 push @$topic, $subj;
1079 } elsif (!$seen->{$subj}) {
1080 push @$topic, $level, $subj;
1082 $seen->{$subj} = $mid; # latest for subject
1083 } else { # ghost message
1084 return 1 if $level != 0; # ignore child ghosts
1085 $topic = [ -666, 0, {} ];
1086 $ctx->{-cur_topic} = $topic;
1087 push @{$ctx->{order}}, $topic;
1094 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1096 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1101 my $ibx = $ctx->{-inbox};
1102 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1104 # sort by recency, this allows new posts to "bump" old topics...
1105 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1106 my ($ds, $n, $seen, $top, @ex) = @$topic;
1108 next unless defined $top; # ghost topic
1109 my $mid = delete $seen->{$top};
1110 my $href = mid_escape($mid);
1111 my $prev_subj = [ split(/ /, $top) ];
1112 $top = PublicInbox::Hval->new($top)->as_html;
1115 # $n isn't the total number of posts on the topic,
1116 # just the number of posts in the current results window
1120 $anchor = '#u'; # top of only message
1122 $n = " ($n+ messages)";
1123 $anchor = '#t'; # thread skeleton
1126 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1127 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1128 my $s = "<a\nhref=\"$href/T/$anchor\">$top</a>\n" .
1129 " $ds UTC $n - $mbox / $atom\n";
1130 for (my $i = 0; $i < scalar(@ex); $i += 2) {
1131 my $level = $ex[$i];
1132 my $subj = $ex[$i + 1];
1133 $mid = delete $seen->{$subj};
1134 my @subj = split(/ /, subject_normalized($subj));
1135 my @next_prev = @subj; # full copy
1136 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1137 $prev_subj = \@next_prev;
1138 $subj = ascii_html(join(' ', @subj));
1139 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1140 $href = mid_escape($mid);
1141 $s .= indent_for($level) . TCHILD;
1142 $s .= "<a\nhref=\"$href/T/#u\">$subj</a>$omit\n";
1146 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1150 # only for the t= query parameter passed to overview DB
1151 sub ts2str ($) { strftime('%Y%m%d%H%M%S', gmtime($_[0])) };
1154 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1155 timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1158 sub pagination_footer ($$) {
1159 my ($ctx, $latest) = @_;
1160 delete $ctx->{qp} or return;
1161 my $next = $ctx->{next_page} || '';
1162 my $prev = $ctx->{prev_page} || '';
1164 $next = $next ? "$next " : ' ';
1165 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1167 "<hr><pre>page: $next$prev</pre>";
1170 sub index_nav { # callback for WwwStream
1171 my (undef, $ctx) = @_;
1172 pagination_footer($ctx, '.')
1175 sub paginate_recent ($$) {
1176 my ($ctx, $lim) = @_;
1177 my $t = $ctx->{qp}->{t} || '';
1178 my $opts = { limit => $lim };
1179 my ($after, $before);
1181 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1182 # if only $after exists "YYYYMMDD.." because "." could be skipped
1183 # if interpreted as an end-of-sentence
1184 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1185 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1187 my $ibx = $ctx->{-inbox};
1188 my $msgs = $ibx->recent($opts, $after, $before);
1189 my $nr = scalar @$msgs;
1190 if ($nr < $lim && defined($after)) {
1191 $after = $before = undef;
1192 $msgs = $ibx->recent($opts);
1193 $nr = scalar @$msgs;
1195 my $more = $nr == $lim;
1196 my ($newest, $oldest);
1198 $newest = $msgs->[0]->{ts};
1199 $oldest = $msgs->[-1]->{ts};
1200 # if we only had $after, our SQL query in ->recent ordered
1201 if ($newest < $oldest) {
1202 ($oldest, $newest) = ($newest, $oldest);
1203 $more = 0 if defined($after) && $after < $oldest;
1206 if (defined($oldest) && $more) {
1207 my $s = ts2str($oldest);
1208 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1210 if (defined($newest) && (defined($before) || defined($after))) {
1211 my $s = ts2str($newest);
1212 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1219 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1221 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1223 PublicInbox::WwwStream->response($ctx, dump_topics($ctx), \&index_nav);
1226 sub thread_adj_level {
1227 my ($ctx, $level) = @_;
1229 my $max = $ctx->{cur_level};
1231 return ('', '') if $max == 0; # flat output
1233 # reset existing lists
1234 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1235 $ctx->{cur_level} = 0;
1237 } elsif ($level == $max) { # continue existing list
1239 } elsif ($level < $max) {
1240 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1241 $ctx->{cur_level} = $level;
1242 ("$beg<li>", '</li>');
1243 } else { # ($level > $max) # start a new level
1244 $ctx->{cur_level} = $level;
1245 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1250 sub ghost_index_entry {
1251 my ($ctx, $level, $node) = @_;
1252 my ($beg, $end) = thread_adj_level($ctx, $level);
1253 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{id})