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 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);
92 my ($anchor_idx, $anchor);
94 $anchor_idx = anchor_for($irt);
95 $anchor = $seen->{$anchor_idx};
98 my $t = $ctx->{flat} ? 'T' : 't';
99 $subj = "<a\nhref=\"${path}$href/$t/#u\">$subj</a>";
101 if ($root_anchor && $root_anchor eq $id) {
102 $subj = "<u\nid=\"u\">$subj</u>";
105 my $ts = _msg_date($mime);
106 my $rv = "<table\nsummary=l$level><tr>";
108 $rv .= '<td><pre>' . (' ' x $level) . '</pre></td>';
110 $rv .= "<td\nid=s$midx>" . PRE_WRAP;
111 $rv .= "<b\nid=\"$id\">$subj</b>\n";
112 $rv .= "- by $from @ $ts UTC - ";
113 $rv .= "<a\nhref=\"#s$next\">next</a>";
115 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
117 $fh->write($rv .= "\n\n");
119 my ($fhref, $more_ref);
120 my $mhref = "${path}$href/";
122 # show full messages at level == 0 in threaded view
123 if ($level > 0 || ($ctx->{flat} && $root_anchor ne $id)) {
124 $fhref = "${path}$href/f/";
127 # scan through all parts, looking for displayable text
128 $mime->walk_parts(sub {
129 index_walk($fh, $_[0], $enc, \$part_nr, $fhref, $more_ref);
133 my $txt = "${path}$href/raw";
134 $rv = "\n<a\nhref=\"$mhref\">$more</a> <a\nhref=\"$txt\">raw</a> ";
135 $rv .= html_footer($mime, 0, undef, $ctx);
138 unless (defined $anchor) {
139 my $v = PublicInbox::Hval->new_msgid($irt);
141 $anchor = "${path}$v/";
142 $seen->{$anchor_idx} = $anchor;
144 $rv .= " <a\nhref=\"$anchor\">parent</a>";
148 $rv .= " [<a\nhref=\"${path}$href/t/#u\">threaded</a>" .
151 $rv .= " [<b>threaded</b>|" .
152 "<a\nhref=\"${path}$href/T/#u\">flat</a>]";
156 $fh->write($rv .= '</pre></td></tr></table>');
160 my ($ctx, $foot, $srch) = @_;
161 sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
164 # only private functions below.
166 sub emit_thread_html {
167 my ($cb, $ctx, $foot, $srch) = @_;
168 my $mid = mid_compress($ctx->{mid});
169 my $res = $srch->get_thread($mid);
170 my $msgs = load_results($res);
171 my $nr = scalar @$msgs;
172 return missing_thread($cb) if $nr == 0;
173 my $flat = $ctx->{flat};
178 root_anchor => anchor_for($mid),
182 require PublicInbox::GitCatFile;
183 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
185 __thread_entry(\$cb, $git, $state, $_, 0) for (@$msgs);
187 my $th = thread_results($msgs);
188 thread_entry(\$cb, $git, $state, $_, 0) for $th->rootset;
191 Email::Address->purge_cache;
193 # there could be a race due to a message being deleted in git
194 # but still being in the Xapian index:
195 return missing_thread($cb) if ($orig_cb eq $cb);
197 my $final_anchor = $state->{anchor_idx};
198 my $next = "<a\nid=\"s$final_anchor\">";
199 $next .= $final_anchor == 1 ? 'only message in' : 'end of';
200 $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>";
202 $next .= " [<a\nhref=\"../t/#u\">threaded</a>|<b>flat</b>]";
204 $next .= " [<b>threaded</b>|<a\nhref=\"../T/#u\">flat</a>]";
206 $next .= "\ndownload thread: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
207 $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>";
208 $cb->write("<hr />" . PRE_WRAP . $next . "\n\n". $foot .
209 "</pre></body></html>");
214 my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
215 my $s = add_text_body($enc, $part, $part_nr, $fhref);
218 # drop the remainder of git patches, they're usually better
219 # to review when the full message is viewed
220 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
223 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
226 # kill any leading or trailing whitespace lines
231 # kill per-line trailing whitespace
232 $s =~ s/[ \t]+$//sgm;
233 $s .= "\n" unless $s =~ /\n\z/s;
239 my ($ct, $default) = @_;
240 $default ||= $enc_utf8;
241 defined $ct or return $default;
242 my $ct_parsed = parse_content_type($ct);
244 if (my $charset = $ct_parsed->{attributes}->{charset}) {
245 my $enc = find_encoding($charset);
252 sub multipart_text_as_html {
253 my ($mime, $full_pfx, $srch) = @_;
256 my $enc = enc_for($mime->header("Content-Type"));
258 # scan through all parts, looking for displayable text
259 $mime->walk_parts(sub {
261 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
267 sub add_filename_line {
271 $fn = $enc->decode($fn);
273 $pad x= ($len/2) if ($len > 0);
274 "$pad " . ascii_html($fn) . " $pad\n";
277 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
279 ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
282 my ($link_map, $s) = @_;
285 # salt this, as this could be exploited to show
286 # links in the HTML which don't show up in the raw mail.
287 my $key = sha1_hex($url . $SALT);
288 $link_map->{$key} = $url;
295 my ($link_map, $s) = @_;
297 # Added "PI-LINK-" prefix to avoid false-positives on git commits
298 $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
300 my $url = $link_map->{$key};
302 $url = ascii_html($url);
303 "<a\nhref=\"$url\">$url</a>";
305 # false positive or somebody tried to mess with us
313 my ($quot, $n, $part_nr, $full_pfx, $final) = @_;
316 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
319 my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
321 $rv = ascii_html($rv);
322 return linkify_2(\%l, $rv);
325 # show a short snippet of quoted text and link to full version:
326 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
327 my $cur = join(' ', @$quot);
328 @$quot = split(/\s+/, $cur);
331 my $tmp = shift(@$quot);
332 my $len = length($tmp) + length($cur);
333 if ($len > MAX_TRUNC_LEN) {
338 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
340 $cur =~ s/ \z/ .../s;
341 $cur = ascii_html($cur);
343 "> [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
345 # show everything in the full version with anchor from
346 # short version (see above)
350 $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
352 $rv = ascii_html($rv);
353 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
358 my ($enc_msg, $part, $part_nr, $full_pfx) = @_;
359 return '' if $part->subparts;
361 my $ct = $part->content_type;
362 # account for filter bugs...
363 if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) {
367 my $enc = enc_for($ct, $enc_msg);
372 $s = $enc->decode($s);
373 my @lines = split(/^/m, $s);
377 my $fn = $part->filename;
378 defined($fn) or $fn = "part #" . ($$part_nr + 1);
379 $s .= add_filename_line($enc, $fn);
383 while (defined(my $cur = shift @lines)) {
385 # show the previously buffered quote inline
387 $s .= flush_quote(\@quot, \$n, $$part_nr,
393 $cur = linkify_1(\%l, $cur);
394 $cur = ascii_html($cur);
395 $s .= linkify_2(\%l, $cur);
400 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1) if scalar @quot;
401 $s .= "\n" unless $s =~ /\n\z/s;
406 sub headers_to_html_header {
407 my ($mime, $full_pfx, $ctx) = @_;
408 my $srch = $ctx->{srch} if $ctx;
411 my $header_obj = $mime->header_obj;
412 my $mid = $header_obj->header('Message-ID');
413 $mid = PublicInbox::Hval->new_msgid($mid);
414 my $mid_href = $mid->as_href;
415 foreach my $h (qw(From To Cc Subject Date)) {
416 my $v = $mime->header($h);
417 defined($v) && ($v ne '') or next;
418 $v = PublicInbox::Hval->new_oneline($v);
421 my @from = Email::Address->parse($v->raw);
422 $title[1] = ascii_html($from[0]->name);
423 } elsif ($h eq 'Subject') {
424 $title[0] = $v->as_html;
426 my $p = $full_pfx ? '' : '../';
427 $rv .= "$h: <a\nid=\"t\"\nhref=\"${p}t/#u\">";
428 $rv .= $v->as_html . "</a>\n";
432 $rv .= "$h: " . $v->as_html . "\n";
435 $rv .= 'Message-ID: <' . $mid->as_html . '> ';
436 my $raw_ref = $full_pfx ? 'raw' : '../raw';
437 $rv .= "(<a\nhref=\"$raw_ref\">raw</a>)\n";
439 $rv .= "<a\nhref=\"#r\">References: [see below]</a>\n";
441 $rv .= _parent_headers_nosrch($header_obj);
445 ("<html><head><title>". join(' - ', @title) .
446 '</title></head><body>' . PRE_WRAP . $rv);
450 my ($dst, $ctx, $cur, $full_pfx) = @_;
451 my $srch = $ctx->{srch};
452 my $mid = mid_compress(mid_clean($cur->header('Message-ID')));
453 my $res = $srch->get_thread($mid);
454 my $nr = $res->{total};
457 $$dst .= "\n[no followups, yet]\n";
460 my $upfx = $full_pfx ? '' : '../';
462 $$dst .= "\n\n~$nr messages in thread: ".
463 "(<a\nhref=\"${upfx}t/#u\">expand</a>)\n";
464 my $subj = $srch->subject_path($cur->header('Subject'));
466 seen => { $subj => 1 },
470 for (thread_results(load_results($res))->rootset) {
471 inline_dump($dst, $state, $upfx, $_, 0);
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);
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($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 = thread_inline(\$idx, $ctx, $mime, $full_pfx);
543 $irt = in_reply_to($mime->header_obj);
545 $irt = PublicInbox::Hval->new_msgid($irt);
546 $irt = $irt->as_href;
547 $irt = "<a\nhref=\"$upfx$irt/\">parent</a> ";
549 $irt = ' ' x length('parent ');
552 $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
560 "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
564 my $v = PublicInbox::Hval->new_msgid($_[0]);
565 my $html = $v->as_html;
566 my $href = $v->as_href;
567 "<<a\nhref=\"../$href/\">$html</a>>";
573 if ($id !~ /\A[a-f0-9]{40}\z/) {
574 $id = mid_compress(mid_clean($id), 1);
579 sub thread_html_head {
580 my ($cb, $mime) = @_;
581 $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
583 my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
585 $$cb->write("<html><head><title>$s</title></head><body>");
589 my ($cb, $git, $state, $mime, $level) = @_;
591 # lazy load the full message from mini_mime:
592 my $path = mid2path(mid_clean($mime->header('Message-ID')));
593 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
595 if ($state->{anchor_idx} == 0) {
596 thread_html_head($cb, $mime);
598 index_entry($$cb, $mime, $level, $state);
603 my ($cb, $git, $state, $node, $level) = @_;
605 if (my $mime = $node->message) {
606 __thread_entry($cb, $git, $state, $mime, $level);
608 thread_entry($cb, $git, $state, $node->child, $level + 1);
609 thread_entry($cb, $git, $state, $node->next, $level);
615 [ map { $_->mini_mime } @{delete $res->{msgs}} ];
620 my $ts = eval { str2time($mime->header('Date')) };
621 defined($ts) ? $ts : 0;
626 require PublicInbox::Thread;
627 my $th = PublicInbox::Thread->new(@$msgs);
630 $th->order(*PublicInbox::Thread::sort_ts);
636 my $title = 'Thread does not exist';
637 $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
638 <html><head><title>$title</title></head><body><pre>$title
639 <a href="../../">Return to index</a></pre></body></html>
645 my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
646 POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
650 my ($dst, $state, $upfx, $mime, $level) = @_;
651 my $pfx = ' ' x $level;
653 my $cur = $state->{cur};
654 my $mid = $mime->header('Message-ID');
655 my $f = $mime->header('X-PI-From');
656 my $d = _msg_date($mime);
657 $f = PublicInbox::Hval->new($f);
658 $d = PublicInbox::Hval->new($d);
660 $d = $d->as_html . ' UTC';
661 my $midc = mid_compress(mid_clean($mid));
664 delete $state->{cur};
665 $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
666 "[this message]</a></b> by $f @ $d\n";
671 $state->{next_msg} ||= $midc;
674 # Subject is never undef, this mail was loaded from
675 # our Xapian which would've resulted in '' if it were
676 # really missing (and Filter rejects empty subjects)
677 my $s = $mime->header('Subject');
678 my $h = $state->{srch}->subject_path($s);
679 if ($state->{seen}->{$h}) {
682 $state->{seen}->{$h} = 1;
683 $s = PublicInbox::Hval->new($s);
686 my $m = PublicInbox::Hval->new_msgid($mid);
687 $m = $upfx . '../' . $m->as_href . '/';
689 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
692 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
697 my ($dst, $state, $upfx, $node, $level) = @_;
699 return if $state->{stopped};
700 if (my $mime = $node->message) {
701 _inline_header($dst, $state, $upfx, $mime, $level);
703 inline_dump($dst, $state, $upfx, $node->child, $level+1);
704 inline_dump($dst, $state, $upfx, $node->next, $level);