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 $subj = "<a\nhref=\"${path}$href/t/#u\">$subj</a>";
86 if ($root_anchor && $root_anchor eq $id) {
87 $subj = "<u\nid=\"u\">$subj</u>";
90 my $ts = _msg_date($mime);
91 my $rv = "<table\nsummary=l$level><tr>";
93 $rv .= '<td><pre>' . (' ' x $level) . '</pre></td>';
95 $rv .= "<td\nid=s$midx>" . PRE_WRAP;
96 $rv .= "<b\nid=\"$id\">$subj</b>\n";
97 $rv .= "- by $from @ $ts UTC - ";
98 $rv .= "<a\nhref=\"#s$next\">next</a>";
100 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
102 $fh->write($rv .= "\n\n");
104 my ($fhref, $more_ref);
105 my $mhref = "${path}$href/";
107 $fhref = "${path}$href/f/";
110 # scan through all parts, looking for displayable text
111 $mime->walk_parts(sub {
112 index_walk($fh, $_[0], $enc, \$part_nr, $fhref, $more_ref);
116 my $txt = "${path}$href/raw";
117 $rv = "\n<a\nhref=\"$mhref\">$more</a> <a\nhref=\"$txt\">raw</a> ";
118 $rv .= html_footer($mime, 0, undef, $ctx);
121 unless (defined $anchor) {
122 my $v = PublicInbox::Hval->new_msgid($irt);
124 $anchor = "${path}$v/";
125 $seen->{$anchor_idx} = $anchor;
127 $rv .= " <a\nhref=\"$anchor\">parent</a>";
130 $fh->write($rv .= '</pre></td></tr></table>');
134 my ($ctx, $foot, $srch) = @_;
135 sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
138 # only private functions below.
140 sub emit_thread_html {
141 my ($cb, $ctx, $foot, $srch) = @_;
142 my $mid = mid_compress($ctx->{mid});
143 my $res = $srch->get_thread($mid);
144 my $msgs = load_results($res);
145 my $nr = scalar @$msgs;
146 return missing_thread($cb) if $nr == 0;
148 my $th = thread_results($msgs);
152 root_anchor => anchor_for($mid),
156 require PublicInbox::GitCatFile;
157 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
158 thread_entry(\$cb, $git, $state, $_, 0) for $th->rootset;
160 Email::Address->purge_cache;
162 # there could be a race due to a message being deleted in git
163 # but still being in the Xapian index:
164 return missing_thread($cb) if ($orig_cb eq $cb);
166 my $final_anchor = $state->{anchor_idx};
167 my $next = "<a\nid=\"s$final_anchor\">";
168 $next .= $final_anchor == 1 ? 'only message in' : 'end of';
169 $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>\n";
170 $next .= "download thread: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
171 $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>\n\n";
172 $cb->write("<hr />" . PRE_WRAP . $next . $foot .
173 "</pre></body></html>");
178 my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
179 my $s = add_text_body($enc, $part, $part_nr, $fhref);
182 # drop the remainder of git patches, they're usually better
183 # to review when the full message is viewed
184 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
187 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
190 # kill any leading or trailing whitespace lines
195 # kill per-line trailing whitespace
196 $s =~ s/[ \t]+$//sgm;
197 $s .= "\n" unless $s =~ /\n\z/s;
203 my ($ct, $default) = @_;
204 $default ||= $enc_utf8;
205 defined $ct or return $default;
206 my $ct_parsed = parse_content_type($ct);
208 if (my $charset = $ct_parsed->{attributes}->{charset}) {
209 my $enc = find_encoding($charset);
216 sub multipart_text_as_html {
217 my ($mime, $full_pfx, $srch) = @_;
220 my $enc = enc_for($mime->header("Content-Type"));
222 # scan through all parts, looking for displayable text
223 $mime->walk_parts(sub {
225 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
231 sub add_filename_line {
235 $fn = $enc->decode($fn);
237 $pad x= ($len/2) if ($len > 0);
238 "$pad " . ascii_html($fn) . " $pad\n";
241 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
243 ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
246 my ($link_map, $s) = @_;
249 # salt this, as this could be exploited to show
250 # links in the HTML which don't show up in the raw mail.
251 my $key = sha1_hex($url . $SALT);
252 $link_map->{$key} = $url;
259 my ($link_map, $s) = @_;
261 # Added "PI-LINK-" prefix to avoid false-positives on git commits
262 $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
264 my $url = $link_map->{$key};
266 $url = ascii_html($url);
267 "<a\nhref=\"$url\">$url</a>";
269 # false positive or somebody tried to mess with us
277 my ($quot, $n, $part_nr, $full_pfx, $final) = @_;
280 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
283 my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
285 $rv = ascii_html($rv);
286 return linkify_2(\%l, $rv);
289 # show a short snippet of quoted text and link to full version:
290 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
291 my $cur = join(' ', @$quot);
292 @$quot = split(/\s+/, $cur);
295 my $tmp = shift(@$quot);
296 my $len = length($tmp) + length($cur);
297 if ($len > MAX_TRUNC_LEN) {
302 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
304 $cur =~ s/ \z/ .../s;
305 $cur = ascii_html($cur);
307 "> [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
309 # show everything in the full version with anchor from
310 # short version (see above)
314 $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
316 $rv = ascii_html($rv);
317 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
322 my ($enc_msg, $part, $part_nr, $full_pfx) = @_;
323 return '' if $part->subparts;
325 my $ct = $part->content_type;
326 # account for filter bugs...
327 if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) {
331 my $enc = enc_for($ct, $enc_msg);
336 $s = $enc->decode($s);
337 my @lines = split(/^/m, $s);
341 my $fn = $part->filename;
342 defined($fn) or $fn = "part #" . ($$part_nr + 1);
343 $s .= add_filename_line($enc, $fn);
347 while (defined(my $cur = shift @lines)) {
349 # show the previously buffered quote inline
351 $s .= flush_quote(\@quot, \$n, $$part_nr,
357 $cur = linkify_1(\%l, $cur);
358 $cur = ascii_html($cur);
359 $s .= linkify_2(\%l, $cur);
364 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1) if scalar @quot;
365 $s .= "\n" unless $s =~ /\n\z/s;
370 sub headers_to_html_header {
371 my ($mime, $full_pfx, $ctx) = @_;
372 my $srch = $ctx->{srch} if $ctx;
375 my $header_obj = $mime->header_obj;
376 my $mid = $header_obj->header('Message-ID');
377 $mid = PublicInbox::Hval->new_msgid($mid);
378 my $mid_href = $mid->as_href;
379 foreach my $h (qw(From To Cc Subject Date)) {
380 my $v = $mime->header($h);
381 defined($v) && ($v ne '') or next;
382 $v = PublicInbox::Hval->new_oneline($v);
385 my @from = Email::Address->parse($v->raw);
386 $title[1] = ascii_html($from[0]->name);
387 } elsif ($h eq 'Subject') {
388 $title[0] = $v->as_html;
390 my $p = $full_pfx ? '' : '../';
391 $rv .= "$h: <a\nid=\"t\"\nhref=\"${p}t/#u\">";
392 $rv .= $v->as_html . "</a>\n";
396 $rv .= "$h: " . $v->as_html . "\n";
399 $rv .= 'Message-ID: <' . $mid->as_html . '> ';
400 my $raw_ref = $full_pfx ? 'raw' : '../raw';
401 $rv .= "(<a\nhref=\"$raw_ref\">raw</a>)\n";
403 $rv .= "<a\nhref=\"#r\">References: [see below]</a>\n";
405 $rv .= _parent_headers_nosrch($header_obj);
409 ("<html><head><title>". join(' - ', @title) .
410 '</title></head><body>' . PRE_WRAP . $rv);
414 my ($dst, $ctx, $cur, $full_pfx) = @_;
415 my $srch = $ctx->{srch};
416 my $mid = mid_compress(mid_clean($cur->header('Message-ID')));
417 my $res = $srch->get_thread($mid);
418 my $nr = $res->{total};
421 $$dst .= "\n[no followups, yet]\n";
424 my $upfx = $full_pfx ? '' : '../';
426 $$dst .= "\n\n~$nr messages in thread: ".
427 "(<a\nhref=\"${upfx}t/#u\">expand</a>)\n";
428 my $subj = $srch->subject_path($cur->header('Subject'));
430 seen => { $subj => 1 },
434 for (thread_results(load_results($res))->rootset) {
435 inline_dump($dst, $state, $upfx, $_, 0);
440 sub _parent_headers_nosrch {
441 my ($header_obj) = @_;
444 my $irt = $header_obj->header('In-Reply-To');
446 my $v = PublicInbox::Hval->new_msgid($irt);
447 my $html = $v->as_html;
448 my $href = $v->as_href;
449 $rv .= "In-Reply-To: <";
450 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
453 my $refs = $header_obj->header('References');
455 # avoid redundant URLs wasting bandwidth
457 $seen{mid_clean($irt)} = 1 if defined $irt;
459 my @raw_refs = ($refs =~ /<([^>]+)>/g);
460 foreach my $ref (@raw_refs) {
463 push @refs, linkify_ref($ref);
467 $rv .= 'References: '. join(' ', @refs) . "\n";
474 my ($mime, $standalone, $full_pfx, $ctx) = @_;
475 my %cc; # everyone else
476 my $to; # this is the From address
478 foreach my $h (qw(From To Cc)) {
479 my $v = $mime->header($h);
480 defined($v) && ($v ne '') or next;
481 my @addrs = Email::Address->parse($v);
482 foreach my $recip (@addrs) {
483 my $address = $recip->address;
484 my $dst = lc($address);
485 $cc{$dst} ||= $address;
489 Email::Address->purge_cache if $standalone;
491 my $subj = $mime->header('Subject') || '';
492 $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
493 my $mid = $mime->header('Message-ID');
494 my $irt = uri_escape_utf8($mid);
496 $to = uri_escape_utf8($to);
497 $subj = uri_escape_utf8($subj);
499 my $cc = uri_escape_utf8(join(',', sort values %cc));
500 my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
502 my $srch = $ctx->{srch} if $ctx;
503 my $upfx = $full_pfx ? '../' : '../../';
504 my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
506 my $next = thread_inline(\$idx, $ctx, $mime, $full_pfx);
507 $irt = $mime->header('In-Reply-To');
509 $irt = PublicInbox::Hval->new_msgid($irt);
510 $irt = $irt->as_href;
511 $irt = "<a\nhref=\"$upfx$irt/\">parent</a> ";
513 $irt = ' ' x length('parent ');
516 $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
524 "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
528 my $v = PublicInbox::Hval->new_msgid($_[0]);
529 my $html = $v->as_html;
530 my $href = $v->as_href;
531 "<<a\nhref=\"../$href/\">$html</a>>";
537 if ($id !~ /\A[a-f0-9]{40}\z/) {
538 $id = mid_compress(mid_clean($id), 1);
543 sub thread_html_head {
544 my ($cb, $mime) = @_;
545 $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
547 my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
549 $$cb->write("<html><head><title>$s</title></head><body>");
553 my ($cb, $git, $state, $node, $level) = @_;
555 if (my $mime = $node->message) {
557 # lazy load the full message from mini_mime:
558 my $path = mid2path(mid_clean($mime->header('Message-ID')));
559 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
561 if ($state->{anchor_idx} == 0) {
562 thread_html_head($cb, $mime);
564 index_entry($$cb, $mime, $level, $state);
567 thread_entry($cb, $git, $state, $node->child, $level + 1);
568 thread_entry($cb, $git, $state, $node->next, $level);
574 [ map { $_->mini_mime } @{delete $res->{msgs}} ];
579 my $ts = eval { str2time($mime->header('Date')) };
580 defined($ts) ? $ts : 0;
585 require PublicInbox::Thread;
586 my $th = PublicInbox::Thread->new(@$msgs);
589 $th->order(*PublicInbox::Thread::sort_ts);
595 my $title = 'Thread does not exist';
596 $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
597 <html><head><title>$title</title></head><body><pre>$title
598 <a href="../../">Return to index</a></pre></body></html>
604 my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
605 POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
609 my ($dst, $state, $upfx, $mime, $level) = @_;
610 my $pfx = ' ' x $level;
612 my $cur = $state->{cur};
613 my $mid = $mime->header('Message-ID');
614 my $f = $mime->header('X-PI-From');
615 my $d = _msg_date($mime);
616 $f = PublicInbox::Hval->new($f);
617 $d = PublicInbox::Hval->new($d);
619 $d = $d->as_html . ' UTC';
620 my $midc = mid_compress(mid_clean($mid));
623 delete $state->{cur};
624 $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
625 "[this message]</a></b> by $f @ $d\n";
630 $state->{next_msg} ||= $midc;
633 # Subject is never undef, this mail was loaded from
634 # our Xapian which would've resulted in '' if it were
635 # really missing (and Filter rejects empty subjects)
636 my $s = $mime->header('Subject');
637 my $h = $state->{srch}->subject_path($s);
638 if ($state->{seen}->{$h}) {
641 $state->{seen}->{$h} = 1;
642 $s = PublicInbox::Hval->new($s);
645 my $m = PublicInbox::Hval->new_msgid($mid);
646 $m = $upfx . '../' . $m->as_href . '/';
648 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
651 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
656 my ($dst, $state, $upfx, $node, $level) = @_;
658 return if $state->{stopped};
659 if (my $mime = $node->message) {
660 _inline_header($dst, $state, $upfx, $mime, $level);
662 inline_dump($dst, $state, $upfx, $node->child, $level+1);
663 inline_dump($dst, $state, $upfx, $node->next, $level);