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: cc7bf3ed556ccf065a6a957e100cd4519a9cc8d8 (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
# 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 unless context[:only_path] == false

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

        doc
      end

      protected

      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 = absolute_link_attr(uri) if uri.relative?
      rescue URI::Error
        # noop
      end

      def absolute_link_attr(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