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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2021 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 < ActiveRecord::Base
  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. ISO-2022-JP
  52. ISO-8859-1
  53. ISO-8859-2
  54. ISO-8859-3
  55. ISO-8859-4
  56. ISO-8859-5
  57. ISO-8859-6
  58. ISO-8859-7
  59. ISO-8859-8
  60. ISO-8859-9
  61. ISO-8859-13
  62. ISO-8859-15
  63. KOI8-R
  64. UTF-8
  65. UTF-16
  66. UTF-16BE
  67. UTF-16LE
  68. EUC-JP
  69. Shift_JIS
  70. CP932
  71. GB18030
  72. GBK
  73. EUC-KR
  74. Big5
  75. Big5-HKSCS
  76. TIS-620)
  77. cattr_accessor :available_settings
  78. self.available_settings ||= {}
  79. validates_uniqueness_of(
  80. :name,
  81. :case_sensitive => true,
  82. :if => Proc.new do |setting|
  83. setting.new_record? || setting.name_changed?
  84. end
  85. )
  86. validates_inclusion_of :name, :in => Proc.new {available_settings.keys}
  87. validates_numericality_of(
  88. :value, :only_integer => true,
  89. :if => Proc.new do |setting|
  90. (s = available_settings[setting.name]) && s['format'] == 'int'
  91. end
  92. )
  93. # Hash used to cache setting values
  94. @cached_settings = {}
  95. @cached_cleared_on = Time.now
  96. def value
  97. v = read_attribute(:value)
  98. # Unserialize serialized settings
  99. if available_settings[name]['serialized'] && v.is_a?(String)
  100. # YAML.load works as YAML.safe_load if Psych >= 4.0 is installed
  101. v = YAML.respond_to?(:unsafe_load) ? YAML.unsafe_load(v) : YAML.load(v)
  102. v = force_utf8_strings(v)
  103. end
  104. v = v.to_sym if available_settings[name]['format'] == 'symbol' && !v.blank?
  105. v
  106. end
  107. def value=(v)
  108. v = v.to_yaml if v && available_settings[name] && available_settings[name]['serialized']
  109. write_attribute(:value, v.to_s)
  110. end
  111. # Returns the value of the setting named name
  112. def self.[](name)
  113. @cached_settings[name] ||= find_or_default(name).value
  114. end
  115. def self.[]=(name, v)
  116. setting = find_or_default(name)
  117. setting.value = v || ''
  118. @cached_settings[name] = nil
  119. setting.save
  120. setting.value
  121. end
  122. # Updates multiple settings from params and sends a security notification if needed
  123. def self.set_all_from_params(settings)
  124. return nil unless settings.is_a?(Hash)
  125. settings = settings.dup.symbolize_keys
  126. errors = validate_all_from_params(settings)
  127. return errors if errors.present?
  128. changes = []
  129. settings.each do |name, value|
  130. next unless available_settings[name.to_s]
  131. previous_value = Setting[name]
  132. set_from_params name, value
  133. if available_settings[name.to_s]['security_notifications'] && Setting[name] != previous_value
  134. changes << name
  135. end
  136. end
  137. if changes.any?
  138. Mailer.deliver_settings_updated(User.current, changes)
  139. end
  140. nil
  141. end
  142. def self.validate_all_from_params(settings)
  143. messages = []
  144. [
  145. [:mail_handler_enable_regex_delimiters,
  146. :mail_handler_body_delimiters,
  147. /[\r\n]+/],
  148. [:mail_handler_enable_regex_excluded_filenames,
  149. :mail_handler_excluded_filenames,
  150. /\s*,\s*/]
  151. ].each do |enable_regex, regex_field, delimiter|
  152. if settings.key?(regex_field) || settings.key?(enable_regex)
  153. regexp = Setting.send("#{enable_regex}?")
  154. if settings.key?(enable_regex)
  155. regexp = settings[enable_regex].to_s != '0'
  156. end
  157. if regexp
  158. settings[regex_field].to_s.split(delimiter).each do |value|
  159. begin
  160. Regexp.new(value)
  161. rescue RegexpError => e
  162. messages << [regex_field, "#{l('activerecord.errors.messages.not_a_regexp')} (#{e.message})"]
  163. end
  164. end
  165. end
  166. end
  167. end
  168. if settings.key?(:mail_from)
  169. begin
  170. mail_from = Mail::Address.new(settings[:mail_from])
  171. raise unless EmailAddress::EMAIL_REGEXP.match?(mail_from.address)
  172. rescue
  173. messages << [:mail_from, l('activerecord.errors.messages.invalid')]
  174. end
  175. end
  176. messages
  177. end
  178. # Sets a setting value from params
  179. def self.set_from_params(name, params)
  180. params = params.dup
  181. params.delete_if {|v| v.blank?} if params.is_a?(Array)
  182. params.symbolize_keys! if params.is_a?(Hash)
  183. m = "#{name}_from_params"
  184. if respond_to? m
  185. self[name.to_sym] = send m, params
  186. else
  187. self[name.to_sym] = params
  188. end
  189. end
  190. # Returns a hash suitable for commit_update_keywords setting
  191. #
  192. # Example:
  193. # params = {:keywords => ['fixes', 'closes'], :status_id => ["3", "5"], :done_ratio => ["", "100"]}
  194. # Setting.commit_update_keywords_from_params(params)
  195. # # => [{'keywords => 'fixes', 'status_id' => "3"}, {'keywords => 'closes', 'status_id' => "5", 'done_ratio' => "100"}]
  196. def self.commit_update_keywords_from_params(params)
  197. s = []
  198. if params.is_a?(Hash) && params.key?(:keywords) && params.values.all? {|v| v.is_a? Array}
  199. attributes = params.except(:keywords).keys
  200. params[:keywords].each_with_index do |keywords, i|
  201. next if keywords.blank?
  202. s << attributes.inject({}) do |h, a|
  203. value = params[a][i].to_s
  204. h[a.to_s] = value if value.present?
  205. h
  206. end.merge('keywords' => keywords)
  207. end
  208. end
  209. s
  210. end
  211. def self.twofa_from_params(params)
  212. # unpair all current 2FA pairings when switching off 2FA
  213. Redmine::Twofa.unpair_all! if params == '0' && self.twofa?
  214. params
  215. end
  216. def self.twofa_required?
  217. twofa == '2'
  218. end
  219. def self.twofa_optional?
  220. twofa == '1'
  221. end
  222. # Helper that returns an array based on per_page_options setting
  223. def self.per_page_options_array
  224. per_page_options.split(%r{[\s,]}).collect(&:to_i).select {|n| n > 0}.sort
  225. end
  226. # Helper that returns a Hash with single update keywords as keys
  227. def self.commit_update_keywords_array
  228. a = []
  229. if commit_update_keywords.is_a?(Array)
  230. commit_update_keywords.each do |rule|
  231. next unless rule.is_a?(Hash)
  232. rule = rule.dup
  233. rule.delete_if {|k, v| v.blank?}
  234. keywords = rule['keywords'].to_s.downcase.split(",").map(&:strip).reject(&:blank?)
  235. next if keywords.empty?
  236. a << rule.merge('keywords' => keywords)
  237. end
  238. end
  239. a
  240. end
  241. # Checks if settings have changed since the values were read
  242. # and clears the cache hash if it's the case
  243. # Called once per request
  244. def self.check_cache
  245. settings_updated_on = Setting.maximum(:updated_on)
  246. if settings_updated_on && @cached_cleared_on <= settings_updated_on
  247. clear_cache
  248. end
  249. end
  250. # Clears the settings cache
  251. def self.clear_cache
  252. @cached_settings.clear
  253. @cached_cleared_on = Time.now
  254. logger.info "Settings cache cleared." if logger
  255. end
  256. def self.define_plugin_setting(plugin)
  257. if plugin.settings
  258. name = "plugin_#{plugin.id}"
  259. define_setting name, {'default' => plugin.settings[:default], 'serialized' => true}
  260. end
  261. end
  262. # Defines getter and setter for each setting
  263. # Then setting values can be read using: Setting.some_setting_name
  264. # or set using Setting.some_setting_name = "some value"
  265. def self.define_setting(name, options={})
  266. available_settings[name.to_s] = options
  267. src = <<~END_SRC
  268. def self.#{name}
  269. self[:#{name}]
  270. end
  271. def self.#{name}?
  272. self[:#{name}].to_i > 0
  273. end
  274. def self.#{name}=(value)
  275. self[:#{name}] = value
  276. end
  277. END_SRC
  278. class_eval src, __FILE__, __LINE__
  279. end
  280. def self.load_available_settings
  281. YAML::load(File.open("#{Rails.root}/config/settings.yml")).each do |name, options|
  282. define_setting name, options
  283. end
  284. end
  285. def self.load_plugin_settings
  286. Redmine::Plugin.all.each do |plugin|
  287. define_plugin_setting(plugin)
  288. end
  289. end
  290. load_available_settings
  291. load_plugin_settings
  292. private
  293. def force_utf8_strings(arg)
  294. if arg.is_a?(String)
  295. arg.dup.force_encoding('UTF-8')
  296. elsif arg.is_a?(Array)
  297. arg.map do |a|
  298. force_utf8_strings(a)
  299. end
  300. elsif arg.is_a?(Hash)
  301. arg = arg.dup
  302. arg.each do |k, v|
  303. arg[k] = force_utf8_strings(v)
  304. end
  305. arg
  306. else
  307. arg
  308. end
  309. end
  310. # Returns the Setting instance for the setting named name
  311. # (record found in database or new record with default value)
  312. def self.find_or_default(name)
  313. name = name.to_s
  314. raise "There's no setting named #{name}" unless available_settings.has_key?(name)
  315. setting = where(:name => name).order(:id => :desc).first
  316. unless setting
  317. setting = new
  318. setting.name = name
  319. setting.value = available_settings[name]['default']
  320. end
  321. setting
  322. end
  323. private_class_method :find_or_default
  324. end