1 # Copyright (C) 2014, Eric Wong <normalperson@yhbt.net> and all contributors
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 package PublicInbox::View;
6 use URI::Escape qw/uri_escape_utf8/;
7 use Date::Parse qw/str2time/;
8 use Encode qw/find_encoding/;
9 use Encode::MIME::Header;
10 use Email::MIME::ContentType qw/parse_content_type/;
11 use PublicInbox::Hval;
12 use PublicInbox::MID qw/mid_clean mid_compress mid2path/;
13 use Digest::SHA qw/sha1_hex/;
17 # TODO: make these constants tunable
18 use constant MAX_INLINE_QUOTED => 12; # half an 80x24 terminal
19 use constant MAX_TRUNC_LEN => 72;
20 use constant PRE_WRAP => "<pre\nstyle=\"white-space:pre-wrap\">";
21 use constant T_ANCHOR => '#u';
23 *ascii_html = *PublicInbox::Hval::ascii_html;
25 my $enc_utf8 = find_encoding('UTF-8');
29 my ($ctx, $mime, $full_pfx, $footer) = @_;
30 if (defined $footer) {
31 $footer = "\n" . $footer;
35 headers_to_html_header($mime, $full_pfx, $ctx) .
36 multipart_text_as_html($mime, $full_pfx) .
37 '</pre><hr />' . PRE_WRAP .
38 html_footer($mime, 1, $full_pfx, $ctx) .
40 '</pre></body></html>';
44 my ($class, $mime, $full_pfx) = @_;
46 PRE_WRAP . multipart_text_as_html($mime, $full_pfx) . '</pre>';
50 my ($header_obj) = @_;
51 my $irt = $header_obj->header('In-Reply-To');
53 return mid_clean($irt) if (defined $irt);
55 my $refs = $header_obj->header('References');
56 if ($refs && $refs =~ /<([^>]+)>\s*\z/s) {
62 # this is already inside a <pre>
64 my ($fh, $mime, $level, $state) = @_;
65 my $midx = $state->{anchor_idx}++;
66 my $ctx = $state->{ctx};
67 my $srch = $ctx->{srch};
68 my ($prev, $next) = ($midx - 1, $midx + 1);
70 my $enc = enc_for($mime->header("Content-Type"));
71 my $subj = $mime->header('Subject');
72 my $header_obj = $mime->header_obj;
74 my $mid_raw = $header_obj->header('Message-ID');
75 my $id = anchor_for($mid_raw);
76 my $seen = $state->{seen};
77 $seen->{$id} = "#$id"; # save the anchor for children, later
79 my $mid = PublicInbox::Hval->new_msgid($mid_raw);
80 my $from = PublicInbox::Hval->new_oneline($mime->header('From'))->raw;
81 my @from = Email::Address->parse($from);
82 $from = $from[0]->name;
84 $from = PublicInbox::Hval->new_oneline($from)->as_html;
85 $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
86 my $more = 'permalink';
87 my $root_anchor = $state->{root_anchor};
88 my $path = $root_anchor ? '../../' : '';
89 my $href = $mid->as_href;
90 my $irt = in_reply_to($header_obj);
91 my $parent_anchor = $seen->{anchor_for($irt)} if defined $irt;
94 my $t = $ctx->{flat} ? 'T' : 't';
95 $subj = "<a\nhref=\"${path}$href/$t/#u\">$subj</a>";
97 if ($root_anchor && $root_anchor eq $id) {
98 $subj = "<u\nid=\"u\">$subj</u>";
101 my $ts = _msg_date($mime);
102 my $rv = "<table\nsummary=l$level><tr>";
104 $rv .= '<td><pre>' . (' ' x $level) . '</pre></td>';
106 $rv .= "<td\nid=s$midx>" . PRE_WRAP;
107 $rv .= "<b\nid=\"$id\">$subj</b>\n";
108 $rv .= "- by $from @ $ts UTC - ";
109 $rv .= "<a\nhref=\"#s$next\">next</a>";
111 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
113 $fh->write($rv .= "\n\n");
115 my ($fhref, $more_ref);
116 my $mhref = "${path}$href/";
118 # show full messages at level == 0 in threaded view
119 if ($level > 0 || ($ctx->{flat} && $root_anchor ne $id)) {
120 $fhref = "${path}$href/f/";
123 # scan through all parts, looking for displayable text
124 $mime->walk_parts(sub {
125 index_walk($fh, $_[0], $enc, \$part_nr, $fhref, $more_ref);
129 my $txt = "${path}$href/raw";
130 $rv = "\n<a\nhref=\"$mhref\">$more</a> <a\nhref=\"$txt\">raw</a> ";
131 $rv .= html_footer($mime, 0, undef, $ctx);
134 unless (defined $parent_anchor) {
135 my $v = PublicInbox::Hval->new_msgid($irt, 1);
137 $parent_anchor = "${path}$v/";
139 $rv .= " <a\nhref=\"$parent_anchor\">parent</a>";
143 $rv .= " [<a\nhref=\"${path}$href/t/#u\">threaded</a>" .
146 $rv .= " [<b>threaded</b>|" .
147 "<a\nhref=\"${path}$href/T/#u\">flat</a>]";
151 $fh->write($rv .= '</pre></td></tr></table>');
155 my ($ctx, $foot, $srch) = @_;
156 sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
159 # only private functions below.
161 sub emit_thread_html {
162 my ($cb, $ctx, $foot, $srch) = @_;
163 my $mid = mid_compress($ctx->{mid});
164 my $res = $srch->get_thread($mid);
165 my $msgs = load_results($res);
166 my $nr = scalar @$msgs;
167 return missing_thread($cb) if $nr == 0;
168 my $flat = $ctx->{flat};
174 root_anchor => anchor_for($mid),
178 require PublicInbox::GitCatFile;
179 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
181 pre_anchor_entry($seen, $_) for (@$msgs);
182 __thread_entry(\$cb, $git, $state, $_, 0) for (@$msgs);
184 my $th = thread_results($msgs);
185 thread_entry(\$cb, $git, $state, $_, 0) for $th->rootset;
188 Email::Address->purge_cache;
190 # there could be a race due to a message being deleted in git
191 # but still being in the Xapian index:
192 return missing_thread($cb) if ($orig_cb eq $cb);
194 my $final_anchor = $state->{anchor_idx};
195 my $next = "<a\nid=\"s$final_anchor\">";
196 $next .= $final_anchor == 1 ? 'only message in' : 'end of';
197 $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>";
199 $next .= " [<a\nhref=\"../t/#u\">threaded</a>|<b>flat</b>]";
201 $next .= " [<b>threaded</b>|<a\nhref=\"../T/#u\">flat</a>]";
203 $next .= "\ndownload thread: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
204 $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>";
205 $cb->write("<hr />" . PRE_WRAP . $next . "\n\n". $foot .
206 "</pre></body></html>");
211 my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
212 my $s = add_text_body($enc, $part, $part_nr, $fhref);
215 # drop the remainder of git patches, they're usually better
216 # to review when the full message is viewed
217 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
220 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
223 # kill any leading or trailing whitespace lines
228 # kill per-line trailing whitespace
229 $s =~ s/[ \t]+$//sgm;
230 $s .= "\n" unless $s =~ /\n\z/s;
236 my ($ct, $default) = @_;
237 $default ||= $enc_utf8;
238 defined $ct or return $default;
239 my $ct_parsed = parse_content_type($ct);
241 if (my $charset = $ct_parsed->{attributes}->{charset}) {
242 my $enc = find_encoding($charset);
249 sub multipart_text_as_html {
250 my ($mime, $full_pfx, $srch) = @_;
253 my $enc = enc_for($mime->header("Content-Type"));
255 # scan through all parts, looking for displayable text
256 $mime->walk_parts(sub {
258 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
264 sub add_filename_line {
268 $fn = $enc->decode($fn);
270 $pad x= ($len/2) if ($len > 0);
271 "$pad " . ascii_html($fn) . " $pad\n";
274 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
276 ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
279 my ($link_map, $s) = @_;
282 # salt this, as this could be exploited to show
283 # links in the HTML which don't show up in the raw mail.
284 my $key = sha1_hex($url . $SALT);
285 $link_map->{$key} = $url;
292 my ($link_map, $s) = @_;
294 # Added "PI-LINK-" prefix to avoid false-positives on git commits
295 $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
297 my $url = $link_map->{$key};
299 $url = ascii_html($url);
300 "<a\nhref=\"$url\">$url</a>";
302 # false positive or somebody tried to mess with us
310 my ($quot, $n, $part_nr, $full_pfx, $final) = @_;
313 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
316 my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
318 $rv = ascii_html($rv);
319 return linkify_2(\%l, $rv);
322 # show a short snippet of quoted text and link to full version:
323 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
324 my $cur = join(' ', @$quot);
325 @$quot = split(/\s+/, $cur);
328 my $tmp = shift(@$quot);
329 my $len = length($tmp) + length($cur);
330 if ($len > MAX_TRUNC_LEN) {
335 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
337 $cur =~ s/ \z/ .../s;
338 $cur = ascii_html($cur);
340 "> [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
342 # show everything in the full version with anchor from
343 # short version (see above)
347 $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
349 $rv = ascii_html($rv);
350 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
355 my ($enc_msg, $part, $part_nr, $full_pfx) = @_;
356 return '' if $part->subparts;
358 my $ct = $part->content_type;
359 # account for filter bugs...
360 if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) {
364 my $enc = enc_for($ct, $enc_msg);
369 $s = $enc->decode($s);
370 my @lines = split(/^/m, $s);
374 my $fn = $part->filename;
375 defined($fn) or $fn = "part #" . ($$part_nr + 1);
376 $s .= add_filename_line($enc, $fn);
380 while (defined(my $cur = shift @lines)) {
382 # show the previously buffered quote inline
384 $s .= flush_quote(\@quot, \$n, $$part_nr,
390 $cur = linkify_1(\%l, $cur);
391 $cur = ascii_html($cur);
392 $s .= linkify_2(\%l, $cur);
397 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1) if scalar @quot;
398 $s .= "\n" unless $s =~ /\n\z/s;
403 sub headers_to_html_header {
404 my ($mime, $full_pfx, $ctx) = @_;
405 my $srch = $ctx->{srch} if $ctx;
408 my $header_obj = $mime->header_obj;
409 my $mid = $header_obj->header('Message-ID');
410 $mid = PublicInbox::Hval->new_msgid($mid);
411 my $mid_href = $mid->as_href;
412 foreach my $h (qw(From To Cc Subject Date)) {
413 my $v = $mime->header($h);
414 defined($v) && ($v ne '') or next;
415 $v = PublicInbox::Hval->new_oneline($v);
418 my @from = Email::Address->parse($v->raw);
419 $title[1] = ascii_html($from[0]->name);
420 } elsif ($h eq 'Subject') {
421 $title[0] = $v->as_html;
423 my $p = $full_pfx ? '' : '../';
424 $rv .= "$h: <a\nid=\"t\"\nhref=\"${p}t/#u\">";
425 $rv .= $v->as_html . "</a>\n";
429 $rv .= "$h: " . $v->as_html . "\n";
432 $rv .= 'Message-ID: <' . $mid->as_html . '> ';
433 my $raw_ref = $full_pfx ? 'raw' : '../raw';
434 $rv .= "(<a\nhref=\"$raw_ref\">raw</a>)\n";
436 $rv .= "<a\nhref=\"#r\">References: [see below]</a>\n";
438 $rv .= _parent_headers_nosrch($header_obj);
442 ("<html><head><title>". join(' - ', @title) .
443 '</title></head><body>' . PRE_WRAP . $rv);
447 my ($dst, $ctx, $cur, $full_pfx) = @_;
448 my $srch = $ctx->{srch};
449 my $mid = mid_compress(mid_clean($cur->header('Message-ID')));
450 my $res = $srch->get_thread($mid);
451 my $nr = $res->{total};
454 $$dst .= "\n[no followups, yet]\n";
455 return (undef, in_reply_to($cur));
457 my $upfx = $full_pfx ? '' : '../';
459 $$dst .= "\n\n~$nr messages in thread: ".
460 "(<a\nhref=\"${upfx}t/#u\">expand</a>)\n";
461 my $subj = $srch->subject_path($cur->header('Subject'));
462 my $parent = in_reply_to($cur);
464 seen => { $subj => 1 },
467 parent_cmp => $parent ? mid_compress($parent) : '',
470 for (thread_results(load_results($res))->rootset) {
471 inline_dump($dst, $state, $upfx, $_, 0);
473 ($state->{next_msg}, $state->{parent});
476 sub _parent_headers_nosrch {
477 my ($header_obj) = @_;
480 my $irt = in_reply_to($header_obj);
482 my $v = PublicInbox::Hval->new_msgid($irt, 1);
483 my $html = $v->as_html;
484 my $href = $v->as_href;
485 $rv .= "In-Reply-To: <";
486 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
489 my $refs = $header_obj->header('References');
491 # avoid redundant URLs wasting bandwidth
493 $seen{$irt} = 1 if defined $irt;
495 my @raw_refs = ($refs =~ /<([^>]+)>/g);
496 foreach my $ref (@raw_refs) {
499 push @refs, linkify_ref_nosrch($ref);
503 $rv .= 'References: '. join(' ', @refs) . "\n";
510 my ($mime, $standalone, $full_pfx, $ctx) = @_;
511 my %cc; # everyone else
512 my $to; # this is the From address
514 foreach my $h (qw(From To Cc)) {
515 my $v = $mime->header($h);
516 defined($v) && ($v ne '') or next;
517 my @addrs = Email::Address->parse($v);
518 foreach my $recip (@addrs) {
519 my $address = $recip->address;
520 my $dst = lc($address);
521 $cc{$dst} ||= $address;
525 Email::Address->purge_cache if $standalone;
527 my $subj = $mime->header('Subject') || '';
528 $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
529 my $mid = $mime->header('Message-ID');
530 my $irt = uri_escape_utf8($mid);
532 $to = uri_escape_utf8($to);
533 $subj = uri_escape_utf8($subj);
535 my $cc = uri_escape_utf8(join(',', sort values %cc));
536 my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
538 my $srch = $ctx->{srch} if $ctx;
539 my $upfx = $full_pfx ? '../' : '../../';
540 my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
542 my ($next, $p) = thread_inline(\$idx, $ctx, $mime, $full_pfx);
544 $p = PublicInbox::Hval->new_oneline($p);
546 $irt = "<a\nhref=\"$upfx$p/\">parent</a> ";
548 $irt = ' ' x length('parent ');
551 $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
559 "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
562 sub linkify_ref_nosrch {
563 my $v = PublicInbox::Hval->new_msgid($_[0], 1);
564 my $html = $v->as_html;
565 my $href = $v->as_href;
566 "<<a\nhref=\"../$href/\">$html</a>>";
572 if ($id !~ /\A[a-f0-9]{40}\z/) {
573 $id = mid_compress(mid_clean($id), 1);
578 sub thread_html_head {
579 my ($cb, $mime) = @_;
580 $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
582 my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
584 $$cb->write("<html><head><title>$s</title></head><body>");
587 sub pre_anchor_entry {
588 my ($seen, $mime) = @_;
589 my $id = anchor_for($mime->header('Message-ID'));
590 $seen->{$id} = "#$id"; # save the anchor for children, later
594 my ($cb, $git, $state, $mime, $level) = @_;
596 # lazy load the full message from mini_mime:
597 my $path = mid2path(mid_clean($mime->header('Message-ID')));
598 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
600 if ($state->{anchor_idx} == 0) {
601 thread_html_head($cb, $mime);
603 index_entry($$cb, $mime, $level, $state);
608 my ($cb, $git, $state, $node, $level) = @_;
610 if (my $mime = $node->message) {
611 __thread_entry($cb, $git, $state, $mime, $level);
613 thread_entry($cb, $git, $state, $node->child, $level + 1);
614 thread_entry($cb, $git, $state, $node->next, $level);
620 [ map { $_->mini_mime } @{delete $res->{msgs}} ];
625 my $ts = eval { str2time($mime->header('Date')) };
626 defined($ts) ? $ts : 0;
631 require PublicInbox::Thread;
632 my $th = PublicInbox::Thread->new(@$msgs);
635 $th->order(*PublicInbox::Thread::sort_ts);
641 my $title = 'Thread does not exist';
642 $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
643 <html><head><title>$title</title></head><body><pre>$title
644 <a href="../../">Return to index</a></pre></body></html>
650 my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
651 POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
655 my ($dst, $state, $upfx, $mime, $level) = @_;
656 my $pfx = ' ' x $level;
658 my $cur = $state->{cur};
659 my $mid = $mime->header('Message-ID');
660 my $f = $mime->header('X-PI-From');
661 my $d = _msg_date($mime);
662 $f = PublicInbox::Hval->new($f);
663 $d = PublicInbox::Hval->new($d);
665 $d = $d->as_html . ' UTC';
666 my $midc = mid_compress(mid_clean($mid));
669 delete $state->{cur};
670 $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
671 "[this message]</a></b> by $f @ $d\n";
676 $state->{next_msg} ||= $midc;
679 # Subject is never undef, this mail was loaded from
680 # our Xapian which would've resulted in '' if it were
681 # really missing (and Filter rejects empty subjects)
682 my $s = $mime->header('Subject');
683 my $h = $state->{srch}->subject_path($s);
684 if ($state->{seen}->{$h}) {
687 $state->{seen}->{$h} = 1;
688 $s = PublicInbox::Hval->new($s);
691 my $m = PublicInbox::Hval->new_msgid($mid);
692 $m = $upfx . '../' . $m->as_href . '/';
694 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
697 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
702 my ($dst, $state, $upfx, $node, $level) = @_;
704 if (my $mime = $node->message) {
705 my $mid = mid_clean($mime->header('Message-ID'));
706 if ($mid eq $state->{parent_cmp}) {
707 $state->{parent} = $mid;
709 _inline_header($dst, $state, $upfx, $mime, $level);
711 inline_dump($dst, $state, $upfx, $node->child, $level+1);
712 inline_dump($dst, $state, $upfx, $node->next, $level);