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