blob: 4f60b6f84c60de206581d5641f47747ea8ee56f0 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# frozen_string_literal: true
module Banzai
module Filter
# HTML Filter to modify the attributes of external links
class ExternalLinkFilter < HTML::Pipeline::Filter
SCHEMES = ['http', 'https', nil].freeze
def call
links.each do |node|
uri = uri(node['href'].to_s)
node.set_attribute('href', uri.to_s) if uri
if SCHEMES.include?(uri&.scheme) && !internal_url?(uri)
node.set_attribute('rel', 'nofollow noreferrer noopener')
node.set_attribute('target', '_blank')
end
end
doc
end
private
def uri(href)
URI.parse(href)
rescue URI::Error
nil
end
def links
query = 'descendant-or-self::a[@href and not(@href = "")]'
doc.xpath(query)
end
def internal_url?(uri)
return false if uri.nil?
# Relative URLs miss a hostname
return true unless uri.hostname
uri.hostname == internal_url.hostname
end
def internal_url
@internal_url ||= URI.parse(Gitlab.config.gitlab.url)
end
end
end
end
|