2018-11-18 11:00:15 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-06-02 11:05:42 +05:30
|
|
|
module Banzai
|
|
|
|
module Filter
|
2016-06-16 23:09:34 +05:30
|
|
|
# HTML filter that "fixes" links to pages/files in a wiki.
|
|
|
|
# Rewrite rules are documented in the `WikiPipeline` spec.
|
2016-06-02 11:05:42 +05:30
|
|
|
#
|
|
|
|
# Context options:
|
2020-06-23 00:09:42 +05:30
|
|
|
# :wiki
|
2016-06-02 11:05:42 +05:30
|
|
|
class WikiLinkFilter < HTML::Pipeline::Filter
|
2019-07-31 22:56:46 +05:30
|
|
|
include Gitlab::Utils::SanitizeNodeLink
|
|
|
|
|
2021-06-02 17:11:27 +05:30
|
|
|
CSS_A = 'a:not(.gfm)'
|
|
|
|
XPATH_A = Gitlab::Utils::Nokogiri.css_to_xpath(CSS_A).freeze
|
|
|
|
CSS_VA = 'video, audio'
|
|
|
|
XPATH_VA = Gitlab::Utils::Nokogiri.css_to_xpath(CSS_VA).freeze
|
|
|
|
CSS_IMG = 'img'
|
|
|
|
XPATH_IMG = Gitlab::Utils::Nokogiri.css_to_xpath(CSS_IMG).freeze
|
|
|
|
|
2016-06-02 11:05:42 +05:30
|
|
|
def call
|
2020-06-23 00:09:42 +05:30
|
|
|
return doc unless wiki?
|
2016-06-02 11:05:42 +05:30
|
|
|
|
2021-06-02 17:11:27 +05:30
|
|
|
doc.xpath(XPATH_A).each { |el| process_link(el.attribute('href'), el) }
|
2019-07-31 22:56:46 +05:30
|
|
|
|
2021-06-02 17:11:27 +05:30
|
|
|
doc.xpath(XPATH_VA).each { |el| process_link(el.attribute('src'), el) }
|
2019-07-31 22:56:46 +05:30
|
|
|
|
2021-06-02 17:11:27 +05:30
|
|
|
doc.xpath(XPATH_IMG).each do |el|
|
2018-11-20 20:47:30 +05:30
|
|
|
attr = el.attribute('data-src') || el.attribute('src')
|
|
|
|
|
2019-07-31 22:56:46 +05:30
|
|
|
process_link(attr, el)
|
2016-06-02 11:05:42 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
doc
|
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
2019-07-31 22:56:46 +05:30
|
|
|
def process_link(link_attr, node)
|
|
|
|
process_link_attr(link_attr)
|
|
|
|
remove_unsafe_links({ node: node }, remove_invalid_links: false)
|
|
|
|
end
|
|
|
|
|
2020-06-23 00:09:42 +05:30
|
|
|
def wiki?
|
|
|
|
!context[:wiki].nil?
|
2016-06-02 11:05:42 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
def process_link_attr(html_attr)
|
2016-06-16 23:09:34 +05:30
|
|
|
return if html_attr.blank?
|
2016-06-02 11:05:42 +05:30
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
html_attr.value = apply_rewrite_rules(html_attr.value)
|
2016-08-24 12:49:21 +05:30
|
|
|
rescue URI::Error, Addressable::URI::InvalidURIError
|
2016-06-02 11:05:42 +05:30
|
|
|
# noop
|
|
|
|
end
|
|
|
|
|
2016-06-16 23:09:34 +05:30
|
|
|
def apply_rewrite_rules(link_string)
|
2020-06-23 00:09:42 +05:30
|
|
|
Rewriter.new(link_string, wiki: context[:wiki], slug: context[:page_slug]).apply_rules
|
2016-06-02 11:05:42 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|