]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: fix spacing on missing ghosts
[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_WRAP .
37                 html_footer($mime, 1, $full_pfx, $srch) . $footer .
38                 '</pre></body></html>';
39 }
40
41 sub feed_entry {
42         my ($class, $mime, $full_pfx) = @_;
43
44         PRE_WRAP . multipart_text_as_html($mime, $full_pfx) . '</pre>';
45 }
46
47 # this is already inside a <pre>
48 # state = [ time, seen = {}, first_commit, page_nr = 0 ]
49 sub index_entry {
50         my (undef, $mime, $level, $state) = @_;
51         my ($srch, $seen, $first_commit) = @$state;
52         my $midx = $state->[3]++;
53         my ($prev, $next) = ($midx - 1, $midx + 1);
54         my $rv = '';
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 $pfx = ('  ' x $level);
73         my $root_anchor = $seen->{root_anchor};
74         my $path;
75         my $more = 'permalink';
76         if ($root_anchor) {
77                 $path = '../';
78         } else {
79                 $path = '';
80         }
81         my $href = $mid->as_href;
82         my $irt = $header_obj->header_raw('In-Reply-To');
83         my ($anchor_idx, $anchor, $t_anchor);
84         if (defined $irt) {
85                 $anchor_idx = anchor_for($irt);
86                 $anchor = $seen->{$anchor_idx};
87                 $t_anchor = T_ANCHOR;
88         } else {
89                 $t_anchor = '';
90         }
91
92         if (defined $srch) {
93                 $subj = "<a\nhref=\"${path}t/$href.html#u\">$subj</a>";
94         }
95         if ($root_anchor && $root_anchor eq $id) {
96                 $subj = "<u\nid=\"u\">$subj</u>";
97         }
98
99         my $ts = $mime->header('X-PI-TS');
100         my $fmt = '%Y-%m-%d %H:%M UTC';
101         $ts = POSIX::strftime($fmt, gmtime($ts));
102
103         $rv .= "$pfx<b\nid=\"$id\">$subj</b>\n$pfx";
104         $rv .= "- by $from @ $ts - ";
105         $rv .= "<a\nid=\"s$midx\"\nhref=\"#s$next\">next</a>";
106         if ($prev >= 0) {
107                 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
108         }
109         $rv .= "\n\n";
110
111         my $mhref = "${path}m/$href.html";
112         my $fhref = "${path}f/$href.html";
113         # scan through all parts, looking for displayable text
114         $mime->walk_parts(sub {
115                 $rv .= index_walk($_[0], $pfx, $enc_msg, $part_nr, $fhref,
116                                   \$more);
117                 $part_nr++;
118         });
119         $mime->body_set('');
120
121         $rv .= "\n$pfx<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 . "\n\n";
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 .= "</pre><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 .= "</pre><hr />" . PRE_WRAP . $next . $foot . "</pre>";
189 }
190
191 # only private functions below.
192
193 sub index_walk {
194         my ($part, $pfx, $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 .= $pfx . add_filename_line($enc->decode($fn));
208         }
209
210         my $s = add_text_body_short($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                 # add prefix:
225                 $s =~ s/^/$pfx/sgm;
226
227                 # kill per-line trailing whitespace
228                 $s =~ s/[ \t]+$//sgm;
229
230                 $rv .= $s . "\n";
231         }
232         $rv;
233 }
234
235 sub enc_for {
236         my ($ct, $default) = @_;
237         $default ||= $enc_utf8;
238         defined $ct or return $default;
239         my $ct_parsed = parse_content_type($ct);
240         if ($ct_parsed) {
241                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
242                         my $enc = find_encoding($charset);
243                         return $enc if $enc;
244                 }
245         }
246         $default;
247 }
248
249 sub multipart_text_as_html {
250         my ($mime, $full_pfx, $srch) = @_;
251         my $rv = "";
252         my $part_nr = 0;
253         my $enc_msg = enc_for($mime->header("Content-Type"));
254
255         # scan through all parts, looking for displayable text
256         $mime->walk_parts(sub {
257                 my ($part) = @_;
258                 return if $part->subparts; # walk_parts already recurses
259                 my $ct = $part->content_type;
260
261                 # account for filter bugs...
262                 return if defined $ct && $ct =~ m!\btext/[xh]+tml\b!i;
263
264                 my $enc = enc_for($ct, $enc_msg);
265
266                 if ($part_nr > 0) {
267                         my $fn = $part->filename;
268                         defined($fn) or $fn = "part #" . ($part_nr + 1);
269                         $rv .= add_filename_line($enc->decode($fn));
270                 }
271
272                 if (defined $full_pfx) {
273                         $rv .= add_text_body_short($enc, $part, $part_nr,
274                                                 $full_pfx);
275                 } else {
276                         $rv .= add_text_body_full($enc, $part, $part_nr);
277                 }
278                 $rv .= "\n" unless $rv =~ /\n\z/s;
279                 ++$part_nr;
280         });
281         $mime->body_set('');
282         $rv;
283 }
284
285 sub add_filename_line {
286         my ($fn) = @_;
287         my $len = 72;
288         my $pad = "-";
289
290         $len -= length($fn);
291         $pad x= ($len/2) if ($len > 0);
292         "$pad " . ascii_html($fn) . " $pad\n";
293 }
294
295 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://[@\w\+\&\?\.\%\;/#=-]+)!;
296
297 sub linkify {
298         # no newlines added here since it'd break the splitting we do
299         # to fold quotes
300         $_[0] =~ s!$LINK_RE!<a href="$1">$1</a>!g;
301 }
302
303 sub add_text_body_short {
304         my ($enc, $part, $part_nr, $full_pfx) = @_;
305         my $n = 0;
306         my $s = ascii_html($enc->decode($part->body));
307         linkify($s);
308         $s =~ s!^((?:(?:&gt;[^\n]*)\n)+)!
309                 my $cur = $1;
310                 my @lines = split(/\n/, $cur);
311                 if (@lines > MAX_INLINE_QUOTED) {
312                         # show a short snippet of quoted text
313                         $cur = join(' ', @lines);
314                         $cur =~ s/^&gt;\s*//;
315
316                         my @sum = split(/\s+/, $cur);
317                         $cur = '';
318                         do {
319                                 my $tmp = shift(@sum);
320                                 my $len = length($tmp) + length($cur);
321                                 if ($len > MAX_TRUNC_LEN) {
322                                         @sum = ();
323                                 } else {
324                                         $cur .= $tmp . ' ';
325                                 }
326                         } while (@sum && length($cur) < MAX_TRUNC_LEN);
327                         $cur =~ s/ \z/ .../;
328                         "&gt; &lt;<a\nhref=\"${full_pfx}#q${part_nr}_" . $n++ .
329                                 "\">$cur<\/a>&gt;\n";
330                 } else {
331                         $cur;
332                 }
333         !emg;
334         $s;
335 }
336
337 sub add_text_body_full {
338         my ($enc, $part, $part_nr) = @_;
339         my $n = 0;
340         my $s = ascii_html($enc->decode($part->body));
341         linkify($s);
342         $s =~ s!^((?:(?:&gt;[^\n]*)\n)+)!
343                 my $cur = $1;
344                 my @lines = split(/\n/, $cur);
345                 if (@lines > MAX_INLINE_QUOTED) {
346                         "<a\nid=q${part_nr}_" . $n++ . ">$cur</a>";
347                 } else {
348                         $cur;
349                 }
350         !emg;
351         $s;
352 }
353
354 sub headers_to_html_header {
355         my ($mime, $full_pfx, $srch) = @_;
356
357         my $rv = "";
358         my @title;
359         my $header_obj = $mime->header_obj;
360         my $mid = $header_obj->header_raw('Message-ID');
361         $mid = PublicInbox::Hval->new_msgid($mid);
362         my $mid_href = $mid->as_href;
363         foreach my $h (qw(From To Cc Subject Date)) {
364                 my $v = $mime->header($h);
365                 defined($v) && length($v) or next;
366                 $v = PublicInbox::Hval->new_oneline($v);
367
368                 if ($h eq 'From') {
369                         my @from = Email::Address->parse($v->raw);
370                         $title[1] = ascii_html($from[0]->name);
371                 } elsif ($h eq 'Subject') {
372                         $title[0] = $v->as_html;
373                         if ($srch) {
374                                 $rv .= "$h: <a\nhref=\"../t/$mid_href.html\">";
375                                 $rv .= $v->as_html . "</a>\n";
376                                 next;
377                         }
378                 }
379                 $rv .= "$h: " . $v->as_html . "\n";
380
381         }
382
383         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
384         $mid_href = "../m/$mid_href" unless $full_pfx;
385         $rv .= "(<a\nhref=\"$mid_href.txt\">raw</a>)\n";
386
387         my $irt = $header_obj->header_raw('In-Reply-To');
388         if (defined $irt) {
389                 my $v = PublicInbox::Hval->new_msgid($irt);
390                 my $html = $v->as_html;
391                 my $href = $v->as_href;
392                 $rv .= "In-Reply-To: &lt;";
393                 $rv .= "<a\nhref=\"$href.html\">$html</a>&gt;\n";
394         }
395
396         my $refs = $header_obj->header_raw('References');
397         if ($refs) {
398                 # avoid redundant URLs wasting bandwidth
399                 my %seen;
400                 $seen{mid_clean($irt)} = 1 if defined $irt;
401                 my @refs;
402                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
403                 foreach my $ref (@raw_refs) {
404                         next if $seen{$ref};
405                         $seen{$ref} = 1;
406                         push @refs, linkify_ref($ref);
407                 }
408
409                 if (@refs) {
410                         $rv .= 'References: '. join(' ', @refs) . "\n";
411                 }
412         }
413
414         $rv .= "\n";
415
416         ("<html><head><title>".  join(' - ', @title) .
417          '</title></head><body>' . PRE_WRAP . $rv);
418 }
419
420 sub html_footer {
421         my ($mime, $standalone, $full_pfx, $srch) = @_;
422         my %cc; # everyone else
423         my $to; # this is the From address
424
425         foreach my $h (qw(From To Cc)) {
426                 my $v = $mime->header($h);
427                 defined($v) && length($v) or next;
428                 my @addrs = Email::Address->parse($v);
429                 foreach my $recip (@addrs) {
430                         my $address = $recip->address;
431                         my $dst = lc($address);
432                         $cc{$dst} ||= $address;
433                         $to ||= $dst;
434                 }
435         }
436         Email::Address->purge_cache if $standalone;
437
438         my $subj = $mime->header('Subject') || '';
439         $subj = "Re: $subj" unless $subj =~ /\bRe:/;
440         my $mid = $mime->header_obj->header_raw('Message-ID');
441         my $irt = uri_escape_utf8($mid);
442         delete $cc{$to};
443         $to = uri_escape_utf8($to);
444         $subj = uri_escape_utf8($subj);
445
446         my $cc = uri_escape_utf8(join(',', sort values %cc));
447         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
448
449         my $idx = $standalone ? " <a\nhref=\"../\">index</a>" : '';
450         if ($idx && $srch) {
451                 $irt = $mime->header_obj->header_raw('In-Reply-To') || '';
452                 $mid = mid_compressed(mid_clean($mid));
453                 my $t_anchor = length $irt ? T_ANCHOR : '';
454                 $idx = " <a\nhref=\"../t/$mid.html$t_anchor\">".
455                        "threadlink</a>$idx";
456                 my $res = $srch->get_followups($mid);
457                 if (my $c = $res->{count}) {
458                         $c = $c == 1 ? '1 followup' : "$c followups";
459                         $idx .= "\n$c:\n";
460                         $res->{srch} = $srch;
461                         thread_followups(\$idx, $mime, $res);
462                 } else {
463                         $idx .= "\n(no followups, yet)\n";
464                 }
465                 if ($irt) {
466                         $irt = PublicInbox::Hval->new_msgid($irt);
467                         $irt = $irt->as_href;
468                         $irt = "<a\nhref=\"$irt\">parent</a> ";
469                 } else {
470                         $irt = ' ' x length('parent ');
471                 }
472         } else {
473                 $irt = '';
474         }
475
476         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
477 }
478
479 sub linkify_ref {
480         my $v = PublicInbox::Hval->new_msgid($_[0]);
481         my $html = $v->as_html;
482         my $href = $v->as_href;
483         "&lt;<a\nhref=\"$href.html\">$html</a>&gt;";
484 }
485
486 sub anchor_for {
487         my ($msgid) = @_;
488         my $id = $msgid;
489         if ($id !~ /\A[a-f0-9]{40}\z/) {
490                 $id = mid_compressed(mid_clean($id), 1);
491         }
492         'm' . $id;
493 }
494
495 sub simple_dump {
496         my ($dst, $root, $node, $level) = @_;
497         # $root = [ Root Message-ID, \%seen, $srch ];
498         if (my $x = $node->message) {
499                 my $mid = $x->header('Message-ID');
500                 if ($root->[0] ne $mid) {
501                         my $pfx = '  ' x $level;
502                         $$dst .= $pfx;
503                         my $s = $x->header('Subject');
504                         my $h = $root->[2]->subject_path($s);
505                         if ($root->[1]->{$h}) {
506                                 $s = '';
507                         } else {
508                                 $root->[1]->{$h} = 1;
509                                 $s = PublicInbox::Hval->new($s);
510                                 $s = $s->as_html;
511                         }
512                         my $m = PublicInbox::Hval->new_msgid($mid);
513                         my $f = PublicInbox::Hval->new($x->header('X-PI-From'));
514                         my $d = PublicInbox::Hval->new($x->header('X-PI-Date'));
515                         $m = $m->as_href . '.html';
516                         $f = $f->as_html;
517                         $d = $d->as_html . ' UTC';
518                         if (length($s) == 0) {
519                                 $$dst .= "` <a\nhref=\"$m\">$f @ $d</a>\n";
520                         } else {
521                                 $$dst .= "` <a\nhref=\"$m\">$s</a>\n" .
522                                      "$pfx  by $f @ $d\n";
523                         }
524                 }
525         }
526         simple_dump($dst, $root, $node->child, $level + 1) if $node->child;
527         simple_dump($dst, $root, $node->next, $level) if $node->next;
528 }
529
530 sub thread_followups {
531         my ($dst, $root, $res) = @_;
532         my @msgs = map { $_->mini_mime } @{$res->{msgs}};
533         require PublicInbox::Thread;
534         $root->header_set('X-PI-TS', '0');
535         my $th = PublicInbox::Thread->new($root, @msgs);
536         $th->thread;
537         $th->order(*PublicInbox::Thread::sort_ts);
538         my $srch = $res->{srch};
539         my $subj = $srch->subject_path($root->header('Subject'));
540         my %seen = ($subj => 1);
541         $root = [ $root->header('Message-ID'), \%seen, $srch ];
542         simple_dump($dst, $root, $_, 0) for $th->rootset;
543 }
544
545 sub thread_html_head {
546         my ($mime) = @_;
547         my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
548         $s = $s->as_html;
549         "<html><head><title>$s</title></head><body>" . PRE_WRAP
550
551 }
552
553 sub thread_entry {
554         my ($dst, $state, $node, $level) = @_;
555         # $state = [ $search_res, $seen, undef, 0 (msg_nr) ];
556         # $seen is overloaded with 3 types of fields:
557         #       1) "root_anchor" => anchor_for(Message-ID),
558         #       2) seen subject hashes: sha1(subject) => 1
559         #       3) anchors hashes: "#$sha1_hex" (same as $seen in index_entry)
560         if (my $mime = $node->message) {
561                 if (length($$dst) == 0) {
562                         $$dst .= thread_html_head($mime);
563                 }
564                 $$dst .= index_entry(undef, $mime, $level, $state);
565         }
566         thread_entry($dst, $state, $node->child, $level + 1) if $node->child;
567         thread_entry($dst, $state, $node->next, $level) if $node->next;
568 }
569
570 sub load_results {
571         my ($ctx, $res) = @_;
572
573         require PublicInbox::GitCatFile;
574         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
575         my @msgs;
576         while (my $smsg = shift @{$res->{msgs}}) {
577                 my $m = $smsg->mid;
578                 my $path = mid2path($m);
579
580                 # FIXME: duplicated code from Feed.pm
581                 my $mime = eval {
582                         my $str = $git->cat_file("HEAD:$path");
583                         Email::MIME->new($str);
584                 };
585                 unless ($@) {
586                         my $t = eval { str2time($mime->header('Date')) };
587                         defined($t) or $t = 0;
588                         $mime->header_set('X-PI-TS', $t);
589                         push @msgs, $mime;
590                 }
591         }
592         \@msgs;
593 }
594
595 1;