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

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