knowledge_base.rb 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class KnowledgeBase < ApplicationModel
  3. include HasTranslations
  4. include HasAgentAllowedParams
  5. include ChecksKbClientNotification
  6. AGENT_ALLOWED_NESTED_RELATIONS = %i[translations].freeze
  7. LAYOUTS = %w[grid list].freeze
  8. ICONSETS = %w[FontAwesome anticon material ionicons Simple-Line-Icons].freeze
  9. has_many :kb_locales, class_name: 'KnowledgeBase::Locale',
  10. inverse_of: :knowledge_base,
  11. dependent: :destroy
  12. accepts_nested_attributes_for :kb_locales, allow_destroy: true
  13. validates :kb_locales, presence: true
  14. validates :kb_locales, length: { maximum: 1, message: __('System supports only one locale for knowledge base. Upgrade your plan to use more locales.') }, unless: :multi_lingual_support?
  15. has_many :categories, class_name: 'KnowledgeBase::Category',
  16. inverse_of: :knowledge_base,
  17. dependent: :restrict_with_exception
  18. has_many :answers, through: :categories
  19. has_many :permissions, class_name: 'KnowledgeBase::Permission',
  20. as: :permissionable,
  21. autosave: true,
  22. dependent: :destroy
  23. validates :category_layout, inclusion: { in: KnowledgeBase::LAYOUTS }
  24. validates :homepage_layout, inclusion: { in: KnowledgeBase::LAYOUTS }
  25. validates :color_highlight, presence: true, color: true
  26. validates :color_header, presence: true, color: true
  27. validates :color_header_link, presence: true, color: true
  28. validates :iconset, inclusion: { in: KnowledgeBase::ICONSETS }
  29. scope :active, -> { where(active: true) }
  30. alias assets_essential assets
  31. def assets(data)
  32. return data if assets_added_to?(data)
  33. data = super(data)
  34. ApplicationModel::CanAssets.reduce(kb_locales + translations, data)
  35. end
  36. # assets without unnecessary bits
  37. def assets_public(data)
  38. data = assets_essential(data)
  39. data[:KnowledgeBase].each do |_, elem|
  40. elem.delete_if do |k, _|
  41. k.end_with?('_ids')
  42. end
  43. end
  44. data
  45. end
  46. def custom_address_uri
  47. return nil if custom_address.blank?
  48. scheme = Setting.get('http_type') || 'http'
  49. URI("#{scheme}://#{custom_address}")
  50. rescue URI::InvalidURIError
  51. nil
  52. end
  53. def custom_address_matches?(request)
  54. uri = custom_address_uri
  55. return false if uri.blank?
  56. given_fqdn = request.headers.env['SERVER_NAME']&.downcase
  57. given_path = request.headers.env['HTTP_X_ORIGINAL_URL']&.downcase
  58. # original url header not present, server not configured
  59. return false if given_path.nil?
  60. # path doesn't match
  61. return false if uri.path.downcase != given_path[0, uri.path.length]
  62. # domain present, but doesn't match
  63. return false if uri.host.present? && uri.host.downcase != given_fqdn
  64. true
  65. rescue URI::InvalidURIError
  66. false
  67. end
  68. def custom_address_prefix(request)
  69. host = custom_address_uri.host.presence || request.headers.env['SERVER_NAME']
  70. port = request.headers.env['SERVER_PORT']
  71. port_silent = (request.ssl? && port == '443') || (!request.ssl? && port == '80')
  72. port_string = port_silent ? '' : ":#{port}"
  73. "#{custom_address_uri.scheme}://#{host}#{port_string}"
  74. end
  75. def custom_address_path(path)
  76. uri = custom_address_uri
  77. return path if !uri
  78. custom_path = custom_address_uri.path || ''
  79. applied_path = path.gsub(%r{^/help}, custom_path)
  80. applied_path.presence || '/'
  81. end
  82. def canonical_host
  83. custom_address_uri&.host.presence || Setting.get('fqdn')
  84. end
  85. def canonical_scheme_host
  86. "#{Setting.get('http_type')}://#{canonical_host}"
  87. end
  88. def canonical_url(path)
  89. "#{canonical_scheme_host}#{custom_address_path(path)}"
  90. end
  91. def full_destroy!
  92. ChecksKbClientNotification.disable_in_all_classes!
  93. transaction do
  94. # get all categories with their children and reverse to delete children first
  95. categories.root.map(&:self_with_children).flatten.reverse.each(&:full_destroy!)
  96. translations.each(&:destroy!)
  97. kb_locales.each(&:destroy!)
  98. destroy!
  99. end
  100. ensure
  101. ChecksKbClientNotification.enable_in_all_classes!
  102. end
  103. def visible?
  104. active?
  105. end
  106. def api_url
  107. Rails.application.routes.url_helpers.knowledge_base_path(self)
  108. end
  109. def load_category(locale, id)
  110. categories.localed(locale).find_by(id: id)
  111. end
  112. def self.with_multiple_locales_exists?
  113. KnowledgeBase
  114. .active
  115. .joins(:kb_locales)
  116. .group('knowledge_bases.id')
  117. .pluck(Arel.sql('COUNT(knowledge_base_locales.id) as locales_count'))
  118. .any? { |e| e > 1 }
  119. end
  120. def permissions_effective
  121. cache_key = KnowledgeBase::Permission.cache_key self
  122. Rails.cache.fetch cache_key do
  123. permissions
  124. end
  125. end
  126. def attributes_with_association_ids
  127. attrs = super
  128. attrs[:permissions_effective] = permissions_effective
  129. attrs
  130. end
  131. def self.granular_permissions?
  132. KnowledgeBase::Permission.any?
  133. end
  134. def public_content?(kb_locale = nil)
  135. scope = answers.published
  136. scope = scope.localed(kb_locale.system_locale) if kb_locale
  137. scope.any?
  138. end
  139. private
  140. def set_defaults
  141. self.translations = kb_locales.map do |kb_locale|
  142. name = Setting.get('organization').presence || Setting.get('product_name').presence || 'Zammad'
  143. kb_suffix = ::Translation.translate kb_locale.system_locale.locale, 'Knowledge Base'
  144. KnowledgeBase::Translation.new(
  145. title: "#{name} #{kb_suffix}",
  146. footer_note: "© #{name}",
  147. kb_locale: kb_locale
  148. )
  149. end
  150. end
  151. before_validation :patch_custom_address
  152. after_create :set_defaults
  153. def validate_custom_address
  154. return if custom_address.nil?
  155. # not domain, but no leading slash
  156. if custom_address.exclude?('.') && custom_address[0] != '/'
  157. errors.add(:custom_address, 'must begin with a slash ("/").')
  158. end
  159. if custom_address.include?('://')
  160. errors.add(:custom_address, 'must not include a protocol (e.g., "http://" or "https://").')
  161. end
  162. if custom_address.last == '/'
  163. errors.add(:custom_address, 'must not end with a slash ("/").')
  164. end
  165. if custom_address == '/' # rubocop:disable Style/GuardClause
  166. errors.add(:custom_address, __('Please enter valid path or domain'))
  167. end
  168. end
  169. validate :validate_custom_address
  170. def patch_custom_address
  171. self.custom_address = nil if custom_address == ''
  172. end
  173. def multi_lingual_support?
  174. Setting.get 'kb_multi_lingual_support'
  175. end
  176. def set_kb_active_setting
  177. Setting.set 'kb_active', KnowledgeBase.active.exists?
  178. CanBePublished.update_active_publicly!
  179. end
  180. after_destroy :set_kb_active_setting
  181. after_save :set_kb_active_setting
  182. end