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 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2019 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%') {Addressable::URI.encode value.to_s}
  230. url.gsub!('%id%') {Addressable::URI.encode customized.id.to_s}
  231. url.gsub!('%project_id%') {
  232. Addressable::URI.encode(
  233. (customized.respond_to?(:project) ? customized.project.try(:id) : nil).to_s
  234. )
  235. }
  236. url.gsub!('%project_identifier%') {
  237. Addressable::URI.encode(
  238. (customized.respond_to?(:project) ? customized.project.try(:identifier) : nil).to_s
  239. )
  240. }
  241. if custom_field.regexp.present?
  242. url.gsub!(%r{%m(\d+)%}) do
  243. m = $1.to_i
  244. if matches ||= value.to_s.match(Regexp.new(custom_field.regexp))
  245. Addressable::URI.encode matches[m].to_s
  246. end
  247. end
  248. end
  249. url
  250. end
  251. protected :url_from_pattern
  252. # Returns the URL pattern with substitution tokens removed,
  253. # for validation purpose
  254. def url_pattern_without_tokens(url_pattern)
  255. url_pattern.to_s.gsub(/%(value|id|project_id|project_identifier|m\d+)%/, '')
  256. end
  257. protected :url_pattern_without_tokens
  258. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  259. view.text_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id))
  260. end
  261. def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
  262. view.text_field_tag(tag_name, value, options.merge(:id => tag_id)) +
  263. bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
  264. end
  265. def bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
  266. if custom_field.is_required?
  267. ''.html_safe
  268. else
  269. view.content_tag(
  270. 'label',
  271. view.check_box_tag(
  272. tag_name,
  273. '__none__', (value == '__none__'), :id => nil,
  274. :data => {:disables => "##{tag_id}"}) + l(:button_clear),
  275. :class => 'inline'
  276. )
  277. end
  278. end
  279. protected :bulk_clear_tag
  280. def query_filter_options(custom_field, query)
  281. {:type => :string}
  282. end
  283. def before_custom_field_save(custom_field)
  284. end
  285. # Returns a ORDER BY clause that can used to sort customized
  286. # objects by their value of the custom field.
  287. # Returns nil if the custom field can not be used for sorting.
  288. def order_statement(custom_field)
  289. # COALESCE is here to make sure that blank and NULL values are sorted equally
  290. Arel.sql "COALESCE(#{join_alias custom_field}.value, '')"
  291. end
  292. # Returns a GROUP BY clause that can used to group by custom value
  293. # Returns nil if the custom field can not be used for grouping.
  294. def group_statement(custom_field)
  295. nil
  296. end
  297. # Returns a JOIN clause that is added to the query when sorting by custom values
  298. def join_for_order_statement(custom_field)
  299. alias_name = join_alias(custom_field)
  300. "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" +
  301. " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" +
  302. " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" +
  303. " AND #{alias_name}.custom_field_id = #{custom_field.id}" +
  304. " AND (#{custom_field.visibility_by_project_condition})" +
  305. " AND #{alias_name}.value <> ''" +
  306. " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" +
  307. " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" +
  308. " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" +
  309. " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)"
  310. end
  311. def join_alias(custom_field)
  312. "cf_#{custom_field.id}"
  313. end
  314. protected :join_alias
  315. end
  316. class Unbounded < Base
  317. def validate_single_value(custom_field, value, customized=nil)
  318. errs = super
  319. value = value.to_s
  320. unless custom_field.regexp.blank? or Regexp.new(custom_field.regexp).match?(value)
  321. errs << ::I18n.t('activerecord.errors.messages.invalid')
  322. end
  323. if custom_field.min_length && value.length < custom_field.min_length
  324. errs << ::I18n.t('activerecord.errors.messages.too_short', :count => custom_field.min_length)
  325. end
  326. if custom_field.max_length && custom_field.max_length > 0 && value.length > custom_field.max_length
  327. errs << ::I18n.t('activerecord.errors.messages.too_long', :count => custom_field.max_length)
  328. end
  329. errs
  330. end
  331. end
  332. class StringFormat < Unbounded
  333. add 'string'
  334. self.searchable_supported = true
  335. self.form_partial = 'custom_fields/formats/string'
  336. field_attributes :text_formatting
  337. def formatted_value(view, custom_field, value, customized=nil, html=false)
  338. if html
  339. if custom_field.url_pattern.present?
  340. super
  341. elsif custom_field.text_formatting == 'full'
  342. view.textilizable(value, :object => customized)
  343. else
  344. value.to_s
  345. end
  346. else
  347. value.to_s
  348. end
  349. end
  350. end
  351. class TextFormat < Unbounded
  352. add 'text'
  353. self.searchable_supported = true
  354. self.form_partial = 'custom_fields/formats/text'
  355. self.change_as_diff = true
  356. def formatted_value(view, custom_field, value, customized=nil, html=false)
  357. if html
  358. if value.present?
  359. if custom_field.text_formatting == 'full'
  360. view.textilizable(value, :object => customized)
  361. else
  362. view.simple_format(html_escape(value))
  363. end
  364. else
  365. ''
  366. end
  367. else
  368. value.to_s
  369. end
  370. end
  371. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  372. view.text_area_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :rows => 8))
  373. end
  374. def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
  375. view.text_area_tag(tag_name, value, options.merge(:id => tag_id, :rows => 8)) +
  376. '<br />'.html_safe +
  377. bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
  378. end
  379. def query_filter_options(custom_field, query)
  380. {:type => :text}
  381. end
  382. end
  383. class LinkFormat < StringFormat
  384. add 'link'
  385. self.searchable_supported = false
  386. self.form_partial = 'custom_fields/formats/link'
  387. def formatted_value(view, custom_field, value, customized=nil, html=false)
  388. if html && value.present?
  389. if custom_field.url_pattern.present?
  390. url = url_from_pattern(custom_field, value, customized)
  391. else
  392. url = value.to_s
  393. unless %r{\A[a-z]+://}i.match?(url)
  394. # no protocol found, use http by default
  395. url = "http://" + url
  396. end
  397. end
  398. css_class = (/^https?:\/\//.match?(url)) ? 'external' : nil
  399. view.link_to value.to_s.truncate(40), url, :class => css_class
  400. else
  401. value.to_s
  402. end
  403. end
  404. end
  405. class Numeric < Unbounded
  406. self.form_partial = 'custom_fields/formats/numeric'
  407. self.totalable_supported = true
  408. def order_statement(custom_field)
  409. # Make the database cast values into numeric
  410. # Postgresql will raise an error if a value can not be casted!
  411. # CustomValue validations should ensure that it doesn't occur
  412. Arel.sql "CAST(CASE #{join_alias custom_field}.value WHEN '' THEN '0' ELSE #{join_alias custom_field}.value END AS decimal(30,3))"
  413. end
  414. # Returns totals for the given scope
  415. def total_for_scope(custom_field, scope)
  416. scope.joins(:custom_values).
  417. where(:custom_values => {:custom_field_id => custom_field.id}).
  418. where.not(:custom_values => {:value => ''}).
  419. sum("CAST(#{CustomValue.table_name}.value AS decimal(30,3))")
  420. end
  421. def cast_total_value(custom_field, value)
  422. cast_single_value(custom_field, value)
  423. end
  424. end
  425. class IntFormat < Numeric
  426. add 'int'
  427. def label
  428. "label_integer"
  429. end
  430. def cast_single_value(custom_field, value, customized=nil)
  431. value.to_i
  432. end
  433. def validate_single_value(custom_field, value, customized=nil)
  434. errs = super
  435. errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless /^[+-]?\d+$/.match?(value.to_s.strip)
  436. errs
  437. end
  438. def query_filter_options(custom_field, query)
  439. {:type => :integer}
  440. end
  441. def group_statement(custom_field)
  442. order_statement(custom_field)
  443. end
  444. end
  445. class FloatFormat < Numeric
  446. add 'float'
  447. def cast_single_value(custom_field, value, customized=nil)
  448. value.to_f
  449. end
  450. def cast_total_value(custom_field, value)
  451. value.to_f.round(2)
  452. end
  453. def validate_single_value(custom_field, value, customized=nil)
  454. errs = super
  455. errs << ::I18n.t('activerecord.errors.messages.invalid') unless (Kernel.Float(value) rescue nil)
  456. errs
  457. end
  458. def query_filter_options(custom_field, query)
  459. {:type => :float}
  460. end
  461. end
  462. class DateFormat < Unbounded
  463. add 'date'
  464. self.form_partial = 'custom_fields/formats/date'
  465. def cast_single_value(custom_field, value, customized=nil)
  466. value.to_date rescue nil
  467. end
  468. def validate_single_value(custom_field, value, customized=nil)
  469. if /^\d{4}-\d{2}-\d{2}$/.match?(value) && (value.to_date rescue false)
  470. []
  471. else
  472. [::I18n.t('activerecord.errors.messages.not_a_date')]
  473. end
  474. end
  475. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  476. view.date_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :size => 10)) +
  477. view.calendar_for(tag_id)
  478. end
  479. def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
  480. view.date_field_tag(tag_name, value, options.merge(:id => tag_id, :size => 10)) +
  481. view.calendar_for(tag_id) +
  482. bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
  483. end
  484. def query_filter_options(custom_field, query)
  485. {:type => :date}
  486. end
  487. def group_statement(custom_field)
  488. order_statement(custom_field)
  489. end
  490. end
  491. class List < Base
  492. self.multiple_supported = true
  493. field_attributes :edit_tag_style
  494. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  495. if custom_value.custom_field.edit_tag_style == 'check_box'
  496. check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
  497. else
  498. select_edit_tag(view, tag_id, tag_name, custom_value, options)
  499. end
  500. end
  501. def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
  502. opts = []
  503. opts << [l(:label_no_change_option), ''] unless custom_field.multiple?
  504. opts << [l(:label_none), '__none__'] unless custom_field.is_required?
  505. opts += possible_values_options(custom_field, objects)
  506. view.select_tag(tag_name, view.options_for_select(opts, value), options.merge(:multiple => custom_field.multiple?))
  507. end
  508. def query_filter_options(custom_field, query)
  509. {:type => :list_optional, :values => lambda { query_filter_values(custom_field, query) }}
  510. end
  511. protected
  512. # Returns the values that are available in the field filter
  513. def query_filter_values(custom_field, query)
  514. possible_values_options(custom_field, query.project)
  515. end
  516. # Renders the edit tag as a select tag
  517. def select_edit_tag(view, tag_id, tag_name, custom_value, options={})
  518. blank_option = ''.html_safe
  519. unless custom_value.custom_field.multiple?
  520. if custom_value.custom_field.is_required?
  521. unless custom_value.custom_field.default_value.present?
  522. blank_option = view.content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---", :value => '')
  523. end
  524. else
  525. blank_option = view.content_tag('option', '&nbsp;'.html_safe, :value => '')
  526. end
  527. end
  528. options_tags = blank_option + view.options_for_select(possible_custom_value_options(custom_value), custom_value.value)
  529. s = view.select_tag(tag_name, options_tags, options.merge(:id => tag_id, :multiple => custom_value.custom_field.multiple?))
  530. if custom_value.custom_field.multiple?
  531. s << view.hidden_field_tag(tag_name, '')
  532. end
  533. s
  534. end
  535. # Renders the edit tag as check box or radio tags
  536. def check_box_edit_tag(view, tag_id, tag_name, custom_value, options={})
  537. opts = []
  538. unless custom_value.custom_field.multiple? || custom_value.custom_field.is_required?
  539. opts << ["(#{l(:label_none)})", '']
  540. end
  541. opts += possible_custom_value_options(custom_value)
  542. s = ''.html_safe
  543. tag_method = custom_value.custom_field.multiple? ? :check_box_tag : :radio_button_tag
  544. opts.each do |label, value|
  545. value ||= label
  546. checked = (custom_value.value.is_a?(Array) && custom_value.value.include?(value)) || custom_value.value.to_s == value
  547. tag = view.send(tag_method, tag_name, value, checked, :id => nil)
  548. s << view.content_tag('label', tag + ' ' + label)
  549. end
  550. if custom_value.custom_field.multiple?
  551. s << view.hidden_field_tag(tag_name, '', :id => nil)
  552. end
  553. css = "#{options[:class]} check_box_group"
  554. view.content_tag('span', s, options.merge(:class => css))
  555. end
  556. end
  557. class ListFormat < List
  558. add 'list'
  559. self.searchable_supported = true
  560. self.form_partial = 'custom_fields/formats/list'
  561. def possible_custom_value_options(custom_value)
  562. options = possible_values_options(custom_value.custom_field)
  563. missing = [custom_value.value].flatten.reject(&:blank?) - options
  564. if missing.any?
  565. options += missing
  566. end
  567. options
  568. end
  569. def possible_values_options(custom_field, object=nil)
  570. custom_field.possible_values
  571. end
  572. def validate_custom_field(custom_field)
  573. errors = []
  574. errors << [:possible_values, :blank] if custom_field.possible_values.blank?
  575. errors << [:possible_values, :invalid] unless custom_field.possible_values.is_a? Array
  576. errors
  577. end
  578. def validate_custom_value(custom_value)
  579. values = Array.wrap(custom_value.value).reject {|value| value.to_s == ''}
  580. invalid_values = values - Array.wrap(custom_value.value_was) - custom_value.custom_field.possible_values
  581. if invalid_values.any?
  582. [::I18n.t('activerecord.errors.messages.inclusion')]
  583. else
  584. []
  585. end
  586. end
  587. def group_statement(custom_field)
  588. order_statement(custom_field)
  589. end
  590. end
  591. class BoolFormat < List
  592. add 'bool'
  593. self.multiple_supported = false
  594. self.form_partial = 'custom_fields/formats/bool'
  595. def label
  596. "label_boolean"
  597. end
  598. def cast_single_value(custom_field, value, customized=nil)
  599. value == '1' ? true : false
  600. end
  601. def possible_values_options(custom_field, object=nil)
  602. [[::I18n.t(:general_text_Yes), '1'], [::I18n.t(:general_text_No), '0']]
  603. end
  604. def group_statement(custom_field)
  605. order_statement(custom_field)
  606. end
  607. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  608. case custom_value.custom_field.edit_tag_style
  609. when 'check_box'
  610. single_check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
  611. when 'radio'
  612. check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
  613. else
  614. select_edit_tag(view, tag_id, tag_name, custom_value, options)
  615. end
  616. end
  617. # Renders the edit tag as a simple check box
  618. def single_check_box_edit_tag(view, tag_id, tag_name, custom_value, options={})
  619. s = ''.html_safe
  620. s << view.hidden_field_tag(tag_name, '0', :id => nil)
  621. s << view.check_box_tag(tag_name, '1', custom_value.value.to_s == '1', :id => tag_id)
  622. view.content_tag('span', s, options)
  623. end
  624. end
  625. class RecordList < List
  626. self.customized_class_names = %w(Issue TimeEntry Version Document Project)
  627. def cast_single_value(custom_field, value, customized=nil)
  628. target_class.find_by_id(value.to_i) if value.present?
  629. end
  630. def target_class
  631. @target_class ||= self.class.name[/^(.*::)?(.+)Format$/, 2].constantize rescue nil
  632. end
  633. def reset_target_class
  634. @target_class = nil
  635. end
  636. def possible_custom_value_options(custom_value)
  637. options = possible_values_options(custom_value.custom_field, custom_value.customized)
  638. missing = [custom_value.value_was].flatten.reject(&:blank?) - options.map(&:last)
  639. if missing.any?
  640. options += target_class.where(:id => missing.map(&:to_i)).map {|o| [o.to_s, o.id.to_s]}
  641. end
  642. options
  643. end
  644. def validate_custom_value(custom_value)
  645. values = Array.wrap(custom_value.value).reject {|value| value.to_s == ''}
  646. invalid_values = values - possible_custom_value_options(custom_value).map(&:last)
  647. if invalid_values.any?
  648. [::I18n.t('activerecord.errors.messages.inclusion')]
  649. else
  650. []
  651. end
  652. end
  653. def order_statement(custom_field)
  654. if target_class.respond_to?(:fields_for_order_statement)
  655. target_class.fields_for_order_statement(value_join_alias(custom_field))
  656. end
  657. end
  658. def group_statement(custom_field)
  659. Arel.sql "COALESCE(#{join_alias custom_field}.value, '')"
  660. end
  661. def join_for_order_statement(custom_field)
  662. alias_name = join_alias(custom_field)
  663. "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" +
  664. " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" +
  665. " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" +
  666. " AND #{alias_name}.custom_field_id = #{custom_field.id}" +
  667. " AND (#{custom_field.visibility_by_project_condition})" +
  668. " AND #{alias_name}.value <> ''" +
  669. " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" +
  670. " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" +
  671. " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" +
  672. " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)" +
  673. " LEFT OUTER JOIN #{target_class.table_name} #{value_join_alias custom_field}" +
  674. " ON CAST(CASE #{alias_name}.value WHEN '' THEN '0' ELSE #{alias_name}.value END AS decimal(30,0)) = #{value_join_alias custom_field}.id"
  675. end
  676. def value_join_alias(custom_field)
  677. join_alias(custom_field) + "_" + custom_field.field_format
  678. end
  679. protected :value_join_alias
  680. end
  681. class EnumerationFormat < RecordList
  682. add 'enumeration'
  683. self.form_partial = 'custom_fields/formats/enumeration'
  684. def label
  685. "label_field_format_enumeration"
  686. end
  687. def target_class
  688. @target_class ||= CustomFieldEnumeration
  689. end
  690. def possible_values_options(custom_field, object=nil)
  691. possible_values_records(custom_field, object).map {|u| [u.name, u.id.to_s]}
  692. end
  693. def possible_values_records(custom_field, object=nil)
  694. custom_field.enumerations.active
  695. end
  696. def value_from_keyword(custom_field, keyword, object)
  697. parse_keyword(custom_field, keyword) do |k|
  698. custom_field.enumerations.where("LOWER(name) LIKE LOWER(?)", k).first.try(:id)
  699. end
  700. end
  701. end
  702. class UserFormat < RecordList
  703. add 'user'
  704. self.form_partial = 'custom_fields/formats/user'
  705. field_attributes :user_role
  706. def possible_values_options(custom_field, object=nil)
  707. users = possible_values_records(custom_field, object)
  708. options = users.map {|u| [u.name, u.id.to_s]}
  709. options = [["<< #{l(:label_me)} >>", User.current.id]] + options if users.include?(User.current)
  710. options
  711. end
  712. def possible_values_records(custom_field, object=nil)
  713. if object.is_a?(Array)
  714. projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq
  715. projects.map {|project| possible_values_records(custom_field, project)}.reduce(:&) || []
  716. elsif object.respond_to?(:project) && object.project
  717. scope = object.project.users
  718. if custom_field.user_role.is_a?(Array)
  719. role_ids = custom_field.user_role.map(&:to_s).reject(&:blank?).map(&:to_i)
  720. if role_ids.any?
  721. scope = scope.where("#{Member.table_name}.id IN (SELECT DISTINCT member_id FROM #{MemberRole.table_name} WHERE role_id IN (?))", role_ids)
  722. end
  723. end
  724. scope.sorted
  725. else
  726. []
  727. end
  728. end
  729. def value_from_keyword(custom_field, keyword, object)
  730. users = possible_values_records(custom_field, object).to_a
  731. parse_keyword(custom_field, keyword) do |k|
  732. Principal.detect_by_keyword(users, k).try(:id)
  733. end
  734. end
  735. def before_custom_field_save(custom_field)
  736. super
  737. if custom_field.user_role.is_a?(Array)
  738. custom_field.user_role.map!(&:to_s).reject!(&:blank?)
  739. end
  740. end
  741. def query_filter_values(custom_field, query)
  742. query.author_values
  743. end
  744. end
  745. class VersionFormat < RecordList
  746. add 'version'
  747. self.form_partial = 'custom_fields/formats/version'
  748. field_attributes :version_status
  749. def possible_values_options(custom_field, object=nil)
  750. possible_values_records(custom_field, object).sort.collect{|v| [v.to_s, v.id.to_s] }
  751. end
  752. def before_custom_field_save(custom_field)
  753. super
  754. if custom_field.version_status.is_a?(Array)
  755. custom_field.version_status.map!(&:to_s).reject!(&:blank?)
  756. end
  757. end
  758. protected
  759. def query_filter_values(custom_field, query)
  760. versions = possible_values_records(custom_field, query.project, true)
  761. Version.sort_by_status(versions).collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s, l("version_status_#{s.status}")] }
  762. end
  763. def possible_values_records(custom_field, object=nil, all_statuses=false)
  764. if object.is_a?(Array)
  765. projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq
  766. projects.map {|project| possible_values_records(custom_field, project)}.reduce(:&) || []
  767. elsif object.respond_to?(:project) && object.project
  768. scope = object.project.shared_versions
  769. filtered_versions_options(custom_field, scope, all_statuses)
  770. elsif object.nil?
  771. scope = ::Version.visible.where(:sharing => 'system')
  772. filtered_versions_options(custom_field, scope, all_statuses)
  773. else
  774. []
  775. end
  776. end
  777. def filtered_versions_options(custom_field, scope, all_statuses=false)
  778. if !all_statuses && custom_field.version_status.is_a?(Array)
  779. statuses = custom_field.version_status.map(&:to_s).reject(&:blank?)
  780. if statuses.any?
  781. scope = scope.where(:status => statuses.map(&:to_s))
  782. end
  783. end
  784. scope
  785. end
  786. end
  787. class AttachmentFormat < Base
  788. add 'attachment'
  789. self.form_partial = 'custom_fields/formats/attachment'
  790. self.is_filter_supported = false
  791. self.change_no_details = true
  792. self.bulk_edit_supported = false
  793. field_attributes :extensions_allowed
  794. def set_custom_field_value(custom_field, custom_field_value, value)
  795. attachment_present = false
  796. if value.is_a?(Hash)
  797. attachment_present = true
  798. value = value.except(:blank)
  799. if value.values.any? && value.values.all? {|v| v.is_a?(Hash)}
  800. value = value.values.first
  801. end
  802. if value.key?(:id)
  803. value = set_custom_field_value_by_id(custom_field, custom_field_value, value[:id])
  804. elsif value[:token].present?
  805. if attachment = Attachment.find_by_token(value[:token])
  806. value = attachment.id.to_s
  807. else
  808. value = ''
  809. end
  810. elsif value.key?(:file)
  811. attachment = Attachment.new(:file => value[:file], :author => User.current)
  812. if attachment.save
  813. value = attachment.id.to_s
  814. else
  815. value = ''
  816. end
  817. else
  818. attachment_present = false
  819. value = ''
  820. end
  821. elsif value.is_a?(String)
  822. value = set_custom_field_value_by_id(custom_field, custom_field_value, value)
  823. end
  824. custom_field_value.instance_variable_set "@attachment_present", attachment_present
  825. value
  826. end
  827. def set_custom_field_value_by_id(custom_field, custom_field_value, id)
  828. attachment = Attachment.find_by_id(id)
  829. if attachment && attachment.container.is_a?(CustomValue) && attachment.container.customized == custom_field_value.customized
  830. id.to_s
  831. else
  832. ''
  833. end
  834. end
  835. private :set_custom_field_value_by_id
  836. def cast_single_value(custom_field, value, customized=nil)
  837. Attachment.find_by_id(value.to_i) if value.present? && value.respond_to?(:to_i)
  838. end
  839. def validate_custom_value(custom_value)
  840. errors = []
  841. if custom_value.value.blank?
  842. if custom_value.instance_variable_get("@attachment_present")
  843. errors << ::I18n.t('activerecord.errors.messages.invalid')
  844. end
  845. else
  846. if custom_value.value.present?
  847. attachment = Attachment.find_by(:id => custom_value.value.to_s)
  848. extensions = custom_value.custom_field.extensions_allowed
  849. if attachment && extensions.present? && !attachment.extension_in?(extensions)
  850. errors << "#{::I18n.t('activerecord.errors.messages.invalid')} (#{l(:setting_attachment_extensions_allowed)}: #{extensions})"
  851. end
  852. end
  853. end
  854. errors.uniq
  855. end
  856. def after_save_custom_value(custom_field, custom_value)
  857. if custom_value.saved_change_to_value?
  858. if custom_value.value.present?
  859. attachment = Attachment.find_by(:id => custom_value.value.to_s)
  860. if attachment
  861. attachment.container = custom_value
  862. attachment.save!
  863. end
  864. end
  865. if custom_value.value_before_last_save.present?
  866. attachment = Attachment.find_by(:id => custom_value.value_before_last_save.to_s)
  867. if attachment
  868. attachment.destroy
  869. end
  870. end
  871. end
  872. end
  873. def edit_tag(view, tag_id, tag_name, custom_value, options={})
  874. attachment = nil
  875. if custom_value.value.present?
  876. attachment = Attachment.find_by_id(custom_value.value)
  877. end
  878. view.hidden_field_tag("#{tag_name}[blank]", "") +
  879. view.render(:partial => 'attachments/form',
  880. :locals => {
  881. :attachment_param => tag_name,
  882. :multiple => false,
  883. :description => false,
  884. :saved_attachments => [attachment].compact,
  885. :filedrop => false
  886. })
  887. end
  888. end
  889. end
  890. end