renderer.rb 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class NotificationFactory::Renderer
  3. =begin
  4. examples how to use
  5. message_subject = NotificationFactory::Renderer.new(
  6. objects: {
  7. ticket: Ticket.first,
  8. },
  9. locale: 'de-de',
  10. timezone: 'America/Port-au-Prince',
  11. template: 'some template <b>#{ticket.title}</b> {config.fqdn}',
  12. escape: false, # Perform HTML encoding on replaced values
  13. url_encode: false, # Perform URI encoding on replaced values
  14. trusted: false, # Allow ERB tags in the template?
  15. ).render
  16. message_body = NotificationFactory::Renderer.new(
  17. objects: {
  18. ticket: Ticket.first,
  19. },
  20. locale: 'de-de',
  21. timezone: 'America/Port-au-Prince',
  22. template: 'some template <b>#{ticket.title}</b> #{config.fqdn}',
  23. ).render
  24. =end
  25. def initialize(objects:, template:, locale: nil, timezone: nil, escape: true, url_encode: false, trusted: false)
  26. @objects = objects
  27. @locale = locale || Locale.default
  28. @timezone = timezone || Setting.get('timezone_default_sanitized')
  29. @template = NotificationFactory::Template.new(template, escape || url_encode, trusted)
  30. @escape = escape
  31. @url_encode = url_encode
  32. end
  33. def render(debug_errors: true)
  34. @debug_errors = debug_errors
  35. ERB.new(@template.to_s).result(binding)
  36. rescue Exception => e # rubocop:disable Lint/RescueException
  37. raise StandardError, e.message if e.is_a? SyntaxError
  38. raise
  39. end
  40. # d - data of object
  41. # d('user.firstname', htmlEscape)
  42. def d(key, escape = nil)
  43. # do validation, ignore some methods
  44. return "\#{#{key} / not allowed}" if !data_key_valid?(key)
  45. article_tags = %w[article last_article last_internal_article last_external_article
  46. created_article created_internal_article created_external_article]
  47. # aliases
  48. map = { 'ticket.tags' => 'ticket.tag_list' }
  49. article_tags.each do |tag|
  50. map["#{tag}.body"] = "#{tag}.body_as_text_with_quote.text2html"
  51. end
  52. if map[key]
  53. key = map[key]
  54. end
  55. # escape in html mode
  56. if escape
  57. no_escape = {}
  58. article_tags.each do |tag|
  59. no_escape["#{tag}.body_as_html"] = true
  60. no_escape["#{tag}.body_as_text_with_quote.text2html"] = true
  61. end
  62. if no_escape[key]
  63. escape = false
  64. end
  65. end
  66. value = nil
  67. object_methods = key.split('.')
  68. object_name = object_methods.shift
  69. # if no object is given, just return
  70. return debug("\#{no such object}") if object_name.blank?
  71. object_refs = @objects[object_name] || @objects[object_name.to_sym]
  72. # if object is not in available objects, just return
  73. return debug("\#{#{object_name} / no such object}") if !object_refs
  74. # if content of method is a complex datatype, just return
  75. if object_methods.blank? && object_refs.class != String && object_refs.class != Float && object_refs.class != Integer
  76. return debug("\#{#{key} / no such method}")
  77. end
  78. previous_object_refs = ''
  79. object_methods_s = ''
  80. object_methods.each do |method_raw|
  81. method = method_raw.strip
  82. if method == 'value'
  83. temp = object_refs
  84. object_refs = display_value(previous_object_refs, method, object_methods_s, object_refs)
  85. previous_object_refs = temp
  86. end
  87. if object_methods_s != ''
  88. object_methods_s += '.'
  89. end
  90. object_methods_s += method
  91. next if method == 'value'
  92. if object_methods_s == ''
  93. value = debug("\#{#{object_name}.#{object_methods_s} / no such method}")
  94. break
  95. end
  96. arguments = nil
  97. if %r{\A(?<method_id>[^(]+)\((?<parameter>[^)]+)\)\z} =~ method
  98. if parameter != parameter.to_i.to_s
  99. value = debug("\#{#{object_name}.#{object_methods_s} / invalid parameter: #{parameter}}")
  100. break
  101. end
  102. begin
  103. arguments = Array(parameter.to_i)
  104. method = method_id
  105. rescue
  106. value = debug("\#{#{object_name}.#{object_methods_s} / #{e.message}}")
  107. break
  108. end
  109. end
  110. # if method exists
  111. if !object_refs.respond_to?(method.to_sym)
  112. value = debug("\#{#{object_name}.#{object_methods_s} / no such method}")
  113. break
  114. end
  115. begin
  116. previous_object_refs = object_refs
  117. object_refs = object_refs.send(method.to_sym, *arguments)
  118. # body_as_html should trigger the cloning of all inline attachments from the parent article (issue #2399)
  119. if method.to_sym == :body_as_html && previous_object_refs.respond_to?(:should_clone_inline_attachments)
  120. previous_object_refs.should_clone_inline_attachments = true
  121. end
  122. rescue => e
  123. value = debug("\#{#{object_name}.#{object_methods_s} / #{e.message}}")
  124. break
  125. end
  126. end
  127. placeholder = value || object_refs
  128. escaping(convert_to_timezone(placeholder), escape)
  129. end
  130. # c - config
  131. # c('fqdn', htmlEscape)
  132. def c(key, escape = nil)
  133. config = Setting.get(key)
  134. escaping(config, escape)
  135. end
  136. # t - translation
  137. # t('yes', htmlEscape)
  138. def t(key, escape = nil)
  139. translation = Translation.translate(@locale, key)
  140. escaping(translation, escape)
  141. end
  142. # h - htmlEscape
  143. # h(htmlEscape)
  144. def h(value)
  145. return value if !value
  146. CGI.escapeHTML(convert_to_timezone(value).to_s)
  147. end
  148. private
  149. def debug(message)
  150. @debug_errors ? message : '-'
  151. end
  152. def convert_to_timezone(value)
  153. return Translation.timestamp(@locale, @timezone, value) if value.instance_of?(ActiveSupport::TimeWithZone)
  154. return Translation.date(@locale, value) if value.instance_of?(Date)
  155. value
  156. end
  157. def escaping(key, escape)
  158. return escaping(key.join(', '), escape) if key.respond_to?(:join)
  159. return key if escape == false
  160. return key if escape.nil? && !@escape && !@url_encode
  161. return ERB::Util.url_encode(key) if @url_encode
  162. h key
  163. end
  164. def data_key_valid?(key)
  165. return false if key =~ %r{`|\.(|\s*)(save|destroy|delete|remove|drop|update|create|new|all|where|find|raise|dump|rollback|freeze)}i && key !~ %r{(update|create)d_(at|by)}i
  166. true
  167. end
  168. def select_value(attribute, key)
  169. key = Array(key)
  170. options = attribute.data_option['options']
  171. if options.is_a?(Array)
  172. key.map { |k| options.detect { |o| o['value'] == k }&.dig('name') || k }
  173. else
  174. key.map { |k| options[k] || k }
  175. end
  176. end
  177. def display_value(object, method_name, previous_method_names, key)
  178. return key if method_name != 'value' ||
  179. (!key.instance_of?(String) && !key.instance_of?(Array))
  180. attributes = ObjectManager::Attribute
  181. .where(object_lookup_id: ObjectLookup.by_name(object.class.to_s))
  182. .where(name: previous_method_names.split('.').last)
  183. case attributes.first.data_type
  184. when %r{^(multi)?select$}
  185. select_value(attributes.first, key)
  186. else
  187. key
  188. end
  189. end
  190. end