1 # Copyright (C) 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 Text::Wrap qw(wrap); # stdlib, we need Perl 5.6+ for $huge
11 use PublicInbox::MsgTime qw(msg_datestamp);
12 use PublicInbox::Hval qw(ascii_html obfuscate_addrs prurl mid_href
14 use PublicInbox::Linkify;
15 use PublicInbox::MID qw(id_compress mids mids_for_index references
17 use PublicInbox::MsgIter;
18 use PublicInbox::Address;
19 use PublicInbox::WwwStream qw(html_oneshot);
20 use PublicInbox::Reply;
21 use PublicInbox::ViewDiff qw(flush_diff);
23 use POSIX qw(strftime);
24 use Time::Local qw(timegm);
25 use PublicInbox::Smsg qw(subject_normalized);
26 use PublicInbox::ContentHash qw(content_hash);
27 use constant COLS => 72;
28 use constant INDENT => ' ';
29 use constant TCHILD => '` ';
30 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
34 if ($eml) { # called by WwwStream::async_eml or getline
35 my $smsg = $ctx->{smsg};
36 my $over = $ctx->{ibx}->over;
37 $ctx->{smsg} = $over ? $over->next_by_mid(@{$ctx->{next_arg}})
39 $ctx->{mhref} = ($ctx->{nr} || $ctx->{smsg}) ?
40 "../${\mid_href($smsg->{mid})}/" : '';
41 if (_msg_page_prepare($eml, $ctx)) {
42 $eml->each_part(\&add_text_body, $ctx, 1);
43 print { $ctx->{zfh} } '</pre><hr>';
45 html_footer($ctx, $ctx->{first_hdr}) if !$ctx->{smsg};
46 ''; # XXX TODO cleanup
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 if (_msg_page_prepare($eml, $ctx)) { # sets {-title_html}
60 $eml->each_part(\&add_text_body, $ctx, 1);
61 print { $ctx->{zfh} } '</pre><hr>';
63 html_footer($ctx, $eml);
67 # public functions: (unstable)
71 my $ibx = $ctx->{ibx};
72 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
73 my $over = $ibx->over or return no_over_html($ctx);
75 my $next_arg = $ctx->{next_arg} = [ $ctx->{mid}, \$id, \$prev ];
77 my $smsg = $ctx->{smsg} = $over->next_by_mid(@$next_arg) or
78 return; # undef == 404
80 # allow user to easily browse the range around this message if
82 $ctx->{-t_max} = $smsg->{ts};
83 PublicInbox::WwwStream::aresponse($ctx, \&msg_page_i);
86 # /$INBOX/$MESSAGE_ID/#R
90 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
92 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
95 my $ibx = $ctx->{ibx};
96 if (my $url = $ibx->{infourl}) {
97 $url = prurl($ctx->{env}, $url);
98 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
101 my ($arg, $link, $reply_to_all) =
102 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
103 if (ref($arg) eq 'SCALAR') {
104 return '<pre id=R>'.ascii_html($$arg).'</pre>';
107 # mailto: link only works if address obfuscation is disabled
111 * If your mail client supports setting the <b>In-Reply-To</b> header
112 via mailto: links, try the <a
113 href="$link">mailto: link</a>
117 push @$arg, '/path/to/YOUR_REPLY';
118 $arg = ascii_html(join(" \\\n ", '', @$arg));
121 id=R><b>Reply instructions:</b>
123 You may reply publicly to <a
124 href=#t>this message</a> via plain-text email
125 using any one of the following methods:
127 * Save the following mbox file, import it into your mail client,
128 and $reply_to_all from there: <a
131 Avoid top-posting and favor interleaved quoting:
133 href="$p_url">$p_url</a>
135 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
136 switches of git-send-email(1):
141 href="$se_url">$se_url</a>
144 Be sure your reply has a <b>Subject:</b> header at the top and a blank line
145 before the message body.
151 my $refs = references($hdr);
155 sub fold_addresses ($) {
156 return $_[0] if length($_[0]) <= COLS;
157 # try to fold on commas after non-word chars before $lim chars,
158 # Try to get the "," preceded by ">" or ")", but avoid folding
159 # on the comma where somebody uses "Lastname, Firstname".
160 # We also try to keep the last and penultimate addresses in
161 # the list on the same line if possible, hence the extra \z
162 # Fall back to folding on spaces at $lim + 1 chars
163 my $lim = COLS - 8; # 8 = "\t" display width
164 my $too_long = $lim + 1;
165 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
167 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
170 .{$too_long,}?)(?:\s|\z)/xgo));
173 sub _hdr_names_html ($$) {
174 my ($hdr, $field) = @_;
175 my @vals = $hdr->header($field) or return '';
176 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
180 my ($nr, $singular, $plural) = @_;
181 return "0 $plural" if $nr == 0;
182 $nr == 1 ? "$nr $singular" : "$nr $plural";
185 # Displays the text of of the message for /$INBOX/$MSGID/[Tt]/ endpoint
186 # this is already inside a <pre>
188 my ($ctx, $eml) = @_;
189 my $smsg = delete $ctx->{smsg};
190 my $subj = delete $smsg->{subject};
191 my $mid_raw = $smsg->{mid};
192 my $id = id_compress($mid_raw, 1);
194 my $root_anchor = $ctx->{root_anchor} || '';
196 my $obfs_ibx = $ctx->{-obfs_ibx};
198 $subj = '(no subject)' if $subj eq '';
199 my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
200 $subj = '<b>'.ascii_html($subj).'</b>';
201 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
202 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
204 $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
206 my $ds = delete $smsg->{ds}; # for v1 non-Xapian/SQLite users
208 # Deleting these fields saves about 400K as we iterate across 1K msgs
209 delete @$smsg{qw(ts blob)};
211 my $from = _hdr_names_html($eml, 'From');
212 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
213 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
214 my $upfx = $ctx->{-upfx};
215 my $mhref = $upfx . mid_href($mid_raw) . '/';
216 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
217 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
218 my $to = fold_addresses(_hdr_names_html($eml, 'To'));
219 my $cc = fold_addresses(_hdr_names_html($eml, 'Cc'));
220 my ($tlen, $clen) = (length($to), length($cc));
222 if (($tlen + $clen) > COLS) {
223 $to_cc .= ' To: '.$to."\n" if $tlen;
224 $to_cc .= ' Cc: '.$cc."\n" if $clen;
227 $to_cc .= ' To: '.$to;
228 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
230 $to_cc .= ' Cc: '.$cc if $clen;
234 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
237 my $mapping = $ctx->{mapping};
238 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($eml)))) {
239 my $href = $upfx . mid_href($irt) . '/';
240 my $html = ascii_html($irt);
241 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
243 say { $ctx->zfh } $rv;
245 # scan through all parts, looking for displayable text
246 $ctx->{mhref} = $mhref;
247 $ctx->{changed_href} = "#e$id"; # for diffstat "files? changed,"
248 $eml->each_part(\&add_text_body, $ctx, 1); # expensive
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>";
256 delete($ctx->{-qry}) and
257 $rv .= qq[ <a\nhref="${mhref}#related">related</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} //
304 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
305 my ($attr, $node, $idx, $level) = @$mid_map;
306 my $children = $node->{children};
307 my $nr_c = scalar @$children;
310 # delete saves about 200KB on a 1K message thread
311 if (my $refs = delete $node->{references}) {
312 ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
314 my $irt_map = $mapping->{$$irt} if defined $$irt;
315 if (defined $irt_map) {
316 $siblings = $irt_map->[1]->{children};
317 $nr_s = scalar(@$siblings) - 1;
318 $rv .= $pad . $irt_map->[0];
320 my $prev = $siblings->[$idx - 1];
321 my $pmid = $prev->{mid};
323 my $s = ($idx - 1). ' preceding siblings ...';
324 $rv .= pad_link($pmid, $level, $s);
325 } elsif ($idx == 2) {
326 $rv .= $pad . _skel_hdr($mapping,
328 $siblings->[0]->{mid} : undef);
330 $rv .= $pad . _skel_hdr($mapping, $pmid);
333 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
334 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
335 chop $attr; # remove "\n"
336 $attr =~ s!<a\nhref.*</a> (?:" )?!!s; # no point in dup subject
337 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
338 $rv .= "<b>@ $attr</b>\n";
340 my $cmid = $children->[0] ? $children->[0]->{mid} : undef;
341 $rv .= $pad . _skel_hdr($mapping, $cmid);
343 my $s = ($nr_c - 1). ' more replies';
344 $rv .= pad_link($cmid, $level + 1, $s);
345 } elsif (my $cn = $children->[1]) {
346 $rv .= $pad . _skel_hdr($mapping, $cn->{mid});
350 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
352 my $nmid = $next->{mid};
353 $rv .= $pad . _skel_hdr($mapping, $nmid);
354 my $nnext = $nr_s - $idx;
356 my $s = ($nnext - 1).' subsequent siblings';
357 $rv .= pad_link($nmid, $level, $s);
358 } elsif (my $nn = $siblings->[$idx + 2]) {
359 $rv .= $pad . _skel_hdr($mapping, $nn->{mid});
362 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
365 # non-recursive thread walker
366 sub walk_thread ($$$) {
367 my ($rootset, $ctx, $cb) = @_;
368 my @q = map { (0, $_, -1) } @$rootset;
370 my ($level, $node, $i) = splice(@q, 0, 3);
371 defined $node or next;
372 $cb->($ctx, $level, $node, $i) or return;
375 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
379 sub pre_thread { # walk_thread callback
380 my ($ctx, $level, $node, $idx) = @_;
381 $ctx->{mapping}->{$node->{mid}} = [ '', $node, $idx, $level ];
382 skel_dump($ctx, $level, $node);
385 sub thread_eml_entry {
386 my ($ctx, $eml) = @_;
387 my ($beg, $end) = thread_adj_level($ctx, $ctx->{level});
388 print { $ctx->zfh } $beg, '<pre>';
389 print { $ctx->{zfh} } 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 print { $ctx->zfh } $ctx->html_top;
420 # buffer the ghost entry and loop
421 print { $ctx->zfh } ghost_index_entry($ctx, $lvl, $smsg)
423 print { $ctx->zfh } thread_adj_level($ctx, 0),
424 ${delete($ctx->{skel})};
430 sub stream_thread ($$) {
431 my ($rootset, $ctx) = @_;
432 @{$ctx->{-queue}} = map { (0, $_) } @$rootset;
433 PublicInbox::WwwStream::aresponse($ctx, \&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, \&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 print { $ctx->zfh } $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
501 print { $ctx->zfh } $$skel;
506 sub submsg_hdr ($$) {
507 my ($ctx, $eml) = @_;
509 for my $h (qw(From To Cc Subject Date Message-ID X-Alt-Message-ID)) {
510 $s .= "$h: $_\n" for $eml->header($h);
512 obfuscate_addrs($ctx->{-obfs_ibx}, $s) if $ctx->{-obfs_ibx};
516 sub attach_link ($$$$;$) {
517 my ($ctx, $ct, $p, $fn, $err) = @_;
518 my ($part, $depth, $idx) = @$p;
520 # Eml iteration clobbers multipart ->{bdy}, so do not offer
521 # downloads for 0-byte multipart attachments
522 return unless $part->{bdy};
524 my $size = length($part->body);
525 delete $part->{bdy}; # save memory
527 # hide attributes normally, unless we want to aid users in
528 # spotting MUA problems:
529 $ct =~ s/;.*// unless $err;
530 $ct = ascii_html($ct);
532 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
534 } elsif ($ct eq 'text/plain') {
539 my $rv = $idx eq '1' ? '' : "\n"; # like join("\n", ...)
540 $rv .= qq(<a\nhref="$ctx->{mhref}$idx-$sfn">);
541 $rv .= <<EOF if $err;
542 [-- Warning: decoded text below may be mangled, UTF-8 assumed --]
544 $rv .= "[-- Attachment #$idx: ";
545 my $desc = $part->header('Content-Description') // $fn // '';
546 $rv .= ascii_html($desc)." --]\n[-- " if $desc ne '';
547 $rv .= "Type: $ct, Size: $size bytes --]</a>\n";
548 $rv .= submsg_hdr($ctx, $part) if $part->{is_submsg};
552 sub add_text_body { # callback for each_part
554 my $upfx = $ctx->{mhref};
555 my $ibx = $ctx->{ibx};
556 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
557 # $p - from each_part: [ Email::MIME-like, depth, $idx ]
558 my ($part, $depth, $idx) = @$p;
559 my $ct = $part->content_type || 'text/plain';
560 my $fn = $part->filename;
561 my ($s, $err) = msg_part_text($part, $ct);
563 $s // return print $zfh (attach_link($ctx, $ct, $p, $fn) // '');
564 say $zfh submsg_hdr($ctx, $part) if $part->{is_submsg};
566 # makes no difference to browsers, and don't screw up filename
567 # link generation in diffs with the extra '%0D'
570 # will be escaped to `•' in HTML
571 obfuscate_addrs($ibx, $s, "\x{2022}") if $ibx->{obfuscate};
573 # always support diff-highlighting, but we can't linkify hunk
574 # headers for solver unless some coderepo are configured:
576 if ($s =~ /^--- [^\n]+\n\+{3} [^\n]+\n@@ /ms) {
577 # diffstat anchors do not link across attachments or messages,
578 # -apfx is just a stable prefix for making diffstat anchors
579 # linkable to the first diff hunk w/o crossing attachments
580 $idx =~ tr!.!/!; # compatibility with previous versions
581 $ctx->{-apfx} = $upfx . $idx;
583 # do attr => filename mappings for diffstats in git diffs:
584 $ctx->{-anchors} = {} if $s =~ /^diff --git /sm;
586 delete $ctx->{-long_path};
588 # absolute URL (Atom feeds)
589 if ($ibx->{coderepo}) {
590 if (index($upfx, '//') >= 0) {
592 $spfx =~ s!/([^/]*)/\z!/!;
594 my $n_slash = $upfx =~ tr!/!/!;
597 } elsif ($n_slash == 1) {
599 } else { # nslash == 2
604 $ctx->{-spfx} = $spfx;
607 # split off quoted and unquoted blocks:
608 my @sections = PublicInbox::MsgIter::split_quotes($s);
609 undef $s; # free memory
610 if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
611 # badly-encoded message with $err? tell the world about it!
612 say $zfh attach_link($ctx, $ct, $p, $fn, $err);
614 delete $part->{bdy}; # save memory
615 for my $cur (@sections) { # $cur may be huge
617 # we use a <span> here to allow users to specify
618 # their own color for quoted text
619 print $zfh qq(<span\nclass="q">),
620 $l->to_html($cur), '</span>';
622 flush_diff($ctx, \$cur);
623 } else { # regular lines, OK
624 print $zfh $l->to_html($cur);
626 undef $cur; # free memory
630 sub _msg_page_prepare {
631 my ($eml, $ctx) = @_;
632 my $have_over = !!$ctx->{ibx}->over;
633 my $mids = mids_for_index($eml);
634 my $nr = $ctx->{nr}++;
635 if ($nr) { # unlikely
636 if ($ctx->{chash} eq content_hash($eml)) {
637 warn "W: BUG? @$mids not deduplicated properly\n";
641 "<pre>WARNING: multiple messages have this Message-ID\n</pre><pre>";
643 $ctx->{first_hdr} = $eml->header_obj;
644 $ctx->{chash} = content_hash($eml) if $ctx->{smsg}; # reused MID
645 $ctx->{-html_tip} = "<pre\nid=b>"; # anchor for body start
647 $ctx->{-upfx} = '../';
648 my @title; # (Subject[0], From[0])
650 for my $v ($eml->header('From')) {
651 my @n = PublicInbox::Address::names($v);
652 $title[1] //= join(', ', @n);
653 $hbuf .= "From: $v\n" if $v ne '';
655 for my $h (qw(To Cc)) {
656 for my $v ($eml->header($h)) {
658 $hbuf .= "$h: $v\n" if $v ne '';
661 my @subj = $eml->header('Subject');
662 $hbuf .= "Subject: $_\n" for @subj;
663 $title[0] = $subj[0] // '(no subject)';
664 $hbuf .= "Date: $_\n" for $eml->header('Date');
665 $hbuf = ascii_html($hbuf);
666 $ctx->{-title_html} = ascii_html(join(' - ', @title));
667 if (my $obfs_ibx = $ctx->{-obfs_ibx}) {
668 obfuscate_addrs($obfs_ibx, $hbuf);
669 obfuscate_addrs($obfs_ibx, $ctx->{-title_html});
672 # [thread overview] link is typically added after Date,
673 # but added after Subject, or even nothing.
675 chop $hbuf; # drop "\n", or noop if $rv eq ''
676 $hbuf .= qq{\t<a\nhref="#r">[thread overview]</a>\n};
677 $hbuf =~ s!^Subject:\x20(.*?)(\n[A-Z]|\z)
678 !Subject: <a\nhref="#r"\nid=t>$1</a>$2!msx or
679 $hbuf .= qq(<a\nhref="#r\nid=t></a>);
681 if (scalar(@$mids) == 1) { # common case
682 my $x = ascii_html($mids->[0]);
683 $hbuf .= qq[Message-ID: <$x> (<a href="raw">raw</a>)\n];
685 if (!$nr) { # first (and only) message, common case
686 print { $ctx->zfh } $ctx->html_top, $hbuf;
688 delete $ctx->{-title_html};
689 print { $ctx->zfh } $ctx->{-html_tip}, $hbuf;
691 $ctx->{-linkify} //= PublicInbox::Linkify->new;
693 if (scalar(@$mids) != 1) { # unlikely, but it happens :<
694 # X-Alt-Message-ID can happen if a message is injected from
695 # public-inbox-nntpd because of multiple Message-ID headers.
696 for my $h (qw(Message-ID X-Alt-Message-ID)) {
697 $hbuf .= "$h: $_\n" for ($eml->header_raw($h));
699 $ctx->{-linkify}->linkify_mids('..', \$hbuf, 1); # escapes HTML
700 print { $ctx->{zfh} } $hbuf;
703 my @irt = $eml->header_raw('In-Reply-To');
706 $refs = references($eml);
707 $irt[0] = pop(@$refs) if scalar @$refs;
709 $hbuf .= "In-Reply-To: $_\n" for @irt;
711 # do not display References: if search is present,
712 # we show the thread skeleton at the bottom, instead.
714 $refs //= references($eml);
715 $hbuf .= 'References: <'.join(">\n\t<", @$refs).">\n" if @$refs;
717 $ctx->{-linkify}->linkify_mids('..', \$hbuf); # escapes HTML
718 say { $ctx->{zfh} } $hbuf;
723 qq(expand[<a\nhref="T/#u">flat</a>) .
724 qq(|<a\nhref="t/#u">nested</a>] ) .
725 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
726 qq(<a\nhref="t.atom">Atom feed</a>);
729 sub thread_skel ($$$) {
730 my ($skel, $ctx, $hdr) = @_;
731 my $mid = mids($hdr)->[0];
732 my $ibx = $ctx->{ibx};
733 my ($nr, $msgs) = $ibx->over->get_thread($mid);
734 my $parent = in_reply_to($hdr);
735 $$skel .= "\n<b>Thread overview: </b>";
737 if (defined $parent) {
738 $$skel .= SKEL_EXPAND."\n ";
739 $$skel .= ghost_parent('../', $parent) . "\n";
741 $$skel .= "<a\nid=r>[no followups]</a> ".
744 $ctx->{next_msg} = undef;
745 $ctx->{parent_msg} = $parent;
750 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
752 # nb: mutt only shows the first Subject in the index pane
753 # when multiple Subject: headers are present, so we follow suit:
754 my $subj = $hdr->header('Subject') // '';
755 $subj = '(no subject)' if $subj eq '';
757 $ctx->{prev_attr} = '';
758 $ctx->{prev_level} = 0;
759 $ctx->{skel} = $skel;
761 # reduce hash lookups in skel_dump
762 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
763 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
765 $ctx->{parent_msg} = $parent;
770 my ($ctx, $hdr) = @_;
772 my (@related, $skel);
774 my $qry = delete $ctx->{-qry};
775 if ($qry && $ctx->{ibx}->isrch) {
776 my $q = ''; # search for either ancestor or descendent patches
777 for (@{$qry->{dfpre}}, @{$qry->{dfpost}}) {
778 chop if length > 7; # include 1 abbrev "older" patches
781 chop $q; # omit trailing SP
782 local $Text::Wrap::columns = COLS;
783 local $Text::Wrap::huge = 'overflow';
784 $q = wrap('', '', $q);
785 my $rows = ($q =~ tr/\n/\n/) + 1;
790 ><pre>find likely ancestor, descendant, or conflicting patches for <a
791 href=#t>this message</a>:
792 <textarea name=q cols=${\COLS} rows=$rows>$q</textarea>
793 <input type=submit value=search
794 />\t(<a href=${upfx}_/text/help/#search>help</a>)</pre></form>
797 if ($ctx->{ibx}->over) {
798 my $t = ts2str($ctx->{-t_max});
799 my $t_fmt = fmt_ts($ctx->{-t_max});
800 my $fallback = @related ? "\t" : "<a id=related>\t</a>";
802 ${fallback}other threads:[<a
803 href="$upfx?t=$t">~$t_fmt UTC</a>|<a
804 href="$upfx">newest</a>]
806 thread_skel(\$skel, $ctx, $hdr);
811 if (my $n = $ctx->{next_msg}) {
813 $next = qq(<a\nhref="$upfx$n/"\nrel=next>next</a>);
815 my $par = $ctx->{parent_msg};
816 my $u = $par ? $upfx.mid_href($par).'/' : undef;
817 if (my $p = $ctx->{prev_msg}) {
818 $prev = mid_href($p);
819 if ($p && $par && $p eq $par) {
820 $prev = qq(<a\nhref="$upfx$prev/"\n) .
821 'rel=prev>prev parent</a>';
824 $prev = qq(<a\nhref="$upfx$prev/"\n) .
826 $parent = qq( <a\nhref="$u">parent</a>) if $u;
828 } elsif ($u) { # unlikely
829 $parent = qq( <a\nhref="$u"\nrel=prev>parent</a>);
831 $foot .= "$next $prev$parent ";
832 } else { # unindexed inboxes w/o over
833 $skel = qq( <a\nhref="$upfx">latest</a>);
835 # $skel may be big for big threads, don't append it to $foot
836 print { $ctx->zfh } $foot, qq(<a\nhref="#R">reply</a>),
837 $skel, '</pre>', @related,
838 msg_reply($ctx, $hdr);
842 my ($upfx, $mid) = @_;
844 my $href = mid_href($mid);
845 my $html = ascii_html($mid);
846 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
851 $level ? INDENT x ($level - 1) : '';
855 my ($ctx, $level, $node, $idx) = @_;
856 ++$ctx->{root_idx} if $level == 0;
857 if ($node->{mid} eq $ctx->{mid}) {
858 $ctx->{found_mid_at} = $ctx->{root_idx};
859 return 0; # stop iterating
864 sub strict_loose_note ($) {
867 " -- strict thread matches above, loose matches on Subject: below --\n";
869 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
871 " -- use mbox.gz link to download all $nr messages --\n";
877 my ($ctx, $msgs) = @_;
878 require PublicInbox::SearchThread;
879 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
881 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
882 # and preserved in the future. This bug is hidden by `sid' matches
883 # in get_thread, so we never noticed it until now. And even when
884 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
885 # bump since reindexing is expensive and users may not do it
887 # loose threading could've returned too many results,
888 # put the root the message we care about at the top:
889 my $mid = $ctx->{mid};
890 if (defined($mid) && scalar(@$rootset) > 1) {
891 $ctx->{root_idx} = -1;
892 my $nr = scalar @$msgs;
893 walk_thread($rootset, $ctx, \&find_mid_root);
894 my $idx = $ctx->{found_mid_at};
895 if (defined($idx) && $idx != 0) {
896 my $tip = splice(@$rootset, $idx, 1);
897 @$rootset = reverse @$rootset;
898 unshift @$rootset, $tip;
899 $ctx->{sl_note} = strict_loose_note($nr);
907 require PublicInbox::ExtMsg;
908 PublicInbox::ExtMsg::ext_msg($ctx);
912 my ($prev_subj, $subj, $val) = @_;
914 my $omit; # '"' denotes identical text omitted
915 my (@prev_pop, @curr_pop);
916 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
917 push(@prev_pop, pop(@$prev_subj));
918 push(@curr_pop, pop(@$subj));
921 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
922 if (scalar(@curr_pop) == 1) {
924 push @$prev_subj, @prev_pop;
925 push @$subj, @curr_pop;
930 sub skel_dump { # walk_thread callback
931 my ($ctx, $level, $smsg) = @_;
932 $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
934 my $skel = $ctx->{skel};
935 my $cur = $ctx->{cur};
936 my $mid = $smsg->{mid};
938 if ($level == 0 && $ctx->{skel_dump_roots}++) {
939 $$skel .= delete($ctx->{sl_note}) || '';
942 my $f = ascii_html(delete $smsg->{from_name});
943 my $obfs_ibx = $ctx->{-obfs_ibx};
944 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
946 my $d = fmt_ts($smsg->{ds});
947 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
948 if (exists $ctx->{searchview}) {
949 if (defined(my $pct = $smsg->{pct})) {
950 $d .= (sprintf(' % 2u', $pct) . '%');
956 $d .= ' ' . indent_for($level) . th_pfx($level);
958 $ctx->{first_level} ||= $level;
960 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
961 $ctx->{prev_attr} = $attr;
963 $ctx->{prev_level} = $level;
968 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
969 "$attr [this message]</a></b>\n";
972 $ctx->{prev_msg} = $mid;
975 $ctx->{next_msg} ||= $mid;
978 # Subject is never undef, this mail was loaded from
979 # our Xapian which would've resulted in '' if it were
980 # really missing (and Filter rejects empty subjects)
981 my @subj = split(/ /, subject_normalized($smsg->{subject}));
982 # remove common suffixes from the subject if it matches the previous,
983 # so we do not show redundant text at the end.
984 my $prev_subj = $ctx->{prev_subj} || [];
985 $ctx->{prev_subj} = [ @subj ];
986 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
989 my $subj = join(' ', @subj);
990 $subj = ascii_html($subj);
991 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
992 $end = "$subj</a> $omit$f\n"
998 my $mapping = $unmatched ? undef : $ctx->{mapping};
1000 my $map = $mapping->{$mid};
1001 $id = id_compress($mid, 1);
1003 $map->[0] = "$d<a\nhref=\"$m\">$end";
1006 $m = $ctx->{-upfx}.mid_href($mid).'/';
1008 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1013 my ($ctx, $level, $node) = @_;
1015 my $mid = $node->{mid};
1016 my $d = ' [not found] ';
1017 $d .= ' ' if exists $ctx->{searchview};
1018 $d .= indent_for($level) . th_pfx($level);
1019 my $upfx = $ctx->{-upfx};
1020 my $href = $upfx . mid_href($mid) . '/';
1021 my $html = ascii_html($mid);
1023 my $mapping = $ctx->{mapping};
1024 my $map = $mapping->{$mid} if $mapping;
1026 my $id = id_compress($mid, 1);
1027 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1028 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1030 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1032 ${$ctx->{skel}} .= $d;
1038 (eval { $a->topmost->{ds} } || 0) <=>
1039 (eval { $b->topmost->{ds} } || 0)
1043 # accumulate recent topics if search is supported
1044 # returns 200 if done, 404 if not
1045 sub acc_topic { # walk_thread callback
1046 my ($ctx, $level, $smsg) = @_;
1047 my $mid = $smsg->{mid};
1048 my $has_blob = $smsg->{blob} // do {
1049 if (my $by_mid = $ctx->{ibx}->smsg_by_mid($mid)) {
1050 %$smsg = (%$smsg, %$by_mid);
1055 my $subj = subject_normalized($smsg->{subject});
1056 $subj = '(no subject)' if $subj eq '';
1057 my $ds = $smsg->{ds};
1058 if ($level == 0) { # new, top-level topic
1059 my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1060 $ctx->{-cur_topic} = $topic;
1061 push @{$ctx->{order}}, $topic;
1065 # continue existing topic
1066 my $topic = $ctx->{-cur_topic}; # should never be undef
1067 $topic->[0] = $ds if $ds > $topic->[0];
1068 $topic->[1]++; # bump N+ message counter
1069 my $seen = $topic->[2];
1070 if (scalar(@$topic) == 3) { # parent was a ghost
1071 push @$topic, $subj;
1072 } elsif (!defined($seen->{$subj})) {
1073 push @$topic, $level, $subj; # @extra messages
1075 $seen->{$subj} = $mid; # latest for subject
1076 } else { # ghost message
1077 return 1 if $level != 0; # ignore child ghosts
1078 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1079 push @{$ctx->{order}}, $topic;
1086 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1088 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1093 my $obfs_ibx = $ctx->{ibx}->{obfuscate} ? $ctx->{ibx} : undef;
1094 if (my $note = delete $ctx->{t_note}) {
1095 push @out, $note; # "messages from ... to ..."
1097 # sort by recency, this allows new posts to "bump" old topics...
1098 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1099 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1101 next unless defined $top_subj; # ghost topic
1102 my $mid = delete $seen->{$top_subj};
1103 my $href = mid_href($mid);
1104 my $prev_subj = [ split(/ /, $top_subj) ];
1105 $top_subj = ascii_html($top_subj);
1108 # $n isn't the total number of posts on the topic,
1109 # just the number of posts in the current results window
1113 $anchor = '#u'; # top of only message
1115 $n = " ($n+ messages)";
1116 $anchor = '#t'; # thread skeleton
1119 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1122 my $level = shift @extra;
1123 my $subj = shift @extra; # already normalized
1124 $mid = delete $seen->{$subj};
1125 my @subj = split(/ /, $subj);
1126 my @next_prev = @subj; # full copy
1127 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1128 $prev_subj = \@next_prev;
1129 $subj = join(' ', @subj);
1130 $subj = ascii_html($subj);
1131 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1132 $href = mid_href($mid);
1133 $s .= indent_for($level) . TCHILD;
1134 $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1138 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1143 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1144 timegm($ss || 0, $mm || 0, $hh || 0, $dd, $mon - 1, $yyyy);
1147 sub pagination_footer ($$) {
1148 my ($ctx, $latest) = @_;
1149 my $next = $ctx->{next_page} || '';
1150 my $prev = $ctx->{prev_page} || '';
1151 if ($prev) { # aligned padding for: 'next (older) | '
1152 $next = $next ? "$next | " : ' | ';
1153 $prev .= qq[ | <a\nhref="$latest">latest</a>];
1155 ($next || $prev) ? "<hr><pre id=nav>page: $next$prev</pre>" : '';
1158 sub paginate_recent ($$) {
1159 my ($ctx, $lim) = @_;
1160 my $t = $ctx->{qp}->{t} || '';
1161 my $opts = { limit => $lim };
1162 my ($after, $before);
1164 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1165 # if only $after exists "YYYYMMDD.." because "." could be skipped
1166 # if interpreted as an end-of-sentence
1167 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1168 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1170 my $msgs = $ctx->{ibx}->over->recent($opts, $after, $before);
1171 if (defined($after) && scalar(@$msgs) < $lim) {
1172 $after = $before = undef;
1173 $msgs = $ctx->{ibx}->over->recent($opts);
1175 my $more = scalar(@$msgs) == $lim;
1176 my ($newest, $oldest);
1178 $newest = $msgs->[0]->{ts};
1179 $oldest = $msgs->[-1]->{ts};
1180 # if we only had $after, our SQL query in ->recent ordered
1181 if ($newest < $oldest) {
1182 ($oldest, $newest) = ($newest, $oldest);
1183 $more = undef if defined($after) && $after < $oldest;
1185 if (defined($after // $before)) {
1186 my $n = strftime('%Y-%m-%d %H:%M:%S', gmtime($newest));
1187 my $o = strftime('%Y-%m-%d %H:%M:%S', gmtime($oldest));
1188 $ctx->{t_note} = <<EOM;
1189 messages from $o to $n UTC [<a href="#nav">more...</a>]
1191 my $s = ts2str($newest);
1192 $ctx->{prev_page} = qq[<a\nhref="?t=$s-"\nrel=prev>] .
1196 if (defined($oldest) && $more) {
1197 my $s = ts2str($oldest);
1198 $ctx->{next_page} = qq[<a\nhref="?t=$s"\nrel=next>] .
1204 # GET /$INBOX - top-level inbox view for indexed inboxes
1207 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1208 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic) if @$msgs;
1209 html_oneshot($ctx, dump_topics($ctx), pagination_footer($ctx, '.'));
1212 sub thread_adj_level {
1213 my ($ctx, $level) = @_;
1215 my $max = $ctx->{cur_level};
1217 return ('', '') if $max == 0; # flat output
1219 # reset existing lists
1220 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1221 $ctx->{cur_level} = 0;
1223 } elsif ($level == $max) { # continue existing list
1225 } elsif ($level < $max) {
1226 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1227 $ctx->{cur_level} = $level;
1228 ("$beg<li>", '</li>');
1229 } else { # ($level > $max) # start a new level
1230 $ctx->{cur_level} = $level;
1231 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1236 sub ghost_index_entry {
1237 my ($ctx, $level, $node) = @_;
1238 my ($beg, $end) = thread_adj_level($ctx, $level);
1239 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{mid} // '?')