You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.rb 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2023 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. class Setting < ApplicationRecord
  19. PASSWORD_CHAR_CLASSES = {
  20. 'uppercase' => /[A-Z]/,
  21. 'lowercase' => /[a-z]/,
  22. 'digits' => /[0-9]/,
  23. 'special_chars' => /[[:ascii:]&&[:graph:]&&[:^alnum:]]/
  24. }
  25. DATE_FORMATS = [
  26. '%Y-%m-%d',
  27. '%d/%m/%Y',
  28. '%d.%m.%Y',
  29. '%d-%m-%Y',
  30. '%m/%d/%Y',
  31. '%d %b %Y',
  32. '%d %B %Y',
  33. '%b %d, %Y',
  34. '%B %d, %Y'
  35. ]
  36. TIME_FORMATS = [
  37. '%H:%M',
  38. '%I:%M %p'
  39. ]
  40. ENCODINGS = %w(US-ASCII
  41. windows-1250
  42. windows-1251
  43. windows-1252
  44. windows-1253
  45. windows-1254
  46. windows-1255
  47. windows-1256
  48. windows-1257
  49. windows-1258
  50. windows-31j
  51. windows-874
  52. ISO-2022-JP
  53. ISO-8859-1
  54. ISO-8859-2
  55. ISO-8859-3
  56. ISO-8859-4
  57. ISO-8859-5
  58. ISO-8859-6
  59. ISO-8859-7
  60. ISO-8859-8
  61. ISO-8859-9
  62. ISO-8859-13
  63. ISO-8859-15
  64. KOI8-R
  65. UTF-8
  66. UTF-16
  67. UTF-16BE
  68. UTF-16LE
  69. EUC-JP
  70. Shift_JIS
  71. CP932
  72. CP949
  73. GB18030
  74. GBK
  75. EUC-KR
  76. Big5
  77. Big5-HKSCS
  78. TIS-620)
  79. cattr_accessor :available_settings
  80. self.available_settings ||= {}
  81. validates_uniqueness_of(
  82. :name,
  83. :case_sensitive => true,
  84. :if => Proc.new do |setting|
  85. setting.new_record? || setting.name_changed?
  86. end
  87. )
  88. validates_inclusion_of :name, :in => Proc.new {available_settings.keys}
  89. validates_numericality_of(
  90. :value, :only_integer => true,
  91. :if => Proc.new do |setting|
  92. (s = available_settings[setting.name]) && s['format'] == 'int'
  93. end
  94. )
  95. # Hash used to cache setting values
  96. @cached_settings = {}
  97. @cached_cleared_on = Time.now
  98. def value
  99. v = read_attribute(:value)
  100. # Unserialize serialized settings
  101. if available_settings[name]['serialized'] && v.is_a?(String)
  102. v = YAML.safe_load(v, permitted_classes: Rails.configuration.active_record.yaml_column_permitted_classes)
  103. v = force_utf8_strings(v)
  104. end
  105. v = v.to_sym if available_settings[name]['format'] == 'symbol' && v.present?
  106. v
  107. end
  108. def value=(v)
  109. v = v.to_yaml if v && available_settings[name] && available_settings[name]['serialized']
  110. write_attribute(:value, v.to_s)
  111. end
  112. # Returns the value of the setting named name
  113. def self.[](name)
  114. @cached_settings[name] ||= find_or_default(name).value
  115. end
  116. def self.[]=(name, v)
  117. setting = find_or_default(name)
  118. setting.value = v || ''
  119. @cached_settings[name] = nil
  120. setting.save
  121. setting.value
  122. end
  123. # Updates multiple settings from params and sends a security notification if needed
  124. def self.set_all_from_params(settings)
  125. return nil unless settings.is_a?(Hash)
  126. settings = settings.dup.symbolize_keys
  127. errors = validate_all_from_params(settings)
  128. return errors if errors.present?
  129. changes = []
  130. settings.each do |name, value|
  131. next unless available_settings[name.to_s]
  132. previous_value = Setting[name]
  133. set_from_params name, value
  134. if available_settings[name.to_s]['security_notifications'] && Setting[name] != previous_value
  135. changes << name
  136. end
  137. end
  138. if changes.any?
  139. Mailer.deliver_settings_updated(User.current, changes)
  140. end
  141. nil
  142. end
  143. def self.validate_all_from_params(settings)
  144. messages = []
  145. [
  146. [:mail_handler_enable_regex_delimiters,
  147. :mail_handler_body_delimiters,
  148. /[\r\n]+/],
  149. [:mail_handler_enable_regex_excluded_filenames,
  150. :mail_handler_excluded_filenames,
  151. /\s*,\s*/]
  152. ].each do |enable_regex, regex_field, delimiter|
  153. if settings.key?(regex_field) || settings.key?(enable_regex)
  154. regexp = Setting.send(:"#{enable_regex}?")
  155. if settings.key?(enable_regex)
  156. regexp = settings[enable_regex].to_s != '0'
  157. end
  158. if regexp
  159. settings[regex_field].to_s.split(delimiter).each do |value|
  160. begin
  161. Regexp.new(value)
  162. rescue RegexpError => e
  163. messages << [regex_field, "#{l('activerecord.errors.messages.not_a_regexp')} (#{e.message})"]
  164. end
  165. end
  166. end
  167. end
  168. end
  169. if settings.key?(:mail_from)
  170. begin
  171. mail_from = Mail::Address.new(settings[:mail_from])
  172. raise unless URI::MailTo::EMAIL_REGEXP.match?(mail_from.address)
  173. rescue
  174. messages << [:mail_from, l('activerecord.errors.messages.invalid')]
  175. end
  176. end
  177. messages
  178. end
  179. # Sets a setting value from params
  180. def self.set_from_params(name, params)
  181. params = params.dup
  182. params.delete_if {|v| v.blank?} if params.is_a?(Array)
  183. params.symbolize_keys! if params.is_a?(Hash)
  184. m = "#{name}_from_params"
  185. if respond_to? m
  186. self[name.to_sym] = send m, params
  187. else
  188. self[name.to_sym] = params
  189. end
  190. end
  191. # Returns a hash suitable for commit_update_keywords setting
  192. #
  193. # Example:
  194. # params = {:keywords => ['fixes', 'closes'], :status_id => ["3", "5"], :done_ratio => ["", "100"]}
  195. # Setting.commit_update_keywords_from_params(params)
  196. # # => [{'keywords => 'fixes', 'status_id' => "3"}, {'keywords => 'closes', 'status_id' => "5", 'done_ratio' => "100"}]
  197. def self.commit_update_keywords_from_params(params)
  198. s = []
  199. if params.is_a?(Hash) && params.key?(:keywords) && params.values.all?(Array)
  200. attributes = params.except(:keywords).keys
  201. params[:keywords].each_with_index do |keywords, i|
  202. next if keywords.blank?
  203. s << attributes.inject({}) do |h, a|
  204. value = params[a][i].to_s
  205. h[a.to_s] = value if value.present?
  206. h
  207. end.merge('keywords' => keywords)
  208. end
  209. end
  210. s
  211. end
  212. def self.twofa_from_params(params)
  213. # unpair all current 2FA pairings when switching off 2FA
  214. Redmine::Twofa.unpair_all! if params == '0' && self.twofa?
  215. params
  216. end
  217. def self.twofa_required?
  218. twofa == '2'
  219. end
  220. def self.twofa_optional?
  221. %w[1 3].include? twofa
  222. end
  223. def self.twofa_required_for_administrators?
  224. twofa == '3'
  225. end
  226. # Helper that returns an array based on per_page_options setting
  227. def self.per_page_options_array
  228. per_page_options.split(%r{[\s,]}).collect(&:to_i).select {|n| n > 0}.sort
  229. end
  230. # Helper that returns a Hash with single update keywords as keys
  231. def self.commit_update_keywords_array
  232. a = []
  233. if commit_update_keywords.is_a?(Array)
  234. commit_update_keywords.each do |rule|
  235. next unless rule.is_a?(Hash)
  236. rule = rule.dup
  237. rule.delete_if {|k, v| v.blank?}
  238. keywords = rule['keywords'].to_s.downcase.split(",").map(&:strip).reject(&:blank?)
  239. next if keywords.empty?
  240. a << rule.merge('keywords' => keywords)
  241. end
  242. end
  243. a
  244. end
  245. # Checks if settings have changed since the values were read
  246. # and clears the cache hash if it's the case
  247. # Called once per request
  248. def self.check_cache
  249. settings_updated_on = Setting.maximum(:updated_on)
  250. if settings_updated_on && @cached_cleared_on <= settings_updated_on
  251. clear_cache
  252. end
  253. end
  254. # Clears the settings cache
  255. def self.clear_cache
  256. @cached_settings.clear
  257. @cached_cleared_on = Time.now
  258. logger.info "Settings cache cleared." if logger
  259. end
  260. def self.define_plugin_setting(plugin)
  261. if plugin.settings
  262. name = "plugin_#{plugin.id}"
  263. define_setting name, {'default' => plugin.settings[:default], 'serialized' => true}
  264. end
  265. end
  266. # Defines getter and setter for each setting
  267. # Then setting values can be read using: Setting.some_setting_name
  268. # or set using Setting.some_setting_name = "some value"
  269. def self.define_setting(name, options={})
  270. available_settings[name.to_s] = options
  271. src = <<~END_SRC
  272. def self.#{name}
  273. self[:#{name}]
  274. end
  275. def self.#{name}?
  276. self[:#{name}].to_i > 0
  277. end
  278. def self.#{name}=(value)
  279. self[:#{name}] = value
  280. end
  281. END_SRC
  282. class_eval src, __FILE__, __LINE__
  283. end
  284. def self.load_available_settings
  285. YAML.load_file(Rails.root.join('config/settings.yml')).each do |name, options|
  286. define_setting name, options
  287. end
  288. end
  289. def self.load_plugin_settings
  290. Redmine::Plugin.all.each do |plugin|
  291. define_plugin_setting(plugin)
  292. end
  293. end
  294. load_available_settings
  295. load_plugin_settings
  296. private
  297. def force_utf8_strings(arg)
  298. if arg.is_a?(String)
  299. arg.dup.force_encoding('UTF-8')
  300. elsif arg.is_a?(Array)
  301. arg.map do |a|
  302. force_utf8_strings(a)
  303. end
  304. elsif arg.is_a?(Hash)
  305. arg = arg.dup
  306. arg.each do |k, v|
  307. arg[k] = force_utf8_strings(v)
  308. end
  309. arg
  310. else
  311. arg
  312. end
  313. end
  314. # Returns the Setting instance for the setting named name
  315. # (record found in database or new record with default value)
  316. def self.find_or_default(name)
  317. name = name.to_s
  318. raise "There's no setting named #{name}" unless available_settings.has_key?(name)
  319. setting = where(:name => name).order(:id => :desc).first
  320. unless setting
  321. setting = new
  322. setting.name = name
  323. setting.value = available_settings[name]['default']
  324. end
  325. setting
  326. end
  327. private_class_method :find_or_default
  328. end