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