summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/external_link_filter.rb
blob: d6327ef31cbc41f9d58c8b40fda9523c423925c7 (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
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)
          next unless uri

          node.set_attribute('href', uri.to_s)

          if SCHEMES.include?(uri.scheme) && external_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 external_url?(uri)
        # Relative URLs miss a hostname
        return false unless uri.hostname

        uri.hostname != internal_url.hostname
      end

      def internal_url
        @internal_url ||= URI.parse(Gitlab.config.gitlab.url)
      end
    end
  end
end