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);
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};
173 root_anchor => anchor_for($mid),
177 require PublicInbox::GitCatFile;
178 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
180 __thread_entry(\$cb, $git, $state, $_, 0) for (@$msgs);
182 my $th = thread_results($msgs);
183 thread_entry(\$cb, $git, $state, $_, 0) for $th->rootset;
186 Email::Address->purge_cache;
188 # there could be a race due to a message being deleted in git
189 # but still being in the Xapian index:
190 return missing_thread($cb) if ($orig_cb eq $cb);
192 my $final_anchor = $state->{anchor_idx};
193 my $next = "<a\nid=\"s$final_anchor\">";
194 $next .= $final_anchor == 1 ? 'only message in' : 'end of';
195 $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>";
197 $next .= " [<a\nhref=\"../t/#u\">threaded</a>|<b>flat</b>]";
199 $next .= " [<b>threaded</b>|<a\nhref=\"../T/#u\">flat</a>]";
201 $next .= "\ndownload thread: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
202 $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>";
203 $cb->write("<hr />" . PRE_WRAP . $next . "\n\n". $foot .
204 "</pre></body></html>");
209 my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
210 my $s = add_text_body($enc, $part, $part_nr, $fhref);
213 # drop the remainder of git patches, they're usually better
214 # to review when the full message is viewed
215 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
218 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
221 # kill any leading or trailing whitespace lines
226 # kill per-line trailing whitespace
227 $s =~ s/[ \t]+$//sgm;
228 $s .= "\n" unless $s =~ /\n\z/s;
234 my ($ct, $default) = @_;
235 $default ||= $enc_utf8;
236 defined $ct or return $default;
237 my $ct_parsed = parse_content_type($ct);
239 if (my $charset = $ct_parsed->{attributes}->{charset}) {
240 my $enc = find_encoding($charset);
247 sub multipart_text_as_html {
248 my ($mime, $full_pfx, $srch) = @_;
251 my $enc = enc_for($mime->header("Content-Type"));
253 # scan through all parts, looking for displayable text
254 $mime->walk_parts(sub {
256 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
262 sub add_filename_line {
266 $fn = $enc->decode($fn);
268 $pad x= ($len/2) if ($len > 0);
269 "$pad " . ascii_html($fn) . " $pad\n";
272 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
274 ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
277 my ($link_map, $s) = @_;
280 # salt this, as this could be exploited to show
281 # links in the HTML which don't show up in the raw mail.
282 my $key = sha1_hex($url . $SALT);
283 $link_map->{$key} = $url;
290 my ($link_map, $s) = @_;
292 # Added "PI-LINK-" prefix to avoid false-positives on git commits
293 $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
295 my $url = $link_map->{$key};
297 $url = ascii_html($url);
298 "<a\nhref=\"$url\">$url</a>";
300 # false positive or somebody tried to mess with us
308 my ($quot, $n, $part_nr, $full_pfx, $final) = @_;
311 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
314 my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
316 $rv = ascii_html($rv);
317 return linkify_2(\%l, $rv);
320 # show a short snippet of quoted text and link to full version:
321 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
322 my $cur = join(' ', @$quot);
323 @$quot = split(/\s+/, $cur);
326 my $tmp = shift(@$quot);
327 my $len = length($tmp) + length($cur);
328 if ($len > MAX_TRUNC_LEN) {
333 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
335 $cur =~ s/ \z/ .../s;
336 $cur = ascii_html($cur);
338 "> [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
340 # show everything in the full version with anchor from
341 # short version (see above)
345 $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
347 $rv = ascii_html($rv);
348 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
353 my ($enc_msg, $part, $part_nr, $full_pfx) = @_;
354 return '' if $part->subparts;
356 my $ct = $part->content_type;
357 # account for filter bugs...
358 if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) {
362 my $enc = enc_for($ct, $enc_msg);
367 $s = $enc->decode($s);
368 my @lines = split(/^/m, $s);
372 my $fn = $part->filename;
373 defined($fn) or $fn = "part #" . ($$part_nr + 1);
374 $s .= add_filename_line($enc, $fn);
378 while (defined(my $cur = shift @lines)) {
380 # show the previously buffered quote inline
382 $s .= flush_quote(\@quot, \$n, $$part_nr,
388 $cur = linkify_1(\%l, $cur);
389 $cur = ascii_html($cur);
390 $s .= linkify_2(\%l, $cur);
395 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1) if scalar @quot;
396 $s .= "\n" unless $s =~ /\n\z/s;
401 sub headers_to_html_header {
402 my ($mime, $full_pfx, $ctx) = @_;
403 my $srch = $ctx->{srch} if $ctx;
406 my $header_obj = $mime->header_obj;
407 my $mid = $header_obj->header('Message-ID');
408 $mid = PublicInbox::Hval->new_msgid($mid);
409 my $mid_href = $mid->as_href;
410 foreach my $h (qw(From To Cc Subject Date)) {
411 my $v = $mime->header($h);
412 defined($v) && ($v ne '') or next;
413 $v = PublicInbox::Hval->new_oneline($v);
416 my @from = Email::Address->parse($v->raw);
417 $title[1] = ascii_html($from[0]->name);
418 } elsif ($h eq 'Subject') {
419 $title[0] = $v->as_html;
421 my $p = $full_pfx ? '' : '../';
422 $rv .= "$h: <a\nid=\"t\"\nhref=\"${p}t/#u\">";
423 $rv .= $v->as_html . "</a>\n";
427 $rv .= "$h: " . $v->as_html . "\n";
430 $rv .= 'Message-ID: <' . $mid->as_html . '> ';
431 my $raw_ref = $full_pfx ? 'raw' : '../raw';
432 $rv .= "(<a\nhref=\"$raw_ref\">raw</a>)\n";
434 $rv .= "<a\nhref=\"#r\">References: [see below]</a>\n";
436 $rv .= _parent_headers_nosrch($header_obj);
440 ("<html><head><title>". join(' - ', @title) .
441 '</title></head><body>' . PRE_WRAP . $rv);
445 my ($dst, $ctx, $cur, $full_pfx) = @_;
446 my $srch = $ctx->{srch};
447 my $mid = mid_compress(mid_clean($cur->header('Message-ID')));
448 my $res = $srch->get_thread($mid);
449 my $nr = $res->{total};
452 $$dst .= "\n[no followups, yet]\n";
455 my $upfx = $full_pfx ? '' : '../';
457 $$dst .= "\n\n~$nr messages in thread: ".
458 "(<a\nhref=\"${upfx}t/#u\">expand</a>)\n";
459 my $subj = $srch->subject_path($cur->header('Subject'));
461 seen => { $subj => 1 },
465 for (thread_results(load_results($res))->rootset) {
466 inline_dump($dst, $state, $upfx, $_, 0);
471 sub _parent_headers_nosrch {
472 my ($header_obj) = @_;
475 my $irt = in_reply_to($header_obj);
477 my $v = PublicInbox::Hval->new_msgid($irt);
478 my $html = $v->as_html;
479 my $href = $v->as_href;
480 $rv .= "In-Reply-To: <";
481 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
484 my $refs = $header_obj->header('References');
486 # avoid redundant URLs wasting bandwidth
488 $seen{$irt} = 1 if defined $irt;
490 my @raw_refs = ($refs =~ /<([^>]+)>/g);
491 foreach my $ref (@raw_refs) {
494 push @refs, linkify_ref($ref);
498 $rv .= 'References: '. join(' ', @refs) . "\n";
505 my ($mime, $standalone, $full_pfx, $ctx) = @_;
506 my %cc; # everyone else
507 my $to; # this is the From address
509 foreach my $h (qw(From To Cc)) {
510 my $v = $mime->header($h);
511 defined($v) && ($v ne '') or next;
512 my @addrs = Email::Address->parse($v);
513 foreach my $recip (@addrs) {
514 my $address = $recip->address;
515 my $dst = lc($address);
516 $cc{$dst} ||= $address;
520 Email::Address->purge_cache if $standalone;
522 my $subj = $mime->header('Subject') || '';
523 $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
524 my $mid = $mime->header('Message-ID');
525 my $irt = uri_escape_utf8($mid);
527 $to = uri_escape_utf8($to);
528 $subj = uri_escape_utf8($subj);
530 my $cc = uri_escape_utf8(join(',', sort values %cc));
531 my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
533 my $srch = $ctx->{srch} if $ctx;
534 my $upfx = $full_pfx ? '../' : '../../';
535 my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
537 my $next = thread_inline(\$idx, $ctx, $mime, $full_pfx);
538 $irt = in_reply_to($mime->header_obj);
540 $irt = PublicInbox::Hval->new_msgid($irt);
541 $irt = $irt->as_href;
542 $irt = "<a\nhref=\"$upfx$irt/\">parent</a> ";
544 $irt = ' ' x length('parent ');
547 $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
555 "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
559 my $v = PublicInbox::Hval->new_msgid($_[0]);
560 my $html = $v->as_html;
561 my $href = $v->as_href;
562 "<<a\nhref=\"../$href/\">$html</a>>";
568 if ($id !~ /\A[a-f0-9]{40}\z/) {
569 $id = mid_compress(mid_clean($id), 1);
574 sub thread_html_head {
575 my ($cb, $mime) = @_;
576 $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
578 my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
580 $$cb->write("<html><head><title>$s</title></head><body>");
584 my ($cb, $git, $state, $mime, $level) = @_;
586 # lazy load the full message from mini_mime:
587 my $path = mid2path(mid_clean($mime->header('Message-ID')));
588 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
590 if ($state->{anchor_idx} == 0) {
591 thread_html_head($cb, $mime);
593 index_entry($$cb, $mime, $level, $state);
598 my ($cb, $git, $state, $node, $level) = @_;
600 if (my $mime = $node->message) {
601 __thread_entry($cb, $git, $state, $mime, $level);
603 thread_entry($cb, $git, $state, $node->child, $level + 1);
604 thread_entry($cb, $git, $state, $node->next, $level);
610 [ map { $_->mini_mime } @{delete $res->{msgs}} ];
615 my $ts = eval { str2time($mime->header('Date')) };
616 defined($ts) ? $ts : 0;
621 require PublicInbox::Thread;
622 my $th = PublicInbox::Thread->new(@$msgs);
625 $th->order(*PublicInbox::Thread::sort_ts);
631 my $title = 'Thread does not exist';
632 $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
633 <html><head><title>$title</title></head><body><pre>$title
634 <a href="../../">Return to index</a></pre></body></html>
640 my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
641 POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
645 my ($dst, $state, $upfx, $mime, $level) = @_;
646 my $pfx = ' ' x $level;
648 my $cur = $state->{cur};
649 my $mid = $mime->header('Message-ID');
650 my $f = $mime->header('X-PI-From');
651 my $d = _msg_date($mime);
652 $f = PublicInbox::Hval->new($f);
653 $d = PublicInbox::Hval->new($d);
655 $d = $d->as_html . ' UTC';
656 my $midc = mid_compress(mid_clean($mid));
659 delete $state->{cur};
660 $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
661 "[this message]</a></b> by $f @ $d\n";
666 $state->{next_msg} ||= $midc;
669 # Subject is never undef, this mail was loaded from
670 # our Xapian which would've resulted in '' if it were
671 # really missing (and Filter rejects empty subjects)
672 my $s = $mime->header('Subject');
673 my $h = $state->{srch}->subject_path($s);
674 if ($state->{seen}->{$h}) {
677 $state->{seen}->{$h} = 1;
678 $s = PublicInbox::Hval->new($s);
681 my $m = PublicInbox::Hval->new_msgid($mid);
682 $m = $upfx . '../' . $m->as_href . '/';
684 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
687 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
692 my ($dst, $state, $upfx, $node, $level) = @_;
694 return if $state->{stopped};
695 if (my $mime = $node->message) {
696 _inline_header($dst, $state, $upfx, $mime, $level);
698 inline_dump($dst, $state, $upfx, $node->child, $level+1);
699 inline_dump($dst, $state, $upfx, $node->next, $level);