]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Linkify.pm
8e1728c71136c78de06af4d53603e54116496edb
[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                  (?:[a-z0-9\-\._~!\$\&\';\(\)\*\+,;=:@/%]*)
21                  (?:\?[a-z0-9\-\._~!\$\&\';\(\)\*\+,;=:@/%]+)?
22                  (?:\#[a-z0-9\-\._~!\$\&\';\(\)\*\+,;=:@/%\?]+)?
23                  )}xi;
24
25 sub new { bless {}, $_[0] }
26
27 sub linkify_1 {
28         $_[1] =~ s!$LINK_RE!
29                 my $beg = $1 || '';
30                 my $url = $2;
31                 my $end = '';
32
33                 # it's fairly common to end URLs in messages with
34                 # '.', ',' or ';' to denote the end of a statement;
35                 # assume the intent was to end the statement/sentence
36                 # in English
37                 # Markdown compatibility:
38                 if ($beg eq '(') {
39                         if ($url =~ s/(\)[\.,;]?)\z//) {
40                                 $end = $1;
41                         }
42                 } elsif ($url =~ s/([\.,;])\z//) {
43                         $end = $1;
44                 }
45
46                 # salt this, as this could be exploited to show
47                 # links in the HTML which don't show up in the raw mail.
48                 my $key = sha1_hex($url . $SALT);
49
50                 # only escape ampersands, others do not match LINK_RE
51                 $url =~ s/&/&#38;/g;
52                 $_[0]->{$key} = $url;
53                 $beg . 'PI-LINK-'. $key . $end;
54         !ge;
55         $_[1];
56 }
57
58 sub linkify_2 {
59         # Added "PI-LINK-" prefix to avoid false-positives on git commits
60         $_[1] =~ s!\bPI-LINK-([a-f0-9]{40})\b!
61                 my $key = $1;
62                 my $url = $_[0]->{$key};
63                 if (defined $url) {
64                         "<a\nhref=\"$url\">$url</a>";
65                 } else {
66                         # false positive or somebody tried to mess with us
67                         $key;
68                 }
69         !ge;
70         $_[1];
71 }
72
73 1;