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, $state) = @_;
101 my $ctx = $state->{ctx};
102 my $srch = $ctx->{srch};
103 my $hdr = $mime->header_obj;
104 my $subj = $hdr->header('Subject');
106 my $mid_raw = mid_clean(mid_mime($mime));
107 my $id = id_compress($mid_raw);
109 my $mid = PublicInbox::Hval->new_msgid($mid_raw);
111 my $root_anchor = $state->{root_anchor} || '';
112 my $path = $root_anchor ? '../../' : '';
113 my $href = $mid->as_href;
114 my $irt = in_reply_to($hdr);
116 $subj = '<b>'.ascii_html($subj).'</b>';
117 $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
119 my $ts = _msg_date($hdr);
120 my $rv = "<a\nhref=#e$id\nid=$id_m>#</a> ";
122 my $mhref = $path.$href.'/';
123 my $from = _hdr_names($hdr, 'From');
124 $rv .= "\n- $from @ $ts UTC\n";
126 foreach my $f (qw(To Cc)) {
127 my $dst = _hdr_names($hdr, $f);
128 push @tocc, "$f: $dst" if $dst ne '';
130 $rv .= ' '.join('; +', @tocc) . "\n" if @tocc;
133 # scan through all parts, looking for displayable text
134 msg_iter($mime, sub { $rv .= add_text_body($mhref, $_[0]) });
135 $rv .= "\n<a\nhref=\"$mhref\"\n>permalink</a>" .
136 " / <a\nhref=\"${mhref}raw\">raw</a> / ";
137 my $mapping = $state->{mapping};
138 my $nr_c = $mapping->{$mid_raw} || 0;
141 $nr_s = ($mapping->{$irt} || 0) - 1;
142 $nr_s = 0 if $nr_s < 0;
143 $irt = anchor_for($irt);
144 $rv .= "<a\nhref=#$irt>#parent</a>,";
146 $rv .= 'root message:';
148 $nr_s = nr_to_s($nr_s, 'sibling', 'siblings');
149 $nr_c = nr_to_s($nr_c, 'reply', 'replies');
150 $rv .= " <a\nhref=#r$id\nid=e$id>$nr_s, $nr_c</a>";
151 $rv .= " / <a\nhref=\"${mhref}#R\">reply</a>";
153 if (my $pct = $state->{pct}) { # used by SearchView.pm
154 $rv .= " [relevance $pct->{$mid_raw}%]";
160 my ($th, $state, $cb) = @_;
161 my @q = map { (0, $_) } $th->rootset;
163 my $level = shift @q;
164 my $node = shift @q or next;
165 $cb->($state, $level, $node);
166 unshift @q, $level+1, $node->child, $level, $node->next;
171 my ($state, $level, $node) = @_;
172 my $parent = $node->parent;
174 my $mid = $parent->messageid;
175 my $m = $state->{mapping};
179 skel_dump($state, $level, $node);
184 my $mid = $ctx->{mid};
185 my $sres = $ctx->{srch}->get_thread($mid, { asc => 1 });
186 my $msgs = load_results($sres);
187 my $nr = $sres->{total};
188 return missing_thread($ctx) if $nr == 0;
189 my $skel = '</pre><hr /><pre>';
190 $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
191 $skel .= ", back to <a\nhref=\"../../\">index</a>";
192 $skel .= "\n<a\nid=t>$nr+ messages in thread:</a> (download: ";
193 $skel .= "<a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
194 $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
199 mapping => {}, # mid -> reply count
202 root_anchor => anchor_for($mid),
204 srch => $ctx->{srch},
208 walk_thread(thread_results($msgs), $state, *pre_thread);
210 # lazy load the full message from mini_mime:
211 my $inbox = $ctx->{-inbox};
213 while ($mime = shift @$msgs) {
214 $mime = $inbox->msg_by_mid(mid_clean(mid_mime($mime))) and last;
216 $mime = Email::MIME->new($mime);
217 $ctx->{-upfx} = '../../';
218 $ctx->{-title_html} = ascii_html($mime->header('Subject'));
219 $ctx->{-html_tip} = '<pre>'.index_entry($mime, $state);
221 my $body = PublicInbox::WwwStream->new($ctx, sub {
223 while ($mime = shift @$msgs) {
224 $mid = mid_clean(mid_mime($mime));
225 $mime = $inbox->msg_by_mid($mid) and last;
227 return index_entry(Email::MIME->new($mime), $state) if $mime;
231 [ 200, ['Content-Type', 'text/html; charset=UTF-8'], $body ];
234 sub multipart_text_as_html {
235 my ($mime, $upfx) = @_;
238 # scan through all parts, looking for displayable text
239 msg_iter($mime, sub {
241 $rv .= add_text_body($upfx, $p);
247 my ($s, $l, $quot) = @_;
249 # show everything in the full version with anchor from
250 # short version (see above)
251 my $rv = $l->linkify_1(join('', @$quot));
254 # we use a <span> here to allow users to specify their own
255 # color for quoted text
256 $rv = $l->linkify_2(ascii_html($rv));
257 $$s .= qq(<span\nclass="q">) . $rv . '</span>'
260 sub attach_link ($$$$) {
261 my ($upfx, $ct, $p, $fn) = @_;
262 my ($part, $depth, @idx) = @$p;
263 my $nl = $idx[-1] > 1 ? "\n" : '';
264 my $idx = join('.', @idx);
265 my $size = bytes::length($part->body);
266 $ct ||= 'text/plain';
267 $ct =~ s/;.*//; # no attributes
268 $ct = ascii_html($ct);
269 my $desc = $part->header('Content-Description');
270 $desc = $fn unless defined $desc;
271 $desc = '' unless defined $desc;
273 if (defined $fn && $fn =~ /\A[[:alnum:]][\w\.-]+[[:alnum:]]\z/) {
275 } elsif ($ct eq 'text/plain') {
280 my @ret = qq($nl<a\nhref="$upfx$idx-$sfn">[-- Attachment #$idx: );
281 my $ts = "Type: $ct, Size: $size bytes";
282 push(@ret, ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]");
283 join('', @ret, "</a>\n");
287 my ($upfx, $p) = @_; # from msg_iter: [ Email::MIME, depth, @idx ]
288 my ($part, $depth, @idx) = @$p;
289 my $ct = $part->content_type;
290 my $fn = $part->filename;
292 if (defined $ct && $ct =~ m!\btext/x?html\b!i) {
293 return attach_link($upfx, $ct, $p, $fn);
296 my $s = eval { $part->body_str };
298 # badly-encoded message? tell the world about it!
299 return attach_link($upfx, $ct, $p, $fn) if $@;
301 my @lines = split(/^/m, $s);
303 if (defined($fn) || $depth > 0) {
304 $s .= attach_link($upfx, $ct, $p, $fn);
308 my $l = PublicInbox::Linkify->new;
309 while (defined(my $cur = shift @lines)) {
311 # show the previously buffered quote inline
312 flush_quote(\$s, $l, \@quot) if @quot;
315 $cur = $l->linkify_1($cur);
316 $cur = ascii_html($cur);
317 $s .= $l->linkify_2($cur);
326 flush_quote(\$s, $l, \@quot);
328 $s =~ s/[ \t]+$//sgm; # kill per-line trailing whitespace
329 $s =~ s/\A\n+//s; # kill leading blank lines
330 $s =~ s/\s+\z//s; # kill all trailing spaces
334 sub _msg_html_prepare {
335 my ($hdr, $ctx) = @_;
336 my $srch = $ctx->{srch} if $ctx;
338 my $rv = "<pre\nid=b>"; # anchor for body start
341 $ctx->{-upfx} = '../';
344 my $mid = $hdr->header_raw('Message-ID');
345 $mid = PublicInbox::Hval->new_msgid($mid);
346 foreach my $h (qw(From To Cc Subject Date)) {
347 my $v = $hdr->header($h);
348 defined($v) && ($v ne '') or next;
349 $v = PublicInbox::Hval->new($v);
352 my @n = PublicInbox::Address::names($v->raw);
353 $title[1] = ascii_html(join(', ', @n));
354 } elsif ($h eq 'Subject') {
355 $title[0] = $v->as_html;
357 $rv .= qq($h: <a\nhref="#r"\nid=t>);
358 $rv .= $v->as_html . "</a>\n";
363 $v =~ s/(\@[^,]+,) /$1\n\t/g if ($h eq 'Cc' || $h eq 'To');
367 $title[0] ||= '(no subject)';
368 $ctx->{-title_html} = join(' - ', @title);
369 $rv .= 'Message-ID: <' . $mid->as_html . '> ';
370 $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
371 $rv .= _parent_headers($hdr, $srch);
376 my ($dst, $ctx, $hdr, $tpfx) = @_;
377 my $srch = $ctx->{srch};
378 my $mid = mid_clean($hdr->header_raw('Message-ID'));
379 my $sres = $srch->get_thread($mid);
380 my $nr = $sres->{total};
381 my $expand = qq(<a\nhref="${tpfx}t/#u">expand</a> ) .
382 qq(/ <a\nhref="${tpfx}t.mbox.gz">mbox.gz</a> ) .
383 qq(/ <a\nhref="${tpfx}t.atom">Atom feed</a>);
385 my $parent = in_reply_to($hdr);
387 if (defined $parent) {
388 $$dst .= "($expand)\n ";
389 $$dst .= ghost_parent("$tpfx../", $parent) . "\n";
391 $$dst .= "[no followups, yet] ($expand)\n";
393 $ctx->{next_msg} = undef;
394 $ctx->{parent_msg} = $parent;
398 $$dst .= "$nr+ messages in thread ($expand";
399 $$dst .= qq! / <a\nhref="#b">[top]</a>)\n!;
401 my $subj = $srch->subject_path($hdr->header('Subject'));
403 seen => { $subj => 1 },
411 walk_thread(thread_results(load_results($sres)), $state, *skel_dump);
412 $ctx->{next_msg} = $state->{next_msg};
413 $ctx->{parent_msg} = $parent;
416 sub _parent_headers {
417 my ($hdr, $srch) = @_;
420 my $irt = in_reply_to($hdr);
422 my $v = PublicInbox::Hval->new_msgid($irt, 1);
423 my $html = $v->as_html;
424 my $href = $v->as_href;
425 $rv .= "In-Reply-To: <";
426 $rv .= "<a\nhref=\"../$href/\">$html</a>>\n";
429 # do not display References: if search is present,
430 # we show the thread skeleton at the bottom, instead.
433 my $refs = $hdr->header_raw('References');
435 # avoid redundant URLs wasting bandwidth
437 $seen{$irt} = 1 if defined $irt;
439 my @raw_refs = ($refs =~ /<([^>]+)>/g);
440 foreach my $ref (@raw_refs) {
443 push @refs, linkify_ref_nosrch($ref);
447 $rv .= 'References: '. join("\n\t", @refs) . "\n";
453 sub squote_maybe ($) {
455 if ($val =~ m{([^\w@\./,\%\+\-])}) {
456 $val =~ s/(['!])/'\\$1'/g; # '!' for csh
462 sub mailto_arg_link {
464 my %cc; # everyone else
465 my $to; # this is the From address
467 foreach my $h (qw(From To Cc)) {
468 my $v = $hdr->header($h);
469 defined($v) && ($v ne '') or next;
470 my @addrs = PublicInbox::Address::emails($v);
471 foreach my $address (@addrs) {
472 my $dst = lc($address);
473 $cc{$dst} ||= $address;
479 my $subj = $hdr->header('Subject') || '';
480 $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
481 my $mid = $hdr->header_raw('Message-ID');
482 push @arg, '--in-reply-to='.ascii_html(squote_maybe(mid_clean($mid)));
483 my $irt = uri_escape_utf8($mid);
485 push @arg, '--to=' . ascii_html($to);
486 $to = uri_escape_utf8($to);
487 $subj = uri_escape_utf8($subj);
488 my $cc = join(',', sort values %cc);
489 push @arg, '--cc=' . ascii_html($cc);
490 $cc = uri_escape_utf8($cc);
491 my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
494 (\@arg, ascii_html($href));
498 my ($hdr, $standalone, $ctx, $rhref) = @_;
500 my $srch = $ctx->{srch} if $ctx;
503 my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
507 thread_skel(\$idx, $ctx, $hdr, $tpfx);
508 my $p = $ctx->{parent_msg};
509 my $next = $ctx->{next_msg};
511 $p = PublicInbox::Hval->new_msgid($p);
513 $irt = "<a\nhref=\"$upfx$p/\"\nrel=prev>parent</a> ";
515 $irt = ' ' x length('parent ');
518 my $n = PublicInbox::Hval->new_msgid($next)->as_href;
519 $irt .= "<a\nhref=\"$upfx$n/\"\nrel=next>next</a> ";
521 $irt .= ' ' x length('next ');
527 $irt .= qq(<a\nhref="$rhref">reply</a>);
531 sub linkify_ref_nosrch {
532 my $v = PublicInbox::Hval->new_msgid($_[0], 1);
533 my $html = $v->as_html;
534 my $href = $v->as_href;
535 "<<a\nhref=\"../$href/\">$html</a>>";
540 'm' . id_compress($msgid, 1);
544 my ($upfx, $mid) = @_;
545 # 'subject dummy' is used internally by Mail::Thread
546 return '[no common parent]' if ($mid eq 'subject dummy');
548 $mid = PublicInbox::Hval->new_msgid($mid);
549 my $href = $mid->as_href;
550 my $html = $mid->as_html;
551 qq{[parent not found: <<a\nhref="$upfx$href/">$html</a>>]};
556 INDENT x ($level - 1);
562 [ map { $_->mini_mime } @{delete $sres->{msgs}} ];
567 my $ts = eval { str2time($hdr->header('Date')) };
568 defined($ts) ? $ts : 0;
573 require PublicInbox::Thread;
574 my $th = PublicInbox::Thread->new(@$msgs);
576 $th->order(*sort_ts);
582 require PublicInbox::ExtMsg;
583 PublicInbox::ExtMsg::ext_msg($ctx);
588 my $ts = $hdr->header('X-PI-TS') || msg_timestamp($hdr);
592 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
595 my ($state, $hdr, $level) = @_;
597 my $dst = $state->{dst};
598 my $cur = $state->{cur};
599 my $mid = mid_clean($hdr->header_raw('Message-ID'));
600 my $f = ascii_html($hdr->header('X-PI-From'));
601 my $d = _msg_date($hdr);
602 my $pfx = "$d " . indent_for($level) . th_pfx($level);
604 $state->{first_level} ||= $level;
606 if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
607 $state->{prev_attr} = $attr;
611 $state->{prev_level} = $level;
615 delete $state->{cur};
616 $$dst .= "$pfx<b><a\nid=r\nhref=\"#t\">".
617 "$attr [this message]</a></b>\n";
622 $state->{next_msg} ||= $mid;
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 = $hdr->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);
639 if ($state->{mapping}) {
640 $id = id_compress($mid, 1);
644 $m = $state->{upfx}.$m->as_href.'/';
646 $$dst .= "$pfx<a\nhref=\"$m\"$id>";
647 $$dst .= defined($s) ? "$s</a> $f\n" : "$f</a>\n";
651 my ($state, $level, $node) = @_;
652 if (my $mime = $node->message) {
653 _skel_header($state, $mime->header_obj, $level);
655 my $mid = $node->messageid;
656 my $dst = $state->{dst};
657 if ($mid eq 'subject dummy') {
658 $$dst .= "\t[no common parent]\n";
661 if ($state->{pct}) { # search result
662 $$dst .= ' [irrelevant] ';
664 $$dst .= ' [not found] ';
666 $$dst .= indent_for($level) . th_pfx($level);
667 my $upfx = $state->{upfx};
669 if ($state->{mapping}) { # thread index view
670 $id = "\nid=".anchor_for($mid);
672 $mid = PublicInbox::Hval->new_msgid($mid);
673 my $href = $upfx . $mid->as_href . '/';
674 my $html = $mid->as_html;
675 $$dst .= qq{<<a\nhref="$href"$id>$html</a>>\n};
681 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
682 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
686 sub _tryload_ghost ($$) {
687 my ($srch, $mid) = @_;
688 my $smsg = $srch->lookup_mail($mid) or return;
692 # accumulate recent topics if search is supported
693 # returns 1 if done, undef if not
695 my ($state, $level, $node) = @_;
696 my $srch = $state->{srch};
697 my $mid = $node->messageid;
698 my $x = $node->message || _tryload_ghost($srch, $mid);
702 $subj = $x->header('Subject');
703 $subj = $srch->subject_normalized($subj);
704 $ts = $x->header('X-PI-TS');
705 } else { # ghost message, do not bump level
709 if (++$state->{subjs}->{$subj} == 1) {
710 push @{$state->{order}}, [ $level, $subj ];
712 my $exist = $state->{latest}->{$subj};
713 if (!$exist || $exist->[1] < $ts) {
714 $state->{latest}->{$subj} = [ $mid, $ts ];
720 my $order = $state->{order};
721 my $subjs = $state->{subjs};
722 my $latest = $state->{latest};
723 my $fh = $state->{fh};
724 return $fh->write("\n[No topics in range]</pre>") unless scalar @$order;
730 while (defined(my $info = shift @$order)) {
731 my ($level, $subj) = @$info;
732 my $n = delete $subjs->{$subj};
733 my ($mid, $ts) = @{delete $latest->{$subj}};
734 $mid = PublicInbox::Hval->new_msgid($mid)->as_href;
735 $pfx = indent_for($level);
736 my $nl = $level == $prev ? "\n" : '';
741 $cur ||= [ $ts, '' ];
742 $cur->[0] = $ts if $ts > $cur->[0];
743 $cur->[1] .= $nl . $pfx . th_pfx($level);
744 if ($ts == -666) { # ghost
745 $cur->[1] .= ghost_parent('', $mid) . "\n";
746 next; # child will have mbox / atom link
749 $subj = PublicInbox::Hval->new($subj)->as_html;
750 $cur->[1] .= "<a\nhref=\"$mid/t/#u\"><b>$subj</b></a>\n";
752 my $attr = " $ts UTC";
754 # $n isn't the total number of posts on the topic,
755 # just the number of posts in the current results window
756 $n = $n == 1 ? '' : " ($n+ messages)";
758 if ($level == 0 || $attr ne $prev_attr) {
759 my $mbox = qq(<a\nhref="$mid/t.mbox.gz">mbox.gz</a>);
760 my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
761 $pfx .= INDENT if $level > 0;
762 $cur->[1] .= $pfx . $attr . $n . " - $mbox / $atom\n";
766 push @recent, $cur if $cur;
767 @recent = map { $_->[1] } sort { $b->[0] <=> $a->[0] } @recent;
768 $fh->write(join('', @recent) . '</pre>');
771 sub emit_index_topics {
773 my ($off) = (($state->{ctx}->{cgi}->param('o') || '0') =~ /(\d+)/);
774 $state->{order} = [];
775 $state->{subjs} = {};
776 $state->{latest} = {};
778 my %opts = ( offset => $off, limit => $max * 4 );
779 while (scalar @{$state->{order}} < $max) {
780 my $sres = $state->{srch}->query('', \%opts);
781 my $nr = scalar @{$sres->{msgs}} or last;
782 $sres = load_results($sres);
783 walk_thread(thread_results($sres), $state, *add_topic);
784 $opts{offset} += $nr;