template.rb 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. class NotificationFactory::Template
  2. =begin
  3. examples how to use
  4. cleaned_template = NotificationFactory::Template.new(
  5. 'some template <b>#{ticket.title}</b> #{config.fqdn}',
  6. true,
  7. ).to_s
  8. =end
  9. def initialize(template, escape)
  10. @template = template
  11. @escape = escape
  12. end
  13. def to_s
  14. @template.gsub(/\#{\s*(.*?)\s*}/m) do
  15. # some browsers start adding HTML tags
  16. # fixes https://github.com/zammad/zammad/issues/385
  17. input_template = $1.gsub(/\A<.+?>\s*|\s*<.+?>\z/, '')
  18. case input_template
  19. when /\At\('(.+?)'\)\z/m
  20. %(<%= t "#{sanitize_text($1)}", #{@escape} %>)
  21. when /\At\((.+?)\)\z/m
  22. %(<%= t d"#{sanitize_object_name($1)}", #{@escape} %>)
  23. when /\Aconfig\.(.+?)\z/m
  24. %(<%= c "#{sanitize_object_name($1)}", #{@escape} %>)
  25. else
  26. %(<%= d "#{sanitize_object_name(input_template)}", #{@escape} %>)
  27. end
  28. end
  29. end
  30. def sanitize_text(string)
  31. string&.tr("\t\r\n", '')
  32. &.gsub(/(?<!\\)(?=")/, '\\')
  33. end
  34. def sanitize_object_name(string)
  35. string&.tr("\t\r\n\f \"'§;", '')
  36. end
  37. end