# Copyright (C) 2014, Eric Wong and all contributors # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt) package PublicInbox::View; use strict; use warnings; use URI::Escape qw/uri_escape_utf8/; use Date::Parse qw/str2time/; use Encode qw/find_encoding/; use Encode::MIME::Header; use Email::MIME::ContentType qw/parse_content_type/; use PublicInbox::Hval; use PublicInbox::MID qw/mid_clean mid_compressed mid2path/; use Digest::SHA; require POSIX; # TODO: make these constants tunable use constant MAX_INLINE_QUOTED => 12; # half an 80x24 terminal use constant MAX_TRUNC_LEN => 72; use constant PRE_WRAP => ""; use constant T_ANCHOR => '#u'; *ascii_html = *PublicInbox::Hval::ascii_html; my $enc_utf8 = find_encoding('UTF-8'); # public functions: sub msg_html { my ($class, $mime, $full_pfx, $footer, $srch) = @_; if (defined $footer) { $footer = "\n" . $footer; } else { $footer = ''; } headers_to_html_header($mime, $full_pfx, $srch) . multipart_text_as_html($mime, $full_pfx) . '
' .
		html_footer($mime, 1, $full_pfx, $srch) .
		$footer .
		'
'; } sub feed_entry { my ($class, $mime, $full_pfx) = @_; PRE_WRAP . multipart_text_as_html($mime, $full_pfx) . ''; } # this is already inside a
# state = [ time, seen = {}, first_commit, page_nr = 0 ]
sub index_entry {
	my (undef, $mime, $level, $state) = @_;
	my ($srch, $seen, $first_commit) = @$state;
	my $midx = $state->[3]++;
	my ($prev, $next) = ($midx - 1, $midx + 1);
	my $part_nr = 0;
	my $enc_msg = enc_for($mime->header("Content-Type"));
	my $subj = $mime->header('Subject');
	my $header_obj = $mime->header_obj;

	my $mid_raw = $header_obj->header_raw('Message-ID');
	my $id = anchor_for($mid_raw);
	$seen->{$id} = "#$id"; # save the anchor for later

	my $mid = PublicInbox::Hval->new_msgid($mid_raw);
	my $from = PublicInbox::Hval->new_oneline($mime->header('From'))->raw;
	my @from = Email::Address->parse($from);
	$from = $from[0]->name;
	(defined($from) && length($from)) or $from = $from[0]->address;

	$from = PublicInbox::Hval->new_oneline($from)->as_html;
	$subj = PublicInbox::Hval->new_oneline($subj)->as_html;
	my $root_anchor = $seen->{root_anchor};
	my $more = 'permalink';
	my $path = $root_anchor ? '../' : '';
	my $href = $mid->as_href;
	my $irt = $header_obj->header_raw('In-Reply-To');
	my ($anchor_idx, $anchor, $t_anchor);
	if (defined $irt) {
		$anchor_idx = anchor_for($irt);
		$anchor = $seen->{$anchor_idx};
		$t_anchor = T_ANCHOR;
	} else {
		$t_anchor = '';
	}
	if (defined $srch) {
		$subj = "$subj";
	}
	if ($root_anchor && $root_anchor eq $id) {
		$subj = "$subj";
	}

	my $ts = $mime->header('X-PI-TS');
	unless (defined $ts) {
		$ts = msg_timestamp($mime);
	}
	my $fmt = '%Y-%m-%d %H:%M';
	$ts = POSIX::strftime($fmt, gmtime($ts));

	my $rv = "";
	if ($level) {
		$rv .= '
' . ('  ' x $level) . '
'; } $rv .= '' . PRE_WRAP; $rv .= "$subj\n"; $rv .= "- by $from @ $ts UTC - "; $rv .= "next"; if ($prev >= 0) { $rv .= "/prev"; } $rv .= "\n\n"; my ($fhref, $more_ref); my $mhref = "${path}m/$href.html"; if ($level > 0) { $fhref = "${path}f/$href.html"; $more_ref = \$more; } # scan through all parts, looking for displayable text $mime->walk_parts(sub { $rv .= index_walk($_[0], $enc_msg, $part_nr, $fhref, $more_ref); $part_nr++; }); $mime->body_set(''); $rv .= "\n$more "; my $txt = "${path}m/$href.txt"; $rv .= "raw "; $rv .= html_footer($mime, 0); if (defined $irt) { unless (defined $anchor) { my $v = PublicInbox::Hval->new_msgid($irt); $v = $v->as_href; $anchor = "${path}m/$v.html"; $seen->{$anchor_idx} = $anchor; } $rv .= " parent"; } if ($srch) { $rv .= " " . "threadlink"; } $rv .= '
'; } sub thread_html { my (undef, $ctx, $foot, $srch) = @_; my $mid = mid_compressed($ctx->{mid}); my $res = $srch->get_thread($mid); my $rv = ''; my $msgs = load_results($res); my $nr = scalar @$msgs; return $rv if $nr == 0; require PublicInbox::Thread; my $th = PublicInbox::Thread->new(@$msgs); $th->thread; $th->order(*PublicInbox::Thread::sort_ts); my $state = [ $srch, { root_anchor => anchor_for($mid) }, undef, 0 ]; { require PublicInbox::GitCatFile; my $git = PublicInbox::GitCatFile->new($ctx->{git_dir}); thread_entry(\$rv, $git, $state, $_, 0) for $th->rootset; } my $final_anchor = $state->[3]; my $next = ""; if ($final_anchor == 1) { $next .= 'only message in thread'; } else { $next .= 'end of thread'; } $next .= ", back to index\n"; $rv .= "
" . PRE_WRAP . $next . $foot . ""; } sub subject_path_html { my (undef, $ctx, $foot, $srch) = @_; my $path = $ctx->{subject_path}; my $res = $srch->get_subject_path($path); my $rv = ''; my $msgs = load_results($res); my $nr = scalar @$msgs; return $rv if $nr == 0; require PublicInbox::Thread; my $th = PublicInbox::Thread->new(@$msgs); $th->thread; $th->order(*PublicInbox::Thread::sort_ts); my $state = [ $srch, { root_anchor => 'dummy' }, undef, 0 ]; { require PublicInbox::GitCatFile; my $git = PublicInbox::GitCatFile->new($ctx->{git_dir}); thread_entry(\$rv, $git, $state, $_, 0) for $th->rootset; } my $final_anchor = $state->[3]; my $next = "end of thread\n"; $rv .= "
" . PRE_WRAP . $next . $foot . ""; } # only private functions below. sub index_walk { my ($part, $enc_msg, $part_nr, $fhref, $more) = @_; my $rv = ''; return $rv if $part->subparts; # walk_parts already recurses my $ct = $part->content_type; # account for filter bugs... if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) { $part->body_set(''); return ''; } my $enc = enc_for($ct, $enc_msg); if ($part_nr > 0) { my $fn = $part->filename; defined($fn) or $fn = "part #" . ($part_nr + 1); $rv .= add_filename_line($enc->decode($fn)); } my $s = add_text_body($enc, $part, $part_nr, $fhref); if ($more) { # drop the remainder of git patches, they're usually better # to review when the full message is viewed $s =~ s!^---+\n.*\z!!ms and $$more = 'more...'; # Drop signatures $s =~ s/^-- \n.*\z//ms and $$more = 'more...'; } # kill any leading or trailing whitespace lines $s =~ s/^\s*$//sgm; $s =~ s/\s+\z//s; if (length $s) { # kill per-line trailing whitespace $s =~ s/[ \t]+$//sgm; $rv .= $s; $s = undef; $rv .= "\n"; } $rv; } sub enc_for { my ($ct, $default) = @_; $default ||= $enc_utf8; defined $ct or return $default; my $ct_parsed = parse_content_type($ct); if ($ct_parsed) { if (my $charset = $ct_parsed->{attributes}->{charset}) { my $enc = find_encoding($charset); return $enc if $enc; } } $default; } sub multipart_text_as_html { my ($mime, $full_pfx, $srch) = @_; my $rv = ""; my $part_nr = 0; my $enc_msg = enc_for($mime->header("Content-Type")); # scan through all parts, looking for displayable text $mime->walk_parts(sub { my ($part) = @_; return if $part->subparts; # walk_parts already recurses my $ct = $part->content_type; # account for filter bugs... return if defined $ct && $ct =~ m!\btext/[xh]+tml\b!i; my $enc = enc_for($ct, $enc_msg); if ($part_nr > 0) { my $fn = $part->filename; defined($fn) or $fn = "part #" . ($part_nr + 1); $rv .= add_filename_line($enc->decode($fn)); } $rv .= add_text_body($enc, $part, $part_nr, $full_pfx); $rv .= "\n" unless $rv =~ /\n\z/s; ++$part_nr; }); $mime->body_set(''); $rv; } sub add_filename_line { my ($fn) = @_; my $len = 72; my $pad = "-"; $len -= length($fn); $pad x= ($len/2) if ($len > 0); "$pad " . ascii_html($fn) . " $pad\n"; } my $LINK_RE = qr!\b((?:ftp|https?|nntp)://[@\w\+\&\?\.\%\;/#=-]+)!; sub linkify { # no newlines added here since it'd break the splitting we do # to fold quotes $_[0] =~ s!$LINK_RE!$1!g; } sub flush_quote { my ($quot, $n, $part_nr, $full_pfx, $final) = @_; if ($full_pfx) { if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) { # show quote inline my $rv = join("\n", map { linkify($_); $_ } @$quot); @$quot = (); return $rv . "\n"; } # show a short snippet of quoted text and link to full version: @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot; my $cur = join(' ', @$quot); @$quot = split(/\s+/, $cur); $cur = ''; do { my $tmp = shift(@$quot); my $len = length($tmp) + length($cur); if ($len > MAX_TRUNC_LEN) { @$quot = (); } else { $cur .= $tmp . ' '; } } while (@$quot && length($cur) < MAX_TRUNC_LEN); @$quot = (); $cur =~ s/ \z/ .../s; my $nr = ++$$n; "> [$cur]\n"; } else { # show everything in the full version with anchor from # short version (see above) my $nr = ++$$n; my $rv = ""; $rv .= join("\n", map { linkify($_); $_ } @$quot) . "\n"; @$quot = (); $rv; } } sub add_text_body { my ($enc, $part, $part_nr, $full_pfx) = @_; my $n = 0; my $nr = 0; my $s = $part->body; $part->body_set(''); $s = $enc->decode($s); $s = ascii_html($s); my @lines = split(/\n/, $s); $s = ''; my @quot; while (defined(my $cur = shift @lines)) { if ($cur !~ /^>/) { # show the previously buffered quote inline if (scalar @quot) { $s .= flush_quote(\@quot, \$n, $part_nr, $full_pfx, 0); } # regular line, OK linkify($cur); $s .= $cur; $s .= "\n"; } else { push @quot, $cur; } } $s .= flush_quote(\@quot, \$n, $part_nr, $full_pfx, 1) if scalar @quot; $s; } sub headers_to_html_header { my ($mime, $full_pfx, $srch) = @_; my $rv = ""; my @title; my $header_obj = $mime->header_obj; my $mid = $header_obj->header_raw('Message-ID'); $mid = PublicInbox::Hval->new_msgid($mid); my $mid_href = $mid->as_href; foreach my $h (qw(From To Cc Subject Date)) { my $v = $mime->header($h); defined($v) && length($v) or next; $v = PublicInbox::Hval->new_oneline($v); if ($h eq 'From') { my @from = Email::Address->parse($v->raw); $title[1] = ascii_html($from[0]->name); } elsif ($h eq 'Subject') { $title[0] = $v->as_html; if ($srch) { $rv .= "$h: "; $rv .= $v->as_html . "\n"; next; } } $rv .= "$h: " . $v->as_html . "\n"; } $rv .= 'Message-ID: <' . $mid->as_html . '> '; $mid_href = "../m/$mid_href" unless $full_pfx; $rv .= "(raw)\n"; my $irt = $header_obj->header_raw('In-Reply-To'); if (defined $irt) { my $v = PublicInbox::Hval->new_msgid($irt); my $html = $v->as_html; my $href = $v->as_href; $rv .= "In-Reply-To: <"; $rv .= "$html>\n"; } my $refs = $header_obj->header_raw('References'); if ($refs) { # avoid redundant URLs wasting bandwidth my %seen; $seen{mid_clean($irt)} = 1 if defined $irt; my @refs; my @raw_refs = ($refs =~ /<([^>]+)>/g); foreach my $ref (@raw_refs) { next if $seen{$ref}; $seen{$ref} = 1; push @refs, linkify_ref($ref); } if (@refs) { $rv .= 'References: '. join(' ', @refs) . "\n"; } } $rv .= "\n"; ("". join(' - ', @title) . '' . PRE_WRAP . $rv); } sub html_footer { my ($mime, $standalone, $full_pfx, $srch) = @_; my %cc; # everyone else my $to; # this is the From address foreach my $h (qw(From To Cc)) { my $v = $mime->header($h); defined($v) && length($v) or next; my @addrs = Email::Address->parse($v); foreach my $recip (@addrs) { my $address = $recip->address; my $dst = lc($address); $cc{$dst} ||= $address; $to ||= $dst; } } Email::Address->purge_cache if $standalone; my $subj = $mime->header('Subject') || ''; $subj = "Re: $subj" unless $subj =~ /\bRe:/; my $mid = $mime->header_obj->header_raw('Message-ID'); my $irt = uri_escape_utf8($mid); delete $cc{$to}; $to = uri_escape_utf8($to); $subj = uri_escape_utf8($subj); my $cc = uri_escape_utf8(join(',', sort values %cc)); my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj"; my $idx = $standalone ? " index" : ''; if ($idx && $srch) { $irt = $mime->header_obj->header_raw('In-Reply-To') || ''; $mid = mid_compressed(mid_clean($mid)); my $t_anchor = length $irt ? T_ANCHOR : ''; $idx = " ". "threadlink$idx"; my $res = $srch->get_followups($mid); if (my $c = $res->{count}) { $c = $c == 1 ? '1 followup' : "$c followups"; $idx .= "\n$c:\n"; $res->{srch} = $srch; thread_followups(\$idx, $mime, $res); } else { $idx .= "\n(no followups, yet)\n"; } if ($irt) { $irt = PublicInbox::Hval->new_msgid($irt); $irt = $irt->as_href; $irt = "parent "; } else { $irt = ' ' x length('parent '); } } else { $irt = ''; } "$irtreply' . $idx; } sub linkify_ref { my $v = PublicInbox::Hval->new_msgid($_[0]); my $html = $v->as_html; my $href = $v->as_href; "<$html>"; } sub anchor_for { my ($msgid) = @_; my $id = $msgid; if ($id !~ /\A[a-f0-9]{40}\z/) { $id = mid_compressed(mid_clean($id), 1); } 'm' . $id; } sub simple_dump { my ($dst, $root, $node, $level) = @_; # $root = [ Root Message-ID, \%seen, $srch ]; if (my $x = $node->message) { my $mid = $x->header('Message-ID'); if ($root->[0] ne $mid) { my $pfx = ' ' x $level; $$dst .= $pfx; my $s = $x->header('Subject'); my $h = $root->[2]->subject_path($s); if ($root->[1]->{$h}) { $s = ''; } else { $root->[1]->{$h} = 1; $s = PublicInbox::Hval->new($s); $s = $s->as_html; } my $m = PublicInbox::Hval->new_msgid($mid); my $f = PublicInbox::Hval->new($x->header('X-PI-From')); my $d = PublicInbox::Hval->new($x->header('X-PI-Date')); $m = $m->as_href . '.html'; $f = $f->as_html; $d = $d->as_html . ' UTC'; if (length($s) == 0) { $$dst .= "` $f @ $d\n"; } else { $$dst .= "` $s\n" . "$pfx by $f @ $d\n"; } } } simple_dump($dst, $root, $node->child, $level + 1) if $node->child; simple_dump($dst, $root, $node->next, $level) if $node->next; } sub thread_followups { my ($dst, $root, $res) = @_; my $msgs = load_results($res); require PublicInbox::Thread; $root->header_set('X-PI-TS', '0'); my $th = PublicInbox::Thread->new($root, @$msgs); $th->thread; $th->order(*PublicInbox::Thread::sort_ts); my $srch = $res->{srch}; my $subj = $srch->subject_path($root->header('Subject')); my %seen = ($subj => 1); $root = [ $root->header('Message-ID'), \%seen, $srch ]; simple_dump($dst, $root, $_, 0) for $th->rootset; } sub thread_html_head { my ($mime) = @_; my $s = PublicInbox::Hval->new_oneline($mime->header('Subject')); $s = $s->as_html; "$s"; } sub thread_entry { my ($dst, $git, $state, $node, $level) = @_; # $state = [ $search_res, $seen, undef, 0 (msg_nr) ]; # $seen is overloaded with 3 types of fields: # 1) "root_anchor" => anchor_for(Message-ID), # 2) seen subject hashes: sha1(subject) => 1 # 3) anchors hashes: "#$sha1_hex" (same as $seen in index_entry) if (my $mime = $node->message) { # lazy load the full message from mini_mime: my $path = mid2path(mid_clean($mime->header('Message-ID'))); $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) }; if ($mime) { if (length($$dst) == 0) { $$dst .= thread_html_head($mime); } $$dst .= index_entry(undef, $mime, $level, $state); } } my $cur; $cur = $node->child and thread_entry($dst, $git, $state, $cur, $level + 1); $cur = $node->next and thread_entry($dst, $git, $state, $cur, $level); } sub load_results { my ($res) = @_; [ map { $_->mini_mime } @{delete $res->{msgs}} ]; } sub msg_timestamp { my ($mime) = @_; my $ts = eval { str2time($mime->header('Date')) }; defined($ts) ? $ts : 0; } 1;