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