template.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright (C) 2012-2022 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.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{\Aconfig\.(.+?)\z}m
  29. %(<%= c "#{sanitize_object_name($1)}", #{@escape} %>)
  30. else
  31. %(<%= d "#{sanitize_object_name(input_template)}", #{@escape} %>)
  32. end
  33. end
  34. end
  35. def sanitize_text(string)
  36. string&.tr("\t\r\n", '')
  37. &.gsub(%r{(?<!\\)(?=")}, '\\')
  38. end
  39. def sanitize_object_name(string)
  40. string&.tr("\t\r\n\f \"'§;", '')
  41. end
  42. end