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.

field_format.rb 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2017 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. require 'uri'
  19. module Redmine
  20. module FieldFormat
  21. def self.add(name, klass)
  22. all[name.to_s] = klass.instance
  23. end
  24. def self.delete(name)
  25. all.delete(name.to_s)
  26. end
  27. def self.all
  28. @formats ||= Hash.new(Base.instance)
  29. end
  30. def self.available_formats
  31. all.keys
  32. end
  33. def self.find(name)
  34. all[name.to_s]
  35. end
  36. # Return an array of custom field formats which can be used in select_tag
  37. def self.as_select(class_name=nil)
  38. formats = all.values.select do |format|
  39. format.class.customized_class_names.nil? || format.class.customized_class_names.include?(class_name)
  40. end
  41. formats.map {|format| [::I18n.t(format.label), format.name] }.sort_by(&:first)
  42. end
  43. # Returns an array of formats that can be used for a custom field class
  44. def self.formats_for_custom_field_class(klass=nil)
  45. all.values.select do |format|
  46. format.class.customized_class_names.nil? || format.class.customized_class_names.include?(klass.name)
  47. end
  48. end
  49. class Base
  50. include Singleton
  51. include Redmine::I18n
  52. include Redmine::Helpers::URL
  53. include ERB::Util
  54. class_attribute :format_name
  55. self.format_name = nil
  56. # Set this to true if the format supports multiple values
  57. class_attribute :multiple_supported
  58. self.multiple_supported = false
  59. # Set this to true if the format supports filtering on custom values
  60. class_attribute :is_filter_supported
  61. self.is_filter_supported = true
  62. # Set this to true if the format supports textual search on custom values
  63. class_attribute :searchable_supported
  64. self.searchable_supported = false
  65. # Set this to true if field values can be summed up
  66. class_attribute :totalable_supported
  67. self.totalable_supported = false
  68. # Set this to false if field cannot be bulk edited
  69. class_attribute :bulk_edit_supported
  70. self.bulk_edit_supported = true
  71. # Restricts the classes that the custom field can be added to
  72. # Set to nil for no restrictions
  73. class_attribute :customized_class_names
  74. self.customized_class_names = nil
  75. # Name of the partial for editing the custom field
  76. class_attribute :form_partial
  77. self.form_partial = nil
  78. class_attribute :change_as_diff
  79. self.change_as_diff = false
  80. class_attribute :change_no_details
  81. self.change_no_details = false
  82. def self.add(name)
  83. self.format_name = name
  84. Redmine::FieldFormat.add(name, self)
  85. end
  86. private_class_method :add
  87. def self.field_attributes(*args)
  88. CustomField.store_accessor :format_store, *args
  89. end
  90. field_attributes :url_pattern, :full_width_layout
  91. def name
  92. self.class.format_name
  93. end
  94. def label
  95. "label_#{name}"
  96. end
  97. def set_custom_field_value(custom_field, custom_field_value, value)
  98. if value.is_a?(Array)
  99. value = value.map(&:to_s).reject{|v| v==''}.uniq
  100. if value.empty?
  101. value << ''
  102. end
  103. else
  104. value = value.to_s
  105. end
  106. value
  107. end
  108. def cast_custom_value(custom_value)
  109. cast_value(custom_value.custom_field, custom_value.value, custom_value.customized)
  110. end
  111. def cast_value(custom_field, value, customized=nil)
  112. if value.blank?
  113. nil
  114. elsif value.is_a?(Array)
  115. casted = value.map do |v|
  116. cast_single_value(custom_field, v, customized)
  117. end
  118. casted.compact.sort
  119. else
  120. cast_single_value(custom_field, value, customized)
  121. end
  122. end
  123. def cast_single_value(custom_field, value, customized=nil)
  124. value.to_s
  125. end
  126. def target_class
  127. nil
  128. end
  129. def possible_custom_value_options(custom_value)
  130. possible_values_options(custom_value.custom_field, custom_value.customized)
  131. end
  132. def possible_values_options(custom_field, object=nil)
  133. []
  134. end
  135. def value_from_keyword(custom_field, keyword, object)
  136. possible_values_options = possible_values_options(custom_field, object)
  137. if possible_values_options.present?
  138. parse_keyword(custom_field, keyword) do |k|
  139. if v = possible_values_options.detect {|text, id| k.casecmp(text) == 0}
  140. if v.is_a?(Array)
  141. v.last
  142. else
  143. v
  144. end
  145. end
  146. end
  147. else
  148. keyword
  149. end
  150. end
  151. def parse_keyword(custom_field, keyword, &block)
  152. separator = Regexp.escape ","
  153. keyword = keyword.dup.to_s
  154. if custom_field.multiple?
  155. values = []
  156. while keyword.length > 0
  157. k = keyword.dup
  158. loop do
  159. if value = yield(k.strip)
  160. values << value
  161. break
  162. elsif k.slice!(/#{separator}([^#{separator}]*)\Z/).nil?
  163. break
  164. end
  165. end
  166. keyword.slice!(/\A#{Regexp.escape k}#{separator}?/)
  167. end
  168. values
  169. else
  170. yield keyword.strip
  171. end
  172. end
  173. protected :parse_keyword
  174. # Returns the validation errors for custom_field
  175. # Should return an empty array if custom_field is valid
  176. def validate_custom_field(custom_field)
  177. errors = []
  178. pattern = custom_field.url_pattern
  179. if pattern.present? && !uri_with_safe_scheme?(url_pattern_without_tokens(pattern))
  180. errors << [:url_pattern, :invalid]
  181. end
  182. errors
  183. end
  184. # Returns the validation error messages for custom_value
  185. # Should return an empty array if custom_value is valid
  186. # custom_value is a CustomFieldValue.
  187. def validate_custom_value(custom_value)
  188. values = Array.wrap(custom_value.value).reject {|value| value.to_s == ''}
  189. errors = values.map do |value|
  190. validate_single_value(custom_value.custom_field, value, custom_value.customized)
  191. end
  192. errors.flatten.uniq
  193. end
  194. def validate_single_value(custom_field, value, customized=nil)
  195. []
  196. end
  197. # CustomValue after_save callback
  198. def after_save_custom_value(custom_field, custom_value)
  199. end
  200. def formatted_custom_value(view, custom_value, html=false)
  201. formatted_value(view, custom_value.custom_field, custom_value.value, custom_value.customized, html)
  202. end
  203. def formatted_value(view, custom_field, value, customized=nil, html=false)
  204. casted = cast_value(custom_field, value, customized)
  205. if html && custom_field.url_pattern.present?
  206. texts_and_urls = Array.wrap(casted).map do |single_value|
  207. text = view.format_object(single_value, false).to_s
  208. url = url_from_pattern(custom_field, single_value, customized)
  209. [text, url]
  210. end
  211. links = texts_and_urls.sort_by(&:first).map do |text, url|
  212. css_class = (/^https?:\/\//.match?(url)) ? 'external' : nil
  213. view.link_to_if uri_with_safe_scheme?(url), text, url, :class => css_class
  214. end
  215. links.join(', ').html_safe
  216. else
  217. casted
  218. end
  219. end
  220. # Returns an URL generated with the custom field URL pattern
  221. # and variables substitution:
  222. # %value% => the custom field value
  223. # %id% => id of the customized object
  224. # %project_id% => id of the project of the customized object if defined
  225. # %project_identifier% => identifier of the project of the customized object if defined
  226. # %m1%, %m2%... => capture groups matches of the custom field regexp if defined
  227. def url_from_pattern(custom_field, value, customized)
  228. url = custom_field.url_pattern.to_s.dup
  229. url.gsub!('%value%') {URI.encode value.to_s}
  230. url.gsub!('%id%') {URI.encode customized.id.to_s}
  231. url.gsub!('%project_id%') {URI.encode (customized.respond_to?(:project) ? customized.project.try(:id) : nil).to_s}
  232. url.gsub!('%project_identifier%') {URI.encode (customized.respond_to?(:project) ? customized.project.try(:identifier) : nil).to_s}
  233. if custom_field.regexp.present?
  234. url.gsub!(%r{%m(\d+)%}) do
  235. m = $1.to_i
  236. if matches ||= value.to_s.match(Regexp.new(custom_field.regexp))
  237. URI.encode matches[m].to_s
  238. end
  239. end
  240. end
  241. url
  242. end
  243. protected :url_from_pattern
  244. # Returns the URL pattern with substitution tokens removed,
  245. # for validation purpose
  246. def url_pattern_without_tokens(url_pattern)
  247. url_pattern.to_s.gsub(/%(value|id|project_id|project_identifier|m\d+)%/, '')
  248. end
  249. protected :url_pattern_without_tokens
  250. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  251. view.text_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id))
  252. end
  253. def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
  254. view.text_field_tag(tag_name, value, options.merge(:id => tag_id)) +
  255. bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
  256. end
  257. def bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
  258. if custom_field.is_required?
  259. ''.html_safe
  260. else
  261. view.content_tag('label',
  262. view.check_box_tag(tag_name, '__none__', (value == '__none__'), :id => nil, :data => {:disables => "##{tag_id}"}) + l(:button_clear),
  263. :class => 'inline'
  264. )
  265. end
  266. end
  267. protected :bulk_clear_tag
  268. def query_filter_options(custom_field, query)
  269. {:type => :string}
  270. end
  271. def before_custom_field_save(custom_field)
  272. end
  273. # Returns a ORDER BY clause that can used to sort customized
  274. # objects by their value of the custom field.
  275. # Returns nil if the custom field can not be used for sorting.
  276. def order_statement(custom_field)
  277. # COALESCE is here to make sure that blank and NULL values are sorted equally
  278. Arel.sql "COALESCE(#{join_alias custom_field}.value, '')"
  279. end
  280. # Returns a GROUP BY clause that can used to group by custom value
  281. # Returns nil if the custom field can not be used for grouping.
  282. def group_statement(custom_field)
  283. nil
  284. end
  285. # Returns a JOIN clause that is added to the query when sorting by custom values
  286. def join_for_order_statement(custom_field)
  287. alias_name = join_alias(custom_field)
  288. "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" +
  289. " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" +
  290. " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" +
  291. " AND #{alias_name}.custom_field_id = #{custom_field.id}" +
  292. " AND (#{custom_field.visibility_by_project_condition})" +
  293. " AND #{alias_name}.value <> ''" +
  294. " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" +
  295. " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" +
  296. " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" +
  297. " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)"
  298. end
  299. def join_alias(custom_field)
  300. "cf_#{custom_field.id}"
  301. end
  302. protected :join_alias
  303. end
  304. class Unbounded < Base
  305. def validate_single_value(custom_field, value, customized=nil)
  306. errs = super
  307. value = value.to_s
  308. unless custom_field.regexp.blank? or Regexp.new(custom_field.regexp).match?(value)
  309. errs << ::I18n.t('activerecord.errors.messages.invalid')
  310. end
  311. if custom_field.min_length && value.length < custom_field.min_length
  312. errs << ::I18n.t('activerecord.errors.messages.too_short', :count => custom_field.min_length)
  313. end
  314. if custom_field.max_length && custom_field.max_length > 0 && value.length > custom_field.max_length
  315. errs << ::I18n.t('activerecord.errors.messages.too_long', :count => custom_field.max_length)
  316. end
  317. errs
  318. end
  319. end
  320. class StringFormat < Unbounded
  321. add 'string'
  322. self.searchable_supported = true
  323. self.form_partial = 'custom_fields/formats/string'
  324. field_attributes :text_formatting
  325. def formatted_value(view, custom_field, value, customized=nil, html=false)
  326. if html
  327. if custom_field.url_pattern.present?
  328. super
  329. elsif custom_field.text_formatting == 'full'
  330. view.textilizable(value, :object => customized)
  331. else
  332. value.to_s
  333. end
  334. else
  335. value.to_s
  336. end
  337. end
  338. end
  339. class TextFormat < Unbounded
  340. add 'text'
  341. self.searchable_supported = true
  342. self.form_partial = 'custom_fields/formats/text'
  343. self.change_as_diff = true
  344. def formatted_value(view, custom_field, value, customized=nil, html=false)
  345. if html
  346. if value.present?
  347. if custom_field.text_formatting == 'full'
  348. view.textilizable(value, :object => customized)
  349. else
  350. view.simple_format(html_escape(value))
  351. end
  352. else
  353. ''
  354. end
  355. else
  356. value.to_s
  357. end
  358. end
  359. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  360. view.text_area_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :rows => 8))
  361. end
  362. def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
  363. view.text_area_tag(tag_name, value, options.merge(:id => tag_id, :rows => 8)) +
  364. '<br />'.html_safe +
  365. bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
  366. end
  367. def query_filter_options(custom_field, query)
  368. {:type => :text}
  369. end
  370. end
  371. class LinkFormat < StringFormat
  372. add 'link'
  373. self.searchable_supported = false
  374. self.form_partial = 'custom_fields/formats/link'
  375. def formatted_value(view, custom_field, value, customized=nil, html=false)
  376. if html && value.present?
  377. if custom_field.url_pattern.present?
  378. url = url_from_pattern(custom_field, value, customized)
  379. else
  380. url = value.to_s
  381. unless %r{\A[a-z]+://}i.match?(url)
  382. # no protocol found, use http by default
  383. url = "http://" + url
  384. end
  385. end
  386. css_class = (/^https?:\/\//.match?(url)) ? 'external' : nil
  387. view.link_to value.to_s.truncate(40), url, :class => css_class
  388. else
  389. value.to_s
  390. end
  391. end
  392. end
  393. class Numeric < Unbounded
  394. self.form_partial = 'custom_fields/formats/numeric'
  395. self.totalable_supported = true
  396. def order_statement(custom_field)
  397. # Make the database cast values into numeric
  398. # Postgresql will raise an error if a value can not be casted!
  399. # CustomValue validations should ensure that it doesn't occur
  400. Arel.sql "CAST(CASE #{join_alias custom_field}.value WHEN '' THEN '0' ELSE #{join_alias custom_field}.value END AS decimal(30,3))"
  401. end
  402. # Returns totals for the given scope
  403. def total_for_scope(custom_field, scope)
  404. scope.joins(:custom_values).
  405. where(:custom_values => {:custom_field_id => custom_field.id}).
  406. where.not(:custom_values => {:value => ''}).
  407. sum("CAST(#{CustomValue.table_name}.value AS decimal(30,3))")
  408. end
  409. def cast_total_value(custom_field, value)
  410. cast_single_value(custom_field, value)
  411. end
  412. end
  413. class IntFormat < Numeric
  414. add 'int'
  415. def label
  416. "label_integer"
  417. end
  418. def cast_single_value(custom_field, value, customized=nil)
  419. value.to_i
  420. end
  421. def validate_single_value(custom_field, value, customized=nil)
  422. errs = super
  423. errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless /^[+-]?\d+$/.match?(value.to_s.strip)
  424. errs
  425. end
  426. def query_filter_options(custom_field, query)
  427. {:type => :integer}
  428. end
  429. def group_statement(custom_field)
  430. order_statement(custom_field)
  431. end
  432. end
  433. class FloatFormat < Numeric
  434. add 'float'
  435. def cast_single_value(custom_field, value, customized=nil)
  436. value.to_f
  437. end
  438. def cast_total_value(custom_field, value)
  439. value.to_f.round(2)
  440. end
  441. def validate_single_value(custom_field, value, customized=nil)
  442. errs = super
  443. errs << ::I18n.t('activerecord.errors.messages.invalid') unless (Kernel.Float(value) rescue nil)
  444. errs
  445. end
  446. def query_filter_options(custom_field, query)
  447. {:type => :float}
  448. end
  449. end
  450. class DateFormat < Unbounded
  451. add 'date'
  452. self.form_partial = 'custom_fields/formats/date'
  453. def cast_single_value(custom_field, value, customized=nil)
  454. value.to_date rescue nil
  455. end
  456. def validate_single_value(custom_field, value, customized=nil)
  457. if /^\d{4}-\d{2}-\d{2}$/.match?(value) && (value.to_date rescue false)
  458. []
  459. else
  460. [::I18n.t('activerecord.errors.messages.not_a_date')]
  461. end
  462. end
  463. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  464. view.date_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :size => 10)) +
  465. view.calendar_for(tag_id)
  466. end
  467. def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
  468. view.date_field_tag(tag_name, value, options.merge(:id => tag_id, :size => 10)) +
  469. view.calendar_for(tag_id) +
  470. bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
  471. end
  472. def query_filter_options(custom_field, query)
  473. {:type => :date}
  474. end
  475. def group_statement(custom_field)
  476. order_statement(custom_field)
  477. end
  478. end
  479. class List < Base
  480. self.multiple_supported = true
  481. field_attributes :edit_tag_style
  482. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  483. if custom_value.custom_field.edit_tag_style == 'check_box'
  484. check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
  485. else
  486. select_edit_tag(view, tag_id, tag_name, custom_value, options)
  487. end
  488. end
  489. def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
  490. opts = []
  491. opts << [l(:label_no_change_option), ''] unless custom_field.multiple?
  492. opts << [l(:label_none), '__none__'] unless custom_field.is_required?
  493. opts += possible_values_options(custom_field, objects)
  494. view.select_tag(tag_name, view.options_for_select(opts, value), options.merge(:multiple => custom_field.multiple?))
  495. end
  496. def query_filter_options(custom_field, query)
  497. {:type => :list_optional, :values => lambda { query_filter_values(custom_field, query) }}
  498. end
  499. protected
  500. # Returns the values that are available in the field filter
  501. def query_filter_values(custom_field, query)
  502. possible_values_options(custom_field, query.project)
  503. end
  504. # Renders the edit tag as a select tag
  505. def select_edit_tag(view, tag_id, tag_name, custom_value, options={})
  506. blank_option = ''.html_safe
  507. unless custom_value.custom_field.multiple?
  508. if custom_value.custom_field.is_required?
  509. unless custom_value.custom_field.default_value.present?
  510. blank_option = view.content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---", :value => '')
  511. end
  512. else
  513. blank_option = view.content_tag('option', '&nbsp;'.html_safe, :value => '')
  514. end
  515. end
  516. options_tags = blank_option + view.options_for_select(possible_custom_value_options(custom_value), custom_value.value)
  517. s = view.select_tag(tag_name, options_tags, options.merge(:id => tag_id, :multiple => custom_value.custom_field.multiple?))
  518. if custom_value.custom_field.multiple?
  519. s << view.hidden_field_tag(tag_name, '')
  520. end
  521. s
  522. end
  523. # Renders the edit tag as check box or radio tags
  524. def check_box_edit_tag(view, tag_id, tag_name, custom_value, options={})
  525. opts = []
  526. unless custom_value.custom_field.multiple? || custom_value.custom_field.is_required?
  527. opts << ["(#{l(:label_none)})", '']
  528. end
  529. opts += possible_custom_value_options(custom_value)
  530. s = ''.html_safe
  531. tag_method = custom_value.custom_field.multiple? ? :check_box_tag : :radio_button_tag
  532. opts.each do |label, value|
  533. value ||= label
  534. checked = (custom_value.value.is_a?(Array) && custom_value.value.include?(value)) || custom_value.value.to_s == value
  535. tag = view.send(tag_method, tag_name, value, checked, :id => nil)
  536. s << view.content_tag('label', tag + ' ' + label)
  537. end
  538. if custom_value.custom_field.multiple?
  539. s << view.hidden_field_tag(tag_name, '', :id => nil)
  540. end
  541. css = "#{options[:class]} check_box_group"
  542. view.content_tag('span', s, options.merge(:class => css))
  543. end
  544. end
  545. class ListFormat < List
  546. add 'list'
  547. self.searchable_supported = true
  548. self.form_partial = 'custom_fields/formats/list'
  549. def possible_custom_value_options(custom_value)
  550. options = possible_values_options(custom_value.custom_field)
  551. missing = [custom_value.value].flatten.reject(&:blank?) - options
  552. if missing.any?
  553. options += missing
  554. end
  555. options
  556. end
  557. def possible_values_options(custom_field, object=nil)
  558. custom_field.possible_values
  559. end
  560. def validate_custom_field(custom_field)
  561. errors = []
  562. errors << [:possible_values, :blank] if custom_field.possible_values.blank?
  563. errors << [:possible_values, :invalid] unless custom_field.possible_values.is_a? Array
  564. errors
  565. end
  566. def validate_custom_value(custom_value)
  567. values = Array.wrap(custom_value.value).reject {|value| value.to_s == ''}
  568. invalid_values = values - Array.wrap(custom_value.value_was) - custom_value.custom_field.possible_values
  569. if invalid_values.any?
  570. [::I18n.t('activerecord.errors.messages.inclusion')]
  571. else
  572. []
  573. end
  574. end
  575. def group_statement(custom_field)
  576. order_statement(custom_field)
  577. end
  578. end
  579. class BoolFormat < List
  580. add 'bool'
  581. self.multiple_supported = false
  582. self.form_partial = 'custom_fields/formats/bool'
  583. def label
  584. "label_boolean"
  585. end
  586. def cast_single_value(custom_field, value, customized=nil)
  587. value == '1' ? true : false
  588. end
  589. def possible_values_options(custom_field, object=nil)
  590. [[::I18n.t(:general_text_Yes), '1'], [::I18n.t(:general_text_No), '0']]
  591. end
  592. def group_statement(custom_field)
  593. order_statement(custom_field)
  594. end
  595. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  596. case custom_value.custom_field.edit_tag_style
  597. when 'check_box'
  598. single_check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
  599. when 'radio'
  600. check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
  601. else
  602. select_edit_tag(view, tag_id, tag_name, custom_value, options)
  603. end
  604. end
  605. # Renders the edit tag as a simple check box
  606. def single_check_box_edit_tag(view, tag_id, tag_name, custom_value, options={})
  607. s = ''.html_safe
  608. s << view.hidden_field_tag(tag_name, '0', :id => nil)
  609. s << view.check_box_tag(tag_name, '1', custom_value.value.to_s == '1', :id => tag_id)
  610. view.content_tag('span', s, options)
  611. end
  612. end
  613. class RecordList < List
  614. self.customized_class_names = %w(Issue TimeEntry Version Document Project)
  615. def cast_single_value(custom_field, value, customized=nil)
  616. target_class.find_by_id(value.to_i) if value.present?
  617. end
  618. def target_class
  619. @target_class ||= self.class.name[/^(.*::)?(.+)Format$/, 2].constantize rescue nil
  620. end
  621. def reset_target_class
  622. @target_class = nil
  623. end
  624. def possible_custom_value_options(custom_value)
  625. options = possible_values_options(custom_value.custom_field, custom_value.customized)
  626. missing = [custom_value.value_was].flatten.reject(&:blank?) - options.map(&:last)
  627. if missing.any?
  628. options += target_class.where(:id => missing.map(&:to_i)).map {|o| [o.to_s, o.id.to_s]}
  629. end
  630. options
  631. end
  632. def validate_custom_value(custom_value)
  633. values = Array.wrap(custom_value.value).reject {|value| value.to_s == ''}
  634. invalid_values = values - possible_custom_value_options(custom_value).map(&:last)
  635. if invalid_values.any?
  636. [::I18n.t('activerecord.errors.messages.inclusion')]
  637. else
  638. []
  639. end
  640. end
  641. def order_statement(custom_field)
  642. if target_class.respond_to?(:fields_for_order_statement)
  643. target_class.fields_for_order_statement(value_join_alias(custom_field))
  644. end
  645. end
  646. def group_statement(custom_field)
  647. Arel.sql "COALESCE(#{join_alias custom_field}.value, '')"
  648. end
  649. def join_for_order_statement(custom_field)
  650. alias_name = join_alias(custom_field)
  651. "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" +
  652. " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" +
  653. " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" +
  654. " AND #{alias_name}.custom_field_id = #{custom_field.id}" +
  655. " AND (#{custom_field.visibility_by_project_condition})" +
  656. " AND #{alias_name}.value <> ''" +
  657. " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" +
  658. " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" +
  659. " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" +
  660. " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)" +
  661. " LEFT OUTER JOIN #{target_class.table_name} #{value_join_alias custom_field}" +
  662. " ON CAST(CASE #{alias_name}.value WHEN '' THEN '0' ELSE #{alias_name}.value END AS decimal(30,0)) = #{value_join_alias custom_field}.id"
  663. end
  664. def value_join_alias(custom_field)
  665. join_alias(custom_field) + "_" + custom_field.field_format
  666. end
  667. protected :value_join_alias
  668. end
  669. class EnumerationFormat < RecordList
  670. add 'enumeration'
  671. self.form_partial = 'custom_fields/formats/enumeration'
  672. def label
  673. "label_field_format_enumeration"
  674. end
  675. def target_class
  676. @target_class ||= CustomFieldEnumeration
  677. end
  678. def possible_values_options(custom_field, object=nil)
  679. possible_values_records(custom_field, object).map {|u| [u.name, u.id.to_s]}
  680. end
  681. def possible_values_records(custom_field, object=nil)
  682. custom_field.enumerations.active
  683. end
  684. def value_from_keyword(custom_field, keyword, object)
  685. parse_keyword(custom_field, keyword) do |k|
  686. custom_field.enumerations.where("LOWER(name) LIKE LOWER(?)", k).first.try(:id)
  687. end
  688. end
  689. end
  690. class UserFormat < RecordList
  691. add 'user'
  692. self.form_partial = 'custom_fields/formats/user'
  693. field_attributes :user_role
  694. def possible_values_options(custom_field, object=nil)
  695. possible_values_records(custom_field, object).map {|u| [u.name, u.id.to_s]}
  696. end
  697. def possible_values_records(custom_field, object=nil)
  698. if object.is_a?(Array)
  699. projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq
  700. projects.map {|project| possible_values_records(custom_field, project)}.reduce(:&) || []
  701. elsif object.respond_to?(:project) && object.project
  702. scope = object.project.users
  703. if custom_field.user_role.is_a?(Array)
  704. role_ids = custom_field.user_role.map(&:to_s).reject(&:blank?).map(&:to_i)
  705. if role_ids.any?
  706. scope = scope.where("#{Member.table_name}.id IN (SELECT DISTINCT member_id FROM #{MemberRole.table_name} WHERE role_id IN (?))", role_ids)
  707. end
  708. end
  709. scope.sorted
  710. else
  711. []
  712. end
  713. end
  714. def value_from_keyword(custom_field, keyword, object)
  715. users = possible_values_records(custom_field, object).to_a
  716. parse_keyword(custom_field, keyword) do |k|
  717. Principal.detect_by_keyword(users, k).try(:id)
  718. end
  719. end
  720. def before_custom_field_save(custom_field)
  721. super
  722. if custom_field.user_role.is_a?(Array)
  723. custom_field.user_role.map!(&:to_s).reject!(&:blank?)
  724. end
  725. end
  726. def query_filter_values(custom_field, query)
  727. query.author_values
  728. end
  729. end
  730. class VersionFormat < RecordList
  731. add 'version'
  732. self.form_partial = 'custom_fields/formats/version'
  733. field_attributes :version_status
  734. def possible_values_options(custom_field, object=nil)
  735. possible_values_records(custom_field, object).sort.collect{|v| [v.to_s, v.id.to_s] }
  736. end
  737. def before_custom_field_save(custom_field)
  738. super
  739. if custom_field.version_status.is_a?(Array)
  740. custom_field.version_status.map!(&:to_s).reject!(&:blank?)
  741. end
  742. end
  743. protected
  744. def query_filter_values(custom_field, query)
  745. versions = possible_values_records(custom_field, query.project, true)
  746. Version.sort_by_status(versions).collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s, l("version_status_#{s.status}")] }
  747. end
  748. def possible_values_records(custom_field, object=nil, all_statuses=false)
  749. if object.is_a?(Array)
  750. projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq
  751. projects.map {|project| possible_values_records(custom_field, project)}.reduce(:&) || []
  752. elsif object.respond_to?(:project) && object.project
  753. scope = object.project.shared_versions
  754. filtered_versions_options(custom_field, scope, all_statuses)
  755. elsif object.nil?
  756. scope = ::Version.visible.where(:sharing => 'system')
  757. filtered_versions_options(custom_field, scope, all_statuses)
  758. else
  759. []
  760. end
  761. end
  762. def filtered_versions_options(custom_field, scope, all_statuses=false)
  763. if !all_statuses && custom_field.version_status.is_a?(Array)
  764. statuses = custom_field.version_status.map(&:to_s).reject(&:blank?)
  765. if statuses.any?
  766. scope = scope.where(:status => statuses.map(&:to_s))
  767. end
  768. end
  769. scope
  770. end
  771. end
  772. class AttachmentFormat < Base
  773. add 'attachment'
  774. self.form_partial = 'custom_fields/formats/attachment'
  775. self.is_filter_supported = false
  776. self.change_no_details = true
  777. self.bulk_edit_supported = false
  778. field_attributes :extensions_allowed
  779. def set_custom_field_value(custom_field, custom_field_value, value)
  780. attachment_present = false
  781. if value.is_a?(Hash)
  782. attachment_present = true
  783. value = value.except(:blank)
  784. if value.values.any? && value.values.all? {|v| v.is_a?(Hash)}
  785. value = value.values.first
  786. end
  787. if value.key?(:id)
  788. value = set_custom_field_value_by_id(custom_field, custom_field_value, value[:id])
  789. elsif value[:token].present?
  790. if attachment = Attachment.find_by_token(value[:token])
  791. value = attachment.id.to_s
  792. else
  793. value = ''
  794. end
  795. elsif value.key?(:file)
  796. attachment = Attachment.new(:file => value[:file], :author => User.current)
  797. if attachment.save
  798. value = attachment.id.to_s
  799. else
  800. value = ''
  801. end
  802. else
  803. attachment_present = false
  804. value = ''
  805. end
  806. elsif value.is_a?(String)
  807. value = set_custom_field_value_by_id(custom_field, custom_field_value, value)
  808. end
  809. custom_field_value.instance_variable_set "@attachment_present", attachment_present
  810. value
  811. end
  812. def set_custom_field_value_by_id(custom_field, custom_field_value, id)
  813. attachment = Attachment.find_by_id(id)
  814. if attachment && attachment.container.is_a?(CustomValue) && attachment.container.customized == custom_field_value.customized
  815. id.to_s
  816. else
  817. ''
  818. end
  819. end
  820. private :set_custom_field_value_by_id
  821. def cast_single_value(custom_field, value, customized=nil)
  822. Attachment.find_by_id(value.to_i) if value.present? && value.respond_to?(:to_i)
  823. end
  824. def validate_custom_value(custom_value)
  825. errors = []
  826. if custom_value.value.blank?
  827. if custom_value.instance_variable_get("@attachment_present")
  828. errors << ::I18n.t('activerecord.errors.messages.invalid')
  829. end
  830. else
  831. if custom_value.value.present?
  832. attachment = Attachment.find_by(:id => custom_value.value.to_s)
  833. extensions = custom_value.custom_field.extensions_allowed
  834. if attachment && extensions.present? && !attachment.extension_in?(extensions)
  835. errors << "#{::I18n.t('activerecord.errors.messages.invalid')} (#{l(:setting_attachment_extensions_allowed)}: #{extensions})"
  836. end
  837. end
  838. end
  839. errors.uniq
  840. end
  841. def after_save_custom_value(custom_field, custom_value)
  842. if custom_value.saved_change_to_value?
  843. if custom_value.value.present?
  844. attachment = Attachment.find_by(:id => custom_value.value.to_s)
  845. if attachment
  846. attachment.container = custom_value
  847. attachment.save!
  848. end
  849. end
  850. if custom_value.value_before_last_save.present?
  851. attachment = Attachment.find_by(:id => custom_value.value_before_last_save.to_s)
  852. if attachment
  853. attachment.destroy
  854. end
  855. end
  856. end
  857. end
  858. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  859. attachment = nil
  860. if custom_value.value.present?
  861. attachment = Attachment.find_by_id(custom_value.value)
  862. end
  863. view.hidden_field_tag("#{tag_name}[blank]", "") +
  864. view.render(:partial => 'attachments/form',
  865. :locals => {
  866. :attachment_param => tag_name,
  867. :multiple => false,
  868. :description => false,
  869. :saved_attachments => [attachment].compact,
  870. :filedrop => false
  871. })
  872. end
  873. end
  874. end
  875. end