renderer.rb 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # Copyright (C) 2012-2024 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')
  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, escaping: true)
  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', 'ticket.group.name' => 'ticket.group.fullname', 'group.name' => 'group.fullname' }
  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. method_whitelist = %w[avatar]
  79. previous_object_refs = ''
  80. object_methods_s = ''
  81. object_methods.each_with_index do |method_raw, index|
  82. method = method_raw.strip
  83. if method == 'value'
  84. escape = textarea_attributes(previous_object_refs).exclude?(object_methods_s.split('.').last)
  85. temp = object_refs
  86. object_refs = display_value(previous_object_refs, method, object_methods_s, object_refs)
  87. previous_object_refs = temp
  88. elsif index == object_methods.length - 1 && (is_textarea_attribute = textarea_attributes(object_refs).include?(method))
  89. temp = object_refs
  90. object_refs = object_refs.send(method.to_sym)&.text2html
  91. previous_object_refs = temp
  92. escape = false
  93. end
  94. if object_methods_s != ''
  95. object_methods_s += '.'
  96. end
  97. object_methods_s += method
  98. next if method == 'value' || is_textarea_attribute
  99. if object_methods_s == ''
  100. value = debug("\#{#{object_name}.#{object_methods_s} / no such method}")
  101. break
  102. end
  103. arguments = nil
  104. if %r{\A(?<method_id>[^(]+)\((?<parameter>[^)]+)\)\z} =~ method
  105. parameters = []
  106. parameter.split(',').each do |p|
  107. p = p.strip!
  108. if p != p.to_i.to_s
  109. value = debug("\#{#{object_name}.#{object_methods_s} / invalid parameter: #{p}}")
  110. break
  111. end
  112. parameters << parameter.to_i
  113. end
  114. # Ensure that e.g. 'ticket.title.slice(3,4)' is not allowed, but 'ticket.owner.avatar(150,150)' is
  115. if !parameters.size.eql?(1) && method_whitelist.exclude?(method_id)
  116. value = debug("\#{#{object_name}.#{object_methods_s} / invalid parameter: #{parameter}}")
  117. break
  118. end
  119. begin
  120. arguments = parameters
  121. method = method_id
  122. rescue
  123. value = debug("\#{#{object_name}.#{object_methods_s} / #{e.message}}")
  124. break
  125. end
  126. end
  127. # if method exists
  128. if !object_refs.respond_to?(method.to_sym) && method_whitelist.exclude?(method)
  129. value = debug("\#{#{object_name}.#{object_methods_s} / no such method}")
  130. break
  131. end
  132. begin
  133. previous_object_refs = object_refs
  134. if method.to_sym.eql?(:avatar)
  135. object_refs = handle_user_avatar(previous_object_refs, *arguments)
  136. escape = false
  137. break
  138. end
  139. object_refs = object_refs.send(method.to_sym, *arguments)
  140. # body_as_html should trigger the cloning of all inline attachments from the parent article (issue #2399)
  141. if method.to_sym == :body_as_html && previous_object_refs.respond_to?(:should_clone_inline_attachments)
  142. previous_object_refs.should_clone_inline_attachments = true
  143. end
  144. rescue => e
  145. value = debug("\#{#{object_name}.#{object_methods_s} / #{e.message}}")
  146. break
  147. end
  148. end
  149. placeholder = value || object_refs
  150. return placeholder if !escaping
  151. escaping(convert_to_timezone(placeholder), escape)
  152. end
  153. # c - config
  154. # c('fqdn', htmlEscape)
  155. def c(key, escape = nil)
  156. config = Setting.get(key)
  157. escaping(config, escape)
  158. end
  159. # t - translation
  160. # t('yes', htmlEscape)
  161. def t(key, escape = nil)
  162. translation = Translation.translate(@locale, key)
  163. escaping(translation, escape)
  164. end
  165. # h - htmlEscape
  166. # h(htmlEscape)
  167. def h(value)
  168. return value if !value
  169. CGI.escapeHTML(convert_to_timezone(value).to_s)
  170. end
  171. def dt(params_string)
  172. datetime_object, format_string, timezone = params_string.scan(%r{(?:['"].*?["']|[^,])+}).map do |param|
  173. param.strip.sub(%r{^["']}, '').sub(%r{["']$}, '')
  174. end
  175. return debug("\#{datetime object missing / invalid parameter}") if datetime_object.blank?
  176. value = d(datetime_object, escaping: false)
  177. allowed_classes = %w[ActiveSupport::TimeWithZone Date Time DateTime].freeze
  178. return debug("\#{#{datetime_object} / invalid parameter}") if allowed_classes.exclude?(value.class.to_s)
  179. format_string = format_string.presence || '%Y-%m-%d %H:%M:%S'
  180. timezone = timezone.presence || @timezone
  181. begin
  182. result = value.in_time_zone(timezone).strftime(format_string)
  183. rescue
  184. return debug("\#{#{timezone} / invalid parameter}")
  185. end
  186. result
  187. end
  188. private
  189. def debug(message)
  190. @debug_errors ? message : '-'
  191. end
  192. def convert_to_timezone(value)
  193. return Translation.timestamp(@locale, @timezone, value) if value.instance_of?(ActiveSupport::TimeWithZone)
  194. return Translation.date(@locale, value) if value.instance_of?(Date)
  195. value
  196. end
  197. def escaping(key, escape)
  198. return escaping(key['value'], escape) if key.is_a?(Hash) && key.key?('value')
  199. return escaping(key.join(', '), escape) if key.respond_to?(:join)
  200. return key if escape == false
  201. return key if escape.nil? && !@escape && !@url_encode
  202. return ERB::Util.url_encode(key) if @url_encode
  203. h key
  204. end
  205. def data_key_valid?(key)
  206. 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
  207. true
  208. end
  209. def select_value(attribute, key)
  210. key = Array(key)
  211. options = attribute.data_option['options']
  212. if options.is_a?(Array)
  213. key.map { |k| options.detect { |o| o['value'] == k }&.dig('name') || k }
  214. else
  215. key.map { |k| options[k] || k }
  216. end
  217. end
  218. def display_value(object, method_name, previous_method_names, key)
  219. return key if method_name != 'value' ||
  220. (!key.instance_of?(String) && !key.instance_of?(Array) && !key.is_a?(Hash))
  221. attribute = object_manager_attributes(object)
  222. .where(name: previous_method_names.split('.').last)
  223. .first
  224. case attribute.data_type
  225. when %r{^(multi)?select$}
  226. select_value(attribute, key)
  227. when 'textarea'
  228. key.text2html
  229. when 'autocompletion_ajax_external_data_source'
  230. key['label']
  231. else
  232. key
  233. end
  234. end
  235. def handle_user_avatar(user, width = 60, height = 60)
  236. return if user.image.blank?
  237. file = avatar_file(user.image)
  238. return if file.nil?
  239. file_content_type = file.preferences['Content-Type'] || file.preferences['Mime-Type']
  240. "<img src='data:#{file_content_type};base64,#{Base64.strict_encode64(file.content)}' width='#{width}' height='#{height}' />"
  241. end
  242. def avatar_file(image_hash)
  243. Avatar.get_by_hash(image_hash)
  244. rescue
  245. nil
  246. end
  247. def object_manager_attributes(object)
  248. ObjectManager::Attribute.where(object_lookup_id: ObjectLookup.by_name(object.class.to_s))
  249. end
  250. def textarea_attributes(object)
  251. object_manager_attributes(object).where(data_type: :textarea).map(&:name)
  252. end
  253. end