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