template.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class NotificationFactory::Template
  3. =begin
  4. examples how to use
  5. cleaned_template = NotificationFactory::Template.new(
  6. 'some template <b>#{ticket.title}</b> #{config.fqdn}',
  7. true,
  8. false, # Allow ERB tags in the template?
  9. ).to_s
  10. =end
  11. def initialize(template, escape, trusted)
  12. @template = template
  13. @escape = escape
  14. @trusted = trusted
  15. end
  16. def to_s
  17. result = @template
  18. result.gsub!(%r{<%(?!%)}, '<%%') if !@trusted
  19. result = result.gsub(%r{(?<!\\)\#{\s*(.*?)\s*}}m) do
  20. # some browsers start adding HTML tags
  21. # fixes https://github.com/zammad/zammad/issues/385
  22. input_template = $1.gsub(%r{\A<.+?>\s*|\s*<.+?>\z}, '')
  23. case input_template
  24. when %r{\At\('(.+?)'\)\z}m
  25. %(<%= t "#{sanitize_text($1)}", #{@escape} %>)
  26. when %r{\At\((.+?)\)\z}m
  27. %(<%= t d"#{sanitize_object_name($1)}", #{@escape} %>)
  28. when %r{\Adt\((.+?)\)\z}m
  29. %(<%= dt "#{sanitize_text($1)}" %>)
  30. when %r{\Aconfig\.(.+?)\z}m
  31. %(<%= c "#{sanitize_object_name($1)}", #{@escape} %>)
  32. else
  33. %(<%= d "#{sanitize_object_name(input_template)}", #{@escape} %>)
  34. end
  35. end
  36. result.gsub(%r{\\\#{\s*(.*?)\s*}}m, '#{\1}') # rubocop:disable Lint/InterpolationCheck
  37. end
  38. def sanitize_text(string)
  39. string&.tr("\t\r\n", '')
  40. &.gsub(%r{(?<!\\)(?=")}, '\\')
  41. end
  42. def sanitize_object_name(string)
  43. string&.tr("\t\r\n\f \"'§;", '')
  44. end
  45. end