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 qw(html_oneshot);
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 ($eml) { # called by WwwStream::async_eml or getline
32 my $smsg = $ctx->{smsg};
33 $ctx->{smsg} = $ctx->{over}->next_by_mid(@{$ctx->{next_arg}});
34 $ctx->{mhref} = ($ctx->{nr} || $ctx->{smsg}) ?
35 "../${\mid_href($smsg->{mid})}/" : '';
36 my $hdr = $eml->header_obj;
37 my $obuf = $ctx->{obuf} = _msg_page_prepare_obuf($hdr, $ctx);
38 multipart_text_as_html($eml, $ctx);
40 $$obuf .= '</pre><hr>';
41 $$obuf .= html_footer($ctx, $ctx->{first_hdr}) if !$ctx->{smsg};
43 } else { # called by WwwStream::async_next or getline
44 $ctx->{smsg}; # may be undef
48 # /$INBOX/$MSGID/ for unindexed v1 inboxes
49 sub no_over_html ($) {
51 my $bref = $ctx->{-inbox}->msg_by_mid($ctx->{mid}) or return; # 404
52 my $eml = PublicInbox::Eml->new($bref);
53 my $hdr = $eml->header_obj;
55 PublicInbox::WwwStream::init($ctx);
56 my $obuf = $ctx->{obuf} = _msg_page_prepare_obuf($hdr, $ctx);
57 multipart_text_as_html($eml, $ctx);
59 $$obuf .= '</pre><hr>';
60 eval { $$obuf .= html_footer($ctx, $hdr) };
61 html_oneshot($ctx, 200, $obuf);
64 # public functions: (unstable)
68 my $ibx = $ctx->{-inbox};
69 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
70 my $over = $ctx->{over} = $ibx->over or return no_over_html($ctx);
72 my $next_arg = $ctx->{next_arg} = [ $ctx->{mid}, \$id, \$prev ];
73 $ctx->{smsg} = $over->next_by_mid(@$next_arg) or return; # undef == 404
74 PublicInbox::WwwStream::aresponse($ctx, 200, \&msg_page_i);
77 # /$INBOX/$MESSAGE_ID/#R
81 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
83 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
86 my $ibx = $ctx->{-inbox};
87 if (my $url = $ibx->{infourl}) {
88 $url = prurl($ctx->{env}, $url);
89 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
92 my ($arg, $link, $reply_to_all) =
93 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
94 if (ref($arg) eq 'SCALAR') {
95 return '<pre id=R>'.ascii_html($$arg).'</pre>';
98 # mailto: link only works if address obfuscation is disabled
102 * If your mail client supports setting the <b>In-Reply-To</b> header
103 via mailto: links, try the <a
104 href="$link">mailto: link</a>
108 push @$arg, '/path/to/YOUR_REPLY';
109 $arg = ascii_html(join(" \\\n ", '', @$arg));
112 id=R><b>Reply instructions:</b>
114 You may reply publicly to <a
115 href=#t>this message</a> via plain-text email
116 using any one of the following methods:
118 * Save the following mbox file, import it into your mail client,
119 and $reply_to_all from there: <a
122 Avoid top-posting and favor interleaved quoting:
124 href="$p_url">$p_url</a>
126 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
127 switches of git-send-email(1):
132 href="$se_url">$se_url</a>
139 my $refs = references($hdr);
143 sub fold_addresses ($) {
144 return $_[0] if length($_[0]) <= COLS;
145 # try to fold on commas after non-word chars before $lim chars,
146 # Try to get the "," preceded by ">" or ")", but avoid folding
147 # on the comma where somebody uses "Lastname, Firstname".
148 # We also try to keep the last and penultimate addresses in
149 # the list on the same line if possible, hence the extra \z
150 # Fall back to folding on spaces at $lim + 1 chars
151 my $lim = COLS - 8; # 8 = "\t" display width
152 my $too_long = $lim + 1;
153 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
155 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
158 .{$too_long,}?)(?:\s|\z)/xgo));
161 sub _hdr_names_html ($$) {
162 my ($hdr, $field) = @_;
163 my @vals = $hdr->header($field) or return '';
164 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
168 my ($nr, $singular, $plural) = @_;
169 return "0 $plural" if $nr == 0;
170 $nr == 1 ? "$nr $singular" : "$nr $plural";
173 # human-friendly format
174 sub fmt_ts ($) { strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
176 # Displays the text of of the message for /$INBOX/$MSGID/[Tt]/ endpoint
177 # this is already inside a <pre>
179 my ($ctx, $eml) = @_;
180 my $smsg = delete $ctx->{smsg};
181 my $subj = delete $smsg->{subject};
182 my $mid_raw = $smsg->{mid};
183 my $id = id_compress($mid_raw, 1);
185 my $root_anchor = $ctx->{root_anchor} || '';
187 my $obfs_ibx = $ctx->{-obfs_ibx};
189 $subj = '(no subject)' if $subj eq '';
190 my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
191 $subj = '<b>'.ascii_html($subj).'</b>';
192 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
193 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
195 $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
197 my $ds = delete $smsg->{ds}; # for v1 non-Xapian/SQLite users
199 # Deleting these fields saves about 400K as we iterate across 1K msgs
200 delete @$smsg{qw(ts blob)};
202 my $hdr = $eml->header_obj;
203 my $from = _hdr_names_html($hdr, 'From');
204 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
205 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
206 my $upfx = $ctx->{-upfx};
207 my $mhref = $upfx . mid_href($mid_raw) . '/';
208 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
209 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
210 my $to = fold_addresses(_hdr_names_html($hdr, 'To'));
211 my $cc = fold_addresses(_hdr_names_html($hdr, 'Cc'));
212 my ($tlen, $clen) = (length($to), length($cc));
214 if (($tlen + $clen) > COLS) {
215 $to_cc .= ' To: '.$to."\n" if $tlen;
216 $to_cc .= ' Cc: '.$cc."\n" if $clen;
219 $to_cc .= ' To: '.$to;
220 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
222 $to_cc .= ' Cc: '.$cc if $clen;
226 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
229 my $mapping = $ctx->{mapping};
230 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
231 my $href = $upfx . mid_href($irt) . '/';
232 my $html = ascii_html($irt);
233 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
237 # scan through all parts, looking for displayable text
238 $ctx->{mhref} = $mhref;
240 $eml->each_part(\&add_text_body, $ctx, 1);
244 $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
245 "<a\nhref=\"$mhref\">permalink</a>" .
246 " <a\nhref=\"${mhref}raw\">raw</a>" .
247 " <a\nhref=\"${mhref}#R\">reply</a>";
250 if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
251 $rv .= "\t[relevance $pct%]";
254 my $nested = 'nested';
259 $flat = "<b>$flat</b>";
261 $nested = "<b>$nested</b>";
263 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
264 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
265 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
270 # do we have more messages? start a new <pre> if so
271 $rv .= scalar(@{$ctx->{msgs}}) ? '</pre><hr><pre>' : '</pre>' if $hr;
275 sub pad_link ($$;$) {
276 my ($mid, $level, $s) = @_;
278 my $id = id_compress($mid, 1);
279 (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
283 my ($mid_raw, $irt, $id, $ctx) = @_;
285 my $mapping = $ctx->{mapping} or return $rv;
287 my $mid_map = $mapping->{$mid_raw};
289 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
290 my ($attr, $node, $idx, $level) = @$mid_map;
291 my $children = $node->{children};
292 my $nr_c = scalar @$children;
295 # delete saves about 200KB on a 1K message thread
296 if (my $refs = delete $node->{references}) {
297 ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
299 my $irt_map = $mapping->{$$irt} if defined $$irt;
300 if (defined $irt_map) {
301 $siblings = $irt_map->[1]->{children};
302 $nr_s = scalar(@$siblings) - 1;
303 $rv .= $pad . $irt_map->[0];
305 my $prev = $siblings->[$idx - 1];
306 my $pmid = $prev->{mid};
308 my $s = ($idx - 1). ' preceding siblings ...';
309 $rv .= pad_link($pmid, $level, $s);
310 } elsif ($idx == 2) {
311 my $ppmid = $siblings->[0]->{mid};
312 $rv .= $pad . $mapping->{$ppmid}->[0];
314 $rv .= $pad . $mapping->{$pmid}->[0];
317 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
318 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
319 $attr =~ s!\n\z!</b>\n!s;
320 $attr =~ s!<a\nhref.*</a> (?:" )?!!s; # no point in dup subject
321 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
324 my $cmid = $children->[0]->{mid};
325 $rv .= $pad . $mapping->{$cmid}->[0];
327 my $s = ($nr_c - 1). ' more replies';
328 $rv .= pad_link($cmid, $level + 1, $s);
329 } elsif (my $cn = $children->[1]) {
330 $rv .= $pad . $mapping->{$cn->{mid}}->[0];
334 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
336 my $nmid = $next->{mid};
337 $rv .= $pad . $mapping->{$nmid}->[0];
338 my $nnext = $nr_s - $idx;
340 my $s = ($nnext - 1).' subsequent siblings';
341 $rv .= pad_link($nmid, $level, $s);
342 } elsif (my $nn = $siblings->[$idx + 2]) {
343 $rv .= $pad . $mapping->{$nn->{mid}}->[0];
346 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
349 # non-recursive thread walker
350 sub walk_thread ($$$) {
351 my ($rootset, $ctx, $cb) = @_;
352 my @q = map { (0, $_, -1) } @$rootset;
354 my ($level, $node, $i) = splice(@q, 0, 3);
355 defined $node or next;
356 $cb->($ctx, $level, $node, $i) or return;
359 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
363 sub pre_thread { # walk_thread callback
364 my ($ctx, $level, $node, $idx) = @_;
365 $ctx->{mapping}->{$node->{mid}} = [ '', $node, $idx, $level ];
366 skel_dump($ctx, $level, $node);
369 sub thread_eml_entry {
370 my ($ctx, $eml) = @_;
371 my ($beg, $end) = thread_adj_level($ctx, $ctx->{level});
372 $beg . '<pre>' . eml_entry($ctx, $eml) . '</pre>' . $end;
375 sub next_in_queue ($$) {
376 my ($q, $ghost_ok) = @_;
378 my ($level, $smsg) = splice(@$q, 0, 2);
380 unshift @$q, map { ($cl, $_) } @{$smsg->{children}};
381 return ($level, $smsg) if $ghost_ok || exists($smsg->{blob});
386 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
387 my ($ctx, $eml) = @_;
388 goto &thread_eml_entry if $eml; # tail recursion
389 return unless exists($ctx->{skel});
390 my $ghost_ok = $ctx->{nr}++;
392 my ($lvl, $smsg) = next_in_queue($ctx->{-queue}, $ghost_ok);
394 if (exists $smsg->{blob}) { # next message for cat-file
395 $ctx->{level} = $lvl;
396 if (!$ghost_ok) { # first non-ghost
397 $ctx->{-title_html} =
398 ascii_html($smsg->{subject});
399 $ctx->zmore($ctx->html_top);
403 # buffer the ghost entry and loop
404 $ctx->zmore(ghost_index_entry($ctx, $lvl, $smsg));
406 $ctx->zmore(join('', thread_adj_level($ctx, 0)));
407 $ctx->zmore(${delete($ctx->{skel})});
413 sub stream_thread ($$) {
414 my ($rootset, $ctx) = @_;
415 $ctx->{-queue} = [ map { (0, $_) } @$rootset ];
416 PublicInbox::WwwStream::aresponse($ctx, 200, \&stream_thread_i);
419 # /$INBOX/$MSGID/t/ and /$INBOX/$MSGID/T/
422 my $mid = $ctx->{mid};
423 my $ibx = $ctx->{-inbox};
424 my ($nr, $msgs) = $ibx->over->get_thread($mid);
425 return missing_thread($ctx) if $nr == 0;
426 my $skel = '<hr><pre>';
427 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
428 $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
429 $skel .= "<b\nid=t>Thread overview:</b> ";
430 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
431 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
432 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
433 $skel .= "-- links below jump to the message on this page --\n";
434 $ctx->{-upfx} = '../../';
435 $ctx->{cur_level} = 0;
436 $ctx->{skel} = \$skel;
437 $ctx->{prev_attr} = '';
438 $ctx->{prev_level} = 0;
439 $ctx->{root_anchor} = anchor_for($mid);
440 $ctx->{mapping} = {};
441 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
444 my $rootset = thread_results($ctx, $msgs);
446 # reduce hash lookups in pre_thread->skel_dump
447 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
448 walk_thread($rootset, $ctx, \&pre_thread);
451 return stream_thread($rootset, $ctx) unless $ctx->{flat};
453 # flat display: lazy load the full message from smsg
454 $ctx->{msgs} = $msgs;
455 $ctx->{-html_tip} = '<pre>';
456 PublicInbox::WwwStream::aresponse($ctx, 200, \&thread_html_i);
459 sub thread_html_i { # PublicInbox::WwwStream::getline callback
460 my ($ctx, $eml) = @_;
462 my $smsg = $ctx->{smsg};
463 if (exists $ctx->{-html_tip}) {
464 $ctx->{-title_html} = ascii_html($smsg->{subject});
465 $ctx->zmore($ctx->html_top);
467 return eml_entry($ctx, $eml);
469 while (my $smsg = shift @{$ctx->{msgs}}) {
470 return $smsg if exists($smsg->{blob});
472 my $skel = delete($ctx->{skel}) or return; # all done
478 sub multipart_text_as_html {
479 # ($mime, $ctx) = @_; # each_part may do "$_[0] = undef"
481 # scan through all parts, looking for displayable text
482 $_[0]->each_part(\&add_text_body, $_[1], 1);
485 sub submsg_hdr ($$) {
486 my ($ctx, $eml) = @_;
487 my $obfs_ibx = $ctx->{-obfs_ibx};
488 my $rv = $ctx->{obuf};
490 for my $h (qw(From To Cc Subject Date Message-ID X-Alt-Message-ID)) {
491 my @v = $eml->header($h);
493 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
500 sub attach_link ($$$$;$) {
501 my ($ctx, $ct, $p, $fn, $err) = @_;
502 my ($part, $depth, $idx) = @$p;
504 # Eml iteration clobbers multipart ->{bdy}, so do not offer
505 # downloads for 0-byte multipart attachments
506 return unless $part->{bdy};
508 my $nl = $idx eq '1' ? '' : "\n"; # like join("\n", ...)
509 my $size = bytes::length($part->body);
511 # hide attributes normally, unless we want to aid users in
512 # spotting MUA problems:
513 $ct =~ s/;.*// unless $err;
514 $ct = ascii_html($ct);
516 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
518 } elsif ($ct eq 'text/plain') {
523 my $rv = $ctx->{obuf};
524 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
527 [-- Warning: decoded text below may be mangled, UTF-8 assumed --]
530 $$rv .= "[-- Attachment #$idx: ";
531 my $ts = "Type: $ct, Size: $size bytes";
532 my $desc = $part->header('Content-Description') // $fn // '';
533 $desc = ascii_html($desc);
534 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
537 submsg_hdr($ctx, $part) if $part->{is_submsg};
542 sub add_text_body { # callback for each_part
544 my $upfx = $ctx->{mhref};
545 my $ibx = $ctx->{-inbox};
546 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
547 # $p - from each_part: [ Email::MIME-like, depth, $idx ]
548 my ($part, $depth, $idx) = @$p;
549 my $ct = $part->content_type || 'text/plain';
550 my $fn = $part->filename;
551 my ($s, $err) = msg_part_text($part, $ct);
552 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
554 my $rv = $ctx->{obuf};
555 if ($part->{is_submsg}) {
556 submsg_hdr($ctx, $part);
560 # makes no difference to browsers, and don't screw up filename
561 # link generation in diffs with the extra '%0D'
564 # will be escaped to `•' in HTML
565 obfuscate_addrs($ibx, $s, "\x{2022}") if $ibx->{obfuscate};
567 # always support diff-highlighting, but we can't linkify hunk
568 # headers for solver unless some coderepo are configured:
570 if ($s =~ /^--- [^\n]+\n\+{3} [^\n]+\n@@ /ms) {
571 # diffstat anchors do not link across attachments or messages,
572 # -apfx is just a stable prefix for making diffstat anchors
573 # linkable to the first diff hunk w/o crossing attachments
574 $idx =~ tr!.!/!; # compatibility with previous versions
575 $ctx->{-apfx} = $upfx . $idx;
577 # do attr => filename mappings for diffstats in git diffs:
578 $ctx->{-anchors} = {} if $s =~ /^diff --git /sm;
580 delete $ctx->{-long_path};
582 if ($ibx->{-repo_objs}) {
583 if (index($upfx, '//') >= 0) { # absolute URL (Atom feeds)
585 $spfx =~ s!/([^/]*)/\z!/!;
587 my $n_slash = $upfx =~ tr!/!/!;
590 } elsif ($n_slash == 1) {
592 } else { # nslash == 2
597 $ctx->{-spfx} = $spfx;
600 # some editors don't put trailing newlines at the end:
601 $s .= "\n" unless $s =~ /\n\z/s;
603 # split off quoted and unquoted blocks:
604 my @sections = PublicInbox::MsgIter::split_quotes($s);
605 undef $s; # free memory
606 if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
607 # badly-encoded message with $err? tell the world about it!
608 attach_link($ctx, $ct, $p, $fn, $err);
611 foreach my $cur (@sections) {
613 # we use a <span> here to allow users to specify
614 # their own color for quoted text
615 $$rv .= qq(<span\nclass="q">);
616 $$rv .= $l->to_html($cur);
619 flush_diff($ctx, \$cur);
622 $$rv .= $l->to_html($cur);
624 undef $cur; # free memory
628 sub _msg_page_prepare_obuf {
629 my ($hdr, $ctx) = @_;
630 my $over = $ctx->{-inbox}->over;
631 my $obfs_ibx = $ctx->{-obfs_ibx};
633 my $mids = mids_for_index($hdr);
634 my $nr = $ctx->{nr}++;
635 if ($nr) { # unlikely
638 $ctx->{first_hdr} = $hdr;
641 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
643 $rv .= "<pre\nid=b>"; # anchor for body start
645 $ctx->{-upfx} = '../' if $over;
646 my @title; # (Subject[0], From[0])
647 for my $v ($hdr->header('From')) {
648 my @n = PublicInbox::Address::names($v);
650 $title[1] //= ascii_html(join(', ', @n));
652 obfuscate_addrs($obfs_ibx, $v);
653 obfuscate_addrs($obfs_ibx, $title[1]);
655 $rv .= "From: $v\n" if $v ne '';
657 foreach my $h (qw(To Cc)) {
658 for my $v ($hdr->header($h)) {
661 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
662 $rv .= "$h: $v\n" if $v ne '';
665 my @subj = $hdr->header('Subject');
667 my $v = ascii_html(shift @subj);
668 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
670 $rv .= $over ? qq(<a\nhref="#r"\nid=t>$v</a>\n) : "$v\n";
672 for $v (@subj) { # multi-Subject message :<
674 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
675 $rv .= "Subject: $v\n";
677 } else { # dummy anchor for thread skeleton at bottom of page
678 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
679 $title[0] = '(no subject)';
681 for my $v ($hdr->header('Date')) {
683 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
686 if (!$nr) { # first (and only) message, common case
687 $ctx->{-title_html} = join(' - ', @title);
688 $rv = $ctx->html_top . $rv;
690 if (scalar(@$mids) == 1) { # common case
691 my $mhtml = ascii_html($mids->[0]);
692 $rv .= "Message-ID: <$mhtml> ";
693 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
695 # X-Alt-Message-ID can happen if a message is injected from
696 # public-inbox-nntpd because of multiple Message-ID headers.
697 my $lnk = PublicInbox::Linkify->new;
699 for my $h (qw(Message-ID X-Alt-Message-ID)) {
700 $s .= "$h: $_\n" for ($hdr->header_raw($h));
702 $lnk->linkify_mids('..', \$s, 1);
705 $rv .= _parent_headers($hdr, $over);
711 qq(expand[<a\nhref="T/#u">flat</a>) .
712 qq(|<a\nhref="t/#u">nested</a>] ) .
713 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
714 qq(<a\nhref="t.atom">Atom feed</a>);
717 sub thread_skel ($$$) {
718 my ($skel, $ctx, $hdr) = @_;
719 my $mid = mids($hdr)->[0];
720 my $ibx = $ctx->{-inbox};
721 my ($nr, $msgs) = $ibx->over->get_thread($mid);
722 my $parent = in_reply_to($hdr);
723 $$skel .= "\n<b>Thread overview: </b>";
725 if (defined $parent) {
726 $$skel .= SKEL_EXPAND."\n ";
727 $$skel .= ghost_parent('../', $parent) . "\n";
729 $$skel .= '[no followups] '.SKEL_EXPAND."\n";
731 $ctx->{next_msg} = undef;
732 $ctx->{parent_msg} = $parent;
737 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
739 # nb: mutt only shows the first Subject in the index pane
740 # when multiple Subject: headers are present, so we follow suit:
741 my $subj = $hdr->header('Subject') // '';
742 $subj = '(no subject)' if $subj eq '';
743 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
745 $ctx->{prev_attr} = '';
746 $ctx->{prev_level} = 0;
747 $ctx->{skel} = $skel;
749 # reduce hash lookups in skel_dump
750 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
751 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
753 $ctx->{parent_msg} = $parent;
756 sub _parent_headers {
757 my ($hdr, $over) = @_;
759 my @irt = $hdr->header_raw('In-Reply-To');
762 my $lnk = PublicInbox::Linkify->new;
763 $rv .= "In-Reply-To: $_\n" for @irt;
764 $lnk->linkify_mids('..', \$rv);
766 $refs = references($hdr);
767 my $irt = pop @$refs;
769 my $html = ascii_html($irt);
770 my $href = mid_href($irt);
771 $rv .= "In-Reply-To: <";
772 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
776 # do not display References: if search is present,
777 # we show the thread skeleton at the bottom, instead.
780 $refs //= references($hdr);
782 @$refs = map { linkify_ref_no_over($_) } @$refs;
783 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
788 # returns a string buffer via ->getline
790 my ($ctx, $hdr) = @_;
791 my $ibx = $ctx->{-inbox};
793 my $skel = " <a\nhref=\"$upfx\">index</a>";
797 thread_skel(\$skel, $ctx, $hdr);
802 if (my $n = $ctx->{next_msg}) {
804 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
807 my $par = $ctx->{parent_msg};
812 if (my $p = $ctx->{prev_msg}) {
813 $prev = mid_href($p);
814 if ($p && $par && $p eq $par) {
815 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
816 'rel=prev>prev parent</a>';
819 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
821 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
823 } elsif ($u) { # unlikely
824 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
826 $rv .= "$next $prev$parent ";
828 $rv .= qq(<a\nhref="#R">reply</a>);
831 $rv .= msg_reply($ctx, $hdr);
834 sub linkify_ref_no_over {
836 my $href = mid_href($mid);
837 my $html = ascii_html($mid);
838 "<<a\nhref=\"../$href/\">$html</a>>";
843 'm' . id_compress($msgid, 1);
847 my ($upfx, $mid) = @_;
849 my $href = mid_href($mid);
850 my $html = ascii_html($mid);
851 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
856 $level ? INDENT x ($level - 1) : '';
860 my ($ctx, $level, $node, $idx) = @_;
861 ++$ctx->{root_idx} if $level == 0;
862 if ($node->{mid} eq $ctx->{mid}) {
863 $ctx->{found_mid_at} = $ctx->{root_idx};
869 sub strict_loose_note ($) {
872 " -- strict thread matches above, loose matches on Subject: below --\n";
874 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
876 " -- use mbox.gz link to download all $nr messages --\n";
882 my ($ctx, $msgs) = @_;
883 require PublicInbox::SearchThread;
884 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
886 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
887 # and preserved in the future. This bug is hidden by `sid' matches
888 # in get_thread, so we never noticed it until now. And even when
889 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
890 # bump since reindexing is expensive and users may not do it
892 # loose threading could've returned too many results,
893 # put the root the message we care about at the top:
894 my $mid = $ctx->{mid};
895 if (defined($mid) && scalar(@$rootset) > 1) {
896 $ctx->{root_idx} = -1;
897 my $nr = scalar @$msgs;
898 walk_thread($rootset, $ctx, \&find_mid_root);
899 my $idx = $ctx->{found_mid_at};
900 if (defined($idx) && $idx != 0) {
901 my $tip = splice(@$rootset, $idx, 1);
902 @$rootset = reverse @$rootset;
903 unshift @$rootset, $tip;
904 $ctx->{sl_note} = strict_loose_note($nr);
912 require PublicInbox::ExtMsg;
913 PublicInbox::ExtMsg::ext_msg($ctx);
917 my ($prev_subj, $subj, $val) = @_;
919 my $omit; # '"' denotes identical text omitted
920 my (@prev_pop, @curr_pop);
921 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
922 push(@prev_pop, pop(@$prev_subj));
923 push(@curr_pop, pop(@$subj));
926 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
927 if (scalar(@curr_pop) == 1) {
929 push @$prev_subj, @prev_pop;
930 push @$subj, @curr_pop;
935 sub skel_dump { # walk_thread callback
936 my ($ctx, $level, $smsg) = @_;
937 $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
939 my $skel = $ctx->{skel};
940 my $cur = $ctx->{cur};
941 my $mid = $smsg->{mid};
943 if ($level == 0 && $ctx->{skel_dump_roots}++) {
944 $$skel .= delete($ctx->{sl_note}) || '';
947 my $f = ascii_html($smsg->{from_name});
948 my $obfs_ibx = $ctx->{-obfs_ibx};
949 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
951 my $d = fmt_ts($smsg->{ds});
952 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
953 if (exists $ctx->{searchview}) {
954 if (defined(my $pct = $smsg->{pct})) {
955 $d .= (sprintf(' % 2u', $pct) . '%');
961 $d .= ' ' . indent_for($level) . th_pfx($level);
963 $ctx->{first_level} ||= $level;
965 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
966 $ctx->{prev_attr} = $attr;
968 $ctx->{prev_level} = $level;
973 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
974 "$attr [this message]</a></b>\n";
977 $ctx->{prev_msg} = $mid;
980 $ctx->{next_msg} ||= $mid;
983 # Subject is never undef, this mail was loaded from
984 # our Xapian which would've resulted in '' if it were
985 # really missing (and Filter rejects empty subjects)
986 my @subj = split(/ /, subject_normalized($smsg->{subject}));
987 # remove common suffixes from the subject if it matches the previous,
988 # so we do not show redundant text at the end.
989 my $prev_subj = $ctx->{prev_subj} || [];
990 $ctx->{prev_subj} = [ @subj ];
991 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
994 my $subj = join(' ', @subj);
995 $subj = ascii_html($subj);
996 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
997 $end = "$subj</a> $omit$f\n"
1003 my $mapping = $unmatched ? undef : $ctx->{mapping};
1005 my $map = $mapping->{$mid};
1006 $id = id_compress($mid, 1);
1008 $map->[0] = "$d<a\nhref=\"$m\">$end";
1011 $m = $ctx->{-upfx}.mid_href($mid).'/';
1013 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1018 my ($ctx, $level, $node) = @_;
1020 my $mid = $node->{mid};
1021 my $d = ' [not found] ';
1022 $d .= ' ' if exists $ctx->{searchview};
1023 $d .= indent_for($level) . th_pfx($level);
1024 my $upfx = $ctx->{-upfx};
1025 my $href = $upfx . mid_href($mid) . '/';
1026 my $html = ascii_html($mid);
1028 my $mapping = $ctx->{mapping};
1029 my $map = $mapping->{$mid} if $mapping;
1031 my $id = id_compress($mid, 1);
1032 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1033 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1035 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1037 ${$ctx->{skel}} .= $d;
1043 (eval { $a->topmost->{ds} } || 0) <=>
1044 (eval { $b->topmost->{ds} } || 0)
1048 # accumulate recent topics if search is supported
1049 # returns 200 if done, 404 if not
1050 sub acc_topic { # walk_thread callback
1051 my ($ctx, $level, $smsg) = @_;
1052 my $mid = $smsg->{mid};
1053 my $has_blob = $smsg->{blob} // do {
1054 if (my $by_mid = $ctx->{-inbox}->smsg_by_mid($mid)) {
1055 %$smsg = (%$smsg, %$by_mid);
1060 my $subj = subject_normalized($smsg->{subject});
1061 $subj = '(no subject)' if $subj eq '';
1062 my $ds = $smsg->{ds};
1063 if ($level == 0) { # new, top-level topic
1064 my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1065 $ctx->{-cur_topic} = $topic;
1066 push @{$ctx->{order}}, $topic;
1070 # continue existing topic
1071 my $topic = $ctx->{-cur_topic}; # should never be undef
1072 $topic->[0] = $ds if $ds > $topic->[0];
1073 $topic->[1]++; # bump N+ message counter
1074 my $seen = $topic->[2];
1075 if (scalar(@$topic) == 3) { # parent was a ghost
1076 push @$topic, $subj;
1077 } elsif (!defined($seen->{$subj})) {
1078 push @$topic, $level, $subj; # @extra messages
1080 $seen->{$subj} = $mid; # latest for subject
1081 } else { # ghost message
1082 return 1 if $level != 0; # ignore child ghosts
1083 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1084 push @{$ctx->{order}}, $topic;
1091 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1093 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1098 my $ibx = $ctx->{-inbox};
1099 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1101 # sort by recency, this allows new posts to "bump" old topics...
1102 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1103 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1105 next unless defined $top_subj; # ghost topic
1106 my $mid = delete $seen->{$top_subj};
1107 my $href = mid_href($mid);
1108 my $prev_subj = [ split(/ /, $top_subj) ];
1109 $top_subj = ascii_html($top_subj);
1112 # $n isn't the total number of posts on the topic,
1113 # just the number of posts in the current results window
1117 $anchor = '#u'; # top of only message
1119 $n = " ($n+ messages)";
1120 $anchor = '#t'; # thread skeleton
1123 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1124 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1125 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1126 " $ds UTC $n - $mbox / $atom\n";
1127 for (my $i = 0; $i < scalar(@extra); $i += 2) {
1128 my $level = $extra[$i];
1129 my $subj = $extra[$i + 1]; # already normalized
1130 $mid = delete $seen->{$subj};
1131 my @subj = split(/ /, $subj);
1132 my @next_prev = @subj; # full copy
1133 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1134 $prev_subj = \@next_prev;
1135 $subj = join(' ', @subj);
1136 $subj = ascii_html($subj);
1137 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1138 $href = mid_href($mid);
1139 $s .= indent_for($level) . TCHILD;
1140 $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1144 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1148 # only for the t= query parameter passed to overview DB
1149 sub ts2str ($) { strftime('%Y%m%d%H%M%S', gmtime($_[0])) };
1152 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1153 timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1156 sub pagination_footer ($$) {
1157 my ($ctx, $latest) = @_;
1158 delete $ctx->{qp} or return;
1159 my $next = $ctx->{next_page} || '';
1160 my $prev = $ctx->{prev_page} || '';
1162 $next = $next ? "$next " : ' ';
1163 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1165 "<hr><pre>page: $next$prev</pre>";
1168 sub paginate_recent ($$) {
1169 my ($ctx, $lim) = @_;
1170 my $t = $ctx->{qp}->{t} || '';
1171 my $opts = { limit => $lim };
1172 my ($after, $before);
1174 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1175 # if only $after exists "YYYYMMDD.." because "." could be skipped
1176 # if interpreted as an end-of-sentence
1177 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1178 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1180 my $ibx = $ctx->{-inbox};
1181 my $msgs = $ibx->recent($opts, $after, $before);
1182 my $nr = scalar @$msgs;
1183 if ($nr < $lim && defined($after)) {
1184 $after = $before = undef;
1185 $msgs = $ibx->recent($opts);
1186 $nr = scalar @$msgs;
1188 my $more = $nr == $lim;
1189 my ($newest, $oldest);
1191 $newest = $msgs->[0]->{ts};
1192 $oldest = $msgs->[-1]->{ts};
1193 # if we only had $after, our SQL query in ->recent ordered
1194 if ($newest < $oldest) {
1195 ($oldest, $newest) = ($newest, $oldest);
1196 $more = 0 if defined($after) && $after < $oldest;
1199 if (defined($oldest) && $more) {
1200 my $s = ts2str($oldest);
1201 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1203 if (defined($newest) && (defined($before) || defined($after))) {
1204 my $s = ts2str($newest);
1205 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1212 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1214 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1216 html_oneshot($ctx, dump_topics($ctx), \pagination_footer($ctx, '.'));
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})