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, $more) = @_;
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 $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
274 sub pad_link ($$;$) {
275 my ($mid, $level, $s) = @_;
277 my $id = id_compress($mid, 1);
278 (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
282 my ($mid_raw, $irt, $id, $ctx) = @_;
284 my $mapping = $ctx->{mapping} or return $rv;
286 my $mid_map = $mapping->{$mid_raw};
288 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
289 my ($attr, $node, $idx, $level) = @$mid_map;
290 my $children = $node->{children};
291 my $nr_c = scalar @$children;
294 # delete saves about 200KB on a 1K message thread
295 if (my $refs = delete $node->{references}) {
296 ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
298 my $irt_map = $mapping->{$$irt} if defined $$irt;
299 if (defined $irt_map) {
300 $siblings = $irt_map->[1]->{children};
301 $nr_s = scalar(@$siblings) - 1;
302 $rv .= $pad . $irt_map->[0];
304 my $prev = $siblings->[$idx - 1];
305 my $pmid = $prev->{mid};
307 my $s = ($idx - 1). ' preceding siblings ...';
308 $rv .= pad_link($pmid, $level, $s);
309 } elsif ($idx == 2) {
310 my $ppmid = $siblings->[0]->{mid};
311 $rv .= $pad . $mapping->{$ppmid}->[0];
313 $rv .= $pad . $mapping->{$pmid}->[0];
316 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
317 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
318 $attr =~ s!\n\z!</b>\n!s;
319 $attr =~ s!<a\nhref.*</a> (?:" )?!!s; # no point in dup subject
320 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
323 my $cmid = $children->[0]->{mid};
324 $rv .= $pad . $mapping->{$cmid}->[0];
326 my $s = ($nr_c - 1). ' more replies';
327 $rv .= pad_link($cmid, $level + 1, $s);
328 } elsif (my $cn = $children->[1]) {
329 $rv .= $pad . $mapping->{$cn->{mid}}->[0];
333 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
335 my $nmid = $next->{mid};
336 $rv .= $pad . $mapping->{$nmid}->[0];
337 my $nnext = $nr_s - $idx;
339 my $s = ($nnext - 1).' subsequent siblings';
340 $rv .= pad_link($nmid, $level, $s);
341 } elsif (my $nn = $siblings->[$idx + 2]) {
342 $rv .= $pad . $mapping->{$nn->{mid}}->[0];
345 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
348 # non-recursive thread walker
349 sub walk_thread ($$$) {
350 my ($rootset, $ctx, $cb) = @_;
351 my @q = map { (0, $_, -1) } @$rootset;
353 my ($level, $node, $i) = splice(@q, 0, 3);
354 defined $node or next;
355 $cb->($ctx, $level, $node, $i) or return;
358 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
362 sub pre_thread { # walk_thread callback
363 my ($ctx, $level, $node, $idx) = @_;
364 $ctx->{mapping}->{$node->{mid}} = [ '', $node, $idx, $level ];
365 skel_dump($ctx, $level, $node);
368 sub thread_eml_entry {
369 my ($ctx, $eml) = @_;
370 my ($beg, $end) = thread_adj_level($ctx, $ctx->{level});
371 $beg . '<pre>' . eml_entry($ctx, $eml, 0) . '</pre>' . $end;
374 sub next_in_queue ($$) {
375 my ($q, $ghost_ok) = @_;
377 my ($level, $smsg) = splice(@$q, 0, 2);
379 unshift @$q, map { ($cl, $_) } @{$smsg->{children}};
380 return ($level, $smsg) if $ghost_ok || exists($smsg->{blob});
385 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
386 my ($ctx, $eml) = @_;
387 goto &thread_eml_entry if $eml; # tail recursion
388 return unless exists($ctx->{skel});
389 my $ghost_ok = $ctx->{nr}++;
391 my ($lvl, $smsg) = next_in_queue($ctx->{-queue}, $ghost_ok);
393 if (exists $smsg->{blob}) { # next message for cat-file
394 $ctx->{level} = $lvl;
395 if (!$ghost_ok) { # first non-ghost
396 $ctx->{-title_html} =
397 ascii_html($smsg->{subject});
398 $ctx->zmore($ctx->html_top);
402 # buffer the ghost entry and loop
403 $ctx->zmore(ghost_index_entry($ctx, $lvl, $smsg));
405 $ctx->zmore(join('', thread_adj_level($ctx, 0)));
406 $ctx->zmore(${delete($ctx->{skel})});
412 sub stream_thread ($$) {
413 my ($rootset, $ctx) = @_;
414 $ctx->{-queue} = [ map { (0, $_) } @$rootset ];
415 PublicInbox::WwwStream::aresponse($ctx, 200, \&stream_thread_i);
418 # /$INBOX/$MSGID/t/ and /$INBOX/$MSGID/T/
421 my $mid = $ctx->{mid};
422 my $ibx = $ctx->{-inbox};
423 my ($nr, $msgs) = $ibx->over->get_thread($mid);
424 return missing_thread($ctx) if $nr == 0;
425 my $skel = '<hr><pre>';
426 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
427 $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
428 $skel .= "<b\nid=t>Thread overview:</b> ";
429 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
430 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
431 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
432 $skel .= "-- links below jump to the message on this page --\n";
433 $ctx->{-upfx} = '../../';
434 $ctx->{cur_level} = 0;
435 $ctx->{skel} = \$skel;
436 $ctx->{prev_attr} = '';
437 $ctx->{prev_level} = 0;
438 $ctx->{root_anchor} = anchor_for($mid);
439 $ctx->{mapping} = {};
440 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
443 my $rootset = thread_results($ctx, $msgs);
445 # reduce hash lookups in pre_thread->skel_dump
446 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
447 walk_thread($rootset, $ctx, \&pre_thread);
450 return stream_thread($rootset, $ctx) unless $ctx->{flat};
452 # flat display: lazy load the full message from smsg
453 $ctx->{msgs} = $msgs;
454 $ctx->{-html_tip} = '<pre>';
455 PublicInbox::WwwStream::aresponse($ctx, 200, \&thread_html_i);
458 sub thread_html_i { # PublicInbox::WwwStream::getline callback
459 my ($ctx, $eml) = @_;
461 my $smsg = $ctx->{smsg};
462 if (exists $ctx->{-html_tip}) {
463 $ctx->{-title_html} = ascii_html($smsg->{subject});
464 $ctx->zmore($ctx->html_top);
466 return eml_entry($ctx, $eml, scalar @{$ctx->{msgs}});
468 while (my $smsg = shift @{$ctx->{msgs}}) {
469 return $smsg if exists($smsg->{blob});
471 my $skel = delete($ctx->{skel}) or return; # all done
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) = @_;
629 my $over = $ctx->{-inbox}->over;
630 my $obfs_ibx = $ctx->{-obfs_ibx};
632 my $mids = mids_for_index($hdr);
633 my $nr = $ctx->{nr}++;
634 if ($nr) { # unlikely
637 $ctx->{first_hdr} = $hdr;
640 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
642 $rv .= "<pre\nid=b>"; # anchor for body start
644 $ctx->{-upfx} = '../' if $over;
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 if (!$nr) { # first (and only) message, common case
686 $ctx->{-title_html} = join(' - ', @title);
687 $rv = $ctx->html_top . $rv;
689 if (scalar(@$mids) == 1) { # common case
690 my $mhtml = ascii_html($mids->[0]);
691 $rv .= "Message-ID: <$mhtml> ";
692 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
694 # X-Alt-Message-ID can happen if a message is injected from
695 # public-inbox-nntpd because of multiple Message-ID headers.
696 my $lnk = PublicInbox::Linkify->new;
698 for my $h (qw(Message-ID X-Alt-Message-ID)) {
699 $s .= "$h: $_\n" for ($hdr->header_raw($h));
701 $lnk->linkify_mids('..', \$s, 1);
704 $rv .= _parent_headers($hdr, $over);
710 qq(expand[<a\nhref="T/#u">flat</a>) .
711 qq(|<a\nhref="t/#u">nested</a>] ) .
712 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
713 qq(<a\nhref="t.atom">Atom feed</a>);
716 sub thread_skel ($$$) {
717 my ($skel, $ctx, $hdr) = @_;
718 my $mid = mids($hdr)->[0];
719 my $ibx = $ctx->{-inbox};
720 my ($nr, $msgs) = $ibx->over->get_thread($mid);
721 my $parent = in_reply_to($hdr);
722 $$skel .= "\n<b>Thread overview: </b>";
724 if (defined $parent) {
725 $$skel .= SKEL_EXPAND."\n ";
726 $$skel .= ghost_parent('../', $parent) . "\n";
728 $$skel .= '[no followups] '.SKEL_EXPAND."\n";
730 $ctx->{next_msg} = undef;
731 $ctx->{parent_msg} = $parent;
736 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
738 # nb: mutt only shows the first Subject in the index pane
739 # when multiple Subject: headers are present, so we follow suit:
740 my $subj = $hdr->header('Subject') // '';
741 $subj = '(no subject)' if $subj eq '';
742 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
744 $ctx->{prev_attr} = '';
745 $ctx->{prev_level} = 0;
746 $ctx->{skel} = $skel;
748 # reduce hash lookups in skel_dump
749 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
750 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
752 $ctx->{parent_msg} = $parent;
755 sub _parent_headers {
756 my ($hdr, $over) = @_;
758 my @irt = $hdr->header_raw('In-Reply-To');
761 my $lnk = PublicInbox::Linkify->new;
762 $rv .= "In-Reply-To: $_\n" for @irt;
763 $lnk->linkify_mids('..', \$rv);
765 $refs = references($hdr);
766 my $irt = pop @$refs;
768 my $html = ascii_html($irt);
769 my $href = mid_href($irt);
770 $rv .= "In-Reply-To: <";
771 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
775 # do not display References: if search is present,
776 # we show the thread skeleton at the bottom, instead.
779 $refs //= references($hdr);
781 @$refs = map { linkify_ref_no_over($_) } @$refs;
782 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
787 # returns a string buffer via ->getline
789 my ($ctx, $hdr) = @_;
790 my $ibx = $ctx->{-inbox};
792 my $skel = " <a\nhref=\"$upfx\">index</a>";
796 thread_skel(\$skel, $ctx, $hdr);
801 if (my $n = $ctx->{next_msg}) {
803 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
806 my $par = $ctx->{parent_msg};
811 if (my $p = $ctx->{prev_msg}) {
812 $prev = mid_href($p);
813 if ($p && $par && $p eq $par) {
814 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
815 'rel=prev>prev parent</a>';
818 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
820 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
822 } elsif ($u) { # unlikely
823 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
825 $rv .= "$next $prev$parent ";
827 $rv .= qq(<a\nhref="#R">reply</a>);
830 $rv .= msg_reply($ctx, $hdr);
833 sub linkify_ref_no_over {
835 my $href = mid_href($mid);
836 my $html = ascii_html($mid);
837 "<<a\nhref=\"../$href/\">$html</a>>";
842 'm' . id_compress($msgid, 1);
846 my ($upfx, $mid) = @_;
848 my $href = mid_href($mid);
849 my $html = ascii_html($mid);
850 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
855 $level ? INDENT x ($level - 1) : '';
859 my ($ctx, $level, $node, $idx) = @_;
860 ++$ctx->{root_idx} if $level == 0;
861 if ($node->{mid} eq $ctx->{mid}) {
862 $ctx->{found_mid_at} = $ctx->{root_idx};
868 sub strict_loose_note ($) {
871 " -- strict thread matches above, loose matches on Subject: below --\n";
873 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
875 " -- use mbox.gz link to download all $nr messages --\n";
881 my ($ctx, $msgs) = @_;
882 require PublicInbox::SearchThread;
883 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
885 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
886 # and preserved in the future. This bug is hidden by `sid' matches
887 # in get_thread, so we never noticed it until now. And even when
888 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
889 # bump since reindexing is expensive and users may not do it
891 # loose threading could've returned too many results,
892 # put the root the message we care about at the top:
893 my $mid = $ctx->{mid};
894 if (defined($mid) && scalar(@$rootset) > 1) {
895 $ctx->{root_idx} = -1;
896 my $nr = scalar @$msgs;
897 walk_thread($rootset, $ctx, \&find_mid_root);
898 my $idx = $ctx->{found_mid_at};
899 if (defined($idx) && $idx != 0) {
900 my $tip = splice(@$rootset, $idx, 1);
901 @$rootset = reverse @$rootset;
902 unshift @$rootset, $tip;
903 $ctx->{sl_note} = strict_loose_note($nr);
911 require PublicInbox::ExtMsg;
912 PublicInbox::ExtMsg::ext_msg($ctx);
916 my ($prev_subj, $subj, $val) = @_;
918 my $omit; # '"' denotes identical text omitted
919 my (@prev_pop, @curr_pop);
920 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
921 push(@prev_pop, pop(@$prev_subj));
922 push(@curr_pop, pop(@$subj));
925 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
926 if (scalar(@curr_pop) == 1) {
928 push @$prev_subj, @prev_pop;
929 push @$subj, @curr_pop;
934 sub skel_dump { # walk_thread callback
935 my ($ctx, $level, $smsg) = @_;
936 $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
938 my $skel = $ctx->{skel};
939 my $cur = $ctx->{cur};
940 my $mid = $smsg->{mid};
942 if ($level == 0 && $ctx->{skel_dump_roots}++) {
943 $$skel .= delete($ctx->{sl_note}) || '';
946 my $f = ascii_html($smsg->{from_name});
947 my $obfs_ibx = $ctx->{-obfs_ibx};
948 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
950 my $d = fmt_ts($smsg->{ds});
951 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
952 if (exists $ctx->{searchview}) {
953 if (defined(my $pct = $smsg->{pct})) {
954 $d .= (sprintf(' % 2u', $pct) . '%');
960 $d .= ' ' . indent_for($level) . th_pfx($level);
962 $ctx->{first_level} ||= $level;
964 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
965 $ctx->{prev_attr} = $attr;
967 $ctx->{prev_level} = $level;
972 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
973 "$attr [this message]</a></b>\n";
976 $ctx->{prev_msg} = $mid;
979 $ctx->{next_msg} ||= $mid;
982 # Subject is never undef, this mail was loaded from
983 # our Xapian which would've resulted in '' if it were
984 # really missing (and Filter rejects empty subjects)
985 my @subj = split(/ /, subject_normalized($smsg->{subject}));
986 # remove common suffixes from the subject if it matches the previous,
987 # so we do not show redundant text at the end.
988 my $prev_subj = $ctx->{prev_subj} || [];
989 $ctx->{prev_subj} = [ @subj ];
990 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
993 my $subj = join(' ', @subj);
994 $subj = ascii_html($subj);
995 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
996 $end = "$subj</a> $omit$f\n"
1002 my $mapping = $unmatched ? undef : $ctx->{mapping};
1004 my $map = $mapping->{$mid};
1005 $id = id_compress($mid, 1);
1007 $map->[0] = "$d<a\nhref=\"$m\">$end";
1010 $m = $ctx->{-upfx}.mid_href($mid).'/';
1012 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1017 my ($ctx, $level, $node) = @_;
1019 my $mid = $node->{mid};
1020 my $d = ' [not found] ';
1021 $d .= ' ' if exists $ctx->{searchview};
1022 $d .= indent_for($level) . th_pfx($level);
1023 my $upfx = $ctx->{-upfx};
1024 my $href = $upfx . mid_href($mid) . '/';
1025 my $html = ascii_html($mid);
1027 my $mapping = $ctx->{mapping};
1028 my $map = $mapping->{$mid} if $mapping;
1030 my $id = id_compress($mid, 1);
1031 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1032 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1034 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1036 ${$ctx->{skel}} .= $d;
1042 (eval { $a->topmost->{ds} } || 0) <=>
1043 (eval { $b->topmost->{ds} } || 0)
1047 # accumulate recent topics if search is supported
1048 # returns 200 if done, 404 if not
1049 sub acc_topic { # walk_thread callback
1050 my ($ctx, $level, $smsg) = @_;
1051 my $mid = $smsg->{mid};
1052 my $has_blob = $smsg->{blob} // do {
1053 if (my $by_mid = $ctx->{-inbox}->smsg_by_mid($mid)) {
1054 %$smsg = (%$smsg, %$by_mid);
1059 my $subj = subject_normalized($smsg->{subject});
1060 $subj = '(no subject)' if $subj eq '';
1061 my $ds = $smsg->{ds};
1062 if ($level == 0) { # new, top-level topic
1063 my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1064 $ctx->{-cur_topic} = $topic;
1065 push @{$ctx->{order}}, $topic;
1069 # continue existing topic
1070 my $topic = $ctx->{-cur_topic}; # should never be undef
1071 $topic->[0] = $ds if $ds > $topic->[0];
1072 $topic->[1]++; # bump N+ message counter
1073 my $seen = $topic->[2];
1074 if (scalar(@$topic) == 3) { # parent was a ghost
1075 push @$topic, $subj;
1076 } elsif (!defined($seen->{$subj})) {
1077 push @$topic, $level, $subj; # @extra messages
1079 $seen->{$subj} = $mid; # latest for subject
1080 } else { # ghost message
1081 return 1 if $level != 0; # ignore child ghosts
1082 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1083 push @{$ctx->{order}}, $topic;
1090 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1092 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1097 my $ibx = $ctx->{-inbox};
1098 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1100 # sort by recency, this allows new posts to "bump" old topics...
1101 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1102 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1104 next unless defined $top_subj; # ghost topic
1105 my $mid = delete $seen->{$top_subj};
1106 my $href = mid_href($mid);
1107 my $prev_subj = [ split(/ /, $top_subj) ];
1108 $top_subj = ascii_html($top_subj);
1111 # $n isn't the total number of posts on the topic,
1112 # just the number of posts in the current results window
1116 $anchor = '#u'; # top of only message
1118 $n = " ($n+ messages)";
1119 $anchor = '#t'; # thread skeleton
1122 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1123 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1124 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1125 " $ds UTC $n - $mbox / $atom\n";
1126 for (my $i = 0; $i < scalar(@extra); $i += 2) {
1127 my $level = $extra[$i];
1128 my $subj = $extra[$i + 1]; # already normalized
1129 $mid = delete $seen->{$subj};
1130 my @subj = split(/ /, $subj);
1131 my @next_prev = @subj; # full copy
1132 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1133 $prev_subj = \@next_prev;
1134 $subj = join(' ', @subj);
1135 $subj = ascii_html($subj);
1136 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1137 $href = mid_href($mid);
1138 $s .= indent_for($level) . TCHILD;
1139 $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1143 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1147 # only for the t= query parameter passed to overview DB
1148 sub ts2str ($) { strftime('%Y%m%d%H%M%S', gmtime($_[0])) };
1151 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1152 timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1155 sub pagination_footer ($$) {
1156 my ($ctx, $latest) = @_;
1157 delete $ctx->{qp} or return;
1158 my $next = $ctx->{next_page} || '';
1159 my $prev = $ctx->{prev_page} || '';
1161 $next = $next ? "$next " : ' ';
1162 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1164 "<hr><pre>page: $next$prev</pre>";
1167 sub paginate_recent ($$) {
1168 my ($ctx, $lim) = @_;
1169 my $t = $ctx->{qp}->{t} || '';
1170 my $opts = { limit => $lim };
1171 my ($after, $before);
1173 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1174 # if only $after exists "YYYYMMDD.." because "." could be skipped
1175 # if interpreted as an end-of-sentence
1176 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1177 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1179 my $ibx = $ctx->{-inbox};
1180 my $msgs = $ibx->recent($opts, $after, $before);
1181 my $nr = scalar @$msgs;
1182 if ($nr < $lim && defined($after)) {
1183 $after = $before = undef;
1184 $msgs = $ibx->recent($opts);
1185 $nr = scalar @$msgs;
1187 my $more = $nr == $lim;
1188 my ($newest, $oldest);
1190 $newest = $msgs->[0]->{ts};
1191 $oldest = $msgs->[-1]->{ts};
1192 # if we only had $after, our SQL query in ->recent ordered
1193 if ($newest < $oldest) {
1194 ($oldest, $newest) = ($newest, $oldest);
1195 $more = 0 if defined($after) && $after < $oldest;
1198 if (defined($oldest) && $more) {
1199 my $s = ts2str($oldest);
1200 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1202 if (defined($newest) && (defined($before) || defined($after))) {
1203 my $s = ts2str($newest);
1204 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1211 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1213 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1215 html_oneshot($ctx, dump_topics($ctx), \pagination_footer($ctx, '.'));
1219 sub thread_adj_level {
1220 my ($ctx, $level) = @_;
1222 my $max = $ctx->{cur_level};
1224 return ('', '') if $max == 0; # flat output
1226 # reset existing lists
1227 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1228 $ctx->{cur_level} = 0;
1230 } elsif ($level == $max) { # continue existing list
1232 } elsif ($level < $max) {
1233 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1234 $ctx->{cur_level} = $level;
1235 ("$beg<li>", '</li>');
1236 } else { # ($level > $max) # start a new level
1237 $ctx->{cur_level} = $level;
1238 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1243 sub ghost_index_entry {
1244 my ($ctx, $level, $node) = @_;
1245 my ($beg, $end) = thread_adj_level($ctx, $level);
1246 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{mid})