debian-mirror-gitlab/lib/gitlab/gfm/uploads_rewriter.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

76 lines
1.9 KiB
Ruby
Raw Normal View History

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
2022-07-23 23:45:48 +05:30
include Gitlab::Utils::StrongMemoize
def initialize(text, _text_html, source_project, _current_user)
2016-06-02 11:05:42 +05:30
@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?
2022-10-02 17:18:49 +05:30
@target_parent = target_parent
2020-03-28 13:19:24 +05:30
2022-10-02 17:18:49 +05:30
rewritten_text = Gitlab::StringRegexMarker.new(@text).mark(@pattern) do |markdown, left:, right:, mode:|
transform_markdown(markdown)
2016-06-02 11:05:42 +05:30
end
2022-10-02 17:18:49 +05:30
# MarkdownContentRewriterService relies on the text being changed _in place_.
@text.gsub!(@text, rewritten_text)
2016-06-02 11:05:42 +05:30
end
def needs_rewrite?
2022-07-23 23:45:48 +05:30
strong_memoize(:needs_rewrite) do
2022-10-02 17:18:49 +05:30
@pattern.match?(@text)
2016-06-02 11:05:42 +05:30
end
end
2022-10-02 17:18:49 +05:30
private
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
2022-10-02 17:18:49 +05:30
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
2016-06-02 11:05:42 +05:30
end
end
end