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 $id = id_compress($mid, 1);
285 (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
289 my ($mid_raw, $irt, $id, $ctx) = @_;
291 my $mapping = $ctx->{mapping} or return $rv;
293 my $mid_map = $mapping->{$mid_raw};
295 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
296 my ($attr, $node, $idx, $level) = @$mid_map;
297 my $children = $node->{children};
298 my $nr_c = scalar @$children;
301 # delete saves about 200KB on a 1K message thread
302 if (my $refs = delete $node->{references}) {
303 ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
305 my $irt_map = $mapping->{$$irt} if defined $$irt;
306 if (defined $irt_map) {
307 $siblings = $irt_map->[1]->{children};
308 $nr_s = scalar(@$siblings) - 1;
309 $rv .= $pad . $irt_map->[0];
311 my $prev = $siblings->[$idx - 1];
312 my $pmid = $prev->{mid};
314 my $s = ($idx - 1). ' preceding siblings ...';
315 $rv .= pad_link($pmid, $level, $s);
316 } elsif ($idx == 2) {
317 my $ppmid = $siblings->[0]->{mid};
318 $rv .= $pad . $mapping->{$ppmid}->[0];
320 $rv .= $pad . $mapping->{$pmid}->[0];
323 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
324 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
325 $attr =~ s!\n\z!</b>\n!s;
326 $attr =~ s!<a\nhref.*</a> (?:" )?!!s; # no point in dup subject
327 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
330 my $cmid = $children->[0]->{mid};
331 $rv .= $pad . $mapping->{$cmid}->[0];
333 my $s = ($nr_c - 1). ' more replies';
334 $rv .= pad_link($cmid, $level + 1, $s);
335 } elsif (my $cn = $children->[1]) {
336 $rv .= $pad . $mapping->{$cn->{mid}}->[0];
340 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
342 my $nmid = $next->{mid};
343 $rv .= $pad . $mapping->{$nmid}->[0];
344 my $nnext = $nr_s - $idx;
346 my $s = ($nnext - 1).' subsequent siblings';
347 $rv .= pad_link($nmid, $level, $s);
348 } elsif (my $nn = $siblings->[$idx + 2]) {
349 $rv .= $pad . $mapping->{$nn->{mid}}->[0];
352 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
355 # non-recursive thread walker
356 sub walk_thread ($$$) {
357 my ($rootset, $ctx, $cb) = @_;
358 my @q = map { (0, $_, -1) } @$rootset;
360 my ($level, $node, $i) = splice(@q, 0, 3);
361 defined $node or next;
362 $cb->($ctx, $level, $node, $i) or return;
365 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
369 sub pre_thread { # walk_thread callback
370 my ($ctx, $level, $node, $idx) = @_;
371 $ctx->{mapping}->{$node->{mid}} = [ '', $node, $idx, $level ];
372 skel_dump($ctx, $level, $node);
375 sub thread_eml_entry {
376 my ($ctx, $eml) = @_;
377 my ($beg, $end) = thread_adj_level($ctx, $ctx->{level});
378 $beg . '<pre>' . eml_entry($ctx, $eml) . '</pre>' . $end;
381 sub next_in_queue ($$) {
382 my ($q, $ghost_ok) = @_;
384 my ($level, $smsg) = splice(@$q, 0, 2);
386 unshift @$q, map { ($cl, $_) } @{$smsg->{children}};
387 return ($level, $smsg) if $ghost_ok || exists($smsg->{blob});
392 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
393 my ($ctx, $eml) = @_;
394 return thread_eml_entry($ctx, $eml) if $eml;
395 return unless exists($ctx->{skel});
396 my $ghost_ok = $ctx->{nr}++;
398 my ($lvl, $smsg) = next_in_queue($ctx->{-queue}, $ghost_ok);
400 if (exists $smsg->{blob}) { # next message for cat-file
401 $ctx->{level} = $lvl;
402 if (!$ghost_ok) { # first non-ghost
403 $ctx->{-title_html} =
404 ascii_html($smsg->{subject});
405 $ctx->zmore($ctx->html_top);
409 # buffer the ghost entry and loop
410 $ctx->zmore(ghost_index_entry($ctx, $lvl, $smsg));
412 $ctx->zmore(join('', thread_adj_level($ctx, 0)));
413 $ctx->zmore(${delete($ctx->{skel})});
419 sub stream_thread ($$) {
420 my ($rootset, $ctx) = @_;
421 $ctx->{-queue} = [ map { (0, $_) } @$rootset ];
422 PublicInbox::WwwStream::aresponse($ctx, 200, \&stream_thread_i);
425 # /$INBOX/$MSGID/t/ and /$INBOX/$MSGID/T/
428 my $mid = $ctx->{mid};
429 my $ibx = $ctx->{ibx};
430 my ($nr, $msgs) = $ibx->over->get_thread($mid);
431 return missing_thread($ctx) if $nr == 0;
433 # link $INBOX_DIR/description text to "index_topics" view around
434 # the newest message in this thread
435 my $t = ts2str($ctx->{-t_max} = max(map { delete $_->{ts} } @$msgs));
436 my $t_fmt = fmt_ts($ctx->{-t_max});
438 my $skel = '<hr><pre>';
439 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
442 href="../../?t=$t">~$t_fmt UTC</a> | <a
443 href="../../">newest</a>]
446 $skel .= "<b\nid=t>Thread overview:</b> ";
447 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
448 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
449 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
450 $skel .= "-- links below jump to the message on this page --\n";
451 $ctx->{-upfx} = '../../';
452 $ctx->{cur_level} = 0;
453 $ctx->{skel} = \$skel;
454 $ctx->{prev_attr} = '';
455 $ctx->{prev_level} = 0;
456 $ctx->{root_anchor} = anchor_for($mid);
457 $ctx->{mapping} = {};
458 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
461 my $rootset = thread_results($ctx, $msgs);
463 # reduce hash lookups in pre_thread->skel_dump
464 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
465 walk_thread($rootset, $ctx, \&pre_thread);
468 return stream_thread($rootset, $ctx) unless $ctx->{flat};
470 # flat display: lazy load the full message from smsg
471 $ctx->{msgs} = $msgs;
472 $ctx->{-html_tip} = '<pre>';
473 PublicInbox::WwwStream::aresponse($ctx, 200, \&thread_html_i);
476 sub thread_html_i { # PublicInbox::WwwStream::getline callback
477 my ($ctx, $eml) = @_;
479 my $smsg = $ctx->{smsg};
480 if (exists $ctx->{-html_tip}) {
481 $ctx->{-title_html} = ascii_html($smsg->{subject});
482 $ctx->zmore($ctx->html_top);
484 return eml_entry($ctx, $eml);
486 while (my $smsg = shift @{$ctx->{msgs}}) {
487 return $smsg if exists($smsg->{blob});
489 my $skel = delete($ctx->{skel}) or return; # all done
495 sub multipart_text_as_html {
496 # ($mime, $ctx) = @_; # each_part may do "$_[0] = undef"
498 # scan through all parts, looking for displayable text
499 $_[0]->each_part(\&add_text_body, $_[1], 1);
502 sub submsg_hdr ($$) {
503 my ($ctx, $eml) = @_;
504 my $obfs_ibx = $ctx->{-obfs_ibx};
505 my $rv = $ctx->{obuf};
507 for my $h (qw(From To Cc Subject Date Message-ID X-Alt-Message-ID)) {
508 my @v = $eml->header($h);
510 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
517 sub attach_link ($$$$;$) {
518 my ($ctx, $ct, $p, $fn, $err) = @_;
519 my ($part, $depth, $idx) = @$p;
521 # Eml iteration clobbers multipart ->{bdy}, so do not offer
522 # downloads for 0-byte multipart attachments
523 return unless $part->{bdy};
525 my $nl = $idx eq '1' ? '' : "\n"; # like join("\n", ...)
526 my $size = bytes::length($part->body);
528 # hide attributes normally, unless we want to aid users in
529 # spotting MUA problems:
530 $ct =~ s/;.*// unless $err;
531 $ct = ascii_html($ct);
533 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
535 } elsif ($ct eq 'text/plain') {
540 my $rv = $ctx->{obuf};
541 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
544 [-- Warning: decoded text below may be mangled, UTF-8 assumed --]
547 $$rv .= "[-- Attachment #$idx: ";
548 my $ts = "Type: $ct, Size: $size bytes";
549 my $desc = $part->header('Content-Description') // $fn // '';
550 $desc = ascii_html($desc);
551 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
554 submsg_hdr($ctx, $part) if $part->{is_submsg};
559 sub add_text_body { # callback for each_part
561 my $upfx = $ctx->{mhref};
562 my $ibx = $ctx->{ibx};
563 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
564 # $p - from each_part: [ Email::MIME-like, depth, $idx ]
565 my ($part, $depth, $idx) = @$p;
566 my $ct = $part->content_type || 'text/plain';
567 my $fn = $part->filename;
568 my ($s, $err) = msg_part_text($part, $ct);
569 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
571 my $rv = $ctx->{obuf};
572 if ($part->{is_submsg}) {
573 submsg_hdr($ctx, $part);
577 # makes no difference to browsers, and don't screw up filename
578 # link generation in diffs with the extra '%0D'
581 # will be escaped to `•' in HTML
582 obfuscate_addrs($ibx, $s, "\x{2022}") if $ibx->{obfuscate};
584 # always support diff-highlighting, but we can't linkify hunk
585 # headers for solver unless some coderepo are configured:
587 if ($s =~ /^--- [^\n]+\n\+{3} [^\n]+\n@@ /ms) {
588 # diffstat anchors do not link across attachments or messages,
589 # -apfx is just a stable prefix for making diffstat anchors
590 # linkable to the first diff hunk w/o crossing attachments
591 $idx =~ tr!.!/!; # compatibility with previous versions
592 $ctx->{-apfx} = $upfx . $idx;
594 # do attr => filename mappings for diffstats in git diffs:
595 $ctx->{-anchors} = {} if $s =~ /^diff --git /sm;
597 delete $ctx->{-long_path};
599 # absolute URL (Atom feeds)
600 if ($ibx->{coderepo}) {
601 if (index($upfx, '//') >= 0) {
603 $spfx =~ s!/([^/]*)/\z!/!;
605 my $n_slash = $upfx =~ tr!/!/!;
608 } elsif ($n_slash == 1) {
610 } else { # nslash == 2
615 $ctx->{-spfx} = $spfx;
618 # some editors don't put trailing newlines at the end:
619 $s .= "\n" unless $s =~ /\n\z/s;
621 # split off quoted and unquoted blocks:
622 my @sections = PublicInbox::MsgIter::split_quotes($s);
623 undef $s; # free memory
624 if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
625 # badly-encoded message with $err? tell the world about it!
626 attach_link($ctx, $ct, $p, $fn, $err);
629 foreach my $cur (@sections) {
631 # we use a <span> here to allow users to specify
632 # their own color for quoted text
633 $$rv .= qq(<span\nclass="q">);
634 $$rv .= $l->to_html($cur);
637 flush_diff($ctx, \$cur);
640 $$rv .= $l->to_html($cur);
642 undef $cur; # free memory
646 sub _msg_page_prepare_obuf {
647 my ($eml, $ctx) = @_;
648 my $over = $ctx->{ibx}->over;
649 my $obfs_ibx = $ctx->{-obfs_ibx};
651 my $mids = mids_for_index($eml);
652 my $nr = $ctx->{nr}++;
653 if ($nr) { # unlikely
654 if ($ctx->{chash} eq content_hash($eml)) {
655 warn "W: BUG? @$mids not deduplicated properly\n";
659 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
662 $ctx->{first_hdr} = $eml->header_obj;
663 $ctx->{chash} = content_hash($eml) if $ctx->{smsg}; # reused MID
664 $rv .= "<pre\nid=b>"; # anchor for body start
666 $ctx->{-upfx} = '../' if $over;
667 my @title; # (Subject[0], From[0])
668 for my $v ($eml->header('From')) {
669 my @n = PublicInbox::Address::names($v);
671 $title[1] //= ascii_html(join(', ', @n));
673 obfuscate_addrs($obfs_ibx, $v);
674 obfuscate_addrs($obfs_ibx, $title[1]);
676 $rv .= "From: $v\n" if $v ne '';
678 foreach my $h (qw(To Cc)) {
679 for my $v ($eml->header($h)) {
682 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
683 $rv .= "$h: $v\n" if $v ne '';
686 my @subj = $eml->header('Subject');
688 my $v = ascii_html(shift @subj);
689 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
691 $rv .= $over ? qq(<a\nhref="#r"\nid=t>$v</a>\n) : "$v\n";
693 for $v (@subj) { # multi-Subject message :<
695 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
696 $rv .= "Subject: $v\n";
698 } else { # dummy anchor for thread skeleton at bottom of page
699 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
700 $title[0] = '(no subject)';
702 for my $v ($eml->header('Date')) {
704 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
705 $rv .= qq{Date: $v\t<a\nhref="#r">[thread overview]</a>\n};
707 if (!$nr) { # first (and only) message, common case
708 $ctx->{-title_html} = join(' - ', @title);
709 $rv = $ctx->html_top . $rv;
711 if (scalar(@$mids) == 1) { # common case
712 my $mhtml = ascii_html($mids->[0]);
713 $rv .= "Message-ID: <$mhtml> ";
714 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
716 # X-Alt-Message-ID can happen if a message is injected from
717 # public-inbox-nntpd because of multiple Message-ID headers.
718 my $lnk = PublicInbox::Linkify->new;
720 for my $h (qw(Message-ID X-Alt-Message-ID)) {
721 $s .= "$h: $_\n" for ($eml->header_raw($h));
723 $lnk->linkify_mids('..', \$s, 1);
726 $rv .= _parent_headers($eml, $over);
732 qq(expand[<a\nhref="T/#u">flat</a>) .
733 qq(|<a\nhref="t/#u">nested</a>] ) .
734 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
735 qq(<a\nhref="t.atom">Atom feed</a>);
738 sub thread_skel ($$$) {
739 my ($skel, $ctx, $hdr) = @_;
740 my $mid = mids($hdr)->[0];
741 my $ibx = $ctx->{ibx};
742 my ($nr, $msgs) = $ibx->over->get_thread($mid);
743 my $parent = in_reply_to($hdr);
744 $$skel .= "\n<b>Thread overview: </b>";
746 if (defined $parent) {
747 $$skel .= SKEL_EXPAND."\n ";
748 $$skel .= ghost_parent('../', $parent) . "\n";
750 $$skel .= "<a\nid=r>[no followups]</a> ".
753 $ctx->{next_msg} = undef;
754 $ctx->{parent_msg} = $parent;
759 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
761 # nb: mutt only shows the first Subject in the index pane
762 # when multiple Subject: headers are present, so we follow suit:
763 my $subj = $hdr->header('Subject') // '';
764 $subj = '(no subject)' if $subj eq '';
765 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
767 $ctx->{prev_attr} = '';
768 $ctx->{prev_level} = 0;
769 $ctx->{skel} = $skel;
771 # reduce hash lookups in skel_dump
772 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
773 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
775 $ctx->{parent_msg} = $parent;
778 sub _parent_headers {
779 my ($hdr, $over) = @_;
781 my @irt = $hdr->header_raw('In-Reply-To');
784 my $lnk = PublicInbox::Linkify->new;
785 $rv .= "In-Reply-To: $_\n" for @irt;
786 $lnk->linkify_mids('..', \$rv);
788 $refs = references($hdr);
789 my $irt = pop @$refs;
791 my $html = ascii_html($irt);
792 my $href = mid_href($irt);
793 $rv .= "In-Reply-To: <";
794 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
798 # do not display References: if search is present,
799 # we show the thread skeleton at the bottom, instead.
802 $refs //= references($hdr);
804 @$refs = map { linkify_ref_no_over($_) } @$refs;
805 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
810 # returns a string buffer
812 my ($ctx, $hdr) = @_;
813 my $ibx = $ctx->{ibx};
818 my $t = ts2str($ctx->{-t_max});
819 my $t_fmt = fmt_ts($ctx->{-t_max});
822 href="$upfx?t=$t">~$t_fmt UTC</a>|<a
823 href="$upfx">newest</a>]
826 thread_skel(\$skel, $ctx, $hdr);
831 if (my $n = $ctx->{next_msg}) {
833 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
836 my $par = $ctx->{parent_msg};
841 if (my $p = $ctx->{prev_msg}) {
842 $prev = mid_href($p);
843 if ($p && $par && $p eq $par) {
844 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
845 'rel=prev>prev parent</a>';
848 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
850 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
852 } elsif ($u) { # unlikely
853 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
855 $rv .= "$next $prev$parent ";
856 } else { # unindexed inboxes w/o over
857 $skel = qq( <a\nhref="$upfx">latest</a>);
859 $rv .= qq(<a\nhref="#R">reply</a>);
862 $rv .= msg_reply($ctx, $hdr);
865 sub linkify_ref_no_over {
867 my $href = mid_href($mid);
868 my $html = ascii_html($mid);
869 "<<a\nhref=\"../$href/\">$html</a>>";
874 'm' . id_compress($msgid, 1);
878 my ($upfx, $mid) = @_;
880 my $href = mid_href($mid);
881 my $html = ascii_html($mid);
882 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
887 $level ? INDENT x ($level - 1) : '';
891 my ($ctx, $level, $node, $idx) = @_;
892 ++$ctx->{root_idx} if $level == 0;
893 if ($node->{mid} eq $ctx->{mid}) {
894 $ctx->{found_mid_at} = $ctx->{root_idx};
895 return 0; # stop iterating
900 sub strict_loose_note ($) {
903 " -- strict thread matches above, loose matches on Subject: below --\n";
905 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
907 " -- use mbox.gz link to download all $nr messages --\n";
913 my ($ctx, $msgs) = @_;
914 require PublicInbox::SearchThread;
915 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
917 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
918 # and preserved in the future. This bug is hidden by `sid' matches
919 # in get_thread, so we never noticed it until now. And even when
920 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
921 # bump since reindexing is expensive and users may not do it
923 # loose threading could've returned too many results,
924 # put the root the message we care about at the top:
925 my $mid = $ctx->{mid};
926 if (defined($mid) && scalar(@$rootset) > 1) {
927 $ctx->{root_idx} = -1;
928 my $nr = scalar @$msgs;
929 walk_thread($rootset, $ctx, \&find_mid_root);
930 my $idx = $ctx->{found_mid_at};
931 if (defined($idx) && $idx != 0) {
932 my $tip = splice(@$rootset, $idx, 1);
933 @$rootset = reverse @$rootset;
934 unshift @$rootset, $tip;
935 $ctx->{sl_note} = strict_loose_note($nr);
943 require PublicInbox::ExtMsg;
944 PublicInbox::ExtMsg::ext_msg($ctx);
948 my ($prev_subj, $subj, $val) = @_;
950 my $omit; # '"' denotes identical text omitted
951 my (@prev_pop, @curr_pop);
952 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
953 push(@prev_pop, pop(@$prev_subj));
954 push(@curr_pop, pop(@$subj));
957 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
958 if (scalar(@curr_pop) == 1) {
960 push @$prev_subj, @prev_pop;
961 push @$subj, @curr_pop;
966 sub skel_dump { # walk_thread callback
967 my ($ctx, $level, $smsg) = @_;
968 $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
970 my $skel = $ctx->{skel};
971 my $cur = $ctx->{cur};
972 my $mid = $smsg->{mid};
974 if ($level == 0 && $ctx->{skel_dump_roots}++) {
975 $$skel .= delete($ctx->{sl_note}) || '';
978 my $f = ascii_html($smsg->{from_name});
979 my $obfs_ibx = $ctx->{-obfs_ibx};
980 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
982 my $d = fmt_ts($smsg->{ds});
983 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
984 if (exists $ctx->{searchview}) {
985 if (defined(my $pct = $smsg->{pct})) {
986 $d .= (sprintf(' % 2u', $pct) . '%');
992 $d .= ' ' . indent_for($level) . th_pfx($level);
994 $ctx->{first_level} ||= $level;
996 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
997 $ctx->{prev_attr} = $attr;
999 $ctx->{prev_level} = $level;
1004 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
1005 "$attr [this message]</a></b>\n";
1008 $ctx->{prev_msg} = $mid;
1011 $ctx->{next_msg} ||= $mid;
1014 # Subject is never undef, this mail was loaded from
1015 # our Xapian which would've resulted in '' if it were
1016 # really missing (and Filter rejects empty subjects)
1017 my @subj = split(/ /, subject_normalized($smsg->{subject}));
1018 # remove common suffixes from the subject if it matches the previous,
1019 # so we do not show redundant text at the end.
1020 my $prev_subj = $ctx->{prev_subj} || [];
1021 $ctx->{prev_subj} = [ @subj ];
1022 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
1025 my $subj = join(' ', @subj);
1026 $subj = ascii_html($subj);
1027 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1028 $end = "$subj</a> $omit$f\n"
1034 my $mapping = $unmatched ? undef : $ctx->{mapping};
1036 my $map = $mapping->{$mid};
1037 $id = id_compress($mid, 1);
1039 $map->[0] = "$d<a\nhref=\"$m\">$end";
1042 $m = $ctx->{-upfx}.mid_href($mid).'/';
1044 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1049 my ($ctx, $level, $node) = @_;
1051 my $mid = $node->{mid};
1052 my $d = ' [not found] ';
1053 $d .= ' ' if exists $ctx->{searchview};
1054 $d .= indent_for($level) . th_pfx($level);
1055 my $upfx = $ctx->{-upfx};
1056 my $href = $upfx . mid_href($mid) . '/';
1057 my $html = ascii_html($mid);
1059 my $mapping = $ctx->{mapping};
1060 my $map = $mapping->{$mid} if $mapping;
1062 my $id = id_compress($mid, 1);
1063 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1064 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1066 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1068 ${$ctx->{skel}} .= $d;
1074 (eval { $a->topmost->{ds} } || 0) <=>
1075 (eval { $b->topmost->{ds} } || 0)
1079 # accumulate recent topics if search is supported
1080 # returns 200 if done, 404 if not
1081 sub acc_topic { # walk_thread callback
1082 my ($ctx, $level, $smsg) = @_;
1083 my $mid = $smsg->{mid};
1084 my $has_blob = $smsg->{blob} // do {
1085 if (my $by_mid = $ctx->{ibx}->smsg_by_mid($mid)) {
1086 %$smsg = (%$smsg, %$by_mid);
1091 my $subj = subject_normalized($smsg->{subject});
1092 $subj = '(no subject)' if $subj eq '';
1093 my $ds = $smsg->{ds};
1094 if ($level == 0) { # new, top-level topic
1095 my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1096 $ctx->{-cur_topic} = $topic;
1097 push @{$ctx->{order}}, $topic;
1101 # continue existing topic
1102 my $topic = $ctx->{-cur_topic}; # should never be undef
1103 $topic->[0] = $ds if $ds > $topic->[0];
1104 $topic->[1]++; # bump N+ message counter
1105 my $seen = $topic->[2];
1106 if (scalar(@$topic) == 3) { # parent was a ghost
1107 push @$topic, $subj;
1108 } elsif (!defined($seen->{$subj})) {
1109 push @$topic, $level, $subj; # @extra messages
1111 $seen->{$subj} = $mid; # latest for subject
1112 } else { # ghost message
1113 return 1 if $level != 0; # ignore child ghosts
1114 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1115 push @{$ctx->{order}}, $topic;
1122 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1124 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1129 my $ibx = $ctx->{ibx};
1130 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1132 # sort by recency, this allows new posts to "bump" old topics...
1133 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1134 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1136 next unless defined $top_subj; # ghost topic
1137 my $mid = delete $seen->{$top_subj};
1138 my $href = mid_href($mid);
1139 my $prev_subj = [ split(/ /, $top_subj) ];
1140 $top_subj = ascii_html($top_subj);
1143 # $n isn't the total number of posts on the topic,
1144 # just the number of posts in the current results window
1148 $anchor = '#u'; # top of only message
1150 $n = " ($n+ messages)";
1151 $anchor = '#t'; # thread skeleton
1154 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1155 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1156 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1157 " $ds UTC $n - $mbox / $atom\n";
1158 for (my $i = 0; $i < scalar(@extra); $i += 2) {
1159 my $level = $extra[$i];
1160 my $subj = $extra[$i + 1]; # already normalized
1161 $mid = delete $seen->{$subj};
1162 my @subj = split(/ /, $subj);
1163 my @next_prev = @subj; # full copy
1164 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1165 $prev_subj = \@next_prev;
1166 $subj = join(' ', @subj);
1167 $subj = ascii_html($subj);
1168 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1169 $href = mid_href($mid);
1170 $s .= indent_for($level) . TCHILD;
1171 $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1175 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1180 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1181 timegm($ss || 0, $mm || 0, $hh || 0, $dd, $mon - 1, $yyyy);
1184 sub pagination_footer ($$) {
1185 my ($ctx, $latest) = @_;
1186 my $next = $ctx->{next_page} || '';
1187 my $prev = $ctx->{prev_page} || '';
1188 if ($prev) { # aligned padding for: 'next (older) | '
1189 $next = $next ? "$next | " : ' | ';
1190 $prev .= qq[ | <a\nhref="$latest">latest</a>];
1192 "<hr><pre>page: $next$prev</pre>";
1195 sub paginate_recent ($$) {
1196 my ($ctx, $lim) = @_;
1197 my $t = $ctx->{qp}->{t} || '';
1198 my $opts = { limit => $lim };
1199 my ($after, $before);
1201 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1202 # if only $after exists "YYYYMMDD.." because "." could be skipped
1203 # if interpreted as an end-of-sentence
1204 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1205 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1207 my $ibx = $ctx->{ibx};
1208 my $msgs = $ibx->recent($opts, $after, $before);
1209 my $nr = scalar @$msgs;
1210 if ($nr < $lim && defined($after)) {
1211 $after = $before = undef;
1212 $msgs = $ibx->recent($opts);
1213 $nr = scalar @$msgs;
1215 my $more = $nr == $lim;
1216 my ($newest, $oldest);
1218 $newest = $msgs->[0]->{ts};
1219 $oldest = $msgs->[-1]->{ts};
1220 # if we only had $after, our SQL query in ->recent ordered
1221 if ($newest < $oldest) {
1222 ($oldest, $newest) = ($newest, $oldest);
1223 $more = 0 if defined($after) && $after < $oldest;
1226 if (defined($oldest) && $more) {
1227 my $s = ts2str($oldest);
1228 $ctx->{next_page} = qq[<a\nhref="?t=$s"\nrel=next>] .
1231 if (defined($newest) && (defined($before) || defined($after))) {
1232 my $s = ts2str($newest);
1233 $ctx->{prev_page} = qq[<a\nhref="?t=$s-"\nrel=prev>] .
1239 # GET /$INBOX - top-level inbox view for indexed inboxes
1242 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1244 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1246 html_oneshot($ctx, dump_topics($ctx), \pagination_footer($ctx, '.'));
1250 sub thread_adj_level {
1251 my ($ctx, $level) = @_;
1253 my $max = $ctx->{cur_level};
1255 return ('', '') if $max == 0; # flat output
1257 # reset existing lists
1258 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1259 $ctx->{cur_level} = 0;
1261 } elsif ($level == $max) { # continue existing list
1263 } elsif ($level < $max) {
1264 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1265 $ctx->{cur_level} = $level;
1266 ("$beg<li>", '</li>');
1267 } else { # ($level > $max) # start a new level
1268 $ctx->{cur_level} = $level;
1269 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1274 sub ghost_index_entry {
1275 my ($ctx, $level, $node) = @_;
1276 my ($beg, $end) = thread_adj_level($ctx, $level);
1277 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{mid})