]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Linkify.pm
linkify: do not capture trailing '.' or ';' in URLs
[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((?:ftp|https?|nntp)://
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                 if ($url =~ s/(\.)\z// || $url =~ s/(;)\z//) {
33                         $end = $1;
34                 }
35
36                 # salt this, as this could be exploited to show
37                 # links in the HTML which don't show up in the raw mail.
38                 my $key = sha1_hex($url . $SALT);
39
40                 # only escape ampersands, others do not match LINK_RE
41                 $url =~ s/&/&#38;/g;
42                 $self->{$key} = $url;
43                 'PI-LINK-'. $key . $end;
44         !ge;
45         $s;
46 }
47
48 sub linkify_2 {
49         my ($self, $s) = @_;
50
51         # Added "PI-LINK-" prefix to avoid false-positives on git commits
52         $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
53                 my $key = $1;
54                 my $url = $self->{$key};
55                 if (defined $url) {
56                         "<a\nhref=\"$url\">$url</a>";
57                 } else {
58                         # false positive or somebody tried to mess with us
59                         $key;
60                 }
61         !ge;
62         $s;
63 }
64
65 1;