2019-02-15 15:39:39 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
require 'fileutils'
|
|
|
|
|
2016-06-02 11:05:42 +05:30
|
|
|
module Gitlab
|
|
|
|
module Gfm
|
|
|
|
##
|
|
|
|
# Class that rewrites markdown links for uploads
|
|
|
|
#
|
|
|
|
# Using a pattern defined in `FileUploader` it copies files to a new
|
2019-02-15 15:39:39 +05:30
|
|
|
# project and rewrites all links to uploads in a given text.
|
2016-06-02 11:05:42 +05:30
|
|
|
#
|
|
|
|
#
|
|
|
|
class UploadsRewriter
|
|
|
|
def initialize(text, source_project, _current_user)
|
|
|
|
@text = text
|
|
|
|
@source_project = source_project
|
|
|
|
@pattern = FileUploader::MARKDOWN_PATTERN
|
|
|
|
end
|
|
|
|
|
2019-02-15 15:39:39 +05:30
|
|
|
def rewrite(target_parent)
|
2016-06-02 11:05:42 +05:30
|
|
|
return @text unless needs_rewrite?
|
|
|
|
|
|
|
|
@text.gsub(@pattern) do |markdown|
|
2020-06-23 00:09:42 +05:30
|
|
|
file = find_file($~[:secret], $~[:file])
|
|
|
|
# No file will be returned for a path traversal
|
|
|
|
next if file.nil?
|
2020-03-28 13:19:24 +05:30
|
|
|
|
2018-10-15 14:42:47 +05:30
|
|
|
break markdown unless file.try(:exists?)
|
2016-06-02 11:05:42 +05:30
|
|
|
|
2019-02-15 15:39:39 +05:30
|
|
|
klass = target_parent.is_a?(Namespace) ? NamespaceFileUploader : FileUploader
|
|
|
|
moved = klass.copy_to(file, target_parent)
|
2019-10-12 21:52:04 +05:30
|
|
|
|
|
|
|
moved_markdown = moved.markdown_link
|
|
|
|
|
|
|
|
# Prevents rewrite of plain links as embedded
|
|
|
|
if was_embedded?(markdown)
|
|
|
|
moved_markdown
|
|
|
|
else
|
2022-06-21 17:19:12 +05:30
|
|
|
moved_markdown.delete_prefix('!')
|
2019-10-12 21:52:04 +05:30
|
|
|
end
|
2016-06-02 11:05:42 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def needs_rewrite?
|
|
|
|
files.any?
|
|
|
|
end
|
|
|
|
|
|
|
|
def files
|
|
|
|
referenced_files = @text.scan(@pattern).map do
|
2020-06-23 00:09:42 +05:30
|
|
|
find_file($~[:secret], $~[:file])
|
2016-06-02 11:05:42 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
referenced_files.compact.select(&:exists?)
|
|
|
|
end
|
|
|
|
|
2019-10-12 21:52:04 +05:30
|
|
|
def was_embedded?(markdown)
|
|
|
|
markdown.starts_with?("!")
|
|
|
|
end
|
|
|
|
|
2020-06-23 00:09:42 +05:30
|
|
|
def find_file(secret, file_name)
|
|
|
|
UploaderFinder.new(@source_project, secret, file_name).execute
|
2017-08-17 22:00:37 +05:30
|
|
|
end
|
2016-06-02 11:05:42 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|