1 # Copyright (C) 2014-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
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 mid_href);
12 use PublicInbox::Linkify;
13 use PublicInbox::MID qw(id_compress mids mids_for_index references
15 use PublicInbox::MsgIter;
16 use PublicInbox::Address;
17 use PublicInbox::WwwStream;
18 use PublicInbox::Reply;
19 use PublicInbox::ViewDiff qw(flush_diff);
21 use POSIX qw(strftime);
22 use Time::Local qw(timegm);
23 use PublicInbox::Smsg qw(subject_normalized);
24 use constant COLS => 72;
25 use constant INDENT => ' ';
26 use constant TCHILD => '` ';
27 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
31 if (my $more = delete $ctx->{more}) { # unlikely
32 # fake an EOF if $more retrieval fails;
33 eval { msg_page_more($ctx, $nr, @$more) };
34 } elsif (my $hdr = delete $ctx->{hdr}) {
35 # fake an EOF if generating the footer fails;
36 # we want to at least show the message if something
38 eval { html_footer($ctx, $hdr) };
44 # public functions: (unstable)
48 my $mid = $ctx->{mid};
49 my $ibx = $ctx->{-inbox};
50 my ($smsg, $first, $next);
51 if (my $over = $ibx->over) {
53 $smsg = $over->next_by_mid($mid, \$id, \$prev) or return;
54 $first = $ibx->msg_by_smsg($smsg) or return;
55 $next = $over->next_by_mid($mid, \$id, \$prev);
56 $ctx->{more} = [ $id, $prev, $next ] if $next;
58 $first = $ibx->msg_by_mid($mid) or return;
60 my $mime = PublicInbox::Eml->new($first);
61 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
62 my $hdr = $ctx->{hdr} = $mime->header_obj;
63 $ctx->{obuf} = _msg_page_prepare_obuf($hdr, $ctx, 0);
65 # $next cannot be true w/o $smsg being defined:
66 $ctx->{mhref} = $next ? '../'.mid_href($smsg->{mid}).'/' : '';
67 multipart_text_as_html($mime, $ctx);
68 $ctx->{-html_tip} = (${delete $ctx->{obuf}} .= '</pre><hr>');
69 PublicInbox::WwwStream->response($ctx, 200, \&msg_page_i);
72 sub msg_page_more { # cold
73 my ($ctx, $nr, $id, $prev, $smsg) = @_;
74 my $ibx = $ctx->{-inbox};
75 my $next = $ibx->over->next_by_mid($ctx->{mid}, \$id, \$prev);
76 $ctx->{more} = [ $id, $prev, $next ] if $next;
77 $smsg = $ibx->smsg_mime($smsg) or return '';
78 $ctx->{mhref} = '../' . mid_href($smsg->{mid}) . '/';
79 my $mime = delete $smsg->{mime};
80 $ctx->{obuf} = _msg_page_prepare_obuf($mime->header_obj, $ctx, $nr);
81 multipart_text_as_html($mime, $ctx);
82 ${delete $ctx->{obuf}} .= '</pre><hr>';
85 # /$INBOX/$MESSAGE_ID/#R
89 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
91 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
94 my $ibx = $ctx->{-inbox};
95 if (my $url = $ibx->{infourl}) {
96 $url = prurl($ctx->{env}, $url);
97 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
100 my ($arg, $link, $reply_to_all) =
101 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
102 if (ref($arg) eq 'SCALAR') {
103 return '<pre id=R>'.ascii_html($$arg).'</pre>';
106 # mailto: link only works if address obfuscation is disabled
110 * If your mail client supports setting the <b>In-Reply-To</b> header
111 via mailto: links, try the <a
112 href="$link">mailto: link</a>
116 push @$arg, '/path/to/YOUR_REPLY';
117 $arg = ascii_html(join(" \\\n ", '', @$arg));
120 id=R><b>Reply instructions:</b>
122 You may reply publicly to <a
123 href=#t>this message</a> via plain-text email
124 using any one of the following methods:
126 * Save the following mbox file, import it into your mail client,
127 and $reply_to_all from there: <a
130 Avoid top-posting and favor interleaved quoting:
132 href="$p_url">$p_url</a>
134 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
135 switches of git-send-email(1):
140 href="$se_url">$se_url</a>
147 my $refs = references($hdr);
151 sub fold_addresses ($) {
152 return $_[0] if length($_[0]) <= COLS;
153 # try to fold on commas after non-word chars before $lim chars,
154 # Try to get the "," preceded by ">" or ")", but avoid folding
155 # on the comma where somebody uses "Lastname, Firstname".
156 # We also try to keep the last and penultimate addresses in
157 # the list on the same line if possible, hence the extra \z
158 # Fall back to folding on spaces at $lim + 1 chars
159 my $lim = COLS - 8; # 8 = "\t" display width
160 my $too_long = $lim + 1;
161 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
163 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
166 .{$too_long,}?)(?:\s|\z)/xgo));
169 sub _hdr_names_html ($$) {
170 my ($hdr, $field) = @_;
171 my @vals = $hdr->header($field) or return '';
172 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
176 my ($nr, $singular, $plural) = @_;
177 return "0 $plural" if $nr == 0;
178 $nr == 1 ? "$nr $singular" : "$nr $plural";
181 # human-friendly format
182 sub fmt_ts ($) { strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
184 # this is already inside a <pre>
186 my ($smsg, $ctx, $more) = @_;
187 my $subj = $smsg->subject;
188 my $mid_raw = $smsg->mid;
189 my $id = id_compress($mid_raw, 1);
192 my $root_anchor = $ctx->{root_anchor} || '';
194 my $obfs_ibx = $ctx->{-obfs_ibx};
196 $subj = '(no subject)' if $subj eq '';
197 my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
198 $subj = '<b>'.ascii_html($subj).'</b>';
199 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
200 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
202 $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
204 my $ds = $smsg->ds; # for v1 non-Xapian/SQLite users
205 # deleting {mime} is critical to memory use,
206 # the rest of the fields saves about 400K as we iterate across 1K msgs
207 my ($mime) = delete @$smsg{qw(mime ds ts blob subject)};
209 my $hdr = $mime->header_obj;
210 my $from = _hdr_names_html($hdr, 'From');
211 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
212 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
213 my $upfx = $ctx->{-upfx};
214 my $mhref = $upfx . mid_href($mid_raw) . '/';
215 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
216 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
217 my $to = fold_addresses(_hdr_names_html($hdr, 'To'));
218 my $cc = fold_addresses(_hdr_names_html($hdr, 'Cc'));
219 my ($tlen, $clen) = (length($to), length($cc));
221 if (($tlen + $clen) > COLS) {
222 $to_cc .= ' To: '.$to."\n" if $tlen;
223 $to_cc .= ' Cc: '.$cc."\n" if $clen;
226 $to_cc .= ' To: '.$to;
227 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
229 $to_cc .= ' Cc: '.$cc if $clen;
233 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
236 my $mapping = $ctx->{mapping};
237 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
238 my $href = $upfx . mid_href($irt) . '/';
239 my $html = ascii_html($irt);
240 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
244 # scan through all parts, looking for displayable text
245 $ctx->{mhref} = $mhref;
247 $mime->each_part(\&add_text_body, $ctx, 1);
251 $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
252 "<a\nhref=\"$mhref\">permalink</a>" .
253 " <a\nhref=\"${mhref}raw\">raw</a>" .
254 " <a\nhref=\"${mhref}#R\">reply</a>";
257 if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
258 $rv .= "\t[relevance $pct%]";
261 my $nested = 'nested';
266 $flat = "<b>$flat</b>";
268 $nested = "<b>$nested</b>";
270 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
271 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
272 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
277 $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
281 sub pad_link ($$;$) {
282 my ($mid, $level, $s) = @_;
284 my $id = id_compress($mid, 1);
285 (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
289 my ($mid_raw, $irt, $id, $ctx) = @_;
291 my $mapping = $ctx->{mapping} or return $rv;
293 my $mid_map = $mapping->{$mid_raw};
295 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
296 my ($attr, $node, $idx, $level) = @$mid_map;
297 my $children = $node->{children};
298 my $nr_c = scalar @$children;
301 # delete saves about 200KB on a 1K message thread
302 if (my $refs = delete $node->{references}) {
303 ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
305 my $irt_map = $mapping->{$$irt} if defined $$irt;
306 if (defined $irt_map) {
307 $siblings = $irt_map->[1]->{children};
308 $nr_s = scalar(@$siblings) - 1;
309 $rv .= $pad . $irt_map->[0];
311 my $prev = $siblings->[$idx - 1];
312 my $pmid = $prev->{mid};
314 my $s = ($idx - 1). ' preceding siblings ...';
315 $rv .= pad_link($pmid, $level, $s);
316 } elsif ($idx == 2) {
317 my $ppmid = $siblings->[0]->{mid};
318 $rv .= $pad . $mapping->{$ppmid}->[0];
320 $rv .= $pad . $mapping->{$pmid}->[0];
323 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
324 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
325 $attr =~ s!\n\z!</b>\n!s;
326 $attr =~ s!<a\nhref.*</a> (?:" )?!!s; # no point in dup subject
327 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
330 my $cmid = $children->[0]->{mid};
331 $rv .= $pad . $mapping->{$cmid}->[0];
333 my $s = ($nr_c - 1). ' more replies';
334 $rv .= pad_link($cmid, $level + 1, $s);
335 } elsif (my $cn = $children->[1]) {
336 $rv .= $pad . $mapping->{$cn->{mid}}->[0];
340 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
342 my $nmid = $next->{mid};
343 $rv .= $pad . $mapping->{$nmid}->[0];
344 my $nnext = $nr_s - $idx;
346 my $s = ($nnext - 1).' subsequent siblings';
347 $rv .= pad_link($nmid, $level, $s);
348 } elsif (my $nn = $siblings->[$idx + 2]) {
349 $rv .= $pad . $mapping->{$nn->{mid}}->[0];
352 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
355 # non-recursive thread walker
356 sub walk_thread ($$$) {
357 my ($rootset, $ctx, $cb) = @_;
358 my @q = map { (0, $_, -1) } @$rootset;
360 my ($level, $node, $i) = splice(@q, 0, 3);
361 defined $node or next;
362 $cb->($ctx, $level, $node, $i) or return;
365 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
369 sub pre_thread { # walk_thread callback
370 my ($ctx, $level, $node, $idx) = @_;
371 $ctx->{mapping}->{$node->{mid}} = [ '', $node, $idx, $level ];
372 skel_dump($ctx, $level, $node);
375 sub thread_index_entry {
376 my ($ctx, $level, $smsg) = @_;
377 my ($beg, $end) = thread_adj_level($ctx, $level);
378 $beg . '<pre>' . index_entry($smsg, $ctx, 0) . '</pre>' . $end;
381 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
383 return unless exists($ctx->{skel});
384 my $q = $ctx->{-queue};
386 my $level = shift @$q;
387 my $node = shift @$q or next;
389 unshift @$q, map { ($cl, $_) } @{$node->{children}};
390 if ($ctx->{-inbox}->smsg_mime($node)) {
391 return thread_index_entry($ctx, $level, $node);
393 return ghost_index_entry($ctx, $level, $node);
396 join('', thread_adj_level($ctx, 0)) . ${delete $ctx->{skel}};
399 sub stream_thread ($$) {
400 my ($rootset, $ctx) = @_;
401 my $ibx = $ctx->{-inbox};
402 my @q = map { (0, $_) } @$rootset;
406 my $node = shift @q or next;
408 unshift @q, map { ($cl, $_) } @{$node->{children}};
409 $smsg = $ibx->smsg_mime($node) and last;
411 return missing_thread($ctx) unless $smsg;
413 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
414 $ctx->{-title_html} = ascii_html($smsg->{subject});
415 $ctx->{-html_tip} = thread_index_entry($ctx, $level, $smsg);
416 $ctx->{-queue} = \@q;
417 PublicInbox::WwwStream->response($ctx, 200, \&stream_thread_i);
420 # /$INBOX/$MESSAGE_ID/t/
423 my $mid = $ctx->{mid};
424 my $ibx = $ctx->{-inbox};
425 my ($nr, $msgs) = $ibx->over->get_thread($mid);
426 return missing_thread($ctx) if $nr == 0;
427 my $skel = '<hr><pre>';
428 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
429 $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
430 $skel .= "<b\nid=t>Thread overview:</b> ";
431 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
432 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
433 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
434 $skel .= "-- links below jump to the message on this page --\n";
435 $ctx->{-upfx} = '../../';
436 $ctx->{cur_level} = 0;
437 $ctx->{skel} = \$skel;
438 $ctx->{prev_attr} = '';
439 $ctx->{prev_level} = 0;
440 $ctx->{root_anchor} = anchor_for($mid);
441 $ctx->{mapping} = {};
442 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
445 my $rootset = thread_results($ctx, $msgs);
447 # reduce hash lookups in pre_thread->skel_dump
448 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
449 walk_thread($rootset, $ctx, \&pre_thread);
452 return stream_thread($rootset, $ctx) unless $ctx->{flat};
454 # flat display: lazy load the full message from smsg
456 while (my $m = shift @$msgs) {
457 $smsg = $ibx->smsg_mime($m) and last;
459 return missing_thread($ctx) unless $smsg;
460 $ctx->{-title_html} = ascii_html($smsg->{subject});
461 $ctx->{-html_tip} = '<pre>'.index_entry($smsg, $ctx, scalar @$msgs);
462 $ctx->{msgs} = $msgs;
463 PublicInbox::WwwStream->response($ctx, 200, \&thread_html_i);
466 sub thread_html_i { # PublicInbox::WwwStream::getline callback
468 my $msgs = $ctx->{msgs} or return;
469 while (my $smsg = shift @$msgs) {
470 $ctx->{-inbox}->smsg_mime($smsg) or next;
471 return index_entry($smsg, $ctx, scalar @$msgs);
473 my ($skel) = delete @$ctx{qw(skel msgs)};
477 sub multipart_text_as_html {
478 # ($mime, $ctx) = @_; # each_part may do "$_[0] = undef"
480 # scan through all parts, looking for displayable text
481 $_[0]->each_part(\&add_text_body, $_[1], 1);
484 sub submsg_hdr ($$) {
485 my ($ctx, $eml) = @_;
486 my $obfs_ibx = $ctx->{-obfs_ibx};
487 my $rv = $ctx->{obuf};
489 for my $h (qw(From To Cc Subject Date Message-ID X-Alt-Message-ID)) {
490 my @v = $eml->header($h);
492 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
499 sub attach_link ($$$$;$) {
500 my ($ctx, $ct, $p, $fn, $err) = @_;
501 my ($part, $depth, $idx) = @$p;
502 my $nl = $idx eq '1' ? '' : "\n"; # like join("\n", ...)
503 my $size = bytes::length($part->body);
505 # hide attributes normally, unless we want to aid users in
506 # spotting MUA problems:
507 $ct =~ s/;.*// unless $err;
508 $ct = ascii_html($ct);
510 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
512 } elsif ($ct eq 'text/plain') {
517 my $rv = $ctx->{obuf};
518 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
521 [-- Warning: decoded text below may be mangled, UTF-8 assumed --]
524 $$rv .= "[-- Attachment #$idx: ";
525 my $ts = "Type: $ct, Size: $size bytes";
526 my $desc = $part->header('Content-Description') // $fn // '';
527 $desc = ascii_html($desc);
528 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
531 submsg_hdr($ctx, $part) if $part->{is_submsg};
536 sub add_text_body { # callback for each_part
538 my $upfx = $ctx->{mhref};
539 my $ibx = $ctx->{-inbox};
540 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
541 # $p - from each_part: [ Email::MIME-like, depth, $idx ]
542 my ($part, $depth, $idx) = @$p;
543 my $ct = $part->content_type || 'text/plain';
544 my $fn = $part->filename;
545 my ($s, $err) = msg_part_text($part, $ct);
546 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
548 my $rv = $ctx->{obuf};
549 if ($part->{is_submsg}) {
550 submsg_hdr($ctx, $part);
554 # makes no difference to browsers, and don't screw up filename
555 # link generation in diffs with the extra '%0D'
558 # will be escaped to `•' in HTML
559 obfuscate_addrs($ibx, $s, "\x{2022}") if $ibx->{obfuscate};
561 # always support diff-highlighting, but we can't linkify hunk
562 # headers for solver unless some coderepo are configured:
564 if ($s =~ /^--- [^\n]+\n\+{3} [^\n]+\n@@ /ms) {
565 # diffstat anchors do not link across attachments or messages,
566 # -apfx is just a stable prefix for making diffstat anchors
567 # linkable to the first diff hunk w/o crossing attachments
568 $idx =~ tr!.!/!; # compatibility with previous versions
569 $ctx->{-apfx} = $upfx . $idx;
571 # do attr => filename mappings for diffstats in git diffs:
572 $ctx->{-anchors} = {} if $s =~ /^diff --git /sm;
574 delete $ctx->{-long_path};
576 if ($ibx->{-repo_objs}) {
577 if (index($upfx, '//') >= 0) { # absolute URL (Atom feeds)
579 $spfx =~ s!/([^/]*)/\z!/!;
581 my $n_slash = $upfx =~ tr!/!/!;
584 } elsif ($n_slash == 1) {
586 } else { # nslash == 2
591 $ctx->{-spfx} = $spfx;
594 # some editors don't put trailing newlines at the end:
595 $s .= "\n" unless $s =~ /\n\z/s;
597 # split off quoted and unquoted blocks:
598 my @sections = PublicInbox::MsgIter::split_quotes($s);
599 undef $s; # free memory
600 if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
601 # badly-encoded message with $err? tell the world about it!
602 attach_link($ctx, $ct, $p, $fn, $err);
605 foreach my $cur (@sections) {
607 # we use a <span> here to allow users to specify
608 # their own color for quoted text
609 $$rv .= qq(<span\nclass="q">);
610 $$rv .= $l->to_html($cur);
613 flush_diff($ctx, \$cur);
616 $$rv .= $l->to_html($cur);
618 undef $cur; # free memory
622 sub _msg_page_prepare_obuf {
623 my ($hdr, $ctx, $nr) = @_;
624 my $over = $ctx->{-inbox}->over;
625 my $obfs_ibx = $ctx->{-obfs_ibx};
627 my $mids = mids_for_index($hdr);
631 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
633 $rv .= "<pre\nid=b>"; # anchor for body start
638 $ctx->{-upfx} = '../';
640 my @title; # (Subject[0], From[0])
641 for my $v ($hdr->header('From')) {
642 my @n = PublicInbox::Address::names($v);
644 $title[1] //= ascii_html(join(', ', @n));
646 obfuscate_addrs($obfs_ibx, $v);
647 obfuscate_addrs($obfs_ibx, $title[1]);
649 $rv .= "From: $v\n" if $v ne '';
651 foreach my $h (qw(To Cc)) {
652 for my $v ($hdr->header($h)) {
655 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
656 $rv .= "$h: $v\n" if $v ne '';
659 my @subj = $hdr->header('Subject');
661 my $v = ascii_html(shift @subj);
662 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
664 $rv .= $over ? qq(<a\nhref="#r"\nid=t>$v</a>\n) : "$v\n";
666 for $v (@subj) { # multi-Subject message :<
668 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
669 $rv .= "Subject: $v\n";
671 } else { # dummy anchor for thread skeleton at bottom of page
672 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
673 $title[0] = '(no subject)';
675 for my $v ($hdr->header('Date')) {
677 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
680 $ctx->{-title_html} = join(' - ', @title);
681 if (scalar(@$mids) == 1) { # common case
682 my $mhtml = ascii_html($mids->[0]);
683 $rv .= "Message-ID: <$mhtml> ";
684 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
686 # X-Alt-Message-ID can happen if a message is injected from
687 # public-inbox-nntpd because of multiple Message-ID headers.
688 my $lnk = PublicInbox::Linkify->new;
690 for my $h (qw(Message-ID X-Alt-Message-ID)) {
691 $s .= "$h: $_\n" for ($hdr->header_raw($h));
693 $lnk->linkify_mids('..', \$s, 1);
696 $rv .= _parent_headers($hdr, $over);
702 qq(expand[<a\nhref="T/#u">flat</a>) .
703 qq(|<a\nhref="t/#u">nested</a>] ) .
704 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
705 qq(<a\nhref="t.atom">Atom feed</a>);
708 sub thread_skel ($$$) {
709 my ($skel, $ctx, $hdr) = @_;
710 my $mid = mids($hdr)->[0];
711 my $ibx = $ctx->{-inbox};
712 my ($nr, $msgs) = $ibx->over->get_thread($mid);
713 my $parent = in_reply_to($hdr);
714 $$skel .= "\n<b>Thread overview: </b>";
716 if (defined $parent) {
717 $$skel .= SKEL_EXPAND."\n ";
718 $$skel .= ghost_parent('../', $parent) . "\n";
720 $$skel .= '[no followups] '.SKEL_EXPAND."\n";
722 $ctx->{next_msg} = undef;
723 $ctx->{parent_msg} = $parent;
728 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
730 # nb: mutt only shows the first Subject in the index pane
731 # when multiple Subject: headers are present, so we follow suit:
732 my $subj = $hdr->header('Subject') // '';
733 $subj = '(no subject)' if $subj eq '';
734 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
736 $ctx->{prev_attr} = '';
737 $ctx->{prev_level} = 0;
738 $ctx->{skel} = $skel;
740 # reduce hash lookups in skel_dump
741 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
742 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
744 $ctx->{parent_msg} = $parent;
747 sub _parent_headers {
748 my ($hdr, $over) = @_;
750 my @irt = $hdr->header_raw('In-Reply-To');
753 my $lnk = PublicInbox::Linkify->new;
754 $rv .= "In-Reply-To: $_\n" for @irt;
755 $lnk->linkify_mids('..', \$rv);
757 $refs = references($hdr);
758 my $irt = pop @$refs;
760 my $html = ascii_html($irt);
761 my $href = mid_href($irt);
762 $rv .= "In-Reply-To: <";
763 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
767 # do not display References: if search is present,
768 # we show the thread skeleton at the bottom, instead.
771 $refs //= references($hdr);
773 @$refs = map { linkify_ref_no_over($_) } @$refs;
774 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
779 # returns a string buffer via ->getline
781 my ($ctx, $hdr) = @_;
782 my $ibx = $ctx->{-inbox};
784 my $skel = " <a\nhref=\"$upfx\">index</a>";
788 thread_skel(\$skel, $ctx, $hdr);
793 if (my $n = $ctx->{next_msg}) {
795 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
798 my $par = $ctx->{parent_msg};
803 if (my $p = $ctx->{prev_msg}) {
804 $prev = mid_href($p);
805 if ($p && $par && $p eq $par) {
806 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
807 'rel=prev>prev parent</a>';
810 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
812 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
814 } elsif ($u) { # unlikely
815 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
817 $rv .= "$next $prev$parent ";
819 $rv .= qq(<a\nhref="#R">reply</a>);
822 $rv .= msg_reply($ctx, $hdr);
825 sub linkify_ref_no_over {
827 my $href = mid_href($mid);
828 my $html = ascii_html($mid);
829 "<<a\nhref=\"../$href/\">$html</a>>";
834 'm' . id_compress($msgid, 1);
838 my ($upfx, $mid) = @_;
840 my $href = mid_href($mid);
841 my $html = ascii_html($mid);
842 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
847 $level ? INDENT x ($level - 1) : '';
851 my ($ctx, $level, $node, $idx) = @_;
852 ++$ctx->{root_idx} if $level == 0;
853 if ($node->{mid} eq $ctx->{mid}) {
854 $ctx->{found_mid_at} = $ctx->{root_idx};
860 sub strict_loose_note ($) {
863 " -- strict thread matches above, loose matches on Subject: below --\n";
865 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
867 " -- use mbox.gz link to download all $nr messages --\n";
873 my ($ctx, $msgs) = @_;
874 require PublicInbox::SearchThread;
875 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
877 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
878 # and preserved in the future. This bug is hidden by `sid' matches
879 # in get_thread, so we never noticed it until now. And even when
880 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
881 # bump since reindexing is expensive and users may not do it
883 # loose threading could've returned too many results,
884 # put the root the message we care about at the top:
885 my $mid = $ctx->{mid};
886 if (defined($mid) && scalar(@$rootset) > 1) {
887 $ctx->{root_idx} = -1;
888 my $nr = scalar @$msgs;
889 walk_thread($rootset, $ctx, \&find_mid_root);
890 my $idx = $ctx->{found_mid_at};
891 if (defined($idx) && $idx != 0) {
892 my $tip = splice(@$rootset, $idx, 1);
893 @$rootset = reverse @$rootset;
894 unshift @$rootset, $tip;
895 $ctx->{sl_note} = strict_loose_note($nr);
903 require PublicInbox::ExtMsg;
904 PublicInbox::ExtMsg::ext_msg($ctx);
908 my ($prev_subj, $subj, $val) = @_;
910 my $omit; # '"' denotes identical text omitted
911 my (@prev_pop, @curr_pop);
912 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
913 push(@prev_pop, pop(@$prev_subj));
914 push(@curr_pop, pop(@$subj));
917 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
918 if (scalar(@curr_pop) == 1) {
920 push @$prev_subj, @prev_pop;
921 push @$subj, @curr_pop;
926 sub skel_dump { # walk_thread callback
927 my ($ctx, $level, $smsg) = @_;
928 $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
930 my $skel = $ctx->{skel};
931 my $cur = $ctx->{cur};
932 my $mid = $smsg->{mid};
934 if ($level == 0 && $ctx->{skel_dump_roots}++) {
935 $$skel .= delete($ctx->{sl_note}) || '';
938 my $f = ascii_html($smsg->{from_name});
939 my $obfs_ibx = $ctx->{-obfs_ibx};
940 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
942 my $d = fmt_ts($smsg->{ds});
943 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
944 if (exists $ctx->{searchview}) {
945 if (defined(my $pct = $smsg->{pct})) {
946 $d .= (sprintf(' % 2u', $pct) . '%');
952 $d .= ' ' . indent_for($level) . th_pfx($level);
954 $ctx->{first_level} ||= $level;
956 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
957 $ctx->{prev_attr} = $attr;
959 $ctx->{prev_level} = $level;
964 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
965 "$attr [this message]</a></b>\n";
968 $ctx->{prev_msg} = $mid;
971 $ctx->{next_msg} ||= $mid;
974 # Subject is never undef, this mail was loaded from
975 # our Xapian which would've resulted in '' if it were
976 # really missing (and Filter rejects empty subjects)
977 my @subj = split(/ /, subject_normalized($smsg->{subject}));
978 # remove common suffixes from the subject if it matches the previous,
979 # so we do not show redundant text at the end.
980 my $prev_subj = $ctx->{prev_subj} || [];
981 $ctx->{prev_subj} = [ @subj ];
982 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
985 my $subj = join(' ', @subj);
986 $subj = ascii_html($subj);
987 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
988 $end = "$subj</a> $omit$f\n"
994 my $mapping = $unmatched ? undef : $ctx->{mapping};
996 my $map = $mapping->{$mid};
997 $id = id_compress($mid, 1);
999 $map->[0] = "$d<a\nhref=\"$m\">$end";
1002 $m = $ctx->{-upfx}.mid_href($mid).'/';
1004 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1009 my ($ctx, $level, $node) = @_;
1011 my $mid = $node->{mid};
1012 my $d = ' [not found] ';
1013 $d .= ' ' if exists $ctx->{searchview};
1014 $d .= indent_for($level) . th_pfx($level);
1015 my $upfx = $ctx->{-upfx};
1016 my $href = $upfx . mid_href($mid) . '/';
1017 my $html = ascii_html($mid);
1019 my $mapping = $ctx->{mapping};
1020 my $map = $mapping->{$mid} if $mapping;
1022 my $id = id_compress($mid, 1);
1023 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1024 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1026 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1028 ${$ctx->{skel}} .= $d;
1034 (eval { $a->topmost->{ds} } || 0) <=>
1035 (eval { $b->topmost->{ds} } || 0)
1039 # accumulate recent topics if search is supported
1040 # returns 200 if done, 404 if not
1041 sub acc_topic { # walk_thread callback
1042 my ($ctx, $level, $smsg) = @_;
1043 my $mid = $smsg->{mid};
1044 my $has_blob = $smsg->{blob} // do {
1045 if (my $by_mid = $ctx->{-inbox}->smsg_by_mid($mid)) {
1046 %$smsg = (%$smsg, %$by_mid);
1051 my $subj = subject_normalized($smsg->{subject});
1052 $subj = '(no subject)' if $subj eq '';
1053 my $ds = $smsg->{ds};
1054 if ($level == 0) { # new, top-level topic
1055 my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1056 $ctx->{-cur_topic} = $topic;
1057 push @{$ctx->{order}}, $topic;
1061 # continue existing topic
1062 my $topic = $ctx->{-cur_topic}; # should never be undef
1063 $topic->[0] = $ds if $ds > $topic->[0];
1064 $topic->[1]++; # bump N+ message counter
1065 my $seen = $topic->[2];
1066 if (scalar(@$topic) == 3) { # parent was a ghost
1067 push @$topic, $subj;
1068 } elsif (!defined($seen->{$subj})) {
1069 push @$topic, $level, $subj; # @extra messages
1071 $seen->{$subj} = $mid; # latest for subject
1072 } else { # ghost message
1073 return 1 if $level != 0; # ignore child ghosts
1074 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1075 push @{$ctx->{order}}, $topic;
1082 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1084 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1089 my $ibx = $ctx->{-inbox};
1090 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1092 # sort by recency, this allows new posts to "bump" old topics...
1093 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1094 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1096 next unless defined $top_subj; # ghost topic
1097 my $mid = delete $seen->{$top_subj};
1098 my $href = mid_href($mid);
1099 my $prev_subj = [ split(/ /, $top_subj) ];
1100 $top_subj = ascii_html($top_subj);
1103 # $n isn't the total number of posts on the topic,
1104 # just the number of posts in the current results window
1108 $anchor = '#u'; # top of only message
1110 $n = " ($n+ messages)";
1111 $anchor = '#t'; # thread skeleton
1114 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1115 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1116 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1117 " $ds UTC $n - $mbox / $atom\n";
1118 for (my $i = 0; $i < scalar(@extra); $i += 2) {
1119 my $level = $extra[$i];
1120 my $subj = $extra[$i + 1]; # already normalized
1121 $mid = delete $seen->{$subj};
1122 my @subj = split(/ /, $subj);
1123 my @next_prev = @subj; # full copy
1124 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1125 $prev_subj = \@next_prev;
1126 $subj = join(' ', @subj);
1127 $subj = ascii_html($subj);
1128 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1129 $href = mid_href($mid);
1130 $s .= indent_for($level) . TCHILD;
1131 $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1135 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1139 # only for the t= query parameter passed to overview DB
1140 sub ts2str ($) { strftime('%Y%m%d%H%M%S', gmtime($_[0])) };
1143 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1144 timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1147 sub pagination_footer ($$) {
1148 my ($ctx, $latest) = @_;
1149 delete $ctx->{qp} or return;
1150 my $next = $ctx->{next_page} || '';
1151 my $prev = $ctx->{prev_page} || '';
1153 $next = $next ? "$next " : ' ';
1154 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1156 "<hr><pre>page: $next$prev</pre>";
1159 sub index_nav { # callback for WwwStream
1160 my (undef, $ctx) = @_;
1161 pagination_footer($ctx, '.')
1164 sub paginate_recent ($$) {
1165 my ($ctx, $lim) = @_;
1166 my $t = $ctx->{qp}->{t} || '';
1167 my $opts = { limit => $lim };
1168 my ($after, $before);
1170 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1171 # if only $after exists "YYYYMMDD.." because "." could be skipped
1172 # if interpreted as an end-of-sentence
1173 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1174 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1176 my $ibx = $ctx->{-inbox};
1177 my $msgs = $ibx->recent($opts, $after, $before);
1178 my $nr = scalar @$msgs;
1179 if ($nr < $lim && defined($after)) {
1180 $after = $before = undef;
1181 $msgs = $ibx->recent($opts);
1182 $nr = scalar @$msgs;
1184 my $more = $nr == $lim;
1185 my ($newest, $oldest);
1187 $newest = $msgs->[0]->{ts};
1188 $oldest = $msgs->[-1]->{ts};
1189 # if we only had $after, our SQL query in ->recent ordered
1190 if ($newest < $oldest) {
1191 ($oldest, $newest) = ($newest, $oldest);
1192 $more = 0 if defined($after) && $after < $oldest;
1195 if (defined($oldest) && $more) {
1196 my $s = ts2str($oldest);
1197 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1199 if (defined($newest) && (defined($before) || defined($after))) {
1200 my $s = ts2str($newest);
1201 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1208 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1210 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1212 PublicInbox::WwwStream->response($ctx, dump_topics($ctx), \&index_nav);
1215 sub thread_adj_level {
1216 my ($ctx, $level) = @_;
1218 my $max = $ctx->{cur_level};
1220 return ('', '') if $max == 0; # flat output
1222 # reset existing lists
1223 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1224 $ctx->{cur_level} = 0;
1226 } elsif ($level == $max) { # continue existing list
1228 } elsif ($level < $max) {
1229 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1230 $ctx->{cur_level} = $level;
1231 ("$beg<li>", '</li>');
1232 } else { # ($level > $max) # start a new level
1233 $ctx->{cur_level} = $level;
1234 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1239 sub ghost_index_entry {
1240 my ($ctx, $level, $node) = @_;
1241 my ($beg, $end) = thread_adj_level($ctx, $level);
1242 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{mid})