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;
147 my $fh = $cb->([200,['Content-Type'=>'text/html; charset=UTF-8']]);
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($fh, $git, $state, $_, 0) for $th->rootset;
160 my $final_anchor = $state->{anchor_idx};
161 my $next = "<a\nid=\"s$final_anchor\">";
162 $next .= $final_anchor == 1 ? 'only message in' : 'end of';
163 $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>\n";
164 $next .= "download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
165 $next .= " / <a\nhref=\"../t.atom\">Atom feed</a>\n\n";
166 $fh->write("<hr />" . PRE_WRAP . $next . $foot .
167 "</pre></body></html>");
172 my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
173 my $s = add_text_body($enc, $part, $part_nr, $fhref);
176 # drop the remainder of git patches, they're usually better
177 # to review when the full message is viewed
178 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
181 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
184 # kill any leading or trailing whitespace lines
189 # kill per-line trailing whitespace
190 $s =~ s/[ \t]+$//sgm;
191 $s .= "\n" unless $s =~ /\n\z/s;
197 my ($ct, $default) = @_;
198 $default ||= $enc_utf8;
199 defined $ct or return $default;
200 my $ct_parsed = parse_content_type($ct);
202 if (my $charset = $ct_parsed->{attributes}->{charset}) {
203 my $enc = find_encoding($charset);
210 sub multipart_text_as_html {
211 my ($mime, $full_pfx, $srch) = @_;
214 my $enc = enc_for($mime->header("Content-Type"));
216 # scan through all parts, looking for displayable text
217 $mime->walk_parts(sub {
219 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
225 sub add_filename_line {
229 $fn = $enc->decode($fn);
231 $pad x= ($len/2) if ($len > 0);
232 "$pad " . ascii_html($fn) . " $pad\n";
235 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
237 ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
240 my ($link_map, $s) = @_;
243 # salt this, as this could be exploited to show
244 # links in the HTML which don't show up in the raw mail.
245 my $key = sha1_hex($url . $SALT);
246 $link_map->{$key} = $url;
253 my ($link_map, $s) = @_;
255 # Added "PI-LINK-" prefix to avoid false-positives on git commits
256 $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
258 my $url = $link_map->{$key};
260 $url = ascii_html($url);
261 "<a\nhref=\"$url\">$url</a>";
263 # false positive or somebody tried to mess with us
271 my ($quot, $n, $part_nr, $full_pfx, $final) = @_;
274 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
277 my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
279 $rv = ascii_html($rv);
280 return linkify_2(\%l, $rv);
283 # show a short snippet of quoted text and link to full version:
284 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
285 my $cur = join(' ', @$quot);
286 @$quot = split(/\s+/, $cur);
289 my $tmp = shift(@$quot);
290 my $len = length($tmp) + length($cur);
291 if ($len > MAX_TRUNC_LEN) {
296 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
298 $cur =~ s/ \z/ .../s;
299 $cur = ascii_html($cur);
301 "> [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
303 # show everything in the full version with anchor from
304 # short version (see above)
308 $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
310 $rv = ascii_html($rv);
311 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
316 my ($enc_msg, $part, $part_nr, $full_pfx) = @_;
317 return '' if $part->subparts;
319 my $ct = $part->content_type;
320 # account for filter bugs...
321 if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) {
325 my $enc = enc_for($ct, $enc_msg);
330 $s = $enc->decode($s);
331 my @lines = split(/^/m, $s);
335 my $fn = $part->filename;
336 defined($fn) or $fn = "part #" . ($$part_nr + 1);
337 $s .= add_filename_line($enc, $fn);
341 while (defined(my $cur = shift @lines)) {
343 # show the previously buffered quote inline
345 $s .= flush_quote(\@quot, \$n, $$part_nr,
351 $cur = linkify_1(\%l, $cur);
352 $cur = ascii_html($cur);
353 $s .= linkify_2(\%l, $cur);
358 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1) if scalar @quot;
359 $s .= "\n" unless $s =~ /\n\z/s;
364 sub headers_to_html_header {
365 my ($mime, $full_pfx, $ctx) = @_;
366 my $srch = $ctx->{srch} if $ctx;
369 my $header_obj = $mime->header_obj;
370 my $mid = $header_obj->header('Message-ID');
371 $mid = PublicInbox::Hval->new_msgid($mid);
372 my $mid_href = $mid->as_href;
373 foreach my $h (qw(From To Cc Subject Date)) {
374 my $v = $mime->header($h);
375 defined($v) && ($v ne '') or next;
376 $v = PublicInbox::Hval->new_oneline($v);
379 my @from = Email::Address->parse($v->raw);
380 $title[1] = ascii_html($from[0]->name);
381 } elsif ($h eq 'Subject') {
382 $title[0] = $v->as_html;
384 my $p = $full_pfx ? '' : '../';
385 $rv .= "$h: <a\nid=\"t\"\nhref=\"${p}t/#u\">";
386 $rv .= $v->as_html . "</a>\n";
390 $rv .= "$h: " . $v->as_html . "\n";
393 $rv .= 'Message-ID: <' . $mid->as_html . '> ';
394 my $raw_ref = $full_pfx ? 'raw' : '../raw';
395 $rv .= "(<a\nhref=\"$raw_ref\">raw</a>)\n";
397 $rv .= "<a\nhref=\"#r\">References: [see below]</a>\n";
399 $rv .= _parent_headers_nosrch($header_obj);
403 ("<html><head><title>". join(' - ', @title) .
404 '</title></head><body>' . PRE_WRAP . $rv);
408 my ($dst, $ctx, $cur, $full_pfx) = @_;
409 my $srch = $ctx->{srch};
410 my $mid = mid_compress(mid_clean($cur->header('Message-ID')));
411 my $res = $srch->get_thread($mid);
412 my $nr = $res->{total};
415 $$dst .= "\n[no followups, yet]\n";
418 my $upfx = $full_pfx ? '' : '../';
420 $$dst .= "\n\n~$nr messages in thread: ".
421 "(<a\nhref=\"${upfx}t/#u\">expand</a>)\n";
422 my $subj = $srch->subject_path($cur->header('Subject'));
424 seen => { $subj => 1 },
428 for (thread_results(load_results($res))->rootset) {
429 inline_dump($dst, $state, $upfx, $_, 0);
434 sub _parent_headers_nosrch {
435 my ($header_obj) = @_;
438 my $irt = $header_obj->header('In-Reply-To');
440 my $v = PublicInbox::Hval->new_msgid($irt);
441 my $html = $v->as_html;
442 my $href = $v->as_href;
443 $rv .= "In-Reply-To: <";
444 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
447 my $refs = $header_obj->header('References');
449 # avoid redundant URLs wasting bandwidth
451 $seen{mid_clean($irt)} = 1 if defined $irt;
453 my @raw_refs = ($refs =~ /<([^>]+)>/g);
454 foreach my $ref (@raw_refs) {
457 push @refs, linkify_ref($ref);
461 $rv .= 'References: '. join(' ', @refs) . "\n";
468 my ($mime, $standalone, $full_pfx, $ctx) = @_;
469 my %cc; # everyone else
470 my $to; # this is the From address
472 foreach my $h (qw(From To Cc)) {
473 my $v = $mime->header($h);
474 defined($v) && ($v ne '') or next;
475 my @addrs = Email::Address->parse($v);
476 foreach my $recip (@addrs) {
477 my $address = $recip->address;
478 my $dst = lc($address);
479 $cc{$dst} ||= $address;
483 Email::Address->purge_cache if $standalone;
485 my $subj = $mime->header('Subject') || '';
486 $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
487 my $mid = $mime->header('Message-ID');
488 my $irt = uri_escape_utf8($mid);
490 $to = uri_escape_utf8($to);
491 $subj = uri_escape_utf8($subj);
493 my $cc = uri_escape_utf8(join(',', sort values %cc));
494 my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
496 my $srch = $ctx->{srch} if $ctx;
497 my $upfx = $full_pfx ? '../' : '../../';
498 my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
500 my $next = thread_inline(\$idx, $ctx, $mime, $full_pfx);
501 $irt = $mime->header('In-Reply-To');
503 $irt = PublicInbox::Hval->new_msgid($irt);
504 $irt = $irt->as_href;
505 $irt = "<a\nhref=\"$upfx$irt/\">parent</a> ";
507 $irt = ' ' x length('parent ');
510 $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
518 "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
522 my $v = PublicInbox::Hval->new_msgid($_[0]);
523 my $html = $v->as_html;
524 my $href = $v->as_href;
525 "<<a\nhref=\"../$href/\">$html</a>>";
531 if ($id !~ /\A[a-f0-9]{40}\z/) {
532 $id = mid_compress(mid_clean($id), 1);
537 sub thread_html_head {
539 my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
541 "<html><head><title>$s</title></head><body>";
545 my ($fh, $git, $state, $node, $level) = @_;
547 if (my $mime = $node->message) {
549 # lazy load the full message from mini_mime:
550 my $path = mid2path(mid_clean($mime->header('Message-ID')));
551 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
553 if ($state->{anchor_idx} == 0) {
554 $fh->write(thread_html_head($mime));
556 index_entry($fh, $mime, $level, $state);
559 thread_entry($fh, $git, $state, $node->child, $level + 1);
560 thread_entry($fh, $git, $state, $node->next, $level);
566 [ map { $_->mini_mime } @{delete $res->{msgs}} ];
571 my $ts = eval { str2time($mime->header('Date')) };
572 defined($ts) ? $ts : 0;
577 require PublicInbox::Thread;
578 my $th = PublicInbox::Thread->new(@$msgs);
581 $th->order(*PublicInbox::Thread::sort_ts);
587 my $title = 'Thread does not exist';
588 $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
589 <html><head><title>$title</title></head><body><pre>$title
590 <a href="../../">Return to index</a></pre></body></html>
596 my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
597 POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
601 my ($dst, $state, $upfx, $mime, $level) = @_;
602 my $pfx = ' ' x $level;
604 my $cur = $state->{cur};
605 my $mid = $mime->header('Message-ID');
606 my $f = $mime->header('X-PI-From');
607 my $d = _msg_date($mime);
608 $f = PublicInbox::Hval->new($f);
609 $d = PublicInbox::Hval->new($d);
611 $d = $d->as_html . ' UTC';
612 my $midc = mid_compress(mid_clean($mid));
615 delete $state->{cur};
616 $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
617 "[this message]</a></b> by $f @ $d\n";
622 $state->{next_msg} ||= $midc;
625 # Subject is never undef, this mail was loaded from
626 # our Xapian which would've resulted in '' if it were
627 # really missing (and Filter rejects empty subjects)
628 my $s = $mime->header('Subject');
629 my $h = $state->{srch}->subject_path($s);
630 if ($state->{seen}->{$h}) {
633 $state->{seen}->{$h} = 1;
634 $s = PublicInbox::Hval->new($s);
637 my $m = PublicInbox::Hval->new_msgid($mid);
638 $m = $upfx . '../' . $m->as_href . '/';
640 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
643 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
648 my ($dst, $state, $upfx, $node, $level) = @_;
650 return if $state->{stopped};
651 if (my $mime = $node->message) {
652 _inline_header($dst, $state, $upfx, $mime, $level);
654 inline_dump($dst, $state, $upfx, $node->child, $level+1);
655 inline_dump($dst, $state, $upfx, $node->next, $level);