1 # Copyright (C) 2014-2021 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 List::Util qw(max);
10 use PublicInbox::MsgTime qw(msg_datestamp);
11 use PublicInbox::Hval qw(ascii_html obfuscate_addrs prurl mid_href
13 use PublicInbox::Linkify;
14 use PublicInbox::MID qw(id_compress mids mids_for_index references
16 use PublicInbox::MsgIter;
17 use PublicInbox::Address;
18 use PublicInbox::WwwStream qw(html_oneshot);
19 use PublicInbox::Reply;
20 use PublicInbox::ViewDiff qw(flush_diff);
22 use Time::Local qw(timegm);
23 use PublicInbox::Smsg qw(subject_normalized);
24 use PublicInbox::ContentHash qw(content_hash);
25 use constant COLS => 72;
26 use constant INDENT => ' ';
27 use constant TCHILD => '` ';
28 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
32 if ($eml) { # called by WwwStream::async_eml or getline
33 my $smsg = $ctx->{smsg};
34 my $over = $ctx->{ibx}->over;
35 $ctx->{smsg} = $over ? $over->next_by_mid(@{$ctx->{next_arg}})
37 $ctx->{mhref} = ($ctx->{nr} || $ctx->{smsg}) ?
38 "../${\mid_href($smsg->{mid})}/" : '';
39 my $obuf = $ctx->{obuf} = _msg_page_prepare_obuf($eml, $ctx);
41 multipart_text_as_html($eml, $ctx);
42 $$obuf .= '</pre><hr>';
45 $$obuf .= html_footer($ctx, $ctx->{first_hdr}) if !$ctx->{smsg};
47 } else { # called by WwwStream::async_next or getline
48 $ctx->{smsg}; # may be undef
52 # /$INBOX/$MSGID/ for unindexed v1 inboxes
53 sub no_over_html ($) {
55 my $bref = $ctx->{ibx}->msg_by_mid($ctx->{mid}) or return; # 404
56 my $eml = PublicInbox::Eml->new($bref);
58 PublicInbox::WwwStream::init($ctx);
59 my $obuf = $ctx->{obuf} = _msg_page_prepare_obuf($eml, $ctx);
61 multipart_text_as_html($eml, $ctx);
62 $$obuf .= '</pre><hr>';
65 eval { $$obuf .= html_footer($ctx, $eml) };
66 html_oneshot($ctx, 200, $obuf);
69 # public functions: (unstable)
73 my $ibx = $ctx->{ibx};
74 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
75 my $over = $ibx->over or return no_over_html($ctx);
77 my $next_arg = $ctx->{next_arg} = [ $ctx->{mid}, \$id, \$prev ];
79 my $smsg = $ctx->{smsg} = $over->next_by_mid(@$next_arg) or
80 return; # undef == 404
82 # allow user to easily browse the range around this message if
84 $ctx->{-t_max} = $smsg->{ts};
85 PublicInbox::WwwStream::aresponse($ctx, 200, \&msg_page_i);
88 # /$INBOX/$MESSAGE_ID/#R
92 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
94 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
97 my $ibx = $ctx->{ibx};
98 if (my $url = $ibx->{infourl}) {
99 $url = prurl($ctx->{env}, $url);
100 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
103 my ($arg, $link, $reply_to_all) =
104 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
105 if (ref($arg) eq 'SCALAR') {
106 return '<pre id=R>'.ascii_html($$arg).'</pre>';
109 # mailto: link only works if address obfuscation is disabled
113 * If your mail client supports setting the <b>In-Reply-To</b> header
114 via mailto: links, try the <a
115 href="$link">mailto: link</a>
119 push @$arg, '/path/to/YOUR_REPLY';
120 $arg = ascii_html(join(" \\\n ", '', @$arg));
123 id=R><b>Reply instructions:</b>
125 You may reply publicly to <a
126 href=#t>this message</a> via plain-text email
127 using any one of the following methods:
129 * Save the following mbox file, import it into your mail client,
130 and $reply_to_all from there: <a
133 Avoid top-posting and favor interleaved quoting:
135 href="$p_url">$p_url</a>
137 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
138 switches of git-send-email(1):
143 href="$se_url">$se_url</a>
146 Be sure your reply has a <b>Subject:</b> header at the top and a blank line
147 before the message body.
153 my $refs = references($hdr);
157 sub fold_addresses ($) {
158 return $_[0] if length($_[0]) <= COLS;
159 # try to fold on commas after non-word chars before $lim chars,
160 # Try to get the "," preceded by ">" or ")", but avoid folding
161 # on the comma where somebody uses "Lastname, Firstname".
162 # We also try to keep the last and penultimate addresses in
163 # the list on the same line if possible, hence the extra \z
164 # Fall back to folding on spaces at $lim + 1 chars
165 my $lim = COLS - 8; # 8 = "\t" display width
166 my $too_long = $lim + 1;
167 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
169 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
172 .{$too_long,}?)(?:\s|\z)/xgo));
175 sub _hdr_names_html ($$) {
176 my ($hdr, $field) = @_;
177 my @vals = $hdr->header($field) or return '';
178 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
182 my ($nr, $singular, $plural) = @_;
183 return "0 $plural" if $nr == 0;
184 $nr == 1 ? "$nr $singular" : "$nr $plural";
187 # Displays the text of of the message for /$INBOX/$MSGID/[Tt]/ endpoint
188 # this is already inside a <pre>
190 my ($ctx, $eml) = @_;
191 my $smsg = delete $ctx->{smsg};
192 my $subj = delete $smsg->{subject};
193 my $mid_raw = $smsg->{mid};
194 my $id = id_compress($mid_raw, 1);
196 my $root_anchor = $ctx->{root_anchor} || '';
198 my $obfs_ibx = $ctx->{-obfs_ibx};
200 $subj = '(no subject)' if $subj eq '';
201 my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
202 $subj = '<b>'.ascii_html($subj).'</b>';
203 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
204 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
206 $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
208 my $ds = delete $smsg->{ds}; # for v1 non-Xapian/SQLite users
210 # Deleting these fields saves about 400K as we iterate across 1K msgs
211 delete @$smsg{qw(ts blob)};
213 my $from = _hdr_names_html($eml, 'From');
214 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
215 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
216 my $upfx = $ctx->{-upfx};
217 my $mhref = $upfx . mid_href($mid_raw) . '/';
218 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
219 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
220 my $to = fold_addresses(_hdr_names_html($eml, 'To'));
221 my $cc = fold_addresses(_hdr_names_html($eml, 'Cc'));
222 my ($tlen, $clen) = (length($to), length($cc));
224 if (($tlen + $clen) > COLS) {
225 $to_cc .= ' To: '.$to."\n" if $tlen;
226 $to_cc .= ' Cc: '.$cc."\n" if $clen;
229 $to_cc .= ' To: '.$to;
230 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
232 $to_cc .= ' Cc: '.$cc if $clen;
236 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
239 my $mapping = $ctx->{mapping};
240 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($eml)))) {
241 my $href = $upfx . mid_href($irt) . '/';
242 my $html = ascii_html($irt);
243 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
247 # scan through all parts, looking for displayable text
248 $ctx->{mhref} = $mhref;
250 $eml->each_part(\&add_text_body, $ctx, 1);
254 $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
255 "<a\nhref=\"$mhref\">permalink</a>" .
256 " <a\nhref=\"${mhref}raw\">raw</a>" .
257 " <a\nhref=\"${mhref}#R\">reply</a>";
260 if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
261 $rv .= "\t[relevance $pct%]";
264 my $nested = 'nested';
268 $flat = "<b>$flat</b>";
270 $nested = "<b>$nested</b>";
272 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
273 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
274 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
279 # do we have more messages? start a new <pre> if so
280 $rv .= scalar(@{$ctx->{msgs}}) ? '</pre><hr><pre>' : '</pre>' if $hr;
284 sub pad_link ($$;$) {
285 my ($mid, $level, $s) = @_;
287 my $href = defined($mid) ?
288 ("<a\nhref=#r".id_compress($mid, 1).">($s)</a>\n") :
290 (' 'x19).indent_for($level).th_pfx($level).$href;
294 # my ($mapping, $mid) = @_;
295 ($_[0]->{$_[1] // \'bogus'} // [ "(?)\n" ])->[0];
299 my ($mid_raw, $irt, $id, $ctx) = @_;
301 my $mapping = $ctx->{mapping} or return $rv;
303 my $mid_map = $mapping->{$mid_raw};
305 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
306 my ($attr, $node, $idx, $level) = @$mid_map;
307 my $children = $node->{children};
308 my $nr_c = scalar @$children;
311 # delete saves about 200KB on a 1K message thread
312 if (my $refs = delete $node->{references}) {
313 ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
315 my $irt_map = $mapping->{$$irt} if defined $$irt;
316 if (defined $irt_map) {
317 $siblings = $irt_map->[1]->{children};
318 $nr_s = scalar(@$siblings) - 1;
319 $rv .= $pad . $irt_map->[0];
321 my $prev = $siblings->[$idx - 1];
322 my $pmid = $prev->{mid};
324 my $s = ($idx - 1). ' preceding siblings ...';
325 $rv .= pad_link($pmid, $level, $s);
326 } elsif ($idx == 2) {
327 $rv .= $pad . _skel_hdr($mapping,
329 $siblings->[0]->{mid} : undef);
331 $rv .= $pad . _skel_hdr($mapping, $pmid);
334 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
335 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
336 $attr =~ s!\n\z!</b>\n!s;
337 $attr =~ s!<a\nhref.*</a> (?:" )?!!s; # no point in dup subject
338 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
341 my $cmid = $children->[0] ? $children->[0]->{mid} : undef;
342 $rv .= $pad . _skel_hdr($mapping, $cmid);
344 my $s = ($nr_c - 1). ' more replies';
345 $rv .= pad_link($cmid, $level + 1, $s);
346 } elsif (my $cn = $children->[1]) {
347 $rv .= $pad . _skel_hdr($mapping, $cn->{mid});
351 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
353 my $nmid = $next->{mid};
354 $rv .= $pad . _skel_hdr($mapping, $nmid);
355 my $nnext = $nr_s - $idx;
357 my $s = ($nnext - 1).' subsequent siblings';
358 $rv .= pad_link($nmid, $level, $s);
359 } elsif (my $nn = $siblings->[$idx + 2]) {
360 $rv .= $pad . _skel_hdr($mapping, $nn->{mid});
363 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
366 # non-recursive thread walker
367 sub walk_thread ($$$) {
368 my ($rootset, $ctx, $cb) = @_;
369 my @q = map { (0, $_, -1) } @$rootset;
371 my ($level, $node, $i) = splice(@q, 0, 3);
372 defined $node or next;
373 $cb->($ctx, $level, $node, $i) or return;
376 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
380 sub pre_thread { # walk_thread callback
381 my ($ctx, $level, $node, $idx) = @_;
382 $ctx->{mapping}->{$node->{mid}} = [ '', $node, $idx, $level ];
383 skel_dump($ctx, $level, $node);
386 sub thread_eml_entry {
387 my ($ctx, $eml) = @_;
388 my ($beg, $end) = thread_adj_level($ctx, $ctx->{level});
389 $beg . '<pre>' . eml_entry($ctx, $eml) . '</pre>' . $end;
392 sub next_in_queue ($$) {
393 my ($q, $ghost_ok) = @_;
395 my ($level, $smsg) = splice(@$q, 0, 2);
397 unshift @$q, map { ($cl, $_) } @{$smsg->{children}};
398 return ($level, $smsg) if $ghost_ok || exists($smsg->{blob});
403 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
404 my ($ctx, $eml) = @_;
405 return thread_eml_entry($ctx, $eml) if $eml;
406 return unless exists($ctx->{skel});
407 my $ghost_ok = $ctx->{nr}++;
409 my ($lvl, $smsg) = next_in_queue($ctx->{-queue}, $ghost_ok);
411 if (exists $smsg->{blob}) { # next message for cat-file
412 $ctx->{level} = $lvl;
413 if (!$ghost_ok) { # first non-ghost
414 $ctx->{-title_html} =
415 ascii_html($smsg->{subject});
416 $ctx->zmore($ctx->html_top);
420 # buffer the ghost entry and loop
421 $ctx->zmore(ghost_index_entry($ctx, $lvl, $smsg));
423 $ctx->zmore(join('', thread_adj_level($ctx, 0)));
424 $ctx->zmore(${delete($ctx->{skel})});
430 sub stream_thread ($$) {
431 my ($rootset, $ctx) = @_;
432 $ctx->{-queue} = [ map { (0, $_) } @$rootset ];
433 PublicInbox::WwwStream::aresponse($ctx, 200, \&stream_thread_i);
436 # /$INBOX/$MSGID/t/ and /$INBOX/$MSGID/T/
439 $ctx->{-upfx} = '../../';
440 my $mid = $ctx->{mid};
441 my $ibx = $ctx->{ibx};
442 my ($nr, $msgs) = $ibx->over->get_thread($mid);
443 return missing_thread($ctx) if $nr == 0;
445 # link $INBOX_DIR/description text to "index_topics" view around
446 # the newest message in this thread
447 my $t = ts2str($ctx->{-t_max} = max(map { delete $_->{ts} } @$msgs));
448 my $t_fmt = fmt_ts($ctx->{-t_max});
450 my $skel = '<hr><pre>';
451 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
454 href="../../?t=$t">~$t_fmt UTC</a> | <a
455 href="../../">newest</a>]
458 $skel .= "<b\nid=t>Thread overview:</b> ";
459 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
460 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
461 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
462 $skel .= "-- links below jump to the message on this page --\n";
463 $ctx->{cur_level} = 0;
464 $ctx->{skel} = \$skel;
465 $ctx->{prev_attr} = '';
466 $ctx->{prev_level} = 0;
467 $ctx->{root_anchor} = 'm' . id_compress($mid, 1);
468 $ctx->{mapping} = {}; # mid -> [ header_summary, node, idx, level ]
469 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
472 my $rootset = thread_results($ctx, $msgs);
474 # reduce hash lookups in pre_thread->skel_dump
475 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
476 walk_thread($rootset, $ctx, \&pre_thread);
479 return stream_thread($rootset, $ctx) unless $ctx->{flat};
481 # flat display: lazy load the full message from smsg
482 $ctx->{msgs} = $msgs;
483 $ctx->{-html_tip} = '<pre>';
484 PublicInbox::WwwStream::aresponse($ctx, 200, \&thread_html_i);
487 sub thread_html_i { # PublicInbox::WwwStream::getline callback
488 my ($ctx, $eml) = @_;
490 my $smsg = $ctx->{smsg};
491 if (exists $ctx->{-html_tip}) {
492 $ctx->{-title_html} = ascii_html($smsg->{subject});
493 $ctx->zmore($ctx->html_top);
495 return eml_entry($ctx, $eml);
497 while (my $smsg = shift @{$ctx->{msgs}}) {
498 return $smsg if exists($smsg->{blob});
500 my $skel = delete($ctx->{skel}) or return; # all done
506 sub multipart_text_as_html {
507 # ($mime, $ctx) = @_; # each_part may do "$_[0] = undef"
509 # scan through all parts, looking for displayable text
510 $_[0]->each_part(\&add_text_body, $_[1], 1);
513 sub submsg_hdr ($$) {
514 my ($ctx, $eml) = @_;
515 my $obfs_ibx = $ctx->{-obfs_ibx};
516 my $rv = $ctx->{obuf};
518 for my $h (qw(From To Cc Subject Date Message-ID X-Alt-Message-ID)) {
519 my @v = $eml->header($h);
521 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
528 sub attach_link ($$$$;$) {
529 my ($ctx, $ct, $p, $fn, $err) = @_;
530 my ($part, $depth, $idx) = @$p;
532 # Eml iteration clobbers multipart ->{bdy}, so do not offer
533 # downloads for 0-byte multipart attachments
534 return unless $part->{bdy};
536 my $nl = $idx eq '1' ? '' : "\n"; # like join("\n", ...)
537 my $size = length($part->body);
538 delete $part->{bdy}; # save memory
540 # hide attributes normally, unless we want to aid users in
541 # spotting MUA problems:
542 $ct =~ s/;.*// unless $err;
543 $ct = ascii_html($ct);
545 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
547 } elsif ($ct eq 'text/plain') {
552 my $rv = $ctx->{obuf};
553 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
556 [-- Warning: decoded text below may be mangled, UTF-8 assumed --]
559 $$rv .= "[-- Attachment #$idx: ";
560 my $ts = "Type: $ct, Size: $size bytes";
561 my $desc = $part->header('Content-Description') // $fn // '';
562 $desc = ascii_html($desc);
563 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
566 submsg_hdr($ctx, $part) if $part->{is_submsg};
571 sub add_text_body { # callback for each_part
573 my $upfx = $ctx->{mhref};
574 my $ibx = $ctx->{ibx};
575 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
576 # $p - from each_part: [ Email::MIME-like, depth, $idx ]
577 my ($part, $depth, $idx) = @$p;
578 my $ct = $part->content_type || 'text/plain';
579 my $fn = $part->filename;
580 my ($s, $err) = msg_part_text($part, $ct);
581 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
583 my $rv = $ctx->{obuf};
584 if ($part->{is_submsg}) {
585 submsg_hdr($ctx, $part);
589 # makes no difference to browsers, and don't screw up filename
590 # link generation in diffs with the extra '%0D'
593 # will be escaped to `•' in HTML
594 obfuscate_addrs($ibx, $s, "\x{2022}") if $ibx->{obfuscate};
596 # always support diff-highlighting, but we can't linkify hunk
597 # headers for solver unless some coderepo are configured:
599 if ($s =~ /^--- [^\n]+\n\+{3} [^\n]+\n@@ /ms) {
600 # diffstat anchors do not link across attachments or messages,
601 # -apfx is just a stable prefix for making diffstat anchors
602 # linkable to the first diff hunk w/o crossing attachments
603 $idx =~ tr!.!/!; # compatibility with previous versions
604 $ctx->{-apfx} = $upfx . $idx;
606 # do attr => filename mappings for diffstats in git diffs:
607 $ctx->{-anchors} = {} if $s =~ /^diff --git /sm;
609 delete $ctx->{-long_path};
611 # absolute URL (Atom feeds)
612 if ($ibx->{coderepo}) {
613 if (index($upfx, '//') >= 0) {
615 $spfx =~ s!/([^/]*)/\z!/!;
617 my $n_slash = $upfx =~ tr!/!/!;
620 } elsif ($n_slash == 1) {
622 } else { # nslash == 2
627 $ctx->{-spfx} = $spfx;
630 # split off quoted and unquoted blocks:
631 my @sections = PublicInbox::MsgIter::split_quotes($s);
632 undef $s; # free memory
633 if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
634 # badly-encoded message with $err? tell the world about it!
635 attach_link($ctx, $ct, $p, $fn, $err);
638 delete $part->{bdy}; # save memory
639 foreach my $cur (@sections) {
641 # we use a <span> here to allow users to specify
642 # their own color for quoted text
643 $$rv .= qq(<span\nclass="q">);
644 $$rv .= $l->to_html($cur);
647 flush_diff($ctx, \$cur);
650 $$rv .= $l->to_html($cur);
652 undef $cur; # free memory
656 sub _msg_page_prepare_obuf {
657 my ($eml, $ctx) = @_;
658 my $over = $ctx->{ibx}->over;
659 my $obfs_ibx = $ctx->{-obfs_ibx};
661 my $mids = mids_for_index($eml);
662 my $nr = $ctx->{nr}++;
663 if ($nr) { # unlikely
664 if ($ctx->{chash} eq content_hash($eml)) {
665 warn "W: BUG? @$mids not deduplicated properly\n";
669 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
672 $ctx->{first_hdr} = $eml->header_obj;
673 $ctx->{chash} = content_hash($eml) if $ctx->{smsg}; # reused MID
674 $rv .= "<pre\nid=b>"; # anchor for body start
676 $ctx->{-upfx} = '../' if $over;
677 my @title; # (Subject[0], From[0])
678 for my $v ($eml->header('From')) {
679 my @n = PublicInbox::Address::names($v);
681 $title[1] //= ascii_html(join(', ', @n));
683 obfuscate_addrs($obfs_ibx, $v);
684 obfuscate_addrs($obfs_ibx, $title[1]);
686 $rv .= "From: $v\n" if $v ne '';
688 foreach my $h (qw(To Cc)) {
689 for my $v ($eml->header($h)) {
692 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
693 $rv .= "$h: $v\n" if $v ne '';
696 my @subj = $eml->header('Subject');
698 my $v = ascii_html(shift @subj);
699 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
701 $rv .= $over ? qq(<a\nhref="#r"\nid=t>$v</a>\n) : "$v\n";
703 for $v (@subj) { # multi-Subject message :<
705 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
706 $rv .= "Subject: $v\n";
708 } else { # dummy anchor for thread skeleton at bottom of page
709 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
710 $title[0] = '(no subject)';
712 for my $v ($eml->header('Date')) {
714 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
715 $rv .= qq{Date: $v\t<a\nhref="#r">[thread overview]</a>\n};
717 if (!$nr) { # first (and only) message, common case
718 $ctx->{-title_html} = join(' - ', @title);
719 $rv = $ctx->html_top . $rv;
721 if (scalar(@$mids) == 1) { # common case
722 my $mhtml = ascii_html($mids->[0]);
723 $rv .= "Message-ID: <$mhtml> ";
724 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
726 # X-Alt-Message-ID can happen if a message is injected from
727 # public-inbox-nntpd because of multiple Message-ID headers.
728 my $lnk = PublicInbox::Linkify->new;
730 for my $h (qw(Message-ID X-Alt-Message-ID)) {
731 $s .= "$h: $_\n" for ($eml->header_raw($h));
733 $lnk->linkify_mids('..', \$s, 1);
736 $rv .= _parent_headers($eml, $over);
742 qq(expand[<a\nhref="T/#u">flat</a>) .
743 qq(|<a\nhref="t/#u">nested</a>] ) .
744 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
745 qq(<a\nhref="t.atom">Atom feed</a>);
748 sub thread_skel ($$$) {
749 my ($skel, $ctx, $hdr) = @_;
750 my $mid = mids($hdr)->[0];
751 my $ibx = $ctx->{ibx};
752 my ($nr, $msgs) = $ibx->over->get_thread($mid);
753 my $parent = in_reply_to($hdr);
754 $$skel .= "\n<b>Thread overview: </b>";
756 if (defined $parent) {
757 $$skel .= SKEL_EXPAND."\n ";
758 $$skel .= ghost_parent('../', $parent) . "\n";
760 $$skel .= "<a\nid=r>[no followups]</a> ".
763 $ctx->{next_msg} = undef;
764 $ctx->{parent_msg} = $parent;
769 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
771 # nb: mutt only shows the first Subject in the index pane
772 # when multiple Subject: headers are present, so we follow suit:
773 my $subj = $hdr->header('Subject') // '';
774 $subj = '(no subject)' if $subj eq '';
775 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
777 $ctx->{prev_attr} = '';
778 $ctx->{prev_level} = 0;
779 $ctx->{skel} = $skel;
781 # reduce hash lookups in skel_dump
782 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
783 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
785 $ctx->{parent_msg} = $parent;
788 sub _parent_headers {
789 my ($hdr, $over) = @_;
791 my @irt = $hdr->header_raw('In-Reply-To');
794 my $lnk = PublicInbox::Linkify->new;
795 $rv .= "In-Reply-To: $_\n" for @irt;
796 $lnk->linkify_mids('..', \$rv);
798 $refs = references($hdr);
799 my $irt = pop @$refs;
801 my $html = ascii_html($irt);
802 my $href = mid_href($irt);
803 $rv .= "In-Reply-To: <";
804 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
808 # do not display References: if search is present,
809 # we show the thread skeleton at the bottom, instead.
812 $refs //= references($hdr);
814 @$refs = map { linkify_ref_no_over($_) } @$refs;
815 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
820 # returns a string buffer
822 my ($ctx, $hdr) = @_;
823 my $ibx = $ctx->{ibx};
828 my $t = ts2str($ctx->{-t_max});
829 my $t_fmt = fmt_ts($ctx->{-t_max});
832 href="$upfx?t=$t">~$t_fmt UTC</a>|<a
833 href="$upfx">newest</a>]
836 thread_skel(\$skel, $ctx, $hdr);
841 if (my $n = $ctx->{next_msg}) {
843 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
846 my $par = $ctx->{parent_msg};
851 if (my $p = $ctx->{prev_msg}) {
852 $prev = mid_href($p);
853 if ($p && $par && $p eq $par) {
854 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
855 'rel=prev>prev parent</a>';
858 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
860 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
862 } elsif ($u) { # unlikely
863 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
865 $rv .= "$next $prev$parent ";
866 } else { # unindexed inboxes w/o over
867 $skel = qq( <a\nhref="$upfx">latest</a>);
869 $rv .= qq(<a\nhref="#R">reply</a>);
872 $rv .= msg_reply($ctx, $hdr);
875 sub linkify_ref_no_over {
877 my $href = mid_href($mid);
878 my $html = ascii_html($mid);
879 "<<a\nhref=\"../$href/\">$html</a>>";
883 my ($upfx, $mid) = @_;
885 my $href = mid_href($mid);
886 my $html = ascii_html($mid);
887 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
892 $level ? INDENT x ($level - 1) : '';
896 my ($ctx, $level, $node, $idx) = @_;
897 ++$ctx->{root_idx} if $level == 0;
898 if ($node->{mid} eq $ctx->{mid}) {
899 $ctx->{found_mid_at} = $ctx->{root_idx};
900 return 0; # stop iterating
905 sub strict_loose_note ($) {
908 " -- strict thread matches above, loose matches on Subject: below --\n";
910 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
912 " -- use mbox.gz link to download all $nr messages --\n";
918 my ($ctx, $msgs) = @_;
919 require PublicInbox::SearchThread;
920 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
922 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
923 # and preserved in the future. This bug is hidden by `sid' matches
924 # in get_thread, so we never noticed it until now. And even when
925 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
926 # bump since reindexing is expensive and users may not do it
928 # loose threading could've returned too many results,
929 # put the root the message we care about at the top:
930 my $mid = $ctx->{mid};
931 if (defined($mid) && scalar(@$rootset) > 1) {
932 $ctx->{root_idx} = -1;
933 my $nr = scalar @$msgs;
934 walk_thread($rootset, $ctx, \&find_mid_root);
935 my $idx = $ctx->{found_mid_at};
936 if (defined($idx) && $idx != 0) {
937 my $tip = splice(@$rootset, $idx, 1);
938 @$rootset = reverse @$rootset;
939 unshift @$rootset, $tip;
940 $ctx->{sl_note} = strict_loose_note($nr);
948 require PublicInbox::ExtMsg;
949 PublicInbox::ExtMsg::ext_msg($ctx);
953 my ($prev_subj, $subj, $val) = @_;
955 my $omit; # '"' denotes identical text omitted
956 my (@prev_pop, @curr_pop);
957 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
958 push(@prev_pop, pop(@$prev_subj));
959 push(@curr_pop, pop(@$subj));
962 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
963 if (scalar(@curr_pop) == 1) {
965 push @$prev_subj, @prev_pop;
966 push @$subj, @curr_pop;
971 sub skel_dump { # walk_thread callback
972 my ($ctx, $level, $smsg) = @_;
973 $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
975 my $skel = $ctx->{skel};
976 my $cur = $ctx->{cur};
977 my $mid = $smsg->{mid};
979 if ($level == 0 && $ctx->{skel_dump_roots}++) {
980 $$skel .= delete($ctx->{sl_note}) || '';
983 my $f = ascii_html(delete $smsg->{from_name});
984 my $obfs_ibx = $ctx->{-obfs_ibx};
985 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
987 my $d = fmt_ts($smsg->{ds});
988 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
989 if (exists $ctx->{searchview}) {
990 if (defined(my $pct = $smsg->{pct})) {
991 $d .= (sprintf(' % 2u', $pct) . '%');
997 $d .= ' ' . indent_for($level) . th_pfx($level);
999 $ctx->{first_level} ||= $level;
1001 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
1002 $ctx->{prev_attr} = $attr;
1004 $ctx->{prev_level} = $level;
1009 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
1010 "$attr [this message]</a></b>\n";
1013 $ctx->{prev_msg} = $mid;
1016 $ctx->{next_msg} ||= $mid;
1019 # Subject is never undef, this mail was loaded from
1020 # our Xapian which would've resulted in '' if it were
1021 # really missing (and Filter rejects empty subjects)
1022 my @subj = split(/ /, subject_normalized($smsg->{subject}));
1023 # remove common suffixes from the subject if it matches the previous,
1024 # so we do not show redundant text at the end.
1025 my $prev_subj = $ctx->{prev_subj} || [];
1026 $ctx->{prev_subj} = [ @subj ];
1027 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
1030 my $subj = join(' ', @subj);
1031 $subj = ascii_html($subj);
1032 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1033 $end = "$subj</a> $omit$f\n"
1039 my $mapping = $unmatched ? undef : $ctx->{mapping};
1041 my $map = $mapping->{$mid};
1042 $id = id_compress($mid, 1);
1044 $map->[0] = "$d<a\nhref=\"$m\">$end";
1047 $m = $ctx->{-upfx}.mid_href($mid).'/';
1049 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1054 my ($ctx, $level, $node) = @_;
1056 my $mid = $node->{mid};
1057 my $d = ' [not found] ';
1058 $d .= ' ' if exists $ctx->{searchview};
1059 $d .= indent_for($level) . th_pfx($level);
1060 my $upfx = $ctx->{-upfx};
1061 my $href = $upfx . mid_href($mid) . '/';
1062 my $html = ascii_html($mid);
1064 my $mapping = $ctx->{mapping};
1065 my $map = $mapping->{$mid} if $mapping;
1067 my $id = id_compress($mid, 1);
1068 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1069 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1071 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1073 ${$ctx->{skel}} .= $d;
1079 (eval { $a->topmost->{ds} } || 0) <=>
1080 (eval { $b->topmost->{ds} } || 0)
1084 # accumulate recent topics if search is supported
1085 # returns 200 if done, 404 if not
1086 sub acc_topic { # walk_thread callback
1087 my ($ctx, $level, $smsg) = @_;
1088 my $mid = $smsg->{mid};
1089 my $has_blob = $smsg->{blob} // do {
1090 if (my $by_mid = $ctx->{ibx}->smsg_by_mid($mid)) {
1091 %$smsg = (%$smsg, %$by_mid);
1096 my $subj = subject_normalized($smsg->{subject});
1097 $subj = '(no subject)' if $subj eq '';
1098 my $ds = $smsg->{ds};
1099 if ($level == 0) { # new, top-level topic
1100 my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1101 $ctx->{-cur_topic} = $topic;
1102 push @{$ctx->{order}}, $topic;
1106 # continue existing topic
1107 my $topic = $ctx->{-cur_topic}; # should never be undef
1108 $topic->[0] = $ds if $ds > $topic->[0];
1109 $topic->[1]++; # bump N+ message counter
1110 my $seen = $topic->[2];
1111 if (scalar(@$topic) == 3) { # parent was a ghost
1112 push @$topic, $subj;
1113 } elsif (!defined($seen->{$subj})) {
1114 push @$topic, $level, $subj; # @extra messages
1116 $seen->{$subj} = $mid; # latest for subject
1117 } else { # ghost message
1118 return 1 if $level != 0; # ignore child ghosts
1119 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1120 push @{$ctx->{order}}, $topic;
1127 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1129 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1134 my $ibx = $ctx->{ibx};
1135 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1137 # sort by recency, this allows new posts to "bump" old topics...
1138 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1139 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1141 next unless defined $top_subj; # ghost topic
1142 my $mid = delete $seen->{$top_subj};
1143 my $href = mid_href($mid);
1144 my $prev_subj = [ split(/ /, $top_subj) ];
1145 $top_subj = ascii_html($top_subj);
1148 # $n isn't the total number of posts on the topic,
1149 # just the number of posts in the current results window
1153 $anchor = '#u'; # top of only message
1155 $n = " ($n+ messages)";
1156 $anchor = '#t'; # thread skeleton
1159 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1161 for (my $i = 0; $i < scalar(@extra); $i += 2) {
1162 my $level = $extra[$i];
1163 my $subj = $extra[$i + 1]; # already normalized
1164 $mid = delete $seen->{$subj};
1165 my @subj = split(/ /, $subj);
1166 my @next_prev = @subj; # full copy
1167 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1168 $prev_subj = \@next_prev;
1169 $subj = join(' ', @subj);
1170 $subj = ascii_html($subj);
1171 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1172 $href = mid_href($mid);
1173 $s .= indent_for($level) . TCHILD;
1174 $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1178 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1183 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1184 timegm($ss || 0, $mm || 0, $hh || 0, $dd, $mon - 1, $yyyy);
1187 sub pagination_footer ($$) {
1188 my ($ctx, $latest) = @_;
1189 my $next = $ctx->{next_page} || '';
1190 my $prev = $ctx->{prev_page} || '';
1191 if ($prev) { # aligned padding for: 'next (older) | '
1192 $next = $next ? "$next | " : ' | ';
1193 $prev .= qq[ | <a\nhref="$latest">latest</a>];
1195 "<hr><pre>page: $next$prev</pre>";
1198 sub paginate_recent ($$) {
1199 my ($ctx, $lim) = @_;
1200 my $t = $ctx->{qp}->{t} || '';
1201 my $opts = { limit => $lim };
1202 my ($after, $before);
1204 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1205 # if only $after exists "YYYYMMDD.." because "." could be skipped
1206 # if interpreted as an end-of-sentence
1207 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1208 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1210 my $ibx = $ctx->{ibx};
1211 my $msgs = $ibx->recent($opts, $after, $before);
1212 my $nr = scalar @$msgs;
1213 if ($nr < $lim && defined($after)) {
1214 $after = $before = undef;
1215 $msgs = $ibx->recent($opts);
1216 $nr = scalar @$msgs;
1218 my $more = $nr == $lim;
1219 my ($newest, $oldest);
1221 $newest = $msgs->[0]->{ts};
1222 $oldest = $msgs->[-1]->{ts};
1223 # if we only had $after, our SQL query in ->recent ordered
1224 if ($newest < $oldest) {
1225 ($oldest, $newest) = ($newest, $oldest);
1226 $more = 0 if defined($after) && $after < $oldest;
1229 if (defined($oldest) && $more) {
1230 my $s = ts2str($oldest);
1231 $ctx->{next_page} = qq[<a\nhref="?t=$s"\nrel=next>] .
1234 if (defined($newest) && (defined($before) || defined($after))) {
1235 my $s = ts2str($newest);
1236 $ctx->{prev_page} = qq[<a\nhref="?t=$s-"\nrel=prev>] .
1242 # GET /$INBOX - top-level inbox view for indexed inboxes
1245 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1247 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1249 html_oneshot($ctx, dump_topics($ctx), \pagination_footer($ctx, '.'));
1253 sub thread_adj_level {
1254 my ($ctx, $level) = @_;
1256 my $max = $ctx->{cur_level};
1258 return ('', '') if $max == 0; # flat output
1260 # reset existing lists
1261 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1262 $ctx->{cur_level} = 0;
1264 } elsif ($level == $max) { # continue existing list
1266 } elsif ($level < $max) {
1267 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1268 $ctx->{cur_level} = $level;
1269 ("$beg<li>", '</li>');
1270 } else { # ($level > $max) # start a new level
1271 $ctx->{cur_level} = $level;
1272 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1277 sub ghost_index_entry {
1278 my ($ctx, $level, $node) = @_;
1279 my ($beg, $end) = thread_adj_level($ctx, $level);
1280 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{mid} // '?')