text_module.rb 2.1 KB

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