]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: avoid broken parent link in per-message view
[public-inbox.git] / lib / PublicInbox / View.pm
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;
4 use strict;
5 use warnings;
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;
14 require POSIX;
15
16 # TODO: make these constants tunable
17 use constant MAX_INLINE_QUOTED => 12; # half an 80x24 terminal
18 use constant MAX_TRUNC_LEN => 72;
19 use constant PRE_WRAP => "<pre\nstyle=\"white-space:pre-wrap\">";
20 use constant T_ANCHOR => '#u';
21
22 *ascii_html = *PublicInbox::Hval::ascii_html;
23
24 my $enc_utf8 = find_encoding('UTF-8');
25
26 # public functions:
27 sub msg_html {
28         my ($ctx, $mime, $full_pfx, $footer) = @_;
29         if (defined $footer) {
30                 $footer = "\n" . $footer;
31         } else {
32                 $footer = '';
33         }
34         headers_to_html_header($mime, $full_pfx, $ctx) .
35                 multipart_text_as_html($mime, $full_pfx) .
36                 '</pre><hr />' . PRE_WRAP .
37                 html_footer($mime, 1, $full_pfx, $ctx) .
38                 $footer .
39                 '</pre></body></html>';
40 }
41
42 sub feed_entry {
43         my ($class, $mime, $full_pfx) = @_;
44
45         PRE_WRAP . multipart_text_as_html($mime, $full_pfx) . '</pre>';
46 }
47
48 # this is already inside a <pre>
49 sub index_entry {
50         my ($fh, $mime, $level, $state) = @_;
51         my $midx = $state->{anchor_idx}++;
52         my $ctx = $state->{ctx};
53         my $srch = $ctx->{srch};
54         my ($prev, $next) = ($midx - 1, $midx + 1);
55         my $part_nr = 0;
56         my $enc = enc_for($mime->header("Content-Type"));
57         my $subj = $mime->header('Subject');
58         my $header_obj = $mime->header_obj;
59
60         my $mid_raw = $header_obj->header('Message-ID');
61         my $id = anchor_for($mid_raw);
62         my $seen = $state->{seen};
63         $seen->{$id} = "#$id"; # save the anchor for later
64
65         my $mid = PublicInbox::Hval->new_msgid($mid_raw);
66         my $from = PublicInbox::Hval->new_oneline($mime->header('From'))->raw;
67         my @from = Email::Address->parse($from);
68         $from = $from[0]->name;
69
70         $from = PublicInbox::Hval->new_oneline($from)->as_html;
71         $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
72         my $more = 'permalink';
73         my $root_anchor = $state->{root_anchor};
74         my $path = $root_anchor ? '../../' : '';
75         my $href = $mid->as_href;
76         my $irt = $header_obj->header('In-Reply-To');
77         my ($anchor_idx, $anchor);
78         if (defined $irt) {
79                 $anchor_idx = anchor_for($irt);
80                 $anchor = $seen->{$anchor_idx};
81         }
82         if ($srch) {
83                 $subj = "<a\nhref=\"${path}t/$href/#u\">$subj</a>";
84         }
85         if ($root_anchor && $root_anchor eq $id) {
86                 $subj = "<u\nid=\"u\">$subj</u>";
87         }
88
89         my $ts = $mime->header('X-PI-TS');
90         unless (defined $ts) {
91                 $ts = msg_timestamp($mime);
92         }
93         $ts = POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
94
95         my $rv = "<table\nsummary=l$level><tr>";
96         if ($level) {
97                 $rv .= '<td><pre>' . ('  ' x $level) . '</pre></td>';
98         }
99         $rv .= "<td\nid=s$midx>" . PRE_WRAP;
100         $rv .= "<b\nid=\"$id\">$subj</b>\n";
101         $rv .= "- by $from @ $ts UTC - ";
102         $rv .= "<a\nhref=\"#s$next\">next</a>";
103         if ($prev >= 0) {
104                 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
105         }
106         $fh->write($rv .= "\n\n");
107
108         my ($fhref, $more_ref);
109         my $mhref = "${path}m/$href/";
110         if ($level > 0) {
111                 $fhref = "${path}f/$href/";
112                 $more_ref = \$more;
113         }
114         # scan through all parts, looking for displayable text
115         $mime->walk_parts(sub {
116                 index_walk($fh, $_[0], $enc, \$part_nr, $fhref, $more_ref);
117         });
118         $mime->body_set('');
119
120         my $txt = "${path}m/$href/raw";
121         $rv = "\n<a\nhref=\"$mhref\">$more</a> <a\nhref=\"$txt\">raw</a> ";
122         $rv .= html_footer($mime, 0, undef, $ctx);
123
124         if (defined $irt) {
125                 unless (defined $anchor) {
126                         my $v = PublicInbox::Hval->new_msgid($irt);
127                         $v = $v->as_href;
128                         $anchor = "${path}m/$v/";
129                         $seen->{$anchor_idx} = $anchor;
130                 }
131                 $rv .= " <a\nhref=\"$anchor\">parent</a>";
132         }
133
134         $fh->write($rv .= '</pre></td></tr></table>');
135 }
136
137 sub thread_html {
138         my ($ctx, $foot, $srch) = @_;
139         sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
140 }
141
142 # only private functions below.
143
144 sub emit_thread_html {
145         my ($cb, $ctx, $foot, $srch) = @_;
146         my $mid = mid_compress($ctx->{mid});
147         my $res = $srch->get_thread($mid);
148         my $msgs = load_results($res);
149         my $nr = scalar @$msgs;
150         return missing_thread($cb) if $nr == 0;
151         my $fh = $cb->([200,['Content-Type'=>'text/html; charset=UTF-8']]);
152         my $th = thread_results($msgs);
153         my $state = {
154                 ctx => $ctx,
155                 seen => {},
156                 root_anchor => anchor_for($mid),
157                 anchor_idx => 0,
158         };
159         {
160                 require PublicInbox::GitCatFile;
161                 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
162                 thread_entry($fh, $git, $state, $_, 0) for $th->rootset;
163         }
164         my $final_anchor = $state->{anchor_idx};
165         my $next = "<a\nid=\"s$final_anchor\">";
166         $next .= $final_anchor == 1 ? 'only message in' : 'end of';
167         $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>\n";
168         $next .= "download: <a\nhref=\"mbox.gz\">mbox.gz</a>\n\n";
169         $fh->write("<hr />" . PRE_WRAP . $next . $foot .
170                    "</pre></body></html>");
171         $fh->close;
172 }
173
174 sub index_walk {
175         my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
176         my $s = add_text_body($enc, $part, $part_nr, $fhref);
177
178         if ($more) {
179                 # drop the remainder of git patches, they're usually better
180                 # to review when the full message is viewed
181                 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
182
183                 # Drop signatures
184                 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
185         }
186
187         # kill any leading or trailing whitespace lines
188         $s =~ s/^\s*$//sgm;
189         $s =~ s/\s+\z//s;
190
191         if ($s ne '') {
192                 # kill per-line trailing whitespace
193                 $s =~ s/[ \t]+$//sgm;
194                 $s .= "\n" unless $s =~ /\n\z/s;
195         }
196         $fh->write($s);
197 }
198
199 sub enc_for {
200         my ($ct, $default) = @_;
201         $default ||= $enc_utf8;
202         defined $ct or return $default;
203         my $ct_parsed = parse_content_type($ct);
204         if ($ct_parsed) {
205                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
206                         my $enc = find_encoding($charset);
207                         return $enc if $enc;
208                 }
209         }
210         $default;
211 }
212
213 sub multipart_text_as_html {
214         my ($mime, $full_pfx, $srch) = @_;
215         my $rv = "";
216         my $part_nr = 0;
217         my $enc = enc_for($mime->header("Content-Type"));
218
219         # scan through all parts, looking for displayable text
220         $mime->walk_parts(sub {
221                 my ($part) = @_;
222                 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
223         });
224         $mime->body_set('');
225         $rv;
226 }
227
228 sub add_filename_line {
229         my ($enc, $fn) = @_;
230         my $len = 72;
231         my $pad = "-";
232         $fn = $enc->decode($fn);
233         $len -= length($fn);
234         $pad x= ($len/2) if ($len > 0);
235         "$pad " . ascii_html($fn) . " $pad\n";
236 }
237
238 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
239                  [\@:\w\.-]+/
240                  ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
241
242 sub linkify {
243         # no newlines added here since it'd break the splitting we do
244         # to fold quotes
245         $_[0] =~ s!$LINK_RE!<a\nhref="$1">$1</a>!g;
246 }
247
248 sub flush_quote {
249         my ($quot, $n, $part_nr, $full_pfx, $final) = @_;
250
251         if ($full_pfx) {
252                 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
253                         # show quote inline
254                         my $rv = join('', map { linkify($_); $_ } @$quot);
255                         @$quot = ();
256                         return $rv;
257                 }
258
259                 # show a short snippet of quoted text and link to full version:
260                 @$quot = map { s/^(?:&gt;\s*)+//gm; $_ } @$quot;
261                 my $cur = join(' ', @$quot);
262                 @$quot = split(/\s+/, $cur);
263                 $cur = '';
264                 do {
265                         my $tmp = shift(@$quot);
266                         my $len = length($tmp) + length($cur);
267                         if ($len > MAX_TRUNC_LEN) {
268                                 @$quot = ();
269                         } else {
270                                 $cur .= $tmp . ' ';
271                         }
272                 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
273                 @$quot = ();
274                 $cur =~ s/ \z/ .../s;
275                 my $nr = ++$$n;
276                 "&gt; [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
277         } else {
278                 # show everything in the full version with anchor from
279                 # short version (see above)
280                 my $nr = ++$$n;
281                 my $rv = "<a\nid=q${part_nr}_$nr></a>";
282                 $rv .= join('', map { linkify($_); $_ } @$quot);
283                 @$quot = ();
284                 $rv;
285         }
286 }
287
288 sub add_text_body {
289         my ($enc_msg, $part, $part_nr, $full_pfx) = @_;
290         return '' if $part->subparts;
291
292         my $ct = $part->content_type;
293         # account for filter bugs...
294         if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) {
295                 $part->body_set('');
296                 return '';
297         }
298         my $enc = enc_for($ct, $enc_msg);
299         my $n = 0;
300         my $nr = 0;
301         my $s = $part->body;
302         $part->body_set('');
303         $s = $enc->decode($s);
304         $s = ascii_html($s);
305         my @lines = split(/^/m, $s);
306         $s = '';
307
308         if ($$part_nr > 0) {
309                 my $fn = $part->filename;
310                 defined($fn) or $fn = "part #" . ($$part_nr + 1);
311                 $s .= add_filename_line($enc, $fn);
312         }
313
314         my @quot;
315         while (defined(my $cur = shift @lines)) {
316                 if ($cur !~ /^&gt;/) {
317                         # show the previously buffered quote inline
318                         if (scalar @quot) {
319                                 $s .= flush_quote(\@quot, \$n, $$part_nr,
320                                                   $full_pfx, 0);
321                         }
322
323                         # regular line, OK
324                         linkify($cur);
325                         $s .= $cur;
326                 } else {
327                         push @quot, $cur;
328                 }
329         }
330         $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1) if scalar @quot;
331         $s .= "\n" unless $s =~ /\n\z/s;
332         ++$$part_nr;
333         $s;
334 }
335
336 sub headers_to_html_header {
337         my ($mime, $full_pfx, $ctx) = @_;
338         my $srch = $ctx->{srch} if $ctx;
339         my $rv = "";
340         my @title;
341         my $header_obj = $mime->header_obj;
342         my $mid = $header_obj->header('Message-ID');
343         $mid = PublicInbox::Hval->new_msgid($mid);
344         my $mid_href = $mid->as_href;
345         foreach my $h (qw(From To Cc Subject Date)) {
346                 my $v = $mime->header($h);
347                 defined($v) && ($v ne '') or next;
348                 $v = PublicInbox::Hval->new_oneline($v);
349
350                 if ($h eq 'From') {
351                         my @from = Email::Address->parse($v->raw);
352                         $title[1] = ascii_html($from[0]->name);
353                 } elsif ($h eq 'Subject') {
354                         $title[0] = $v->as_html;
355                         if ($srch) {
356                                 $rv .= "$h: <a\nid=\"t\"\n" .
357                                         "href=\"../../t/$mid_href/\">";
358                                 $rv .= $v->as_html . "</a>\n";
359                                 next;
360                         }
361                 }
362                 $rv .= "$h: " . $v->as_html . "\n";
363
364         }
365         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
366         my $raw_ref = $full_pfx ? 'raw' : "../../m/$mid_href/raw";
367         $rv .= "(<a\nhref=\"$raw_ref\">raw</a>)\n";
368         if ($srch) {
369                 $rv .= "<a\nhref=\"#r\">References: [see below]</a>\n";
370         } else {
371                 $rv .= _parent_headers_nosrch($header_obj);
372         }
373         $rv .= "\n";
374
375         ("<html><head><title>".  join(' - ', @title) .
376          '</title></head><body>' . PRE_WRAP . $rv);
377 }
378
379 sub thread_inline {
380         my ($dst, $ctx, $cur) = @_;
381         my $srch = $ctx->{srch};
382         my $mid = mid_compress(mid_clean($cur->header('Message-ID')));
383         my $res = $srch->get_thread($mid);
384         my $nr = $res->{total};
385
386         if ($nr <= 1) {
387                 $$dst .= "\n[no followups, yet]</a>\n";
388                 return;
389         }
390
391         $$dst .= "\n\n~$nr messages in thread: ".
392                  "(<a\nhref=\"../../t/$mid/#u\">expand</a>)\n";
393         my $subj = $srch->subject_path($cur->header('Subject'));
394         my $state = {
395                 seen => { $subj => 1 },
396                 srch => $srch,
397                 cur => $mid,
398         };
399         for (thread_results(load_results($res))->rootset) {
400                 inline_dump($dst, $state, $_, 0);
401         }
402         $state->{next_msg};
403 }
404
405 sub _parent_headers_nosrch {
406         my ($header_obj) = @_;
407         my $rv = '';
408
409         my $irt = $header_obj->header('In-Reply-To');
410         if (defined $irt) {
411                 my $v = PublicInbox::Hval->new_msgid($irt);
412                 my $html = $v->as_html;
413                 my $href = $v->as_href;
414                 $rv .= "In-Reply-To: &lt;";
415                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
416         }
417
418         my $refs = $header_obj->header('References');
419         if ($refs) {
420                 # avoid redundant URLs wasting bandwidth
421                 my %seen;
422                 $seen{mid_clean($irt)} = 1 if defined $irt;
423                 my @refs;
424                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
425                 foreach my $ref (@raw_refs) {
426                         next if $seen{$ref};
427                         $seen{$ref} = 1;
428                         push @refs, linkify_ref($ref);
429                 }
430
431                 if (@refs) {
432                         $rv .= 'References: '. join(' ', @refs) . "\n";
433                 }
434         }
435         $rv;
436 }
437
438 sub html_footer {
439         my ($mime, $standalone, $full_pfx, $ctx) = @_;
440         my %cc; # everyone else
441         my $to; # this is the From address
442
443         foreach my $h (qw(From To Cc)) {
444                 my $v = $mime->header($h);
445                 defined($v) && ($v ne '') or next;
446                 my @addrs = Email::Address->parse($v);
447                 foreach my $recip (@addrs) {
448                         my $address = $recip->address;
449                         my $dst = lc($address);
450                         $cc{$dst} ||= $address;
451                         $to ||= $dst;
452                 }
453         }
454         Email::Address->purge_cache if $standalone;
455
456         my $subj = $mime->header('Subject') || '';
457         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
458         my $mid = $mime->header('Message-ID');
459         my $irt = uri_escape_utf8($mid);
460         delete $cc{$to};
461         $to = uri_escape_utf8($to);
462         $subj = uri_escape_utf8($subj);
463
464         my $cc = uri_escape_utf8(join(',', sort values %cc));
465         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
466
467         my $srch = $ctx->{srch} if $ctx;
468         my $idx = $standalone ? " <a\nhref=\"../../\">index</a>" : '';
469         if ($idx && $srch) {
470                 my $next = thread_inline(\$idx, $ctx, $mime);
471                 $irt = $mime->header('In-Reply-To');
472                 if (defined $irt) {
473                         $irt = PublicInbox::Hval->new_msgid($irt);
474                         $irt = $irt->as_href;
475                         $irt = "<a\nhref=\"../$irt/\">parent</a> ";
476                 } else {
477                         $irt = ' ' x length('parent ');
478                 }
479                 if ($next) {
480                         $irt .= "<a\nhref=\"../$next/\">next</a> ";
481                 } else {
482                         $irt .= '     ';
483                 }
484         } else {
485                 $irt = '';
486         }
487
488         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
489 }
490
491 sub linkify_ref {
492         my $v = PublicInbox::Hval->new_msgid($_[0]);
493         my $html = $v->as_html;
494         my $href = $v->as_href;
495         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
496 }
497
498 sub anchor_for {
499         my ($msgid) = @_;
500         my $id = $msgid;
501         if ($id !~ /\A[a-f0-9]{40}\z/) {
502                 $id = mid_compress(mid_clean($id), 1);
503         }
504         'm' . $id;
505 }
506
507 sub thread_html_head {
508         my ($mime) = @_;
509         my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
510         $s = $s->as_html;
511         "<html><head><title>$s</title></head><body>";
512 }
513
514 sub thread_entry {
515         my ($fh, $git, $state, $node, $level) = @_;
516         return unless $node;
517         if (my $mime = $node->message) {
518
519                 # lazy load the full message from mini_mime:
520                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
521                 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
522                 if ($mime) {
523                         if ($state->{anchor_idx} == 0) {
524                                 $fh->write(thread_html_head($mime));
525                         }
526                         index_entry($fh, $mime, $level, $state);
527                 }
528         }
529         thread_entry($fh, $git, $state, $node->child, $level + 1);
530         thread_entry($fh, $git, $state, $node->next, $level);
531 }
532
533 sub load_results {
534         my ($res) = @_;
535
536         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
537 }
538
539 sub msg_timestamp {
540         my ($mime) = @_;
541         my $ts = eval { str2time($mime->header('Date')) };
542         defined($ts) ? $ts : 0;
543 }
544
545 sub thread_results {
546         my ($msgs) = @_;
547         require PublicInbox::Thread;
548         my $th = PublicInbox::Thread->new(@$msgs);
549         $th->thread;
550         no warnings 'once';
551         $th->order(*PublicInbox::Thread::sort_ts);
552         $th
553 }
554
555 sub missing_thread {
556         my ($cb) = @_;
557         my $title = 'Thread does not exist';
558         $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
559 <html><head><title>$title</title></head><body><pre>$title
560 <a href="../../">Return to index</a></pre></body></html>
561 EOF
562 }
563
564 sub _inline_header {
565         my ($dst, $state, $mime, $level) = @_;
566         my $pfx = '  ' x $level;
567
568         my $cur = $state->{cur};
569         my $mid = $mime->header('Message-ID');
570         my $f = $mime->header('X-PI-From');
571         my $d = $mime->header('X-PI-Date');
572         $f = PublicInbox::Hval->new($f);
573         $d = PublicInbox::Hval->new($d);
574         $f = $f->as_html;
575         $d = $d->as_html . ' UTC';
576         my $midc = mid_compress(mid_clean($mid));
577         if ($cur) {
578                 if ($cur eq $midc) {
579                         delete $state->{cur};
580                         $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
581                                  "[this message]</a></b> by $f @ $d\n";
582
583                         return;
584                 }
585         } else {
586                 $state->{next_msg} ||= $midc;
587         }
588
589         # Subject is never undef, this mail was loaded from
590         # our Xapian which would've resulted in '' if it were
591         # really missing (and Filter rejects empty subjects)
592         my $s = $mime->header('Subject');
593         my $h = $state->{srch}->subject_path($s);
594         if ($state->{seen}->{$h}) {
595                 $s = undef;
596         } else {
597                 $state->{seen}->{$h} = 1;
598                 $s = PublicInbox::Hval->new($s);
599                 $s = $s->as_html;
600         }
601         my $m = PublicInbox::Hval->new_msgid($mid);
602         $m = '../' . $m->as_href . '/';
603         if (defined $s) {
604                 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
605                          "$pfx  $f @ $d\n";
606         } else {
607                 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
608         }
609 }
610
611 sub inline_dump {
612         my ($dst, $state, $node, $level) = @_;
613         return unless $node;
614         return if $state->{stopped};
615         if (my $mime = $node->message) {
616                 _inline_header($dst, $state, $mime, $level);
617         }
618         inline_dump($dst, $state, $node->child, $level+1);
619         inline_dump($dst, $state, $node->next, $level);
620 }
621
622 1;