insert_inline_images.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class HtmlSanitizer
  3. module Scrubber
  4. class InsertInlineImages < Base
  5. attr_reader :attachments
  6. def initialize(attachments)
  7. @attachments = attachments
  8. super()
  9. end
  10. def scrub(node)
  11. return CONTINUE if !contains_inline_images?(node)
  12. attachment = matching_attachment(node)
  13. return CONTINUE if !attachment
  14. node.delete('cid')
  15. node['src'] = base64_data_url(attachment)
  16. end
  17. private
  18. def matching_attachment(node)
  19. node_cids = inline_images_cids(node)
  20. attachments.find do |elem|
  21. attachment_cid = elem.preferences&.dig('Content-ID')
  22. node_cids.include?(attachment_cid)
  23. end
  24. end
  25. def contains_inline_images?(node)
  26. return false if node.name != 'img'
  27. return false if !node['src']&.start_with?('cid:')
  28. true
  29. end
  30. def inline_images_cids(node)
  31. cid = node['src'].delete_prefix('cid:')
  32. [cid, "<#{cid}>"]
  33. end
  34. def base64_data_url(attachment)
  35. "data:#{attachment.preferences['Content-Type']};base64,#{Base64.strict_encode64(attachment.content)}"
  36. end
  37. end
  38. end
  39. end