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 ($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/$MESSAGE_ID/ for unindexed v1 inboxes
51 my $eml = delete $ctx->{eml} or return;
52 my $hdr = $eml->header_obj;
54 my $obuf = $ctx->{obuf} = _msg_page_prepare_obuf($hdr, $ctx);
55 multipart_text_as_html($eml, $ctx);
57 $$obuf .= '</pre><hr>';
58 eval { $$obuf .= html_footer($ctx, $hdr) };
62 sub no_over_html ($) {
64 my $bref = $ctx->{-inbox}->msg_by_mid($ctx->{mid}) or return; # 404
65 $ctx->{eml} = PublicInbox::Eml->new($bref);
66 PublicInbox::WwwStream::response($ctx, 200, \&no_over_i);
69 # public functions: (unstable)
73 my $ibx = $ctx->{-inbox};
74 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
75 my $over = $ctx->{over} = $ibx->over or return no_over_html($ctx);
77 my $next_arg = $ctx->{next_arg} = [ $ctx->{mid}, \$id, \$prev ];
78 $ctx->{smsg} = $over->next_by_mid(@$next_arg) or return; # undef == 404
79 PublicInbox::WwwStream::aresponse($ctx, 200, \&msg_page_i);
82 # /$INBOX/$MESSAGE_ID/#R
86 'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
88 'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
91 my $ibx = $ctx->{-inbox};
92 if (my $url = $ibx->{infourl}) {
93 $url = prurl($ctx->{env}, $url);
94 $info = qq(\n List information: <a\nhref="$url">$url</a>\n);
97 my ($arg, $link, $reply_to_all) =
98 PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
99 if (ref($arg) eq 'SCALAR') {
100 return '<pre id=R>'.ascii_html($$arg).'</pre>';
103 # mailto: link only works if address obfuscation is disabled
107 * If your mail client supports setting the <b>In-Reply-To</b> header
108 via mailto: links, try the <a
109 href="$link">mailto: link</a>
113 push @$arg, '/path/to/YOUR_REPLY';
114 $arg = ascii_html(join(" \\\n ", '', @$arg));
117 id=R><b>Reply instructions:</b>
119 You may reply publicly to <a
120 href=#t>this message</a> via plain-text email
121 using any one of the following methods:
123 * Save the following mbox file, import it into your mail client,
124 and $reply_to_all from there: <a
127 Avoid top-posting and favor interleaved quoting:
129 href="$p_url">$p_url</a>
131 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
132 switches of git-send-email(1):
137 href="$se_url">$se_url</a>
144 my $refs = references($hdr);
148 sub fold_addresses ($) {
149 return $_[0] if length($_[0]) <= COLS;
150 # try to fold on commas after non-word chars before $lim chars,
151 # Try to get the "," preceded by ">" or ")", but avoid folding
152 # on the comma where somebody uses "Lastname, Firstname".
153 # We also try to keep the last and penultimate addresses in
154 # the list on the same line if possible, hence the extra \z
155 # Fall back to folding on spaces at $lim + 1 chars
156 my $lim = COLS - 8; # 8 = "\t" display width
157 my $too_long = $lim + 1;
158 $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
160 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
163 .{$too_long,}?)(?:\s|\z)/xgo));
166 sub _hdr_names_html ($$) {
167 my ($hdr, $field) = @_;
168 my @vals = $hdr->header($field) or return '';
169 ascii_html(join(', ', PublicInbox::Address::names(join(',', @vals))));
173 my ($nr, $singular, $plural) = @_;
174 return "0 $plural" if $nr == 0;
175 $nr == 1 ? "$nr $singular" : "$nr $plural";
178 # human-friendly format
179 sub fmt_ts ($) { strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
181 # Displays the text of of the message for /$INBOX/$MSGID/[Tt]/ endpoint
182 # this is already inside a <pre>
184 my ($ctx, $eml, $more) = @_;
185 my $smsg = delete $ctx->{smsg};
186 my $subj = delete $smsg->{subject};
187 my $mid_raw = $smsg->{mid};
188 my $id = id_compress($mid_raw, 1);
190 my $root_anchor = $ctx->{root_anchor} || '';
192 my $obfs_ibx = $ctx->{-obfs_ibx};
194 $subj = '(no subject)' if $subj eq '';
195 my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
196 $subj = '<b>'.ascii_html($subj).'</b>';
197 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
198 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
200 $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
202 my $ds = delete $smsg->{ds}; # for v1 non-Xapian/SQLite users
204 # Deleting these fields saves about 400K as we iterate across 1K msgs
205 delete @$smsg{qw(ts blob)};
207 my $hdr = $eml->header_obj;
208 my $from = _hdr_names_html($hdr, 'From');
209 obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
210 $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
211 my $upfx = $ctx->{-upfx};
212 my $mhref = $upfx . mid_href($mid_raw) . '/';
213 $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
214 $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
215 my $to = fold_addresses(_hdr_names_html($hdr, 'To'));
216 my $cc = fold_addresses(_hdr_names_html($hdr, 'Cc'));
217 my ($tlen, $clen) = (length($to), length($cc));
219 if (($tlen + $clen) > COLS) {
220 $to_cc .= ' To: '.$to."\n" if $tlen;
221 $to_cc .= ' Cc: '.$cc."\n" if $clen;
224 $to_cc .= ' To: '.$to;
225 $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
227 $to_cc .= ' Cc: '.$cc if $clen;
231 obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
234 my $mapping = $ctx->{mapping};
235 if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
236 my $href = $upfx . mid_href($irt) . '/';
237 my $html = ascii_html($irt);
238 $rv .= qq(In-Reply-To: <<a\nhref="$href">$html</a>>\n)
242 # scan through all parts, looking for displayable text
243 $ctx->{mhref} = $mhref;
245 $eml->each_part(\&add_text_body, $ctx, 1);
249 $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
250 "<a\nhref=\"$mhref\">permalink</a>" .
251 " <a\nhref=\"${mhref}raw\">raw</a>" .
252 " <a\nhref=\"${mhref}#R\">reply</a>";
255 if (defined(my $pct = $smsg->{pct})) { # used by SearchView.pm
256 $rv .= "\t[relevance $pct%]";
259 my $nested = 'nested';
264 $flat = "<b>$flat</b>";
266 $nested = "<b>$nested</b>";
268 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
269 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
270 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
275 $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
279 sub pad_link ($$;$) {
280 my ($mid, $level, $s) = @_;
282 my $id = id_compress($mid, 1);
283 (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
287 my ($mid_raw, $irt, $id, $ctx) = @_;
289 my $mapping = $ctx->{mapping} or return $rv;
291 my $mid_map = $mapping->{$mid_raw};
293 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
294 my ($attr, $node, $idx, $level) = @$mid_map;
295 my $children = $node->{children};
296 my $nr_c = scalar @$children;
299 # delete saves about 200KB on a 1K message thread
300 if (my $refs = delete $node->{references}) {
301 ($$irt) = ($refs =~ m/$MID_EXTRACT\z/o);
303 my $irt_map = $mapping->{$$irt} if defined $$irt;
304 if (defined $irt_map) {
305 $siblings = $irt_map->[1]->{children};
306 $nr_s = scalar(@$siblings) - 1;
307 $rv .= $pad . $irt_map->[0];
309 my $prev = $siblings->[$idx - 1];
310 my $pmid = $prev->{mid};
312 my $s = ($idx - 1). ' preceding siblings ...';
313 $rv .= pad_link($pmid, $level, $s);
314 } elsif ($idx == 2) {
315 my $ppmid = $siblings->[0]->{mid};
316 $rv .= $pad . $mapping->{$ppmid}->[0];
318 $rv .= $pad . $mapping->{$pmid}->[0];
321 my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
322 my $s_c = nr_to_s($nr_c, 'reply', 'replies');
323 $attr =~ s!\n\z!</b>\n!s;
324 $attr =~ s!<a\nhref.*</a> (?:" )?!!s; # no point in dup subject
325 $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
328 my $cmid = $children->[0]->{mid};
329 $rv .= $pad . $mapping->{$cmid}->[0];
331 my $s = ($nr_c - 1). ' more replies';
332 $rv .= pad_link($cmid, $level + 1, $s);
333 } elsif (my $cn = $children->[1]) {
334 $rv .= $pad . $mapping->{$cn->{mid}}->[0];
338 my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
340 my $nmid = $next->{mid};
341 $rv .= $pad . $mapping->{$nmid}->[0];
342 my $nnext = $nr_s - $idx;
344 my $s = ($nnext - 1).' subsequent siblings';
345 $rv .= pad_link($nmid, $level, $s);
346 } elsif (my $nn = $siblings->[$idx + 2]) {
347 $rv .= $pad . $mapping->{$nn->{mid}}->[0];
350 $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
353 # non-recursive thread walker
354 sub walk_thread ($$$) {
355 my ($rootset, $ctx, $cb) = @_;
356 my @q = map { (0, $_, -1) } @$rootset;
358 my ($level, $node, $i) = splice(@q, 0, 3);
359 defined $node or next;
360 $cb->($ctx, $level, $node, $i) or return;
363 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
367 sub pre_thread { # walk_thread callback
368 my ($ctx, $level, $node, $idx) = @_;
369 $ctx->{mapping}->{$node->{mid}} = [ '', $node, $idx, $level ];
370 skel_dump($ctx, $level, $node);
373 sub thread_eml_entry {
374 my ($ctx, $eml) = @_;
375 my ($beg, $end) = thread_adj_level($ctx, $ctx->{level});
376 $beg . '<pre>' . eml_entry($ctx, $eml, 0) . '</pre>' . $end;
379 sub next_in_queue ($$) {
380 my ($q, $ghost_ok) = @_;
382 my ($level, $smsg) = splice(@$q, 0, 2);
384 unshift @$q, map { ($cl, $_) } @{$smsg->{children}};
385 return ($level, $smsg) if $ghost_ok || exists($smsg->{blob});
390 sub stream_thread_i { # PublicInbox::WwwStream::getline callback
391 my ($ctx, $eml) = @_;
394 if ($ctx->{nr} == 1) {
395 $ctx->{-title_html} =
396 ascii_html($ctx->{smsg}->{subject});
397 $ctx->zmore($ctx->html_top);
399 goto &thread_eml_entry; # tail recursion
401 return unless exists($ctx->{skel});
402 my $ghost_ok = $ctx->{nr}++;
404 my ($lvl, $smsg) = next_in_queue($ctx->{-queue}, $ghost_ok);
406 if (exists $smsg->{blob}) { # next message for cat-file
407 $ctx->{level} = $lvl;
410 # buffer the ghost entry and loop
411 $ctx->zmore(ghost_index_entry($ctx, $lvl, $smsg));
413 $ctx->zmore(join('', thread_adj_level($ctx, 0)));
414 $ctx->zmore(${delete($ctx->{skel})});
420 sub stream_thread ($$) {
421 my ($rootset, $ctx) = @_;
422 $ctx->{-queue} = [ map { (0, $_) } @$rootset ];
423 PublicInbox::WwwStream::aresponse($ctx, 200, \&stream_thread_i);
426 # /$INBOX/$MESSAGE_ID/t/
429 my $mid = $ctx->{mid};
430 my $ibx = $ctx->{-inbox};
431 my ($nr, $msgs) = $ibx->over->get_thread($mid);
432 return missing_thread($ctx) if $nr == 0;
433 my $skel = '<hr><pre>';
434 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
435 $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
436 $skel .= "<b\nid=t>Thread overview:</b> ";
437 $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
438 $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
439 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
440 $skel .= "-- links below jump to the message on this page --\n";
441 $ctx->{-upfx} = '../../';
442 $ctx->{cur_level} = 0;
443 $ctx->{skel} = \$skel;
444 $ctx->{prev_attr} = '';
445 $ctx->{prev_level} = 0;
446 $ctx->{root_anchor} = anchor_for($mid);
447 $ctx->{mapping} = {};
448 $ctx->{s_nr} = ($nr > 1 ? "$nr+ messages" : 'only message')
451 my $rootset = thread_results($ctx, $msgs);
453 # reduce hash lookups in pre_thread->skel_dump
454 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
455 walk_thread($rootset, $ctx, \&pre_thread);
458 return stream_thread($rootset, $ctx) unless $ctx->{flat};
460 # flat display: lazy load the full message from smsg
461 $ctx->{msgs} = $msgs;
462 $ctx->{-html_tip} = '<pre>';
463 PublicInbox::WwwStream::aresponse($ctx, 200, \&thread_html_i);
466 sub thread_html_i { # PublicInbox::WwwStream::getline callback
467 my ($ctx, $eml) = @_;
469 my $smsg = $ctx->{smsg};
470 if (exists $ctx->{-html_tip}) {
471 $ctx->{-title_html} = ascii_html($smsg->{subject});
472 $ctx->zmore($ctx->html_top);
474 return eml_entry($ctx, $eml, scalar @{$ctx->{msgs}});
476 while (my $smsg = shift @{$ctx->{msgs}}) {
477 return $smsg if exists($smsg->{blob});
479 my $skel = delete($ctx->{skel}) or return; # all done
485 sub multipart_text_as_html {
486 # ($mime, $ctx) = @_; # each_part may do "$_[0] = undef"
488 # scan through all parts, looking for displayable text
489 $_[0]->each_part(\&add_text_body, $_[1], 1);
492 sub submsg_hdr ($$) {
493 my ($ctx, $eml) = @_;
494 my $obfs_ibx = $ctx->{-obfs_ibx};
495 my $rv = $ctx->{obuf};
497 for my $h (qw(From To Cc Subject Date Message-ID X-Alt-Message-ID)) {
498 my @v = $eml->header($h);
500 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
507 sub attach_link ($$$$;$) {
508 my ($ctx, $ct, $p, $fn, $err) = @_;
509 my ($part, $depth, $idx) = @$p;
511 # Eml iteration clobbers multipart ->{bdy}, so do not offer
512 # downloads for 0-byte multipart attachments
513 return unless $part->{bdy};
515 my $nl = $idx eq '1' ? '' : "\n"; # like join("\n", ...)
516 my $size = bytes::length($part->body);
518 # hide attributes normally, unless we want to aid users in
519 # spotting MUA problems:
520 $ct =~ s/;.*// unless $err;
521 $ct = ascii_html($ct);
523 if (defined $fn && $fn =~ /\A$PublicInbox::Hval::FN\z/o) {
525 } elsif ($ct eq 'text/plain') {
530 my $rv = $ctx->{obuf};
531 $$rv .= qq($nl<a\nhref="$ctx->{mhref}$idx-$sfn">);
534 [-- Warning: decoded text below may be mangled, UTF-8 assumed --]
537 $$rv .= "[-- Attachment #$idx: ";
538 my $ts = "Type: $ct, Size: $size bytes";
539 my $desc = $part->header('Content-Description') // $fn // '';
540 $desc = ascii_html($desc);
541 $$rv .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
544 submsg_hdr($ctx, $part) if $part->{is_submsg};
549 sub add_text_body { # callback for each_part
551 my $upfx = $ctx->{mhref};
552 my $ibx = $ctx->{-inbox};
553 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
554 # $p - from each_part: [ Email::MIME-like, depth, $idx ]
555 my ($part, $depth, $idx) = @$p;
556 my $ct = $part->content_type || 'text/plain';
557 my $fn = $part->filename;
558 my ($s, $err) = msg_part_text($part, $ct);
559 return attach_link($ctx, $ct, $p, $fn) unless defined $s;
561 my $rv = $ctx->{obuf};
562 if ($part->{is_submsg}) {
563 submsg_hdr($ctx, $part);
567 # makes no difference to browsers, and don't screw up filename
568 # link generation in diffs with the extra '%0D'
571 # will be escaped to `•' in HTML
572 obfuscate_addrs($ibx, $s, "\x{2022}") if $ibx->{obfuscate};
574 # always support diff-highlighting, but we can't linkify hunk
575 # headers for solver unless some coderepo are configured:
577 if ($s =~ /^--- [^\n]+\n\+{3} [^\n]+\n@@ /ms) {
578 # diffstat anchors do not link across attachments or messages,
579 # -apfx is just a stable prefix for making diffstat anchors
580 # linkable to the first diff hunk w/o crossing attachments
581 $idx =~ tr!.!/!; # compatibility with previous versions
582 $ctx->{-apfx} = $upfx . $idx;
584 # do attr => filename mappings for diffstats in git diffs:
585 $ctx->{-anchors} = {} if $s =~ /^diff --git /sm;
587 delete $ctx->{-long_path};
589 if ($ibx->{-repo_objs}) {
590 if (index($upfx, '//') >= 0) { # absolute URL (Atom feeds)
592 $spfx =~ s!/([^/]*)/\z!/!;
594 my $n_slash = $upfx =~ tr!/!/!;
597 } elsif ($n_slash == 1) {
599 } else { # nslash == 2
604 $ctx->{-spfx} = $spfx;
607 # some editors don't put trailing newlines at the end:
608 $s .= "\n" unless $s =~ /\n\z/s;
610 # split off quoted and unquoted blocks:
611 my @sections = PublicInbox::MsgIter::split_quotes($s);
612 undef $s; # free memory
613 if (defined($fn) || ($depth > 0 && !$part->{is_submsg}) || $err) {
614 # badly-encoded message with $err? tell the world about it!
615 attach_link($ctx, $ct, $p, $fn, $err);
618 foreach my $cur (@sections) {
620 # we use a <span> here to allow users to specify
621 # their own color for quoted text
622 $$rv .= qq(<span\nclass="q">);
623 $$rv .= $l->to_html($cur);
626 flush_diff($ctx, \$cur);
629 $$rv .= $l->to_html($cur);
631 undef $cur; # free memory
635 sub _msg_page_prepare_obuf {
636 my ($hdr, $ctx) = @_;
637 my $over = $ctx->{-inbox}->over;
638 my $obfs_ibx = $ctx->{-obfs_ibx};
640 my $mids = mids_for_index($hdr);
641 my $nr = $ctx->{nr}++;
642 if ($nr) { # unlikely
645 $ctx->{first_hdr} = $hdr;
648 "<pre>WARNING: multiple messages have this Message-ID\n</pre>";
650 $rv .= "<pre\nid=b>"; # anchor for body start
652 $ctx->{-upfx} = '../' if $over;
653 my @title; # (Subject[0], From[0])
654 for my $v ($hdr->header('From')) {
655 my @n = PublicInbox::Address::names($v);
657 $title[1] //= ascii_html(join(', ', @n));
659 obfuscate_addrs($obfs_ibx, $v);
660 obfuscate_addrs($obfs_ibx, $title[1]);
662 $rv .= "From: $v\n" if $v ne '';
664 foreach my $h (qw(To Cc)) {
665 for my $v ($hdr->header($h)) {
668 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
669 $rv .= "$h: $v\n" if $v ne '';
672 my @subj = $hdr->header('Subject');
674 my $v = ascii_html(shift @subj);
675 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
677 $rv .= $over ? qq(<a\nhref="#r"\nid=t>$v</a>\n) : "$v\n";
679 for $v (@subj) { # multi-Subject message :<
681 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
682 $rv .= "Subject: $v\n";
684 } else { # dummy anchor for thread skeleton at bottom of page
685 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $over;
686 $title[0] = '(no subject)';
688 for my $v ($hdr->header('Date')) {
690 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
693 if (!$nr) { # first (and only) message, common case
694 $ctx->{-title_html} = join(' - ', @title);
695 $rv = $ctx->html_top . $rv;
697 if (scalar(@$mids) == 1) { # common case
698 my $mhtml = ascii_html($mids->[0]);
699 $rv .= "Message-ID: <$mhtml> ";
700 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
702 # X-Alt-Message-ID can happen if a message is injected from
703 # public-inbox-nntpd because of multiple Message-ID headers.
704 my $lnk = PublicInbox::Linkify->new;
706 for my $h (qw(Message-ID X-Alt-Message-ID)) {
707 $s .= "$h: $_\n" for ($hdr->header_raw($h));
709 $lnk->linkify_mids('..', \$s, 1);
712 $rv .= _parent_headers($hdr, $over);
718 qq(expand[<a\nhref="T/#u">flat</a>) .
719 qq(|<a\nhref="t/#u">nested</a>] ) .
720 qq(<a\nhref="t.mbox.gz">mbox.gz</a> ) .
721 qq(<a\nhref="t.atom">Atom feed</a>);
724 sub thread_skel ($$$) {
725 my ($skel, $ctx, $hdr) = @_;
726 my $mid = mids($hdr)->[0];
727 my $ibx = $ctx->{-inbox};
728 my ($nr, $msgs) = $ibx->over->get_thread($mid);
729 my $parent = in_reply_to($hdr);
730 $$skel .= "\n<b>Thread overview: </b>";
732 if (defined $parent) {
733 $$skel .= SKEL_EXPAND."\n ";
734 $$skel .= ghost_parent('../', $parent) . "\n";
736 $$skel .= '[no followups] '.SKEL_EXPAND."\n";
738 $ctx->{next_msg} = undef;
739 $ctx->{parent_msg} = $parent;
744 $$skel .= '+ messages / '.SKEL_EXPAND.qq! <a\nhref="#b">top</a>\n!;
746 # nb: mutt only shows the first Subject in the index pane
747 # when multiple Subject: headers are present, so we follow suit:
748 my $subj = $hdr->header('Subject') // '';
749 $subj = '(no subject)' if $subj eq '';
750 $ctx->{prev_subj} = [ split(/ /, subject_normalized($subj)) ];
752 $ctx->{prev_attr} = '';
753 $ctx->{prev_level} = 0;
754 $ctx->{skel} = $skel;
756 # reduce hash lookups in skel_dump
757 $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
758 walk_thread(thread_results($ctx, $msgs), $ctx, \&skel_dump);
760 $ctx->{parent_msg} = $parent;
763 sub _parent_headers {
764 my ($hdr, $over) = @_;
766 my @irt = $hdr->header_raw('In-Reply-To');
769 my $lnk = PublicInbox::Linkify->new;
770 $rv .= "In-Reply-To: $_\n" for @irt;
771 $lnk->linkify_mids('..', \$rv);
773 $refs = references($hdr);
774 my $irt = pop @$refs;
776 my $html = ascii_html($irt);
777 my $href = mid_href($irt);
778 $rv .= "In-Reply-To: <";
779 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
783 # do not display References: if search is present,
784 # we show the thread skeleton at the bottom, instead.
787 $refs //= references($hdr);
789 @$refs = map { linkify_ref_no_over($_) } @$refs;
790 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
795 # returns a string buffer via ->getline
797 my ($ctx, $hdr) = @_;
798 my $ibx = $ctx->{-inbox};
800 my $skel = " <a\nhref=\"$upfx\">index</a>";
804 thread_skel(\$skel, $ctx, $hdr);
809 if (my $n = $ctx->{next_msg}) {
811 $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
814 my $par = $ctx->{parent_msg};
819 if (my $p = $ctx->{prev_msg}) {
820 $prev = mid_href($p);
821 if ($p && $par && $p eq $par) {
822 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
823 'rel=prev>prev parent</a>';
826 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
828 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
830 } elsif ($u) { # unlikely
831 $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
833 $rv .= "$next $prev$parent ";
835 $rv .= qq(<a\nhref="#R">reply</a>);
838 $rv .= msg_reply($ctx, $hdr);
841 sub linkify_ref_no_over {
843 my $href = mid_href($mid);
844 my $html = ascii_html($mid);
845 "<<a\nhref=\"../$href/\">$html</a>>";
850 'm' . id_compress($msgid, 1);
854 my ($upfx, $mid) = @_;
856 my $href = mid_href($mid);
857 my $html = ascii_html($mid);
858 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
863 $level ? INDENT x ($level - 1) : '';
867 my ($ctx, $level, $node, $idx) = @_;
868 ++$ctx->{root_idx} if $level == 0;
869 if ($node->{mid} eq $ctx->{mid}) {
870 $ctx->{found_mid_at} = $ctx->{root_idx};
876 sub strict_loose_note ($) {
879 " -- strict thread matches above, loose matches on Subject: below --\n";
881 if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
883 " -- use mbox.gz link to download all $nr messages --\n";
889 my ($ctx, $msgs) = @_;
890 require PublicInbox::SearchThread;
891 my $rootset = PublicInbox::SearchThread::thread($msgs, \&sort_ds, $ctx);
893 # FIXME: `tid' is broken on --reindex, so that needs to be fixed
894 # and preserved in the future. This bug is hidden by `sid' matches
895 # in get_thread, so we never noticed it until now. And even when
896 # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
897 # bump since reindexing is expensive and users may not do it
899 # loose threading could've returned too many results,
900 # put the root the message we care about at the top:
901 my $mid = $ctx->{mid};
902 if (defined($mid) && scalar(@$rootset) > 1) {
903 $ctx->{root_idx} = -1;
904 my $nr = scalar @$msgs;
905 walk_thread($rootset, $ctx, \&find_mid_root);
906 my $idx = $ctx->{found_mid_at};
907 if (defined($idx) && $idx != 0) {
908 my $tip = splice(@$rootset, $idx, 1);
909 @$rootset = reverse @$rootset;
910 unshift @$rootset, $tip;
911 $ctx->{sl_note} = strict_loose_note($nr);
919 require PublicInbox::ExtMsg;
920 PublicInbox::ExtMsg::ext_msg($ctx);
924 my ($prev_subj, $subj, $val) = @_;
926 my $omit; # '"' denotes identical text omitted
927 my (@prev_pop, @curr_pop);
928 while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
929 push(@prev_pop, pop(@$prev_subj));
930 push(@curr_pop, pop(@$subj));
933 pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
934 if (scalar(@curr_pop) == 1) {
936 push @$prev_subj, @prev_pop;
937 push @$subj, @curr_pop;
942 sub skel_dump { # walk_thread callback
943 my ($ctx, $level, $smsg) = @_;
944 $smsg->{blob} or return _skel_ghost($ctx, $level, $smsg);
946 my $skel = $ctx->{skel};
947 my $cur = $ctx->{cur};
948 my $mid = $smsg->{mid};
950 if ($level == 0 && $ctx->{skel_dump_roots}++) {
951 $$skel .= delete($ctx->{sl_note}) || '';
954 my $f = ascii_html($smsg->{from_name});
955 my $obfs_ibx = $ctx->{-obfs_ibx};
956 obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
958 my $d = fmt_ts($smsg->{ds});
959 my $unmatched; # if lazy-loaded by SearchThread::Msg::visible()
960 if (exists $ctx->{searchview}) {
961 if (defined(my $pct = $smsg->{pct})) {
962 $d .= (sprintf(' % 2u', $pct) . '%');
968 $d .= ' ' . indent_for($level) . th_pfx($level);
970 $ctx->{first_level} ||= $level;
972 if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
973 $ctx->{prev_attr} = $attr;
975 $ctx->{prev_level} = $level;
980 $$skel .= "<b>$d<a\nid=r\nhref=\"#t\">".
981 "$attr [this message]</a></b>\n";
984 $ctx->{prev_msg} = $mid;
987 $ctx->{next_msg} ||= $mid;
990 # Subject is never undef, this mail was loaded from
991 # our Xapian which would've resulted in '' if it were
992 # really missing (and Filter rejects empty subjects)
993 my @subj = split(/ /, subject_normalized($smsg->{subject}));
994 # remove common suffixes from the subject if it matches the previous,
995 # so we do not show redundant text at the end.
996 my $prev_subj = $ctx->{prev_subj} || [];
997 $ctx->{prev_subj} = [ @subj ];
998 my $omit = dedupe_subject($prev_subj, \@subj, '" ');
1001 my $subj = join(' ', @subj);
1002 $subj = ascii_html($subj);
1003 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1004 $end = "$subj</a> $omit$f\n"
1010 my $mapping = $unmatched ? undef : $ctx->{mapping};
1012 my $map = $mapping->{$mid};
1013 $id = id_compress($mid, 1);
1015 $map->[0] = "$d<a\nhref=\"$m\">$end";
1018 $m = $ctx->{-upfx}.mid_href($mid).'/';
1020 $$skel .= $d . "<a\nhref=\"$m\"$id>" . $end;
1025 my ($ctx, $level, $node) = @_;
1027 my $mid = $node->{mid};
1028 my $d = ' [not found] ';
1029 $d .= ' ' if exists $ctx->{searchview};
1030 $d .= indent_for($level) . th_pfx($level);
1031 my $upfx = $ctx->{-upfx};
1032 my $href = $upfx . mid_href($mid) . '/';
1033 my $html = ascii_html($mid);
1035 my $mapping = $ctx->{mapping};
1036 my $map = $mapping->{$mid} if $mapping;
1038 my $id = id_compress($mid, 1);
1039 $map->[0] = $d . qq{<<a\nhref=#r$id>$html</a>>\n};
1040 $d .= qq{<<a\nhref="$href"\nid=r$id>$html</a>>\n};
1042 $d .= qq{<<a\nhref="$href">$html</a>>\n};
1044 ${$ctx->{skel}} .= $d;
1050 (eval { $a->topmost->{ds} } || 0) <=>
1051 (eval { $b->topmost->{ds} } || 0)
1055 # accumulate recent topics if search is supported
1056 # returns 200 if done, 404 if not
1057 sub acc_topic { # walk_thread callback
1058 my ($ctx, $level, $smsg) = @_;
1059 my $mid = $smsg->{mid};
1060 my $has_blob = $smsg->{blob} // do {
1061 if (my $by_mid = $ctx->{-inbox}->smsg_by_mid($mid)) {
1062 %$smsg = (%$smsg, %$by_mid);
1067 my $subj = subject_normalized($smsg->{subject});
1068 $subj = '(no subject)' if $subj eq '';
1069 my $ds = $smsg->{ds};
1070 if ($level == 0) { # new, top-level topic
1071 my $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1072 $ctx->{-cur_topic} = $topic;
1073 push @{$ctx->{order}}, $topic;
1077 # continue existing topic
1078 my $topic = $ctx->{-cur_topic}; # should never be undef
1079 $topic->[0] = $ds if $ds > $topic->[0];
1080 $topic->[1]++; # bump N+ message counter
1081 my $seen = $topic->[2];
1082 if (scalar(@$topic) == 3) { # parent was a ghost
1083 push @$topic, $subj;
1084 } elsif (!defined($seen->{$subj})) {
1085 push @$topic, $level, $subj; # @extra messages
1087 $seen->{$subj} = $mid; # latest for subject
1088 } else { # ghost message
1089 return 1 if $level != 0; # ignore child ghosts
1090 my $topic = $ctx->{-cur_topic} = [ -666, 0, {} ];
1091 push @{$ctx->{order}}, $topic;
1098 my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1100 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1105 my $ibx = $ctx->{-inbox};
1106 my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1108 # sort by recency, this allows new posts to "bump" old topics...
1109 foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1110 my ($ds, $n, $seen, $top_subj, @extra) = @$topic;
1112 next unless defined $top_subj; # ghost topic
1113 my $mid = delete $seen->{$top_subj};
1114 my $href = mid_href($mid);
1115 my $prev_subj = [ split(/ /, $top_subj) ];
1116 $top_subj = ascii_html($top_subj);
1119 # $n isn't the total number of posts on the topic,
1120 # just the number of posts in the current results window
1124 $anchor = '#u'; # top of only message
1126 $n = " ($n+ messages)";
1127 $anchor = '#t'; # thread skeleton
1130 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1131 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1132 my $s = "<a\nhref=\"$href/T/$anchor\">$top_subj</a>\n" .
1133 " $ds UTC $n - $mbox / $atom\n";
1134 for (my $i = 0; $i < scalar(@extra); $i += 2) {
1135 my $level = $extra[$i];
1136 my $subj = $extra[$i + 1]; # already normalized
1137 $mid = delete $seen->{$subj};
1138 my @subj = split(/ /, $subj);
1139 my @next_prev = @subj; # full copy
1140 my $omit = dedupe_subject($prev_subj, \@subj, ' "');
1141 $prev_subj = \@next_prev;
1142 $subj = join(' ', @subj);
1143 $subj = ascii_html($subj);
1144 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1145 $href = mid_href($mid);
1146 $s .= indent_for($level) . TCHILD;
1147 $s .= qq(<a\nhref="$href/T/#u">$subj</a>$omit\n);
1151 $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1155 # only for the t= query parameter passed to overview DB
1156 sub ts2str ($) { strftime('%Y%m%d%H%M%S', gmtime($_[0])) };
1159 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1160 timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1163 sub pagination_footer ($$) {
1164 my ($ctx, $latest) = @_;
1165 delete $ctx->{qp} or return;
1166 my $next = $ctx->{next_page} || '';
1167 my $prev = $ctx->{prev_page} || '';
1169 $next = $next ? "$next " : ' ';
1170 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1172 "<hr><pre>page: $next$prev</pre>";
1175 sub index_nav { # callback for WwwStream::getline
1177 return $ctx->html_top if exists $ctx->{-html_tip};
1178 pagination_footer($ctx, '.')
1181 sub paginate_recent ($$) {
1182 my ($ctx, $lim) = @_;
1183 my $t = $ctx->{qp}->{t} || '';
1184 my $opts = { limit => $lim };
1185 my ($after, $before);
1187 # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1188 # if only $after exists "YYYYMMDD.." because "." could be skipped
1189 # if interpreted as an end-of-sentence
1190 $t =~ s/\A([0-9]{8,14})-// and $after = str2ts($1);
1191 $t =~ /\A([0-9]{8,14})\z/ and $before = str2ts($1);
1193 my $ibx = $ctx->{-inbox};
1194 my $msgs = $ibx->recent($opts, $after, $before);
1195 my $nr = scalar @$msgs;
1196 if ($nr < $lim && defined($after)) {
1197 $after = $before = undef;
1198 $msgs = $ibx->recent($opts);
1199 $nr = scalar @$msgs;
1201 my $more = $nr == $lim;
1202 my ($newest, $oldest);
1204 $newest = $msgs->[0]->{ts};
1205 $oldest = $msgs->[-1]->{ts};
1206 # if we only had $after, our SQL query in ->recent ordered
1207 if ($newest < $oldest) {
1208 ($oldest, $newest) = ($newest, $oldest);
1209 $more = 0 if defined($after) && $after < $oldest;
1212 if (defined($oldest) && $more) {
1213 my $s = ts2str($oldest);
1214 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1216 if (defined($newest) && (defined($before) || defined($after))) {
1217 my $s = ts2str($newest);
1218 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1225 my $msgs = paginate_recent($ctx, 200); # 200 is our window
1227 walk_thread(thread_results($ctx, $msgs), $ctx, \&acc_topic);
1229 PublicInbox::WwwStream::response($ctx, dump_topics($ctx), \&index_nav);
1232 sub thread_adj_level {
1233 my ($ctx, $level) = @_;
1235 my $max = $ctx->{cur_level};
1237 return ('', '') if $max == 0; # flat output
1239 # reset existing lists
1240 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1241 $ctx->{cur_level} = 0;
1243 } elsif ($level == $max) { # continue existing list
1245 } elsif ($level < $max) {
1246 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1247 $ctx->{cur_level} = $level;
1248 ("$beg<li>", '</li>');
1249 } else { # ($level > $max) # start a new level
1250 $ctx->{cur_level} = $level;
1251 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1256 sub ghost_index_entry {
1257 my ($ctx, $level, $node) = @_;
1258 my ($beg, $end) = thread_adj_level($ctx, $level);
1259 $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{mid})