1 # Copyright (C) 2014-2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
4 # Used for displaying the HTML web interface.
5 # See Documentation/design_www.txt for this.
6 package PublicInbox::View;
9 use URI::Escape qw/uri_escape_utf8/;
10 use Date::Parse qw/str2time/;
11 use Encode::MIME::Header;
13 use PublicInbox::Hval qw/ascii_html/;
14 use PublicInbox::Linkify;
15 use PublicInbox::MID qw/mid_clean id_compress mid_mime/;
16 use PublicInbox::MsgIter;
17 use PublicInbox::Address;
18 use PublicInbox::WwwStream;
21 use constant INDENT => ' ';
22 use constant TCHILD => '` ';
23 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
25 # public functions: (unstable)
27 my ($ctx, $mime, $footer) = @_;
28 my $hdr = $mime->header_obj;
29 my $tip = _msg_html_prepare($hdr, $ctx);
30 PublicInbox::WwwStream->new($ctx, sub {
33 $tip . multipart_text_as_html($mime, '') .
36 # fake an EOF if generating the footer fails;
37 # we want to at least show the message if something
40 '<pre>' . html_footer($hdr, 1, $ctx) .
41 '</pre>' . msg_reply($ctx, $hdr)
49 # /$INBOX/$MESSAGE_ID/#R
52 my $se_url = 'https://git-htmldocs.bogomips.org/git-send-email.html';
54 my ($arg, $link) = mailto_arg_link($hdr);
55 push @$arg, '/path/to/YOUR_REPLY';
58 "You may reply publically to <a\nhref=#t>this message</a> via\n".
59 "plain-text email using any one of the following methods:\n\n" .
60 "* Save the following mbox file, import it into your mail client,\n" .
61 " and reply-to-all from there: <a\nhref=raw>mbox</a>\n\n" .
62 "* Reply to all the recipients using the <b>--to</b>, <b>--cc</b>,\n" .
63 " and <b>--in-reply-to</b> switches of git-send-email(1):\n\n" .
64 " git send-email \\\n " .
65 join(" \\\n ", @$arg ). "\n\n" .
66 qq( <a\nhref="$se_url">$se_url</a>\n\n) .
67 "* If your mail client supports setting the <b>In-Reply-To</b>" .
68 " header\n via mailto: links, try the " .
69 qq(<a\nhref="$link">mailto: link</a>\n) .
75 my $irt = $hdr->header_raw('In-Reply-To');
77 return mid_clean($irt) if (defined $irt);
79 my $refs = $hdr->header_raw('References');
80 if ($refs && $refs =~ /<([^>]+)>\s*\z/s) {
87 my ($hdr, $field) = @_;
88 my $val = $hdr->header($field) or return '';
89 ascii_html(join(', ', PublicInbox::Address::names($val)));
93 my ($nr, $singular, $plural) = @_;
94 return "0 $plural" if $nr == 0;
95 $nr == 1 ? "$nr $singular" : "$nr $plural";
98 # this is already inside a <pre>
100 my ($mime, $level, $state) = @_;
101 $state->{anchor_idx}++;
102 my $ctx = $state->{ctx};
103 my $srch = $ctx->{srch};
104 my $hdr = $mime->header_obj;
105 my $subj = $hdr->header('Subject');
107 my $mid_raw = mid_clean(mid_mime($mime));
108 my $id = id_compress($mid_raw);
110 my $mid = PublicInbox::Hval->new_msgid($mid_raw);
112 my $root_anchor = $state->{root_anchor} || '';
113 my $path = $root_anchor ? '../../' : '';
114 my $href = $mid->as_href;
115 my $irt = in_reply_to($hdr);
117 $subj = '<b>'.ascii_html($subj).'</b>';
118 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
120 my $ts = _msg_date($hdr);
121 my $rv = "<pre><a\nhref=#e$id\nid=$id_m>#</a> ";
123 my $mhref = $path.$href.'/';
124 my $from = _hdr_names($hdr, 'From');
125 $rv .= "\n- $from @ $ts UTC\n";
127 foreach my $f (qw(To Cc)) {
128 my $dst = _hdr_names($hdr, $f);
129 push @tocc, "$f: $dst" if $dst ne '';
131 $rv .= ' '.join('; +', @tocc) . "\n" if @tocc;
134 # scan through all parts, looking for displayable text
135 msg_iter($mime, sub { $rv .= add_text_body($mhref, $_[0]) });
136 $rv .= "\n<a\nhref=\"$mhref\"\n>permalink</a>" .
137 " / <a\nhref=\"${mhref}raw\">raw</a> / ";
138 my $mapping = $state->{mapping};
139 my $nr_c = $mapping->{$mid_raw} || 0;
142 $nr_s = ($mapping->{$irt} || 0) - 1;
143 $nr_s = 0 if $nr_s < 0;
144 $irt = anchor_for($irt);
145 $rv .= "<a\nhref=#$irt>#parent</a>,";
147 $rv .= 'root message:';
149 $nr_s = nr_to_s($nr_s, 'sibling', 'siblings');
150 $nr_c = nr_to_s($nr_c, 'reply', 'replies');
151 $rv .= " <a\nhref=#r$id\nid=e$id>$nr_s, $nr_c</a>";
152 $rv .= " / <a\nhref=\"${mhref}#R\">reply</a>";
154 if (my $pct = $state->{pct}) { # used by SearchView.pm
155 $rv .= " [relevance $pct->{$mid_raw}%]";
157 $state->{fh}->write($rv .= "\n</pre>"); # '\n' for lynx
161 my ($ctx, $foot, $srch) = @_;
162 # $_[0] in sub is the Plack callback
163 sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
167 my ($th, $state, $cb) = @_;
168 my @q = map { (0, $_) } $th->rootset;
170 my $level = shift @q;
171 my $node = shift @q or next;
172 $cb->($state, $level, $node);
173 unshift @q, $level+1, $node->child, $level, $node->next;
178 my ($state, $level, $node) = @_;
179 my $parent = $node->parent;
181 my $mid = $parent->messageid;
182 my $m = $state->{mapping};
186 skel_dump($state, $level, $node);
189 # only private functions below.
191 sub emit_thread_html {
192 my ($res, $ctx, $foot, $srch) = @_;
193 my $mid = $ctx->{mid};
194 my $sres = $srch->get_thread($mid, { asc => 1 });
195 my $msgs = load_results($sres);
196 my $nr = $sres->{total};
197 return missing_thread($res, $ctx) if $nr == 0;
204 mapping => {}, # mid -> reply count
208 root_anchor => anchor_for($mid),
210 srch => $ctx->{srch},
214 walk_thread(thread_results($msgs), $state, *pre_thread);
216 thread_entry($state, $_, 0) for @$msgs;
218 # there could be a race due to a message being deleted in git
219 # but still being in the Xapian index:
220 my $fh = delete $state->{fh} or return missing_thread($res, $ctx);
222 my $next = @$msgs == 1 ? 'only message in thread' : 'end of thread';
223 $next .= ", back to <a\nhref=\"../../\">index</a>";
224 $next .= "\n<a\nid=t>$nr+ messages in thread:</a> (download: ";
225 $next .= "<a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
226 $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
228 $fh->write('<hr /><pre>' . $next . "\n\n".
229 $foot . '</pre></body></html>');
233 sub multipart_text_as_html {
234 my ($mime, $upfx) = @_;
237 # scan through all parts, looking for displayable text
238 msg_iter($mime, sub {
240 $rv .= add_text_body($upfx, $p);
246 my ($s, $l, $quot) = @_;
248 # show everything in the full version with anchor from
249 # short version (see above)
250 my $rv = $l->linkify_1(join('', @$quot));
253 # we use a <span> here to allow users to specify their own
254 # color for quoted text
255 $rv = $l->linkify_2(ascii_html($rv));
256 $$s .= qq(<span\nclass="q">) . $rv . '</span>'
259 sub attach_link ($$$$) {
260 my ($upfx, $ct, $p, $fn) = @_;
261 my ($part, $depth, @idx) = @$p;
262 my $nl = $idx[-1] > 1 ? "\n" : '';
263 my $idx = join('.', @idx);
264 my $size = bytes::length($part->body);
265 $ct ||= 'text/plain';
266 $ct =~ s/;.*//; # no attributes
267 $ct = ascii_html($ct);
268 my $desc = $part->header('Content-Description');
269 $desc = $fn unless defined $desc;
270 $desc = '' unless defined $desc;
272 if (defined $fn && $fn =~ /\A[[:alnum:]][\w\.-]+[[:alnum:]]\z/) {
274 } elsif ($ct eq 'text/plain') {
279 my @ret = qq($nl<a\nhref="$upfx$idx-$sfn">[-- Attachment #$idx: );
280 my $ts = "Type: $ct, Size: $size bytes";
281 push(@ret, ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]");
282 join('', @ret, "</a>\n");
286 my ($upfx, $p) = @_; # from msg_iter: [ Email::MIME, depth, @idx ]
287 my ($part, $depth, @idx) = @$p;
288 my $ct = $part->content_type;
289 my $fn = $part->filename;
291 if (defined $ct && $ct =~ m!\btext/x?html\b!i) {
292 return attach_link($upfx, $ct, $p, $fn);
295 my $s = eval { $part->body_str };
297 # badly-encoded message? tell the world about it!
298 return attach_link($upfx, $ct, $p, $fn) if $@;
300 my @lines = split(/^/m, $s);
302 if (defined($fn) || $depth > 0) {
303 $s .= attach_link($upfx, $ct, $p, $fn);
307 my $l = PublicInbox::Linkify->new;
308 while (defined(my $cur = shift @lines)) {
310 # show the previously buffered quote inline
311 flush_quote(\$s, $l, \@quot) if @quot;
314 $cur = $l->linkify_1($cur);
315 $cur = ascii_html($cur);
316 $s .= $l->linkify_2($cur);
325 flush_quote(\$s, $l, \@quot);
327 $s =~ s/[ \t]+$//sgm; # kill per-line trailing whitespace
328 $s =~ s/\A\n+//s; # kill leading blank lines
329 $s =~ s/\s+\z//s; # kill all trailing spaces
333 sub _msg_html_prepare {
334 my ($hdr, $ctx) = @_;
335 my $srch = $ctx->{srch} if $ctx;
337 my $rv = "<pre\nid=b>"; # anchor for body start
340 $ctx->{-upfx} = '../';
343 my $mid = $hdr->header_raw('Message-ID');
344 $mid = PublicInbox::Hval->new_msgid($mid);
345 foreach my $h (qw(From To Cc Subject Date)) {
346 my $v = $hdr->header($h);
347 defined($v) && ($v ne '') or next;
348 $v = PublicInbox::Hval->new($v);
351 my @n = PublicInbox::Address::names($v->raw);
352 $title[1] = ascii_html(join(', ', @n));
353 } elsif ($h eq 'Subject') {
354 $title[0] = $v->as_html;
356 $rv .= qq($h: <a\nhref="#r"\nid=t>);
357 $rv .= $v->as_html . "</a>\n";
362 $v =~ s/(\@[^,]+,) /$1\n\t/g if ($h eq 'Cc' || $h eq 'To');
366 $title[0] ||= '(no subject)';
367 $ctx->{-title_html} = join(' - ', @title);
368 $rv .= 'Message-ID: <' . $mid->as_html . '> ';
369 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
370 $rv .= _parent_headers($hdr, $srch);
375 my ($dst, $ctx, $hdr, $tpfx) = @_;
376 my $srch = $ctx->{srch};
377 my $mid = mid_clean($hdr->header_raw('Message-ID'));
378 my $sres = $srch->get_thread($mid);
379 my $nr = $sres->{total};
380 my $expand = qq(<a\nhref="${tpfx}t/#u">expand</a> ) .
381 qq(/ <a\nhref="${tpfx}t.mbox.gz">mbox.gz</a> ) .
382 qq(/ <a\nhref="${tpfx}t.atom">Atom feed</a>);
384 my $parent = in_reply_to($hdr);
386 if (defined $parent) {
387 $$dst .= "($expand)\n ";
388 $$dst .= ghost_parent("$tpfx../", $parent) . "\n";
390 $$dst .= "[no followups, yet] ($expand)\n";
392 $ctx->{next_msg} = undef;
393 $ctx->{parent_msg} = $parent;
397 $$dst .= "$nr+ messages in thread ($expand";
398 $$dst .= qq! / <a\nhref="#b">[top]</a>)\n!;
400 my $subj = $srch->subject_path($hdr->header('Subject'));
402 seen => { $subj => 1 },
410 walk_thread(thread_results(load_results($sres)), $state, *skel_dump);
411 $ctx->{next_msg} = $state->{next_msg};
412 $ctx->{parent_msg} = $parent;
415 sub _parent_headers {
416 my ($hdr, $srch) = @_;
419 my $irt = in_reply_to($hdr);
421 my $v = PublicInbox::Hval->new_msgid($irt, 1);
422 my $html = $v->as_html;
423 my $href = $v->as_href;
424 $rv .= "In-Reply-To: <";
425 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
428 # do not display References: if search is present,
429 # we show the thread skeleton at the bottom, instead.
432 my $refs = $hdr->header_raw('References');
434 # avoid redundant URLs wasting bandwidth
436 $seen{$irt} = 1 if defined $irt;
438 my @raw_refs = ($refs =~ /<([^>]+)>/g);
439 foreach my $ref (@raw_refs) {
442 push @refs, linkify_ref_nosrch($ref);
446 $rv .= 'References: '. join("\n\t", @refs) . "\n";
452 sub squote_maybe ($) {
454 if ($val =~ m{([^\w@\./,\%\+\-])}) {
455 $val =~ s/(['!])/'\\$1'/g; # '!' for csh
461 sub mailto_arg_link {
463 my %cc; # everyone else
464 my $to; # this is the From address
466 foreach my $h (qw(From To Cc)) {
467 my $v = $hdr->header($h);
468 defined($v) && ($v ne '') or next;
469 my @addrs = PublicInbox::Address::emails($v);
470 foreach my $address (@addrs) {
471 my $dst = lc($address);
472 $cc{$dst} ||= $address;
478 my $subj = $hdr->header('Subject') || '';
479 $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
480 my $mid = $hdr->header_raw('Message-ID');
481 push @arg, '--in-reply-to='.ascii_html(squote_maybe(mid_clean($mid)));
482 my $irt = uri_escape_utf8($mid);
484 push @arg, '--to=' . ascii_html($to);
485 $to = uri_escape_utf8($to);
486 $subj = uri_escape_utf8($subj);
487 my $cc = join(',', sort values %cc);
488 push @arg, '--cc=' . ascii_html($cc);
489 $cc = uri_escape_utf8($cc);
490 my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
493 (\@arg, ascii_html($href));
497 my ($hdr, $standalone, $ctx, $rhref) = @_;
499 my $srch = $ctx->{srch} if $ctx;
502 my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
506 thread_skel(\$idx, $ctx, $hdr, $tpfx);
507 my $p = $ctx->{parent_msg};
508 my $next = $ctx->{next_msg};
510 $p = PublicInbox::Hval->new_msgid($p);
512 $irt = "<a\nhref=\"$upfx$p/\"\nrel=prev>parent</a> ";
514 $irt = ' ' x length('parent ');
517 my $n = PublicInbox::Hval->new_msgid($next)->as_href;
518 $irt .= "<a\nhref=\"$upfx$n/\"\nrel=next>next</a> ";
520 $irt .= ' ' x length('next ');
526 $irt .= qq(<a\nhref="$rhref">reply</a>);
530 sub linkify_ref_nosrch {
531 my $v = PublicInbox::Hval->new_msgid($_[0], 1);
532 my $html = $v->as_html;
533 my $href = $v->as_href;
534 "<<a\nhref=\"../$href/\">$html</a>>";
539 'm' . id_compress($msgid, 1);
542 sub thread_html_head {
543 my ($hdr, $state) = @_;
544 my $res = delete $state->{res} or die "BUG: no Plack callback in {res}";
545 my $fh = $res->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
548 my $s = ascii_html($hdr->header('Subject'));
549 $fh->write("<html><head><title>$s</title>".
550 qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
551 qq!href="../t.atom"\ntype="application/atom+xml"/>! .
552 PublicInbox::Hval::STYLE .
557 my ($upfx, $mid) = @_;
558 # 'subject dummy' is used internally by Mail::Thread
559 return '[no common parent]' if ($mid eq 'subject dummy');
561 $mid = PublicInbox::Hval->new_msgid($mid);
562 my $href = $mid->as_href;
563 my $html = $mid->as_html;
564 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
568 my ($state, $mime, $level) = @_;
570 # lazy load the full message from mini_mime:
572 my $mid = mid_clean(mid_mime($mime));
573 $state->{ctx}->{-inbox}->msg_by_mid($mid);
575 $mime = Email::MIME->new($mime);
577 thread_html_head($mime, $state) if $state->{anchor_idx} == 0;
578 index_entry($mime, $level, $state);
584 INDENT x ($level - 1);
590 [ map { $_->mini_mime } @{delete $sres->{msgs}} ];
595 my $ts = eval { str2time($hdr->header('Date')) };
596 defined($ts) ? $ts : 0;
601 require PublicInbox::Thread;
602 my $th = PublicInbox::Thread->new(@$msgs);
604 $th->order(*sort_ts);
609 my ($res, $ctx) = @_;
610 require PublicInbox::ExtMsg;
612 $res->(PublicInbox::ExtMsg::ext_msg($ctx))
617 my $ts = $hdr->header('X-PI-TS') || msg_timestamp($hdr);
621 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
624 my ($state, $hdr, $level) = @_;
626 my $dst = $state->{dst};
627 my $cur = $state->{cur};
628 my $mid = mid_clean($hdr->header_raw('Message-ID'));
629 my $f = ascii_html($hdr->header('X-PI-From'));
630 my $d = _msg_date($hdr);
631 my $pfx = "$d " . indent_for($level) . th_pfx($level);
633 $state->{first_level} ||= $level;
635 if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
636 $state->{prev_attr} = $attr;
640 $state->{prev_level} = $level;
644 delete $state->{cur};
645 $$dst .= "$pfx<b><a\nid=r\nhref=\"#t\">".
646 "$attr [this message]</a></b>\n";
651 $state->{next_msg} ||= $mid;
654 # Subject is never undef, this mail was loaded from
655 # our Xapian which would've resulted in '' if it were
656 # really missing (and Filter rejects empty subjects)
657 my $s = $hdr->header('Subject');
658 my $h = $state->{srch}->subject_path($s);
659 if ($state->{seen}->{$h}) {
662 $state->{seen}->{$h} = 1;
663 $s = PublicInbox::Hval->new($s);
666 my $m = PublicInbox::Hval->new_msgid($mid);
668 if ($state->{mapping}) {
669 $id = id_compress($mid, 1);
673 $m = $state->{upfx}.$m->as_href.'/';
675 $$dst .= "$pfx<a\nhref=\"$m\"$id>";
676 $$dst .= defined($s) ? "$s</a> $f\n" : "$f</a>\n";
680 my ($state, $level, $node) = @_;
681 if (my $mime = $node->message) {
682 _skel_header($state, $mime->header_obj, $level);
684 my $mid = $node->messageid;
685 my $dst = $state->{dst};
686 if ($mid eq 'subject dummy') {
687 $$dst .= "\t[no common parent]\n";
690 if ($state->{pct}) { # search result
691 $$dst .= ' [irrelevant] ';
693 $$dst .= ' [not found] ';
695 $$dst .= indent_for($level) . th_pfx($level);
696 my $upfx = $state->{upfx};
698 if ($state->{mapping}) { # thread index view
699 $id = "\nid=".anchor_for($mid);
701 $mid = PublicInbox::Hval->new_msgid($mid);
702 my $href = $upfx . $mid->as_href . '/';
703 my $html = $mid->as_html;
704 $$dst .= qq{<<a\nhref="$href"$id>$html</a>>\n};
710 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
711 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
715 sub _tryload_ghost ($$) {
716 my ($srch, $mid) = @_;
717 my $smsg = $srch->lookup_mail($mid) or return;
721 # accumulate recent topics if search is supported
722 # returns 1 if done, undef if not
724 my ($state, $level, $node) = @_;
725 my $srch = $state->{srch};
726 my $mid = $node->messageid;
727 my $x = $node->message || _tryload_ghost($srch, $mid);
731 $subj = $x->header('Subject');
732 $subj = $srch->subject_normalized($subj);
733 $ts = $x->header('X-PI-TS');
734 } else { # ghost message, do not bump level
738 if (++$state->{subjs}->{$subj} == 1) {
739 push @{$state->{order}}, [ $level, $subj ];
741 my $exist = $state->{latest}->{$subj};
742 if (!$exist || $exist->[1] < $ts) {
743 $state->{latest}->{$subj} = [ $mid, $ts ];
749 my $order = $state->{order};
750 my $subjs = $state->{subjs};
751 my $latest = $state->{latest};
752 my $fh = $state->{fh};
753 return $fh->write("\n[No topics in range]</pre>") unless scalar @$order;
759 while (defined(my $info = shift @$order)) {
760 my ($level, $subj) = @$info;
761 my $n = delete $subjs->{$subj};
762 my ($mid, $ts) = @{delete $latest->{$subj}};
763 $mid = PublicInbox::Hval->new_msgid($mid)->as_href;
764 $pfx = indent_for($level);
765 my $nl = $level == $prev ? "\n" : '';
770 $cur ||= [ $ts, '' ];
771 $cur->[0] = $ts if $ts > $cur->[0];
772 $cur->[1] .= $nl . $pfx . th_pfx($level);
773 if ($ts == -666) { # ghost
774 $cur->[1] .= ghost_parent('', $mid) . "\n";
775 next; # child will have mbox / atom link
778 $subj = PublicInbox::Hval->new($subj)->as_html;
779 $cur->[1] .= "<a\nhref=\"$mid/t/#u\"><b>$subj</b></a>\n";
781 my $attr = " $ts UTC";
783 # $n isn't the total number of posts on the topic,
784 # just the number of posts in the current results window
785 $n = $n == 1 ? '' : " ($n+ messages)";
787 if ($level == 0 || $attr ne $prev_attr) {
788 my $mbox = qq(<a\nhref="$mid/t.mbox.gz">mbox.gz</a>);
789 my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
790 $pfx .= INDENT if $level > 0;
791 $cur->[1] .= $pfx . $attr . $n . " - $mbox / $atom\n";
795 push @recent, $cur if $cur;
796 @recent = map { $_->[1] } sort { $b->[0] <=> $a->[0] } @recent;
797 $fh->write(join('', @recent) . '</pre>');
800 sub emit_index_topics {
802 my ($off) = (($state->{ctx}->{cgi}->param('o') || '0') =~ /(\d+)/);
803 $state->{order} = [];
804 $state->{subjs} = {};
805 $state->{latest} = {};
807 my %opts = ( offset => $off, limit => $max * 4 );
808 while (scalar @{$state->{order}} < $max) {
809 my $sres = $state->{srch}->query('', \%opts);
810 my $nr = scalar @{$sres->{msgs}} or last;
811 $sres = load_results($sres);
812 walk_thread(thread_results($sres), $state, *add_topic);
813 $opts{offset} += $nr;