text_module.rb 2.0 KB

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