diff options
author | Eric Wong <e@80x24.org> | 2016-03-01 03:44:03 +0000 |
---|---|---|
committer | Eric Wong <e@80x24.org> | 2016-03-01 03:44:25 +0000 |
commit | 704d1886ec4c34ffee0a37293970329418582211 (patch) | |
tree | d836a2c5183e1b35aea165effb281ca93bd1ec97 /lib/PublicInbox/Linkify.pm | |
parent | 5e7e5e3b5cdee82c753197264b5b683177f26b2a (diff) | |
download | public-inbox-704d1886ec4c34ffee0a37293970329418582211.tar.gz |
This will allow us to more easily reuse it elsewhere.
Diffstat (limited to 'lib/PublicInbox/Linkify.pm')
-rw-r--r-- | lib/PublicInbox/Linkify.pm | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/lib/PublicInbox/Linkify.pm b/lib/PublicInbox/Linkify.pm new file mode 100644 index 00000000..8f634f48 --- /dev/null +++ b/lib/PublicInbox/Linkify.pm @@ -0,0 +1,57 @@ +# Copyright (C) 2014-2016 all contributors <meta@public-inbox.org> +# License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt> + +# two-step linkification. +# intended usage is in the following order: +# +# linkify_1 +# <escape unsafe chars for HTML> +# linkify_2 +# +# Maybe this could be done more efficiently... +package PublicInbox::Linkify; +use strict; +use warnings; +use Digest::SHA qw/sha1_hex/; + +my $SALT = rand; +my $LINK_RE = qr!\b((?:ftp|https?|nntp):// + [\@:\w\.-]+/ + ?[\@\w\+\&\?\.\%\;/#=-]*)!x; + +sub new { bless {}, shift } + +sub linkify_1 { + my ($self, $s) = @_; + $s =~ s!$LINK_RE! + my $url = $1; + # salt this, as this could be exploited to show + # links in the HTML which don't show up in the raw mail. + my $key = sha1_hex($url . $SALT); + + # only escape ampersands, others do not match LINK_RE + $url =~ s/&/&/g; + $self->{$key} = $url; + 'PI-LINK-'. $key; + !ge; + $s; +} + +sub linkify_2 { + my ($self, $s) = @_; + + # Added "PI-LINK-" prefix to avoid false-positives on git commits + $s =~ s!\bPI-LINK-([a-f0-9]{40})\b! + my $key = $1; + my $url = $self->{$key}; + if (defined $url) { + "<a\nhref=\"$url\">$url</a>"; + } else { + # false positive or somebody tried to mess with us + $key; + } + !ge; + $s; +} + +1; |