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

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