text_module.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class TextModule < ApplicationModel
  3. include ChecksClientNotification
  4. include ChecksHtmlSanitized
  5. include CanCsvImport
  6. validates :name, presence: true
  7. validates :content, presence: true
  8. before_create :validate_content
  9. before_update :validate_content
  10. sanitized_html :content, :note
  11. csv_delete_possible true
  12. has_and_belongs_to_many :groups, after_add: :cache_update, after_remove: :cache_update, class_name: 'Group'
  13. association_attributes_ignored :user
  14. =begin
  15. import text modules from i18n/text_modules/*.yml if no text modules exist yet.
  16. TextModule.load('de-de') # e. g. 'en-us' or 'de-de'
  17. =end
  18. def self.load(locale)
  19. raise __('Got no locale') if locale.blank?
  20. return if !TextModule.count.zero?
  21. locale = locale.split(',').first.downcase # in case of accept_language header is given
  22. # First check the full locale, e.g. 'de-de'.
  23. filename = Rails.root.join("i18n/text_modules/#{locale}.yml")
  24. if !File.exist?(filename)
  25. # Fall back to the more generic language if needed, e.g. 'de'.
  26. locale = locale.split('-').first
  27. filename = Rails.root.join("i18n/text_modules/#{locale}.yml")
  28. end
  29. if !File.exist?(filename)
  30. # No text modules available for current locale data.
  31. return
  32. end
  33. file_content = File.read(filename)
  34. result = Psych.load(file_content)
  35. raise "Can't load text modules from #{filename}" if result.length.zero?
  36. ActiveRecord::Base.transaction do
  37. result.each do |text_module|
  38. text_module[:updated_by_id] = 1
  39. text_module[:created_by_id] = 1
  40. TextModule.create(text_module.symbolize_keys!)
  41. end
  42. end
  43. true
  44. end
  45. private
  46. def validate_content
  47. return true if content.blank?
  48. return true if content.match?(%r{<.+?>})
  49. content.gsub!(%r{(\r\n|\n\r|\r)}, "\n")
  50. self.content = content.text2html
  51. true
  52. end
  53. end