1 # Copyright (C) 2014-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # two-step linkification.
5 # intended usage is in the following order:
8 # <escape unsafe chars for HTML>
11 # Maybe this could be done more efficiently...
12 package PublicInbox::Linkify;
15 use Digest::SHA qw/sha1_hex/;
18 my $LINK_RE = qr{([\('!])?\b((?:ftps?|https?|nntps?|gopher)://
20 (?:[a-z0-9\-\._~!\$\&\';\(\)\*\+,;=:@/%]*)
21 (?:\?[a-z0-9\-\._~!\$\&\';\(\)\*\+,;=:@/%]+)?
22 (?:\#[a-z0-9\-\._~!\$\&\';\(\)\*\+,;=:@/%\?]+)?
26 sub new { bless {}, $_[0] }
28 # try to distinguish paired punctuation chars from the URL itself
29 # Maybe other languages/formats can be supported here, too...
31 "(" => qr/(\)[\.,;\+]?)\z/, # Markdown (,), Ruby (+) (, for arrays)
32 "'" => qr/('[\.,;\+]?)\z/, # Perl / Ruby
33 "!" => qr/(![\.,;\+]?)\z/, # Perl / Ruby
42 # it's fairly common to end URLs in messages with
43 # '.', ',' or ';' to denote the end of a statement;
44 # assume the intent was to end the statement/sentence
46 if (defined(my $re = $pairs{$beg})) {
47 if ($url =~ s/$re//) {
50 } elsif ($url =~ s/([\.,;])\z//) {
52 } elsif ($url !~ /\(/ && $url =~ s/\)\z//) {
56 # salt this, as this could be exploited to show
57 # links in the HTML which don't show up in the raw mail.
58 my $key = sha1_hex($url . $SALT);
60 # only escape ampersands, others do not match LINK_RE
63 $beg . 'PI-LINK-'. $key . $end;
69 # Added "PI-LINK-" prefix to avoid false-positives on git commits
70 $_[1] =~ s!\bPI-LINK-([a-f0-9]{40})\b!
72 my $url = $_[0]->{$key};
74 "<a\nhref=\"$url\">$url</a>";
76 # false positive or somebody tried to mess with us