gitlab-org--gitlab-foss/lib/banzai/filter/wiki_link_filter.rb

54 lines
1.3 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2016-04-01 03:17:37 +00:00
module Banzai
module Filter
# HTML filter that "fixes" links to pages/files in a wiki.
# Rewrite rules are documented in the `WikiPipeline` spec.
2016-04-01 03:17:37 +00:00
#
# Context options:
# :wiki
2016-04-01 03:17:37 +00:00
class WikiLinkFilter < HTML::Pipeline::Filter
include Gitlab::Utils::SanitizeNodeLink
2016-04-01 03:17:37 +00:00
def call
return doc unless wiki?
2016-04-01 03:17:37 +00:00
doc.search('a:not(.gfm)').each { |el| process_link(el.attribute('href'), el) }
doc.search('video, audio').each { |el| process_link(el.attribute('src'), el) }
doc.search('img').each do |el|
attr = el.attribute('data-src') || el.attribute('src')
process_link(attr, el)
2016-04-01 03:17:37 +00:00
end
doc
end
protected
def process_link(link_attr, node)
process_link_attr(link_attr)
remove_unsafe_links({ node: node }, remove_invalid_links: false)
end
def wiki?
!context[:wiki].nil?
2016-04-01 03:17:37 +00:00
end
def process_link_attr(html_attr)
return if html_attr.blank?
2016-04-01 03:17:37 +00:00
html_attr.value = apply_rewrite_rules(html_attr.value)
rescue URI::Error, Addressable::URI::InvalidURIError
2016-04-01 03:17:37 +00:00
# noop
end
def apply_rewrite_rules(link_string)
Rewriter.new(link_string, wiki: context[:wiki], slug: context[:page_slug]).apply_rules
2016-04-01 03:17:37 +00:00
end
end
end
end