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.

63 lines
1.6 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-07-23 23:45:48 +05:30
@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?
2022-07-23 23:45:48 +05:30
strong_memoize(:needs_rewrite) do
FileUploader::MARKDOWN_PATTERN.match?(@text)
2016-06-02 11:05:42 +05:30
end
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