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