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 bytes (); # only for bytes::length
10 use List::Util qw(max);
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 Time::Local qw(timegm);
24 use PublicInbox::Smsg qw(subject_normalized);
25 use PublicInbox::ContentHash qw(content_hash);
26 use constant COLS => 72;
27 use constant INDENT => ' ';
28 use constant TCHILD => '` ';
29 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
33 if ($eml) { # called by WwwStream::async_eml or getline
34 my $smsg = $ctx->{smsg};
35 $ctx->{smsg} = $ctx->{over}->next_by_mid(@{$ctx->{next_arg}});
36 $ctx->{mhref} = ($ctx->{nr} || $ctx->{smsg}) ?
37 "../${\mid_href($smsg->{mid})}/" : '';
38 my $obuf = $ctx->{obuf} = _msg_page_prepare_obuf($eml, $ctx);
40 multipart_text_as_html($eml, $ctx);
41 $$obuf .= '</pre><hr>';
44 $$obuf .= html_footer($ctx, $ctx->{first_hdr}) if !$ctx->{smsg};
46 } else { # called by WwwStream::async_next or getline
47 $ctx->{smsg}; # may be undef
51 # /$INBOX/$MSGID/ for unindexed v1 inboxes
52 sub no_over_html ($) {
54 my $bref = $ctx->{ibx}->msg_by_mid($ctx->{mid}) or return; # 404
55 my $eml = PublicInbox::Eml->new($bref);
57 PublicInbox::WwwStream::init($ctx);
58 my $obuf = $ctx->{obuf} = _msg_page_prepare_obuf($eml, $ctx);
60 multipart_text_as_html($eml, $ctx);
61 $$obuf .= '</pre><hr>';
64 eval { $$obuf .= html_footer($ctx, $eml) };
65 html_oneshot($ctx, 200, $obuf);
68 # public functions: (unstable)
72 my $ibx = $ctx->{ibx};
73 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
74 my $over = $ctx->{over} = $ibx->over or return no_over_html($ctx);
76 my $next_arg = $ctx->{next_arg} = [ $ctx->{mid}, \$id, \$prev ];
78 my $smsg = $ctx->{smsg} = $over->next_by_mid(@$next_arg) or
79 return; # undef == 404
81 # allow user to easily browse the range around this message if
83 $ctx->{-t_max} = $smsg->{ts};
84 PublicInbox::WwwStream::aresponse($ctx, 200, \&msg_page_i);
87 # /$INBOX/$MESSAGE_ID/#R
91 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
93 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
96 my $ibx = $ctx->{ibx};
97 if (my $url = $ibx->{infourl}) {
98 $url = prurl($ctx->{env}, $url);
99 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
102 my ($arg, $link, $reply_to_all) =
103 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
104 if (ref($arg) eq 'SCALAR') {
105 return '<pre id=R>'.ascii_html($$arg).'</pre>';
108 # mailto: link only works if address obfuscation is disabled
112 * If your mail client supports setting the <b>In-Reply-To</b> header
113 via mailto: links, try the <a
114 href="$link">mailto: link</a>
118 push @$arg, '/path/to/YOUR_REPLY';
119 $arg = ascii_html(join(" \\\n ", '', @$arg));
122 id=R><b>Reply instructions:</b>
124 You may reply publicly to <a
125 href=#t>this message</a> via plain-text email
126 using any one of the following methods:
128 * Save the following mbox file, import it into your mail client,
129 and $reply_to_all from there: <a
132 Avoid top-posting and favor interleaved quoting:
134 href="$p_url">$p_url</a>
136 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
137 switches of git-send-email(1):
142 href="$se_url">$se_url</a>
149 my $refs = references($hdr);
153 sub fold_addresses ($) {
154 return $_[0] if length($_[0]) <= COLS;
155 # try to fold on commas after non-word chars before $lim chars,
156 # Try to get the "," preceded by ">" or ")", but avoid folding
157 # on the comma where somebody uses "Lastname, Firstname".
158 # We also try to keep the last and penultimate addresses in
159 # the list on the same line if possible, hence the extra \z
160 # Fall back to folding on spaces at $lim + 1 chars
161 my $lim = COLS - 8; # 8 = "\t" display width
162 my $too_long = $lim + 1;
163 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
165 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
168 .{$too_long,}?)(?:\s|\z)/xgo));
171 sub _hdr_names_html ($$) {
172 my ($hdr, $field) = @_;
173 my @vals = $hdr->header($field) or return '';
174 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
178 my ($nr, $singular, $plural) = @_;
179 return "0 $plural" if $nr == 0;
180 $nr == 1 ? "$nr $singular" : "$nr $plural";
183 # Displays the text of of the message for /$INBOX/$MSGID/[Tt]/ endpoint
184 # this is already inside a <pre>
186 my ($ctx, $eml) = @_;
187 my $smsg = delete $ctx->{smsg};
188 my $subj = delete $smsg->{subject};
189 my $mid_raw = $smsg->{mid};
190 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 = delete $smsg->{ds}; # for v1 non-Xapian/SQLite users
206 # Deleting these fields saves about 400K as we iterate across 1K msgs
207 delete @$smsg{qw(ts blob)};
209 my $from = _hdr_names_html($eml, 'From');
210 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
211 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
212 my $upfx = $ctx->{-upfx};
213 my $mhref = $upfx . mid_href($mid_raw) . '/';
214 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
215 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
216 my $to = fold_addresses(_hdr_names_html($eml, 'To'));
217 my $cc = fold_addresses(_hdr_names_html($eml, 'Cc'));
218 my ($tlen, $clen) = (length($to), length($cc));
220 if (($tlen + $clen) > COLS) {
221 $to_cc .= ' To: '.$to."\n" if $tlen;
222 $to_cc .= ' Cc: '.$cc."\n" if $clen;
225 $to_cc .= ' To: '.$to;
226 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
228 $to_cc .= ' Cc: '.$cc if $clen;
232 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
235 my $mapping = $ctx->{mapping};
236 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($eml)))) {
237 my $href = $upfx . mid_href($irt) . '/';
238 my $html = ascii_html($irt);
239 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
243 # scan through all parts, looking for displayable text
244 $ctx->{mhref} = $mhref;
246 $eml->each_part(\&add_text_body, $ctx, 1);
250 $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
251 "<a\nhref=\"$mhref\">permalink</a>" .
252 " <a\nhref=\"${mhref}raw\">raw</a>" .
253 " <a\nhref=\"${mhref}#R\">reply</a>";
256 if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
257 $rv .= "\t[relevance $pct%]";
260 my $nested = 'nested';
265 $flat = "<b>$flat</b>";
267 $nested = "<b>$nested</b>";
269 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
270 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
271 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
276 # do we have more messages? start a new <pre> if so
277 $rv .= scalar(@{$ctx->{msgs}}) ? '</pre><hr><pre>' : '</pre>' if $hr;
281 sub pad_link ($$;$) {
282 my ($mid, $level, $s) = @_;
284 my $href = defined($mid) ?
285 ("<a\nhref=#r".id_compress($mid, 1).">($s)</a>\n") :
287 (' 'x19).indent_for($level).th_pfx($level).$href;
291 # my ($mapping, $mid) = @_;
292 ($_[0]->{$_[1] // \'bogus'} // [ "(?)\n" ])->[0];
296 my ($mid_raw, $irt, $id, $ctx) = @_;
298 my $mapping = $ctx->{mapping} or return $rv;
300 my $mid_map = $mapping->{$mid_raw};
302 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
303 my ($attr, $node, $idx, $level) = @$mid_map;
304 my $children = $node->{children};
305 my $nr_c = scalar @$children;
308 # delete saves about 200KB on a 1K message thread
309 if (my $refs = delete $node->{references}) {
310 ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
312 my $irt_map = $mapping->{$$irt} if defined $$irt;
313 if (defined $irt_map) {
314 $siblings = $irt_map->[1]->{children};
315 $nr_s = scalar(@$siblings) - 1;
316 $rv .= $pad . $irt_map->[0];
318 my $prev = $siblings->[$idx - 1];
319 my $pmid = $prev->{mid};
321 my $s = ($idx - 1). ' preceding siblings ...';
322 $rv .= pad_link($pmid, $level, $s);
323 } elsif ($idx == 2) {
324 $rv .= $pad . _skel_hdr($mapping,
326 $siblings->[0]->{mid} : undef);
328 $rv .= $pad . _skel_hdr($mapping, $pmid);
331 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
332 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
333 $attr =~ s!\n\z!</b>\n!s;
334 $attr =~ s!<a\nhref.*</a> (?:" )?!!s; # no point in dup subject
335 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
338 my $cmid = $children->[0] ? $children->[0]->{mid} : undef;
339 $rv .= $pad . _skel_hdr($mapping, $cmid);
341 my $s = ($nr_c - 1). ' more replies';
342 $rv .= pad_link($cmid, $level + 1, $s);
343 } elsif (my $cn = $children->[1]) {
344 $rv .= $pad . _skel_hdr($mapping, $cn->{mid});
348 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
350 my $nmid = $next->{mid};
351 $rv .= $pad . _skel_hdr($mapping, $nmid);
352 my $nnext = $nr_s - $idx;
354 my $s = ($nnext - 1).' subsequent siblings';
355 $rv .= pad_link($nmid, $level, $s);
356 } elsif (my $nn = $siblings->[$idx + 2]) {
357 $rv .= $pad . _skel_hdr($mapping, $nn->{mid});
360 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
363 # non-recursive thread walker
364 sub walk_thread ($$$) {
365 my ($rootset, $ctx, $cb) = @_;
366 my @q = map { (0, $_, -1) } @$rootset;
368 my ($level, $node, $i) = splice(@q, 0, 3);
369 defined $node or next;
370 $cb->($ctx, $level, $node, $i) or return;
373 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
377 sub pre_thread { # walk_thread callback
378 my ($ctx, $level, $node, $idx) = @_;
379 $ctx->{mapping}->{$node->{mid}} = [ '', $node, $idx, $level ];
380 skel_dump($ctx, $level, $node);
383 sub thread_eml_entry {
384 my ($ctx, $eml) = @_;
385 my ($beg, $end) = thread_adj_level($ctx, $ctx->{level});
386 $beg . '<pre>' . eml_entry($ctx, $eml) . '</pre>' . $end;
389 sub next_in_queue ($$) {
390 my ($q, $ghost_ok) = @_;
392 my ($level, $smsg) = splice(@$q, 0, 2);
394 unshift @$q, map { ($cl, $_) } @{$smsg->{children}};
395 return ($level, $smsg) if $ghost_ok || exists($smsg->{blob});
400 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
401 my ($ctx, $eml) = @_;
402 return thread_eml_entry($ctx, $eml) if $eml;
403 return unless exists($ctx->{skel});
404 my $ghost_ok = $ctx->{nr}++;
406 my ($lvl, $smsg) = next_in_queue($ctx->{-queue}, $ghost_ok);
408 if (exists $smsg->{blob}) { # next message for cat-file
409 $ctx->{level} = $lvl;
410 if (!$ghost_ok) { # first non-ghost
411 $ctx->{-title_html} =
412 ascii_html($smsg->{subject});
413 $ctx->zmore($ctx->html_top);
417 # buffer the ghost entry and loop
418 $ctx->zmore(ghost_index_entry($ctx, $lvl, $smsg));
420 $ctx->zmore(join('', thread_adj_level($ctx, 0)));
421 $ctx->zmore(${delete($ctx->{skel})});
427 sub stream_thread ($$) {
428 my ($rootset, $ctx) = @_;
429 $ctx->{-queue} = [ map { (0, $_) } @$rootset ];
430 PublicInbox::WwwStream::aresponse($ctx, 200, \&stream_thread_i);
433 # /$INBOX/$MSGID/t/ and /$INBOX/$MSGID/T/
436 my $mid = $ctx->{mid};
437 my $ibx = $ctx->{ibx};
438 my ($nr, $msgs) = $ibx->over->get_thread($mid);
439 return missing_thread($ctx) if $nr == 0;
441 # link $INBOX_DIR/description text to "index_topics" view around
442 # the newest message in this thread
443 my $t = ts2str($ctx->{-t_max} = max(map { delete $_->{ts} } @$msgs));
444 my $t_fmt = fmt_ts($ctx->{-t_max});
446 my $skel = '<hr><pre>';
447 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
450 href="../../?t=$t">~$t_fmt UTC</a> | <a
451 href="../../">newest</a>]
454 $skel .= "<b\nid=t>Thread overview:</b> ";
455 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
456 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
457 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
458 $skel .= "-- links below jump to the message on this page --\n";
459 $ctx->{-upfx} = '../../';
460 $ctx->{cur_level} = 0;
461 $ctx->{skel} = \$skel;
462 $ctx->{prev_attr} = '';
463 $ctx->{prev_level} = 0;
464 $ctx->{root_anchor} = 'm' . id_compress($mid, 1);
465 $ctx->{mapping} = {}; # mid -> [ header_summary, node, idx, level ]
466 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
469 my $rootset = thread_results($ctx, $msgs);
471 # reduce hash lookups in pre_thread->skel_dump
472 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
473 walk_thread($rootset, $ctx, \&pre_thread);
476 return stream_thread($rootset, $ctx) unless $ctx->{flat};
478 # flat display: lazy load the full message from smsg
479 $ctx->{msgs} = $msgs;
480 $ctx->{-html_tip} = '<pre>';
481 PublicInbox::WwwStream::aresponse($ctx, 200, \&thread_html_i);
484 sub thread_html_i { # PublicInbox::WwwStream::getline callback
485 my ($ctx, $eml) = @_;
487 my $smsg = $ctx->{smsg};
488 if (exists $ctx->{-html_tip}) {
489 $ctx->{-title_html} = ascii_html($smsg->{subject});
490 $ctx->zmore($ctx->html_top);
492 return eml_entry($ctx, $eml);
494 while (my $smsg = shift @{$ctx->{msgs}}) {
495 return $smsg if exists($smsg->{blob});
497 my $skel = delete($ctx->{skel}) or return; # all done
503 sub multipart_text_as_html {
504 # ($mime, $ctx) = @_; # each_part may do "$_[0] = undef"
506 # scan through all parts, looking for displayable text
507 $_[0]->each_part(\&add_text_body, $_[1], 1);
510 sub submsg_hdr ($$) {
511 my ($ctx, $eml) = @_;
512 my $obfs_ibx = $ctx->{-obfs_ibx};
513 my $rv = $ctx->{obuf};
515 for my $h (qw(From To Cc Subject Date Message-ID X-Alt-Message-ID)) {
516 my @v = $eml->header($h);
518 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
525 sub attach_link ($$$$;$) {
526 my ($ctx, $ct, $p, $fn, $err) = @_;
527 my ($part, $depth, $idx) = @$p;
529 # Eml iteration clobbers multipart ->{bdy}, so do not offer
530 # downloads for 0-byte multipart attachments
531 return unless $part->{bdy};
533 my $nl = $idx eq '1' ? '' : "\n"; # like join("\n", ...)
534 my $size = bytes::length($part->body);
536 # hide attributes normally, unless we want to aid users in
537 # spotting MUA problems:
538 $ct =~ s/;.*// unless $err;
539 $ct = ascii_html($ct);
541 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
543 } elsif ($ct eq 'text/plain') {
548 my $rv = $ctx->{obuf};
549 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
552 [-- Warning: decoded text below may be mangled, UTF-8 assumed --]
555 $$rv .= "[-- Attachment #$idx: ";
556 my $ts = "Type: $ct, Size: $size bytes";
557 my $desc = $part->header('Content-Description') // $fn // '';
558 $desc = ascii_html($desc);
559 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
562 submsg_hdr($ctx, $part) if $part->{is_submsg};
567 sub add_text_body { # callback for each_part
569 my $upfx = $ctx->{mhref};
570 my $ibx = $ctx->{ibx};
571 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
572 # $p - from each_part: [ Email::MIME-like, depth, $idx ]
573 my ($part, $depth, $idx) = @$p;
574 my $ct = $part->content_type || 'text/plain';
575 my $fn = $part->filename;
576 my ($s, $err) = msg_part_text($part, $ct);
577 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
579 my $rv = $ctx->{obuf};
580 if ($part->{is_submsg}) {
581 submsg_hdr($ctx, $part);
585 # makes no difference to browsers, and don't screw up filename
586 # link generation in diffs with the extra '%0D'
589 # will be escaped to `•' in HTML
590 obfuscate_addrs($ibx, $s, "\x{2022}") if $ibx->{obfuscate};
592 # always support diff-highlighting, but we can't linkify hunk
593 # headers for solver unless some coderepo are configured:
595 if ($s =~ /^--- [^\n]+\n\+{3} [^\n]+\n@@ /ms) {
596 # diffstat anchors do not link across attachments or messages,
597 # -apfx is just a stable prefix for making diffstat anchors
598 # linkable to the first diff hunk w/o crossing attachments
599 $idx =~ tr!.!/!; # compatibility with previous versions
600 $ctx->{-apfx} = $upfx . $idx;
602 # do attr => filename mappings for diffstats in git diffs:
603 $ctx->{-anchors} = {} if $s =~ /^diff --git /sm;
605 delete $ctx->{-long_path};
607 # absolute URL (Atom feeds)
608 if ($ibx->{coderepo}) {
609 if (index($upfx, '//') >= 0) {
611 $spfx =~ s!/([^/]*)/\z!/!;
613 my $n_slash = $upfx =~ tr!/!/!;
616 } elsif ($n_slash == 1) {
618 } else { # nslash == 2
623 $ctx->{-spfx} = $spfx;
626 # some editors don't put trailing newlines at the end:
627 $s .= "\n" unless $s =~ /\n\z/s;
629 # split off quoted and unquoted blocks:
630 my @sections = PublicInbox::MsgIter::split_quotes($s);
631 undef $s; # free memory
632 if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
633 # badly-encoded message with $err? tell the world about it!
634 attach_link($ctx, $ct, $p, $fn, $err);
637 foreach my $cur (@sections) {
639 # we use a <span> here to allow users to specify
640 # their own color for quoted text
641 $$rv .= qq(<span\nclass="q">);
642 $$rv .= $l->to_html($cur);
645 flush_diff($ctx, \$cur);
648 $$rv .= $l->to_html($cur);
650 undef $cur; # free memory
654 sub _msg_page_prepare_obuf {
655 my ($eml, $ctx) = @_;
656 my $over = $ctx->{ibx}->over;
657 my $obfs_ibx = $ctx->{-obfs_ibx};
659 my $mids = mids_for_index($eml);
660 my $nr = $ctx->{nr}++;
661 if ($nr) { # unlikely
662 if ($ctx->{chash} eq content_hash($eml)) {
663 warn "W: BUG? @$mids not deduplicated properly\n";
667 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
670 $ctx->{first_hdr} = $eml->header_obj;
671 $ctx->{chash} = content_hash($eml) if $ctx->{smsg}; # reused MID
672 $rv .= "<pre\nid=b>"; # anchor for body start
674 $ctx->{-upfx} = '../' if $over;
675 my @title; # (Subject[0], From[0])
676 for my $v ($eml->header('From')) {
677 my @n = PublicInbox::Address::names($v);
679 $title[1] //= ascii_html(join(', ', @n));
681 obfuscate_addrs($obfs_ibx, $v);
682 obfuscate_addrs($obfs_ibx, $title[1]);
684 $rv .= "From: $v\n" if $v ne '';
686 foreach my $h (qw(To Cc)) {
687 for my $v ($eml->header($h)) {
690 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
691 $rv .= "$h: $v\n" if $v ne '';
694 my @subj = $eml->header('Subject');
696 my $v = ascii_html(shift @subj);
697 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
699 $rv .= $over ? qq(<a\nhref="#r"\nid=t>$v</a>\n) : "$v\n";
701 for $v (@subj) { # multi-Subject message :<
703 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
704 $rv .= "Subject: $v\n";
706 } else { # dummy anchor for thread skeleton at bottom of page
707 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
708 $title[0] = '(no subject)';
710 for my $v ($eml->header('Date')) {
712 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
713 $rv .= qq{Date: $v\t<a\nhref="#r">[thread overview]</a>\n};
715 if (!$nr) { # first (and only) message, common case
716 $ctx->{-title_html} = join(' - ', @title);
717 $rv = $ctx->html_top . $rv;
719 if (scalar(@$mids) == 1) { # common case
720 my $mhtml = ascii_html($mids->[0]);
721 $rv .= "Message-ID: <$mhtml> ";
722 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
724 # X-Alt-Message-ID can happen if a message is injected from
725 # public-inbox-nntpd because of multiple Message-ID headers.
726 my $lnk = PublicInbox::Linkify->new;
728 for my $h (qw(Message-ID X-Alt-Message-ID)) {
729 $s .= "$h: $_\n" for ($eml->header_raw($h));
731 $lnk->linkify_mids('..', \$s, 1);
734 $rv .= _parent_headers($eml, $over);
740 qq(expand[<a\nhref="T/#u">flat</a>) .
741 qq(|<a\nhref="t/#u">nested</a>] ) .
742 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
743 qq(<a\nhref="t.atom">Atom feed</a>);
746 sub thread_skel ($$$) {
747 my ($skel, $ctx, $hdr) = @_;
748 my $mid = mids($hdr)->[0];
749 my $ibx = $ctx->{ibx};
750 my ($nr, $msgs) = $ibx->over->get_thread($mid);
751 my $parent = in_reply_to($hdr);
752 $$skel .= "\n<b>Thread overview: </b>";
754 if (defined $parent) {
755 $$skel .= SKEL_EXPAND."\n ";
756 $$skel .= ghost_parent('../', $parent) . "\n";
758 $$skel .= "<a\nid=r>[no followups]</a> ".
761 $ctx->{next_msg} = undef;
762 $ctx->{parent_msg} = $parent;
767 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
769 # nb: mutt only shows the first Subject in the index pane
770 # when multiple Subject: headers are present, so we follow suit:
771 my $subj = $hdr->header('Subject') // '';
772 $subj = '(no subject)' if $subj eq '';
773 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
775 $ctx->{prev_attr} = '';
776 $ctx->{prev_level} = 0;
777 $ctx->{skel} = $skel;
779 # reduce hash lookups in skel_dump
780 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
781 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
783 $ctx->{parent_msg} = $parent;
786 sub _parent_headers {
787 my ($hdr, $over) = @_;
789 my @irt = $hdr->header_raw('In-Reply-To');
792 my $lnk = PublicInbox::Linkify->new;
793 $rv .= "In-Reply-To: $_\n" for @irt;
794 $lnk->linkify_mids('..', \$rv);
796 $refs = references($hdr);
797 my $irt = pop @$refs;
799 my $html = ascii_html($irt);
800 my $href = mid_href($irt);
801 $rv .= "In-Reply-To: <";
802 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
806 # do not display References: if search is present,
807 # we show the thread skeleton at the bottom, instead.
810 $refs //= references($hdr);
812 @$refs = map { linkify_ref_no_over($_) } @$refs;
813 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
818 # returns a string buffer
820 my ($ctx, $hdr) = @_;
821 my $ibx = $ctx->{ibx};
826 my $t = ts2str($ctx->{-t_max});
827 my $t_fmt = fmt_ts($ctx->{-t_max});
830 href="$upfx?t=$t">~$t_fmt UTC</a>|<a
831 href="$upfx">newest</a>]
834 thread_skel(\$skel, $ctx, $hdr);
839 if (my $n = $ctx->{next_msg}) {
841 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
844 my $par = $ctx->{parent_msg};
849 if (my $p = $ctx->{prev_msg}) {
850 $prev = mid_href($p);
851 if ($p && $par && $p eq $par) {
852 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
853 'rel=prev>prev parent</a>';
856 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
858 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
860 } elsif ($u) { # unlikely
861 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
863 $rv .= "$next $prev$parent ";
864 } else { # unindexed inboxes w/o over
865 $skel = qq( <a\nhref="$upfx">latest</a>);
867 $rv .= qq(<a\nhref="#R">reply</a>);
870 $rv .= msg_reply($ctx, $hdr);
873 sub linkify_ref_no_over {
875 my $href = mid_href($mid);
876 my $html = ascii_html($mid);
877 "<<a\nhref=\"../$href/\">$html</a>>";
881 my ($upfx, $mid) = @_;
883 my $href = mid_href($mid);
884 my $html = ascii_html($mid);
885 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
890 $level ? INDENT x ($level - 1) : '';
894 my ($ctx, $level, $node, $idx) = @_;
895 ++$ctx->{root_idx} if $level == 0;
896 if ($node->{mid} eq $ctx->{mid}) {
897 $ctx->{found_mid_at} = $ctx->{root_idx};
898 return 0; # stop iterating
903 sub strict_loose_note ($) {
906 " -- strict thread matches above, loose matches on Subject: below --\n";
908 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
910 " -- use mbox.gz link to download all $nr messages --\n";
916 my ($ctx, $msgs) = @_;
917 require PublicInbox::SearchThread;
918 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
920 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
921 # and preserved in the future. This bug is hidden by `sid' matches
922 # in get_thread, so we never noticed it until now. And even when
923 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
924 # bump since reindexing is expensive and users may not do it
926 # loose threading could've returned too many results,
927 # put the root the message we care about at the top:
928 my $mid = $ctx->{mid};
929 if (defined($mid) && scalar(@$rootset) > 1) {
930 $ctx->{root_idx} = -1;
931 my $nr = scalar @$msgs;
932 walk_thread($rootset, $ctx, \&find_mid_root);
933 my $idx = $ctx->{found_mid_at};
934 if (defined($idx) && $idx != 0) {
935 my $tip = splice(@$rootset, $idx, 1);
936 @$rootset = reverse @$rootset;
937 unshift @$rootset, $tip;
938 $ctx->{sl_note} = strict_loose_note($nr);
946 require PublicInbox::ExtMsg;
947 PublicInbox::ExtMsg::ext_msg($ctx);
951 my ($prev_subj, $subj, $val) = @_;
953 my $omit; # '"' denotes identical text omitted
954 my (@prev_pop, @curr_pop);
955 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
956 push(@prev_pop, pop(@$prev_subj));
957 push(@curr_pop, pop(@$subj));
960 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
961 if (scalar(@curr_pop) == 1) {
963 push @$prev_subj, @prev_pop;
964 push @$subj, @curr_pop;
969 sub skel_dump { # walk_thread callback
970 my ($ctx, $level, $smsg) = @_;
971 $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
973 my $skel = $ctx->{skel};
974 my $cur = $ctx->{cur};
975 my $mid = $smsg->{mid};
977 if ($level == 0 && $ctx->{skel_dump_roots}++) {
978 $$skel .= delete($ctx->{sl_note}) || '';
981 my $f = ascii_html($smsg->{from_name});
982 my $obfs_ibx = $ctx->{-obfs_ibx};
983 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
985 my $d = fmt_ts($smsg->{ds});
986 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
987 if (exists $ctx->{searchview}) {
988 if (defined(my $pct = $smsg->{pct})) {
989 $d .= (sprintf(' % 2u', $pct) . '%');
995 $d .= ' ' . indent_for($level) . th_pfx($level);
997 $ctx->{first_level} ||= $level;
999 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
1000 $ctx->{prev_attr} = $attr;
1002 $ctx->{prev_level} = $level;
1007 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
1008 "$attr [this message]</a></b>\n";
1011 $ctx->{prev_msg} = $mid;
1014 $ctx->{next_msg} ||= $mid;
1017 # Subject is never undef, this mail was loaded from
1018 # our Xapian which would've resulted in '' if it were
1019 # really missing (and Filter rejects empty subjects)
1020 my @subj = split(/ /, subject_normalized($smsg->{subject}));
1021 # remove common suffixes from the subject if it matches the previous,
1022 # so we do not show redundant text at the end.
1023 my $prev_subj = $ctx->{prev_subj} || [];
1024 $ctx->{prev_subj} = [ @subj ];
1025 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
1028 my $subj = join(' ', @subj);
1029 $subj = ascii_html($subj);
1030 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1031 $end = "$subj</a> $omit$f\n"
1037 my $mapping = $unmatched ? undef : $ctx->{mapping};
1039 my $map = $mapping->{$mid};
1040 $id = id_compress($mid, 1);
1042 $map->[0] = "$d<a\nhref=\"$m\">$end";
1045 $m = $ctx->{-upfx}.mid_href($mid).'/';
1047 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1052 my ($ctx, $level, $node) = @_;
1054 my $mid = $node->{mid};
1055 my $d = ' [not found] ';
1056 $d .= ' ' if exists $ctx->{searchview};
1057 $d .= indent_for($level) . th_pfx($level);
1058 my $upfx = $ctx->{-upfx};
1059 my $href = $upfx . mid_href($mid) . '/';
1060 my $html = ascii_html($mid);
1062 my $mapping = $ctx->{mapping};
1063 my $map = $mapping->{$mid} if $mapping;
1065 my $id = id_compress($mid, 1);
1066 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1067 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1069 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1071 ${$ctx->{skel}} .= $d;
1077 (eval { $a->topmost->{ds} } || 0) <=>
1078 (eval { $b->topmost->{ds} } || 0)
1082 # accumulate recent topics if search is supported
1083 # returns 200 if done, 404 if not
1084 sub acc_topic { # walk_thread callback
1085 my ($ctx, $level, $smsg) = @_;
1086 my $mid = $smsg->{mid};
1087 my $has_blob = $smsg->{blob} // do {
1088 if (my $by_mid = $ctx->{ibx}->smsg_by_mid($mid)) {
1089 %$smsg = (%$smsg, %$by_mid);
1094 my $subj = subject_normalized($smsg->{subject});
1095 $subj = '(no subject)' if $subj eq '';
1096 my $ds = $smsg->{ds};
1097 if ($level == 0) { # new, top-level topic
1098 my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1099 $ctx->{-cur_topic} = $topic;
1100 push @{$ctx->{order}}, $topic;
1104 # continue existing topic
1105 my $topic = $ctx->{-cur_topic}; # should never be undef
1106 $topic->[0] = $ds if $ds > $topic->[0];
1107 $topic->[1]++; # bump N+ message counter
1108 my $seen = $topic->[2];
1109 if (scalar(@$topic) == 3) { # parent was a ghost
1110 push @$topic, $subj;
1111 } elsif (!defined($seen->{$subj})) {
1112 push @$topic, $level, $subj; # @extra messages
1114 $seen->{$subj} = $mid; # latest for subject
1115 } else { # ghost message
1116 return 1 if $level != 0; # ignore child ghosts
1117 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1118 push @{$ctx->{order}}, $topic;
1125 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1127 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1132 my $ibx = $ctx->{ibx};
1133 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1135 # sort by recency, this allows new posts to "bump" old topics...
1136 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1137 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1139 next unless defined $top_subj; # ghost topic
1140 my $mid = delete $seen->{$top_subj};
1141 my $href = mid_href($mid);
1142 my $prev_subj = [ split(/ /, $top_subj) ];
1143 $top_subj = ascii_html($top_subj);
1146 # $n isn't the total number of posts on the topic,
1147 # just the number of posts in the current results window
1151 $anchor = '#u'; # top of only message
1153 $n = " ($n+ messages)";
1154 $anchor = '#t'; # thread skeleton
1157 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1158 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1159 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1160 " $ds UTC $n - $mbox / $atom\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} // '?')