]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Linkify.pm
www: use WwwStream for dumping thread and search views
[public-inbox.git] / lib / PublicInbox / Linkify.pm
1 # Copyright (C) 2014-2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # two-step linkification.
5 # intended usage is in the following order:
6 #
7 #   linkify_1
8 #   <escape unsafe chars for HTML>
9 #   linkify_2
10 #
11 # Maybe this could be done more efficiently...
12 package PublicInbox::Linkify;
13 use strict;
14 use warnings;
15 use Digest::SHA qw/sha1_hex/;
16
17 my $SALT = rand;
18 my $LINK_RE = qr!\b((?:ftps?|https?|nntps?|gopher)://
19                  [\@:\w\.-]+/
20                  ?[,:~\$\@\w\+\&\?\.\%\;/#=-]*)!x;
21
22 sub new { bless {}, shift }
23
24 sub linkify_1 {
25         my ($self, $s) = @_;
26         $s =~ s!$LINK_RE!
27                 my $url = $1;
28                 my $end = '';
29
30                 # it's fairly common to end URLs in messages with
31                 # '.', ',' or ';' to denote the end of a statement;
32                 # assume the intent was to end the statement/sentence
33                 # in English
34                 if ($url =~ s/([\.,;])\z//) {
35                         $end = $1;
36                 }
37
38                 # salt this, as this could be exploited to show
39                 # links in the HTML which don't show up in the raw mail.
40                 my $key = sha1_hex($url . $SALT);
41
42                 # only escape ampersands, others do not match LINK_RE
43                 $url =~ s/&/&#38;/g;
44                 $self->{$key} = $url;
45                 'PI-LINK-'. $key . $end;
46         !ge;
47         $s;
48 }
49
50 sub linkify_2 {
51         my ($self, $s) = @_;
52
53         # Added "PI-LINK-" prefix to avoid false-positives on git commits
54         $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
55                 my $key = $1;
56                 my $url = $self->{$key};
57                 if (defined $url) {
58                         "<a\nhref=\"$url\">$url</a>";
59                 } else {
60                         # false positive or somebody tried to mess with us
61                         $key;
62                 }
63         !ge;
64         $s;
65 }
66
67 1;