You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

external_links_filter.rb 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006- Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. require 'uri'
  19. module Redmine
  20. module WikiFormatting
  21. module CommonMark
  22. # adds class="external" to external links, and class="email" to mailto
  23. # links
  24. class ExternalLinksFilter < HTML::Pipeline::Filter
  25. def call
  26. doc.search("a").each do |node|
  27. url = node["href"]
  28. next unless url
  29. next if url.starts_with?("/") || url.starts_with?("#") || !url.include?(':')
  30. scheme = begin
  31. URI.parse(url).scheme
  32. rescue
  33. nil
  34. end
  35. next if scheme.blank?
  36. klass = node["class"].presence
  37. node["class"] = [
  38. klass,
  39. (scheme == "mailto" ? "email" : "external")
  40. ].compact.join " "
  41. if node["target"].present? && scheme != "mailto"
  42. rel = node["rel"]&.split || []
  43. rel << "noopener"
  44. node["rel"] = rel.join(" ")
  45. end
  46. end
  47. doc
  48. end
  49. end
  50. end
  51. end
  52. end