1 # Copyright (C) 2014-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Used for displaying the HTML web interface.
5 # See Documentation/design_www.txt for this.
6 package PublicInbox::View;
9 use bytes (); # only for bytes::length
10 use PublicInbox::MsgTime qw(msg_datestamp);
11 use PublicInbox::Hval qw(ascii_html obfuscate_addrs prurl mid_href);
12 use PublicInbox::Linkify;
13 use PublicInbox::MID qw(id_compress mids mids_for_index references
15 use PublicInbox::MsgIter;
16 use PublicInbox::Address;
17 use PublicInbox::WwwStream;
18 use PublicInbox::Reply;
19 use PublicInbox::ViewDiff qw(flush_diff);
21 use POSIX qw(strftime);
22 use Time::Local qw(timegm);
23 use PublicInbox::Smsg qw(subject_normalized);
24 use constant COLS => 72;
25 use constant INDENT => ' ';
26 use constant TCHILD => '` ';
27 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
31 if (my $more = delete $ctx->{more}) { # unlikely
32 # fake an EOF if $more retrieval fails;
33 eval { msg_page_more($ctx, $nr, @$more) };
34 } elsif (my $hdr = delete $ctx->{hdr}) {
35 # fake an EOF if generating the footer fails;
36 # we want to at least show the message if something
38 eval { html_footer($ctx, $hdr) };
44 # public functions: (unstable)
48 my $mid = $ctx->{mid};
49 my $ibx = $ctx->{-inbox};
50 my ($smsg, $first, $next);
51 if (my $over = $ibx->over) {
53 $smsg = $over->next_by_mid($mid, \$id, \$prev) or return;
54 $first = $ibx->msg_by_smsg($smsg) or return;
55 $next = $over->next_by_mid($mid, \$id, \$prev);
56 $ctx->{more} = [ $id, $prev, $next ] if $next;
58 $first = $ibx->msg_by_mid($mid) or return;
60 my $mime = PublicInbox::Eml->new($first);
61 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
62 my $hdr = $ctx->{hdr} = $mime->header_obj;
63 $ctx->{obuf} = _msg_page_prepare_obuf($hdr, $ctx, 0);
65 # $next cannot be true w/o $smsg being defined:
66 $ctx->{mhref} = $next ? '../'.mid_href($smsg->{mid}).'/' : '';
67 multipart_text_as_html($mime, $ctx);
68 $ctx->{-html_tip} = (${delete $ctx->{obuf}} .= '</pre><hr>');
69 PublicInbox::WwwStream->response($ctx, 200, \&msg_page_i);
72 sub msg_page_more { # cold
73 my ($ctx, $nr, $id, $prev, $smsg) = @_;
74 my $ibx = $ctx->{-inbox};
75 my $next = $ibx->over->next_by_mid($ctx->{mid}, \$id, \$prev);
76 $ctx->{more} = [ $id, $prev, $next ] if $next;
77 $smsg = $ibx->smsg_mime($smsg) or return '';
78 $ctx->{mhref} = '../' . mid_href($smsg->{mid}) . '/';
79 my $mime = delete $smsg->{mime};
80 $ctx->{obuf} = _msg_page_prepare_obuf($mime->header_obj, $ctx, $nr);
81 multipart_text_as_html($mime, $ctx);
82 ${delete $ctx->{obuf}} .= '</pre><hr>';
85 # /$INBOX/$MESSAGE_ID/#R
89 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
91 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
94 my $ibx = $ctx->{-inbox};
95 if (my $url = $ibx->{infourl}) {
96 $url = prurl($ctx->{env}, $url);
97 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
100 my ($arg, $link, $reply_to_all) =
101 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
102 if (ref($arg) eq 'SCALAR') {
103 return '<pre id=R>'.ascii_html($$arg).'</pre>';
106 # mailto: link only works if address obfuscation is disabled
110 * If your mail client supports setting the <b>In-Reply-To</b> header
111 via mailto: links, try the <a
112 href="$link">mailto: link</a>
116 push @$arg, '/path/to/YOUR_REPLY';
117 $arg = ascii_html(join(" \\\n ", '', @$arg));
120 id=R><b>Reply instructions:</b>
122 You may reply publicly to <a
123 href=#t>this message</a> via plain-text email
124 using any one of the following methods:
126 * Save the following mbox file, import it into your mail client,
127 and $reply_to_all from there: <a
130 Avoid top-posting and favor interleaved quoting:
132 href="$p_url">$p_url</a>
134 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
135 switches of git-send-email(1):
140 href="$se_url">$se_url</a>
147 my $refs = references($hdr);
151 sub fold_addresses ($) {
152 return $_[0] if length($_[0]) <= COLS;
153 # try to fold on commas after non-word chars before $lim chars,
154 # Try to get the "," preceded by ">" or ")", but avoid folding
155 # on the comma where somebody uses "Lastname, Firstname".
156 # We also try to keep the last and penultimate addresses in
157 # the list on the same line if possible, hence the extra \z
158 # Fall back to folding on spaces at $lim + 1 chars
159 my $lim = COLS - 8; # 8 = "\t" display width
160 my $too_long = $lim + 1;
161 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
163 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
166 .{$too_long,}?)(?:\s|\z)/xgo));
169 sub _hdr_names_html ($$) {
170 my ($hdr, $field) = @_;
171 my @vals = $hdr->header($field) or return '';
172 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
176 my ($nr, $singular, $plural) = @_;
177 return "0 $plural" if $nr == 0;
178 $nr == 1 ? "$nr $singular" : "$nr $plural";
181 # human-friendly format
182 sub fmt_ts ($) { strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
184 # this is already inside a <pre>
186 my ($smsg, $ctx, $more) = @_;
187 my $subj = $smsg->subject;
188 my $mid_raw = $smsg->mid;
189 my $id = id_compress($mid_raw, 1);
192 my $root_anchor = $ctx->{root_anchor} || '';
194 my $obfs_ibx = $ctx->{-obfs_ibx};
196 $subj = '(no subject)' if $subj eq '';
197 my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
198 $subj = '<b>'.ascii_html($subj).'</b>';
199 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
200 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
202 $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
204 my $ds = $smsg->ds; # for v1 non-Xapian/SQLite users
205 # deleting {mime} is critical to memory use,
206 # the rest of the fields saves about 400K as we iterate across 1K msgs
207 my ($mime) = delete @$smsg{qw(mime ds ts blob subject)};
209 my $hdr = $mime->header_obj;
210 my $from = _hdr_names_html($hdr, 'From');
211 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
212 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
213 my $upfx = $ctx->{-upfx};
214 my $mhref = $upfx . mid_href($mid_raw) . '/';
215 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
216 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
217 my $to = fold_addresses(_hdr_names_html($hdr, 'To'));
218 my $cc = fold_addresses(_hdr_names_html($hdr, 'Cc'));
219 my ($tlen, $clen) = (length($to), length($cc));
221 if (($tlen + $clen) > COLS) {
222 $to_cc .= ' To: '.$to."\n" if $tlen;
223 $to_cc .= ' Cc: '.$cc."\n" if $clen;
226 $to_cc .= ' To: '.$to;
227 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
229 $to_cc .= ' Cc: '.$cc if $clen;
233 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
236 my $mapping = $ctx->{mapping};
237 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
238 my $href = $upfx . mid_href($irt) . '/';
239 my $html = ascii_html($irt);
240 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
244 # scan through all parts, looking for displayable text
245 $ctx->{mhref} = $mhref;
247 $mime->each_part(\&add_text_body, $ctx, 1);
251 $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
252 "<a\nhref=\"$mhref\">permalink</a>" .
253 " <a\nhref=\"${mhref}raw\">raw</a>" .
254 " <a\nhref=\"${mhref}#R\">reply</a>";
257 if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
258 $rv .= "\t[relevance $pct%]";
261 my $nested = 'nested';
266 $flat = "<b>$flat</b>";
268 $nested = "<b>$nested</b>";
270 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
271 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
272 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
277 $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
281 sub pad_link ($$;$) {
282 my ($mid, $level, $s) = @_;
284 my $id = id_compress($mid, 1);
285 (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
289 my ($mid_raw, $irt, $id, $ctx) = @_;
291 my $mapping = $ctx->{mapping} or return $rv;
293 my $mid_map = $mapping->{$mid_raw};
295 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
296 my ($attr, $node, $idx, $level) = @$mid_map;
297 my $children = $node->{children};
298 my $nr_c = scalar @$children;
301 # delete saves about 200KB on a 1K message thread
302 if (my $refs = delete $node->{references}) {
303 ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
305 my $irt_map = $mapping->{$$irt} if defined $$irt;
306 if (defined $irt_map) {
307 $siblings = $irt_map->[1]->{children};
308 $nr_s = scalar(@$siblings) - 1;
309 $rv .= $pad . $irt_map->[0];
311 my $prev = $siblings->[$idx - 1];
312 my $pmid = $prev->{mid};
314 my $s = ($idx - 1). ' preceding siblings ...';
315 $rv .= pad_link($pmid, $level, $s);
316 } elsif ($idx == 2) {
317 my $ppmid = $siblings->[0]->{mid};
318 $rv .= $pad . $mapping->{$ppmid}->[0];
320 $rv .= $pad . $mapping->{$pmid}->[0];
323 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
324 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
325 $attr =~ s!\n\z!</b>\n!s;
326 $attr =~ s!<a\nhref.*</a> (?:" )?!!s; # no point in dup subject
327 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
330 my $cmid = $children->[0]->{mid};
331 $rv .= $pad . $mapping->{$cmid}->[0];
333 my $s = ($nr_c - 1). ' more replies';
334 $rv .= pad_link($cmid, $level + 1, $s);
335 } elsif (my $cn = $children->[1]) {
336 $rv .= $pad . $mapping->{$cn->{mid}}->[0];
340 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
342 my $nmid = $next->{mid};
343 $rv .= $pad . $mapping->{$nmid}->[0];
344 my $nnext = $nr_s - $idx;
346 my $s = ($nnext - 1).' subsequent siblings';
347 $rv .= pad_link($nmid, $level, $s);
348 } elsif (my $nn = $siblings->[$idx + 2]) {
349 $rv .= $pad . $mapping->{$nn->{mid}}->[0];
352 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
355 # non-recursive thread walker
356 sub walk_thread ($$$) {
357 my ($rootset, $ctx, $cb) = @_;
358 my @q = map { (0, $_, -1) } @$rootset;
360 my ($level, $node, $i) = splice(@q, 0, 3);
361 defined $node or next;
362 $cb->($ctx, $level, $node, $i) or return;
365 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
369 sub pre_thread { # walk_thread callback
370 my ($ctx, $level, $node, $idx) = @_;
371 $ctx->{mapping}->{$node->{mid}} = [ '', $node, $idx, $level ];
372 skel_dump($ctx, $level, $node);
375 sub thread_index_entry {
376 my ($ctx, $level, $smsg) = @_;
377 my ($beg, $end) = thread_adj_level($ctx, $level);
378 $beg . '<pre>' . index_entry($smsg, $ctx, 0) . '</pre>' . $end;
381 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
383 return unless exists($ctx->{skel});
384 my $q = $ctx->{-queue};
386 my $level = shift @$q;
387 my $node = shift @$q or next;
389 unshift @$q, map { ($cl, $_) } @{$node->{children}};
390 if ($ctx->{-inbox}->smsg_mime($node)) {
391 return thread_index_entry($ctx, $level, $node);
393 return ghost_index_entry($ctx, $level, $node);
396 join('', thread_adj_level($ctx, 0)) . ${delete $ctx->{skel}};
399 sub stream_thread ($$) {
400 my ($rootset, $ctx) = @_;
401 my $ibx = $ctx->{-inbox};
402 my @q = map { (0, $_) } @$rootset;
406 my $node = shift @q or next;
408 unshift @q, map { ($cl, $_) } @{$node->{children}};
409 $smsg = $ibx->smsg_mime($node) and last;
411 return missing_thread($ctx) unless $smsg;
413 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
414 $ctx->{-title_html} = ascii_html($smsg->{subject});
415 $ctx->{-html_tip} = thread_index_entry($ctx, $level, $smsg);
416 $ctx->{-queue} = \@q;
417 PublicInbox::WwwStream->response($ctx, 200, \&stream_thread_i);
420 # /$INBOX/$MESSAGE_ID/t/
423 my $mid = $ctx->{mid};
424 my $ibx = $ctx->{-inbox};
425 my ($nr, $msgs) = $ibx->over->get_thread($mid);
426 return missing_thread($ctx) if $nr == 0;
427 my $skel = '<hr><pre>';
428 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
429 $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
430 $skel .= "<b\nid=t>Thread overview:</b> ";
431 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
432 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
433 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
434 $skel .= "-- links below jump to the message on this page --\n";
435 $ctx->{-upfx} = '../../';
436 $ctx->{cur_level} = 0;
437 $ctx->{skel} = \$skel;
438 $ctx->{prev_attr} = '';
439 $ctx->{prev_level} = 0;
440 $ctx->{root_anchor} = anchor_for($mid);
441 $ctx->{mapping} = {};
442 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
445 my $rootset = thread_results($ctx, $msgs);
447 # reduce hash lookups in pre_thread->skel_dump
448 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
449 walk_thread($rootset, $ctx, \&pre_thread);
452 return stream_thread($rootset, $ctx) unless $ctx->{flat};
454 # flat display: lazy load the full message from smsg
456 while (my $m = shift @$msgs) {
457 $smsg = $ibx->smsg_mime($m) and last;
459 return missing_thread($ctx) unless $smsg;
460 $ctx->{-title_html} = ascii_html($smsg->{subject});
461 $ctx->{-html_tip} = '<pre>'.index_entry($smsg, $ctx, scalar @$msgs);
462 $ctx->{msgs} = $msgs;
463 PublicInbox::WwwStream->response($ctx, 200, \&thread_html_i);
466 sub thread_html_i { # PublicInbox::WwwStream::getline callback
468 my $msgs = $ctx->{msgs} or return;
469 while (my $smsg = shift @$msgs) {
470 $ctx->{-inbox}->smsg_mime($smsg) or next;
471 return index_entry($smsg, $ctx, scalar @$msgs);
473 my ($skel) = delete @$ctx{qw(skel msgs)};
477 sub multipart_text_as_html {
478 # ($mime, $ctx) = @_; # each_part may do "$_[0] = undef"
480 # scan through all parts, looking for displayable text
481 $_[0]->each_part(\&add_text_body, $_[1], 1);
484 sub submsg_hdr ($$) {
485 my ($ctx, $eml) = @_;
486 my $obfs_ibx = $ctx->{-obfs_ibx};
487 my $rv = $ctx->{obuf};
489 for my $h (qw(From To Cc Subject Date Message-ID X-Alt-Message-ID)) {
490 my @v = $eml->header($h);
492 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
499 sub attach_link ($$$$;$) {
500 my ($ctx, $ct, $p, $fn, $err) = @_;
501 my ($part, $depth, $idx) = @$p;
503 # Eml iteration clobbers multipart ->{bdy}, so do not offer
504 # downloads for 0-byte multipart attachments
505 return unless $part->{bdy};
507 my $nl = $idx eq '1' ? '' : "\n"; # like join("\n", ...)
508 my $size = bytes::length($part->body);
510 # hide attributes normally, unless we want to aid users in
511 # spotting MUA problems:
512 $ct =~ s/;.*// unless $err;
513 $ct = ascii_html($ct);
515 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
517 } elsif ($ct eq 'text/plain') {
522 my $rv = $ctx->{obuf};
523 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
526 [-- Warning: decoded text below may be mangled, UTF-8 assumed --]
529 $$rv .= "[-- Attachment #$idx: ";
530 my $ts = "Type: $ct, Size: $size bytes";
531 my $desc = $part->header('Content-Description') // $fn // '';
532 $desc = ascii_html($desc);
533 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
536 submsg_hdr($ctx, $part) if $part->{is_submsg};
541 sub add_text_body { # callback for each_part
543 my $upfx = $ctx->{mhref};
544 my $ibx = $ctx->{-inbox};
545 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
546 # $p - from each_part: [ Email::MIME-like, depth, $idx ]
547 my ($part, $depth, $idx) = @$p;
548 my $ct = $part->content_type || 'text/plain';
549 my $fn = $part->filename;
550 my ($s, $err) = msg_part_text($part, $ct);
551 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
553 my $rv = $ctx->{obuf};
554 if ($part->{is_submsg}) {
555 submsg_hdr($ctx, $part);
559 # makes no difference to browsers, and don't screw up filename
560 # link generation in diffs with the extra '%0D'
563 # will be escaped to `•' in HTML
564 obfuscate_addrs($ibx, $s, "\x{2022}") if $ibx->{obfuscate};
566 # always support diff-highlighting, but we can't linkify hunk
567 # headers for solver unless some coderepo are configured:
569 if ($s =~ /^--- [^\n]+\n\+{3} [^\n]+\n@@ /ms) {
570 # diffstat anchors do not link across attachments or messages,
571 # -apfx is just a stable prefix for making diffstat anchors
572 # linkable to the first diff hunk w/o crossing attachments
573 $idx =~ tr!.!/!; # compatibility with previous versions
574 $ctx->{-apfx} = $upfx . $idx;
576 # do attr => filename mappings for diffstats in git diffs:
577 $ctx->{-anchors} = {} if $s =~ /^diff --git /sm;
579 delete $ctx->{-long_path};
581 if ($ibx->{-repo_objs}) {
582 if (index($upfx, '//') >= 0) { # absolute URL (Atom feeds)
584 $spfx =~ s!/([^/]*)/\z!/!;
586 my $n_slash = $upfx =~ tr!/!/!;
589 } elsif ($n_slash == 1) {
591 } else { # nslash == 2
596 $ctx->{-spfx} = $spfx;
599 # some editors don't put trailing newlines at the end:
600 $s .= "\n" unless $s =~ /\n\z/s;
602 # split off quoted and unquoted blocks:
603 my @sections = PublicInbox::MsgIter::split_quotes($s);
604 undef $s; # free memory
605 if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
606 # badly-encoded message with $err? tell the world about it!
607 attach_link($ctx, $ct, $p, $fn, $err);
610 foreach my $cur (@sections) {
612 # we use a <span> here to allow users to specify
613 # their own color for quoted text
614 $$rv .= qq(<span\nclass="q">);
615 $$rv .= $l->to_html($cur);
618 flush_diff($ctx, \$cur);
621 $$rv .= $l->to_html($cur);
623 undef $cur; # free memory
627 sub _msg_page_prepare_obuf {
628 my ($hdr, $ctx, $nr) = @_;
629 my $over = $ctx->{-inbox}->over;
630 my $obfs_ibx = $ctx->{-obfs_ibx};
632 my $mids = mids_for_index($hdr);
636 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
638 $rv .= "<pre\nid=b>"; # anchor for body start
643 $ctx->{-upfx} = '../';
645 my @title; # (Subject[0], From[0])
646 for my $v ($hdr->header('From')) {
647 my @n = PublicInbox::Address::names($v);
649 $title[1] //= ascii_html(join(', ', @n));
651 obfuscate_addrs($obfs_ibx, $v);
652 obfuscate_addrs($obfs_ibx, $title[1]);
654 $rv .= "From: $v\n" if $v ne '';
656 foreach my $h (qw(To Cc)) {
657 for my $v ($hdr->header($h)) {
660 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
661 $rv .= "$h: $v\n" if $v ne '';
664 my @subj = $hdr->header('Subject');
666 my $v = ascii_html(shift @subj);
667 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
669 $rv .= $over ? qq(<a\nhref="#r"\nid=t>$v</a>\n) : "$v\n";
671 for $v (@subj) { # multi-Subject message :<
673 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
674 $rv .= "Subject: $v\n";
676 } else { # dummy anchor for thread skeleton at bottom of page
677 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
678 $title[0] = '(no subject)';
680 for my $v ($hdr->header('Date')) {
682 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
685 $ctx->{-title_html} = join(' - ', @title);
686 if (scalar(@$mids) == 1) { # common case
687 my $mhtml = ascii_html($mids->[0]);
688 $rv .= "Message-ID: <$mhtml> ";
689 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
691 # X-Alt-Message-ID can happen if a message is injected from
692 # public-inbox-nntpd because of multiple Message-ID headers.
693 my $lnk = PublicInbox::Linkify->new;
695 for my $h (qw(Message-ID X-Alt-Message-ID)) {
696 $s .= "$h: $_\n" for ($hdr->header_raw($h));
698 $lnk->linkify_mids('..', \$s, 1);
701 $rv .= _parent_headers($hdr, $over);
707 qq(expand[<a\nhref="T/#u">flat</a>) .
708 qq(|<a\nhref="t/#u">nested</a>] ) .
709 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
710 qq(<a\nhref="t.atom">Atom feed</a>);
713 sub thread_skel ($$$) {
714 my ($skel, $ctx, $hdr) = @_;
715 my $mid = mids($hdr)->[0];
716 my $ibx = $ctx->{-inbox};
717 my ($nr, $msgs) = $ibx->over->get_thread($mid);
718 my $parent = in_reply_to($hdr);
719 $$skel .= "\n<b>Thread overview: </b>";
721 if (defined $parent) {
722 $$skel .= SKEL_EXPAND."\n ";
723 $$skel .= ghost_parent('../', $parent) . "\n";
725 $$skel .= '[no followups] '.SKEL_EXPAND."\n";
727 $ctx->{next_msg} = undef;
728 $ctx->{parent_msg} = $parent;
733 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
735 # nb: mutt only shows the first Subject in the index pane
736 # when multiple Subject: headers are present, so we follow suit:
737 my $subj = $hdr->header('Subject') // '';
738 $subj = '(no subject)' if $subj eq '';
739 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
741 $ctx->{prev_attr} = '';
742 $ctx->{prev_level} = 0;
743 $ctx->{skel} = $skel;
745 # reduce hash lookups in skel_dump
746 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
747 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
749 $ctx->{parent_msg} = $parent;
752 sub _parent_headers {
753 my ($hdr, $over) = @_;
755 my @irt = $hdr->header_raw('In-Reply-To');
758 my $lnk = PublicInbox::Linkify->new;
759 $rv .= "In-Reply-To: $_\n" for @irt;
760 $lnk->linkify_mids('..', \$rv);
762 $refs = references($hdr);
763 my $irt = pop @$refs;
765 my $html = ascii_html($irt);
766 my $href = mid_href($irt);
767 $rv .= "In-Reply-To: <";
768 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
772 # do not display References: if search is present,
773 # we show the thread skeleton at the bottom, instead.
776 $refs //= references($hdr);
778 @$refs = map { linkify_ref_no_over($_) } @$refs;
779 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
784 # returns a string buffer via ->getline
786 my ($ctx, $hdr) = @_;
787 my $ibx = $ctx->{-inbox};
789 my $skel = " <a\nhref=\"$upfx\">index</a>";
793 thread_skel(\$skel, $ctx, $hdr);
798 if (my $n = $ctx->{next_msg}) {
800 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
803 my $par = $ctx->{parent_msg};
808 if (my $p = $ctx->{prev_msg}) {
809 $prev = mid_href($p);
810 if ($p && $par && $p eq $par) {
811 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
812 'rel=prev>prev parent</a>';
815 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
817 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
819 } elsif ($u) { # unlikely
820 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
822 $rv .= "$next $prev$parent ";
824 $rv .= qq(<a\nhref="#R">reply</a>);
827 $rv .= msg_reply($ctx, $hdr);
830 sub linkify_ref_no_over {
832 my $href = mid_href($mid);
833 my $html = ascii_html($mid);
834 "<<a\nhref=\"../$href/\">$html</a>>";
839 'm' . id_compress($msgid, 1);
843 my ($upfx, $mid) = @_;
845 my $href = mid_href($mid);
846 my $html = ascii_html($mid);
847 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
852 $level ? INDENT x ($level - 1) : '';
856 my ($ctx, $level, $node, $idx) = @_;
857 ++$ctx->{root_idx} if $level == 0;
858 if ($node->{mid} eq $ctx->{mid}) {
859 $ctx->{found_mid_at} = $ctx->{root_idx};
865 sub strict_loose_note ($) {
868 " -- strict thread matches above, loose matches on Subject: below --\n";
870 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
872 " -- use mbox.gz link to download all $nr messages --\n";
878 my ($ctx, $msgs) = @_;
879 require PublicInbox::SearchThread;
880 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
882 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
883 # and preserved in the future. This bug is hidden by `sid' matches
884 # in get_thread, so we never noticed it until now. And even when
885 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
886 # bump since reindexing is expensive and users may not do it
888 # loose threading could've returned too many results,
889 # put the root the message we care about at the top:
890 my $mid = $ctx->{mid};
891 if (defined($mid) && scalar(@$rootset) > 1) {
892 $ctx->{root_idx} = -1;
893 my $nr = scalar @$msgs;
894 walk_thread($rootset, $ctx, \&find_mid_root);
895 my $idx = $ctx->{found_mid_at};
896 if (defined($idx) && $idx != 0) {
897 my $tip = splice(@$rootset, $idx, 1);
898 @$rootset = reverse @$rootset;
899 unshift @$rootset, $tip;
900 $ctx->{sl_note} = strict_loose_note($nr);
908 require PublicInbox::ExtMsg;
909 PublicInbox::ExtMsg::ext_msg($ctx);
913 my ($prev_subj, $subj, $val) = @_;
915 my $omit; # '"' denotes identical text omitted
916 my (@prev_pop, @curr_pop);
917 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
918 push(@prev_pop, pop(@$prev_subj));
919 push(@curr_pop, pop(@$subj));
922 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
923 if (scalar(@curr_pop) == 1) {
925 push @$prev_subj, @prev_pop;
926 push @$subj, @curr_pop;
931 sub skel_dump { # walk_thread callback
932 my ($ctx, $level, $smsg) = @_;
933 $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
935 my $skel = $ctx->{skel};
936 my $cur = $ctx->{cur};
937 my $mid = $smsg->{mid};
939 if ($level == 0 && $ctx->{skel_dump_roots}++) {
940 $$skel .= delete($ctx->{sl_note}) || '';
943 my $f = ascii_html($smsg->{from_name});
944 my $obfs_ibx = $ctx->{-obfs_ibx};
945 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
947 my $d = fmt_ts($smsg->{ds});
948 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
949 if (exists $ctx->{searchview}) {
950 if (defined(my $pct = $smsg->{pct})) {
951 $d .= (sprintf(' % 2u', $pct) . '%');
957 $d .= ' ' . indent_for($level) . th_pfx($level);
959 $ctx->{first_level} ||= $level;
961 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
962 $ctx->{prev_attr} = $attr;
964 $ctx->{prev_level} = $level;
969 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
970 "$attr [this message]</a></b>\n";
973 $ctx->{prev_msg} = $mid;
976 $ctx->{next_msg} ||= $mid;
979 # Subject is never undef, this mail was loaded from
980 # our Xapian which would've resulted in '' if it were
981 # really missing (and Filter rejects empty subjects)
982 my @subj = split(/ /, subject_normalized($smsg->{subject}));
983 # remove common suffixes from the subject if it matches the previous,
984 # so we do not show redundant text at the end.
985 my $prev_subj = $ctx->{prev_subj} || [];
986 $ctx->{prev_subj} = [ @subj ];
987 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
990 my $subj = join(' ', @subj);
991 $subj = ascii_html($subj);
992 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
993 $end = "$subj</a> $omit$f\n"
999 my $mapping = $unmatched ? undef : $ctx->{mapping};
1001 my $map = $mapping->{$mid};
1002 $id = id_compress($mid, 1);
1004 $map->[0] = "$d<a\nhref=\"$m\">$end";
1007 $m = $ctx->{-upfx}.mid_href($mid).'/';
1009 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1014 my ($ctx, $level, $node) = @_;
1016 my $mid = $node->{mid};
1017 my $d = ' [not found] ';
1018 $d .= ' ' if exists $ctx->{searchview};
1019 $d .= indent_for($level) . th_pfx($level);
1020 my $upfx = $ctx->{-upfx};
1021 my $href = $upfx . mid_href($mid) . '/';
1022 my $html = ascii_html($mid);
1024 my $mapping = $ctx->{mapping};
1025 my $map = $mapping->{$mid} if $mapping;
1027 my $id = id_compress($mid, 1);
1028 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1029 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1031 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1033 ${$ctx->{skel}} .= $d;
1039 (eval { $a->topmost->{ds} } || 0) <=>
1040 (eval { $b->topmost->{ds} } || 0)
1044 # accumulate recent topics if search is supported
1045 # returns 200 if done, 404 if not
1046 sub acc_topic { # walk_thread callback
1047 my ($ctx, $level, $smsg) = @_;
1048 my $mid = $smsg->{mid};
1049 my $has_blob = $smsg->{blob} // do {
1050 if (my $by_mid = $ctx->{-inbox}->smsg_by_mid($mid)) {
1051 %$smsg = (%$smsg, %$by_mid);
1056 my $subj = subject_normalized($smsg->{subject});
1057 $subj = '(no subject)' if $subj eq '';
1058 my $ds = $smsg->{ds};
1059 if ($level == 0) { # new, top-level topic
1060 my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1061 $ctx->{-cur_topic} = $topic;
1062 push @{$ctx->{order}}, $topic;
1066 # continue existing topic
1067 my $topic = $ctx->{-cur_topic}; # should never be undef
1068 $topic->[0] = $ds if $ds > $topic->[0];
1069 $topic->[1]++; # bump N+ message counter
1070 my $seen = $topic->[2];
1071 if (scalar(@$topic) == 3) { # parent was a ghost
1072 push @$topic, $subj;
1073 } elsif (!defined($seen->{$subj})) {
1074 push @$topic, $level, $subj; # @extra messages
1076 $seen->{$subj} = $mid; # latest for subject
1077 } else { # ghost message
1078 return 1 if $level != 0; # ignore child ghosts
1079 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1080 push @{$ctx->{order}}, $topic;
1087 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1089 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1094 my $ibx = $ctx->{-inbox};
1095 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
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 $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1120 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1121 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1122 " $ds UTC $n - $mbox / $atom\n";
1123 for (my $i = 0; $i < scalar(@extra); $i += 2) {
1124 my $level = $extra[$i];
1125 my $subj = $extra[$i + 1]; # already normalized
1126 $mid = delete $seen->{$subj};
1127 my @subj = split(/ /, $subj);
1128 my @next_prev = @subj; # full copy
1129 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1130 $prev_subj = \@next_prev;
1131 $subj = join(' ', @subj);
1132 $subj = ascii_html($subj);
1133 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1134 $href = mid_href($mid);
1135 $s .= indent_for($level) . TCHILD;
1136 $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1140 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1144 # only for the t= query parameter passed to overview DB
1145 sub ts2str ($) { strftime('%Y%m%d%H%M%S', gmtime($_[0])) };
1148 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1149 timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1152 sub pagination_footer ($$) {
1153 my ($ctx, $latest) = @_;
1154 delete $ctx->{qp} or return;
1155 my $next = $ctx->{next_page} || '';
1156 my $prev = $ctx->{prev_page} || '';
1158 $next = $next ? "$next " : ' ';
1159 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1161 "<hr><pre>page: $next$prev</pre>";
1164 sub index_nav { # callback for WwwStream
1165 my (undef, $ctx) = @_;
1166 pagination_footer($ctx, '.')
1169 sub paginate_recent ($$) {
1170 my ($ctx, $lim) = @_;
1171 my $t = $ctx->{qp}->{t} || '';
1172 my $opts = { limit => $lim };
1173 my ($after, $before);
1175 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1176 # if only $after exists "YYYYMMDD.." because "." could be skipped
1177 # if interpreted as an end-of-sentence
1178 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1179 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1181 my $ibx = $ctx->{-inbox};
1182 my $msgs = $ibx->recent($opts, $after, $before);
1183 my $nr = scalar @$msgs;
1184 if ($nr < $lim && defined($after)) {
1185 $after = $before = undef;
1186 $msgs = $ibx->recent($opts);
1187 $nr = scalar @$msgs;
1189 my $more = $nr == $lim;
1190 my ($newest, $oldest);
1192 $newest = $msgs->[0]->{ts};
1193 $oldest = $msgs->[-1]->{ts};
1194 # if we only had $after, our SQL query in ->recent ordered
1195 if ($newest < $oldest) {
1196 ($oldest, $newest) = ($newest, $oldest);
1197 $more = 0 if defined($after) && $after < $oldest;
1200 if (defined($oldest) && $more) {
1201 my $s = ts2str($oldest);
1202 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1204 if (defined($newest) && (defined($before) || defined($after))) {
1205 my $s = ts2str($newest);
1206 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1213 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1215 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1217 PublicInbox::WwwStream->response($ctx, dump_topics($ctx), \&index_nav);
1220 sub thread_adj_level {
1221 my ($ctx, $level) = @_;
1223 my $max = $ctx->{cur_level};
1225 return ('', '') if $max == 0; # flat output
1227 # reset existing lists
1228 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1229 $ctx->{cur_level} = 0;
1231 } elsif ($level == $max) { # continue existing list
1233 } elsif ($level < $max) {
1234 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1235 $ctx->{cur_level} = $level;
1236 ("$beg<li>", '</li>');
1237 } else { # ($level > $max) # start a new level
1238 $ctx->{cur_level} = $level;
1239 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1244 sub ghost_index_entry {
1245 my ($ctx, $level, $node) = @_;
1246 my ($beg, $end) = thread_adj_level($ctx, $level);
1247 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{mid})