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>';
49 # this is already inside a <pre>
51 my ($fh, $mime, $level, $state) = @_;
52 my $midx = $state->{anchor_idx}++;
53 my $ctx = $state->{ctx};
54 my $srch = $ctx->{srch};
55 my ($prev, $next) = ($midx - 1, $midx + 1);
57 my $enc = enc_for($mime->header("Content-Type"));
58 my $subj = $mime->header('Subject');
59 my $header_obj = $mime->header_obj;
61 my $mid_raw = $header_obj->header('Message-ID');
62 my $id = anchor_for($mid_raw);
63 my $seen = $state->{seen};
64 $seen->{$id} = "#$id"; # save the anchor for later
66 my $mid = PublicInbox::Hval->new_msgid($mid_raw);
67 my $from = PublicInbox::Hval->new_oneline($mime->header('From'))->raw;
68 my @from = Email::Address->parse($from);
69 $from = $from[0]->name;
71 $from = PublicInbox::Hval->new_oneline($from)->as_html;
72 $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
73 my $more = 'permalink';
74 my $root_anchor = $state->{root_anchor};
75 my $path = $root_anchor ? '../../' : '';
76 my $href = $mid->as_href;
77 my $irt = $header_obj->header('In-Reply-To');
78 my ($anchor_idx, $anchor);
80 $anchor_idx = anchor_for($irt);
81 $anchor = $seen->{$anchor_idx};
84 my $t = $ctx->{flat} ? 'T' : 't';
85 $subj = "<a\nhref=\"${path}$href/$t/#u\">$subj</a>";
87 if ($root_anchor && $root_anchor eq $id) {
88 $subj = "<u\nid=\"u\">$subj</u>";
91 my $ts = _msg_date($mime);
92 my $rv = "<table\nsummary=l$level><tr>";
94 $rv .= '<td><pre>' . (' ' x $level) . '</pre></td>';
96 $rv .= "<td\nid=s$midx>" . PRE_WRAP;
97 $rv .= "<b\nid=\"$id\">$subj</b>\n";
98 $rv .= "- by $from @ $ts UTC - ";
99 $rv .= "<a\nhref=\"#s$next\">next</a>";
101 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
103 $fh->write($rv .= "\n\n");
105 my ($fhref, $more_ref);
106 my $mhref = "${path}$href/";
108 # show full messages at level == 0 in threaded view
109 if ($level > 0 || ($ctx->{flat} && $root_anchor ne $id)) {
110 $fhref = "${path}$href/f/";
113 # scan through all parts, looking for displayable text
114 $mime->walk_parts(sub {
115 index_walk($fh, $_[0], $enc, \$part_nr, $fhref, $more_ref);
119 my $txt = "${path}$href/raw";
120 $rv = "\n<a\nhref=\"$mhref\">$more</a> <a\nhref=\"$txt\">raw</a> ";
121 $rv .= html_footer($mime, 0, undef, $ctx);
124 unless (defined $anchor) {
125 my $v = PublicInbox::Hval->new_msgid($irt);
127 $anchor = "${path}$v/";
128 $seen->{$anchor_idx} = $anchor;
130 $rv .= " <a\nhref=\"$anchor\">parent</a>";
134 $rv .= " [<a\nhref=\"${path}$href/t/#u\">threaded</a>" .
137 $rv .= " [<b>threaded</b>|" .
138 "<a\nhref=\"${path}$href/T/#u\">flat</a>]";
142 $fh->write($rv .= '</pre></td></tr></table>');
146 my ($ctx, $foot, $srch) = @_;
147 sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
150 # only private functions below.
152 sub emit_thread_html {
153 my ($cb, $ctx, $foot, $srch) = @_;
154 my $mid = mid_compress($ctx->{mid});
155 my $res = $srch->get_thread($mid);
156 my $msgs = load_results($res);
157 my $nr = scalar @$msgs;
158 return missing_thread($cb) if $nr == 0;
159 my $flat = $ctx->{flat};
164 root_anchor => anchor_for($mid),
168 require PublicInbox::GitCatFile;
169 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
171 __thread_entry(\$cb, $git, $state, $_, 0) for (@$msgs);
173 my $th = thread_results($msgs);
174 thread_entry(\$cb, $git, $state, $_, 0) for $th->rootset;
177 Email::Address->purge_cache;
179 # there could be a race due to a message being deleted in git
180 # but still being in the Xapian index:
181 return missing_thread($cb) if ($orig_cb eq $cb);
183 my $final_anchor = $state->{anchor_idx};
184 my $next = "<a\nid=\"s$final_anchor\">";
185 $next .= $final_anchor == 1 ? 'only message in' : 'end of';
186 $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>";
188 $next .= " [<a\nhref=\"../t/#u\">threaded</a>|<b>flat</b>]";
190 $next .= " [<b>threaded</b>|<a\nhref=\"../T/#u\">flat</a>]";
192 $next .= "\ndownload thread: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
193 $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>";
194 $cb->write("<hr />" . PRE_WRAP . $next . "\n\n". $foot .
195 "</pre></body></html>");
200 my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
201 my $s = add_text_body($enc, $part, $part_nr, $fhref);
204 # drop the remainder of git patches, they're usually better
205 # to review when the full message is viewed
206 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
209 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
212 # kill any leading or trailing whitespace lines
217 # kill per-line trailing whitespace
218 $s =~ s/[ \t]+$//sgm;
219 $s .= "\n" unless $s =~ /\n\z/s;
225 my ($ct, $default) = @_;
226 $default ||= $enc_utf8;
227 defined $ct or return $default;
228 my $ct_parsed = parse_content_type($ct);
230 if (my $charset = $ct_parsed->{attributes}->{charset}) {
231 my $enc = find_encoding($charset);
238 sub multipart_text_as_html {
239 my ($mime, $full_pfx, $srch) = @_;
242 my $enc = enc_for($mime->header("Content-Type"));
244 # scan through all parts, looking for displayable text
245 $mime->walk_parts(sub {
247 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
253 sub add_filename_line {
257 $fn = $enc->decode($fn);
259 $pad x= ($len/2) if ($len > 0);
260 "$pad " . ascii_html($fn) . " $pad\n";
263 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
265 ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
268 my ($link_map, $s) = @_;
271 # salt this, as this could be exploited to show
272 # links in the HTML which don't show up in the raw mail.
273 my $key = sha1_hex($url . $SALT);
274 $link_map->{$key} = $url;
281 my ($link_map, $s) = @_;
283 # Added "PI-LINK-" prefix to avoid false-positives on git commits
284 $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
286 my $url = $link_map->{$key};
288 $url = ascii_html($url);
289 "<a\nhref=\"$url\">$url</a>";
291 # false positive or somebody tried to mess with us
299 my ($quot, $n, $part_nr, $full_pfx, $final) = @_;
302 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
305 my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
307 $rv = ascii_html($rv);
308 return linkify_2(\%l, $rv);
311 # show a short snippet of quoted text and link to full version:
312 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
313 my $cur = join(' ', @$quot);
314 @$quot = split(/\s+/, $cur);
317 my $tmp = shift(@$quot);
318 my $len = length($tmp) + length($cur);
319 if ($len > MAX_TRUNC_LEN) {
324 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
326 $cur =~ s/ \z/ .../s;
327 $cur = ascii_html($cur);
329 "> [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
331 # show everything in the full version with anchor from
332 # short version (see above)
336 $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
338 $rv = ascii_html($rv);
339 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
344 my ($enc_msg, $part, $part_nr, $full_pfx) = @_;
345 return '' if $part->subparts;
347 my $ct = $part->content_type;
348 # account for filter bugs...
349 if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) {
353 my $enc = enc_for($ct, $enc_msg);
358 $s = $enc->decode($s);
359 my @lines = split(/^/m, $s);
363 my $fn = $part->filename;
364 defined($fn) or $fn = "part #" . ($$part_nr + 1);
365 $s .= add_filename_line($enc, $fn);
369 while (defined(my $cur = shift @lines)) {
371 # show the previously buffered quote inline
373 $s .= flush_quote(\@quot, \$n, $$part_nr,
379 $cur = linkify_1(\%l, $cur);
380 $cur = ascii_html($cur);
381 $s .= linkify_2(\%l, $cur);
386 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1) if scalar @quot;
387 $s .= "\n" unless $s =~ /\n\z/s;
392 sub headers_to_html_header {
393 my ($mime, $full_pfx, $ctx) = @_;
394 my $srch = $ctx->{srch} if $ctx;
397 my $header_obj = $mime->header_obj;
398 my $mid = $header_obj->header('Message-ID');
399 $mid = PublicInbox::Hval->new_msgid($mid);
400 my $mid_href = $mid->as_href;
401 foreach my $h (qw(From To Cc Subject Date)) {
402 my $v = $mime->header($h);
403 defined($v) && ($v ne '') or next;
404 $v = PublicInbox::Hval->new_oneline($v);
407 my @from = Email::Address->parse($v->raw);
408 $title[1] = ascii_html($from[0]->name);
409 } elsif ($h eq 'Subject') {
410 $title[0] = $v->as_html;
412 my $p = $full_pfx ? '' : '../';
413 $rv .= "$h: <a\nid=\"t\"\nhref=\"${p}t/#u\">";
414 $rv .= $v->as_html . "</a>\n";
418 $rv .= "$h: " . $v->as_html . "\n";
421 $rv .= 'Message-ID: <' . $mid->as_html . '> ';
422 my $raw_ref = $full_pfx ? 'raw' : '../raw';
423 $rv .= "(<a\nhref=\"$raw_ref\">raw</a>)\n";
425 $rv .= "<a\nhref=\"#r\">References: [see below]</a>\n";
427 $rv .= _parent_headers_nosrch($header_obj);
431 ("<html><head><title>". join(' - ', @title) .
432 '</title></head><body>' . PRE_WRAP . $rv);
436 my ($dst, $ctx, $cur, $full_pfx) = @_;
437 my $srch = $ctx->{srch};
438 my $mid = mid_compress(mid_clean($cur->header('Message-ID')));
439 my $res = $srch->get_thread($mid);
440 my $nr = $res->{total};
443 $$dst .= "\n[no followups, yet]\n";
446 my $upfx = $full_pfx ? '' : '../';
448 $$dst .= "\n\n~$nr messages in thread: ".
449 "(<a\nhref=\"${upfx}t/#u\">expand</a>)\n";
450 my $subj = $srch->subject_path($cur->header('Subject'));
452 seen => { $subj => 1 },
456 for (thread_results(load_results($res))->rootset) {
457 inline_dump($dst, $state, $upfx, $_, 0);
462 sub _parent_headers_nosrch {
463 my ($header_obj) = @_;
466 my $irt = $header_obj->header('In-Reply-To');
468 my $v = PublicInbox::Hval->new_msgid($irt);
469 my $html = $v->as_html;
470 my $href = $v->as_href;
471 $rv .= "In-Reply-To: <";
472 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
475 my $refs = $header_obj->header('References');
477 # avoid redundant URLs wasting bandwidth
479 $seen{mid_clean($irt)} = 1 if defined $irt;
481 my @raw_refs = ($refs =~ /<([^>]+)>/g);
482 foreach my $ref (@raw_refs) {
485 push @refs, linkify_ref($ref);
489 $rv .= 'References: '. join(' ', @refs) . "\n";
496 my ($mime, $standalone, $full_pfx, $ctx) = @_;
497 my %cc; # everyone else
498 my $to; # this is the From address
500 foreach my $h (qw(From To Cc)) {
501 my $v = $mime->header($h);
502 defined($v) && ($v ne '') or next;
503 my @addrs = Email::Address->parse($v);
504 foreach my $recip (@addrs) {
505 my $address = $recip->address;
506 my $dst = lc($address);
507 $cc{$dst} ||= $address;
511 Email::Address->purge_cache if $standalone;
513 my $subj = $mime->header('Subject') || '';
514 $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
515 my $mid = $mime->header('Message-ID');
516 my $irt = uri_escape_utf8($mid);
518 $to = uri_escape_utf8($to);
519 $subj = uri_escape_utf8($subj);
521 my $cc = uri_escape_utf8(join(',', sort values %cc));
522 my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
524 my $srch = $ctx->{srch} if $ctx;
525 my $upfx = $full_pfx ? '../' : '../../';
526 my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
528 my $next = thread_inline(\$idx, $ctx, $mime, $full_pfx);
529 $irt = $mime->header('In-Reply-To');
531 $irt = PublicInbox::Hval->new_msgid($irt);
532 $irt = $irt->as_href;
533 $irt = "<a\nhref=\"$upfx$irt/\">parent</a> ";
535 $irt = ' ' x length('parent ');
538 $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
546 "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
550 my $v = PublicInbox::Hval->new_msgid($_[0]);
551 my $html = $v->as_html;
552 my $href = $v->as_href;
553 "<<a\nhref=\"../$href/\">$html</a>>";
559 if ($id !~ /\A[a-f0-9]{40}\z/) {
560 $id = mid_compress(mid_clean($id), 1);
565 sub thread_html_head {
566 my ($cb, $mime) = @_;
567 $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
569 my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
571 $$cb->write("<html><head><title>$s</title></head><body>");
575 my ($cb, $git, $state, $mime, $level) = @_;
577 # lazy load the full message from mini_mime:
578 my $path = mid2path(mid_clean($mime->header('Message-ID')));
579 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
581 if ($state->{anchor_idx} == 0) {
582 thread_html_head($cb, $mime);
584 index_entry($$cb, $mime, $level, $state);
589 my ($cb, $git, $state, $node, $level) = @_;
591 if (my $mime = $node->message) {
592 __thread_entry($cb, $git, $state, $mime, $level);
594 thread_entry($cb, $git, $state, $node->child, $level + 1);
595 thread_entry($cb, $git, $state, $node->next, $level);
601 [ map { $_->mini_mime } @{delete $res->{msgs}} ];
606 my $ts = eval { str2time($mime->header('Date')) };
607 defined($ts) ? $ts : 0;
612 require PublicInbox::Thread;
613 my $th = PublicInbox::Thread->new(@$msgs);
616 $th->order(*PublicInbox::Thread::sort_ts);
622 my $title = 'Thread does not exist';
623 $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
624 <html><head><title>$title</title></head><body><pre>$title
625 <a href="../../">Return to index</a></pre></body></html>
631 my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
632 POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
636 my ($dst, $state, $upfx, $mime, $level) = @_;
637 my $pfx = ' ' x $level;
639 my $cur = $state->{cur};
640 my $mid = $mime->header('Message-ID');
641 my $f = $mime->header('X-PI-From');
642 my $d = _msg_date($mime);
643 $f = PublicInbox::Hval->new($f);
644 $d = PublicInbox::Hval->new($d);
646 $d = $d->as_html . ' UTC';
647 my $midc = mid_compress(mid_clean($mid));
650 delete $state->{cur};
651 $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
652 "[this message]</a></b> by $f @ $d\n";
657 $state->{next_msg} ||= $midc;
660 # Subject is never undef, this mail was loaded from
661 # our Xapian which would've resulted in '' if it were
662 # really missing (and Filter rejects empty subjects)
663 my $s = $mime->header('Subject');
664 my $h = $state->{srch}->subject_path($s);
665 if ($state->{seen}->{$h}) {
668 $state->{seen}->{$h} = 1;
669 $s = PublicInbox::Hval->new($s);
672 my $m = PublicInbox::Hval->new_msgid($mid);
673 $m = $upfx . '../' . $m->as_href . '/';
675 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
678 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
683 my ($dst, $state, $upfx, $node, $level) = @_;
685 return if $state->{stopped};
686 if (my $mime = $node->message) {
687 _inline_header($dst, $state, $upfx, $mime, $level);
689 inline_dump($dst, $state, $upfx, $node->child, $level+1);
690 inline_dump($dst, $state, $upfx, $node->next, $level);