knowledge_base_rich_text_helper.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module KnowledgeBaseRichTextHelper
  3. def prepare_rich_text(input)
  4. prepare_rich_text_videos(prepare_rich_text_links(input))
  5. end
  6. def prepare_rich_text_links(input)
  7. scrubber = Loofah::Scrubber.new do |node|
  8. next if node.name != 'a'
  9. next if !node.key? 'data-target-type'
  10. case node['data-target-type']
  11. when 'knowledge-base-answer'
  12. if (translation = KnowledgeBase::Answer::Translation.find_by(id: node['data-target-id']))
  13. path = help_answer_path(translation.answer.category.translation_preferred(translation.kb_locale),
  14. translation,
  15. locale: translation.kb_locale.system_locale.locale)
  16. node['href'] = custom_path_if_needed path, translation.kb_locale.knowledge_base
  17. else
  18. node['href'] = '#'
  19. end
  20. end
  21. end
  22. Loofah.scrub_fragment(input, scrubber).to_s.html_safe # rubocop:disable Rails/OutputSafety
  23. end
  24. def prepare_rich_text_videos(input)
  25. input.gsub(%r{\((\s*)widget:(\s*)video\W([\s\S])+?\)}) do |match|
  26. settings = match
  27. .slice(1...-1)
  28. .split(',')
  29. .to_h { |pair| pair.split(':').map(&:strip) }
  30. .symbolize_keys
  31. url = case settings[:provider]
  32. when 'youtube'
  33. "https://www.youtube.com/embed/#{settings[:id]}"
  34. when 'vimeo'
  35. "https://player.vimeo.com/video/#{settings[:id]}"
  36. end
  37. return match if !url
  38. "<div class='videoWrapper'><iframe allowfullscreen id='#{settings[:provider]}#{settings[:id]}' type='text/html' src='#{url}' frameborder='0'></iframe></div>"
  39. end
  40. end
  41. def simplify_rich_text(input)
  42. scrubber_link = Loofah::Scrubber.new do |node|
  43. next if node.name != 'a'
  44. next if !node.key? 'data-target-type'
  45. node.replace node.text
  46. end
  47. scrubber_images = Loofah::Scrubber.new do |node|
  48. next if node.name != 'img'
  49. node.remove
  50. end
  51. Loofah
  52. .fragment(input)
  53. .scrub!(scrubber_link)
  54. .scrub!(scrubber_images)
  55. .to_s
  56. .gsub(%r{\((\s*)widget:(\s*)video\W([\s\S])+?\)}, '')
  57. .strip
  58. .html_safe # rubocop:disable Rails/OutputSafety
  59. end
  60. end