Welcome to mirror list, hosted at ThFree Co, Russian Federation.

absolute_link_filter.rb « filter « banzai « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7e3024c521c49fabcbc9c20b91300b36c342f9a8 (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
# frozen_string_literal: true

require 'uri'

module Banzai
  module Filter
    # HTML filter that converts relative urls into absolute ones.
    class AbsoluteLinkFilter < HTML::Pipeline::Filter
      CSS = 'a.gfm'
      XPATH = Gitlab::Utils::Nokogiri.css_to_xpath(CSS).freeze

      def call
        return doc if skip?

        doc.xpath(self.class::XPATH).each do |el|
          process_link_attr el.attribute('href')
        end

        doc
      end

      protected

      def skip?
        context[:only_path] != false
      end

      def process_link_attr(html_attr)
        return if html_attr.blank?
        return if html_attr.value.start_with?('//')

        uri = URI(html_attr.value)
        html_attr.value = convert_link_href(uri) if uri.relative?
      rescue URI::Error
        # noop
      end

      def convert_link_href(uri)
        # Here we really want to expand relative path to absolute path
        URI.join(Gitlab.config.gitlab.url, uri).to_s
      end
    end
  end
end