text_module.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright (C) 2012-2025 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. include HasOptionalGroups
  11. validates :name, presence: true
  12. validates :content, presence: true
  13. before_create :validate_content
  14. before_update :validate_content
  15. validates :note, length: { maximum: 250 }
  16. sanitized_html :content, :note
  17. csv_delete_possible true
  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