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

uploads_rewriter.rb « gfm « gitlab « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 58b46a85aae56909bc285282c4ddc3016ee17c3e (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# frozen_string_literal: true

require 'fileutils'

module Gitlab
  module Gfm
    ##
    # Class that rewrites markdown links for uploads
    #
    # Using a pattern defined in `FileUploader` it copies files to a new
    # project and rewrites all links to uploads in a given text.
    #
    #
    class UploadsRewriter
      include Gitlab::Utils::StrongMemoize

      def initialize(text, _text_html, source_project, _current_user)
        @text = text
        @source_project = source_project
        @pattern = FileUploader::MARKDOWN_PATTERN
      end

      def rewrite(target_parent)
        return @text unless needs_rewrite?

        @target_parent = target_parent

        rewritten_text = Gitlab::StringRegexMarker.new(@text).mark(@pattern) do |markdown, left:, right:, mode:|
          transform_markdown(markdown)
        end

        # MarkdownContentRewriterService relies on the text being changed _in place_.
        @text.gsub!(@text, rewritten_text)
      end

      def needs_rewrite?
        strong_memoize(:needs_rewrite) do
          @pattern.match?(@text)
        end
      end

      private

      def was_embedded?(markdown)
        markdown.starts_with?("!")
      end

      def find_file(secret, file_name)
        UploaderFinder.new(@source_project, secret, file_name).execute
      end

      def transform_markdown(markdown)
        match = @pattern.match(markdown)
        file = find_file(match[:secret], match[:file])

        # No file will be returned for a path traversal
        return '' if file.nil?

        return markdown unless file.try(:exists?)

        klass = @target_parent.is_a?(Namespace) ? NamespaceFileUploader : FileUploader
        moved = klass.copy_to(file, @target_parent)

        moved_markdown = moved.markdown_link

        # Prevents rewrite of plain links as embedded
        if was_embedded?(markdown)
          moved_markdown
        else
          moved_markdown.delete_prefix('!')
        end
      end
    end
  end
end