summaryrefslogtreecommitdiffstats
path: root/app/models/custom_field.rb
blob: 52594de99f5c915c1dcbf601b9eba414ad4c219d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# frozen_string_literal: true

# Redmine - project management software
# Copyright (C) 2006-2017  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

class CustomField < ActiveRecord::Base
  include Redmine::SafeAttributes
  include Redmine::SubclassFactory

  has_many :enumerations,
           lambda { order(:position) },
           :class_name => 'CustomFieldEnumeration',
           :dependent => :delete_all
  has_many :custom_values, :dependent => :delete_all
  has_and_belongs_to_many :roles, :join_table => "#{table_name_prefix}custom_fields_roles#{table_name_suffix}", :foreign_key => "custom_field_id"
  acts_as_positioned
  serialize :possible_values
  store :format_store

  validates_presence_of :name, :field_format
  validates_uniqueness_of :name, :scope => :type
  validates_length_of :name, :maximum => 30
  validates_length_of :regexp, maximum: 255
  validates_inclusion_of :field_format, :in => Proc.new { Redmine::FieldFormat.available_formats }
  validate :validate_custom_field

  before_validation :set_searchable
  before_save do |field|
    field.format.before_custom_field_save(field)
  end
  after_save :handle_multiplicity_change
  after_save do |field|
    if field.saved_change_to_visible? && field.visible
      field.roles.clear
    end
  end

  scope :sorted, lambda { order(:position) }
  scope :visible, lambda {|*args|
    user = args.shift || User.current
    if user.admin?
      # nop
    elsif user.memberships.any?
      where("#{table_name}.visible = ? OR #{table_name}.id IN (SELECT DISTINCT cfr.custom_field_id FROM #{Member.table_name} m" +
        " INNER JOIN #{MemberRole.table_name} mr ON mr.member_id = m.id" +
        " INNER JOIN #{table_name_prefix}custom_fields_roles#{table_name_suffix} cfr ON cfr.role_id = mr.role_id" +
        " WHERE m.user_id = ?)",
        true, user.id)
    else
      where(:visible => true)
    end
  }
  def visible_by?(project, user=User.current)
    visible? || user.admin?
  end

  safe_attributes 'name',
    'field_format',
    'possible_values',
    'regexp',
    'min_length',
    'max_length',
    'is_required',
    'is_for_all',
    'is_filter',
    'position',
    'searchable',
    'default_value',
    'editable',
    'visible',
    'multiple',
    'description',
    'role_ids',
    'url_pattern',
    'text_formatting',
    'edit_tag_style',
    'user_role',
    'version_status',
    'extensions_allowed',
    'full_width_layout'

  def format
    @format ||= Redmine::FieldFormat.find(field_format)
  end

  def field_format=(arg)
    # cannot change format of a saved custom field
    if new_record?
      @format = nil
      super
    end
  end

  def set_searchable
    # make sure these fields are not searchable
    self.searchable = false unless format.class.searchable_supported
    # make sure only these fields can have multiple values
    self.multiple = false unless format.class.multiple_supported
    true
  end

  def validate_custom_field
    format.validate_custom_field(self).each do |attribute, message|
      errors.add attribute, message
    end

    if regexp.present?
      begin
        Regexp.new(regexp)
      rescue
        errors.add(:regexp, :invalid)
      end
    end

    if default_value.present?
      validate_field_value(default_value).each do |message|
        errors.add :default_value, message
      end
    end
  end

  def possible_custom_value_options(custom_value)
    format.possible_custom_value_options(custom_value)
  end

  def possible_values_options(object=nil)
    if object.is_a?(Array)
      object.map {|o| format.possible_values_options(self, o)}.reduce(:&) || []
    else
      format.possible_values_options(self, object) || []
    end
  end

  def possible_values
    values = read_attribute(:possible_values)
    if values.is_a?(Array)
      values.each do |value|
        value.to_s.force_encoding('UTF-8')
      end
      values
    else
      []
    end
  end

  # Makes possible_values accept a multiline string
  def possible_values=(arg)
    if arg.is_a?(Array)
      values = arg.compact.map {|a| a.to_s.strip}.reject(&:blank?)
      write_attribute(:possible_values, values)
    else
      self.possible_values = arg.to_s.split(/[\n\r]+/)
    end
  end

  def set_custom_field_value(custom_field_value, value)
    format.set_custom_field_value(self, custom_field_value, value)
  end

  def cast_value(value)
    format.cast_value(self, value)
  end

  def value_from_keyword(keyword, customized)
    format.value_from_keyword(self, keyword, customized)
  end

  # Returns the options hash used to build a query filter for the field
  def query_filter_options(query)
    format.query_filter_options(self, query)
  end

  def totalable?
    format.totalable_supported
  end

  def full_width_layout?
    full_width_layout == '1'
  end

  def full_text_formatting?
    text_formatting == 'full'
  end

  # Returns a ORDER BY clause that can used to sort customized
  # objects by their value of the custom field.
  # Returns nil if the custom field can not be used for sorting.
  def order_statement
    return nil if multiple?
    format.order_statement(self)
  end

  # Returns a GROUP BY clause that can used to group by custom value
  # Returns nil if the custom field can not be used for grouping.
  def group_statement
    return nil if multiple?
    format.group_statement(self)
  end

  def join_for_order_statement
    format.join_for_order_statement(self)
  end

  def visibility_by_project_condition(project_key=nil, user=User.current, id_column=nil)
    if visible? || user.admin?
      "1=1"
    elsif user.anonymous?
      "1=0"
    else
      project_key ||= "#{self.class.customized_class.table_name}.project_id"
      id_column ||= id
      "#{project_key} IN (SELECT DISTINCT m.project_id FROM #{Member.table_name} m" +
        " INNER JOIN #{MemberRole.table_name} mr ON mr.member_id = m.id" +
        " INNER JOIN #{table_name_prefix}custom_fields_roles#{table_name_suffix} cfr ON cfr.role_id = mr.role_id" +
        " WHERE m.user_id = #{user.id} AND cfr.custom_field_id = #{id_column})"
    end
  end

  def <=>(field)
    position <=> field.position
  end

  # Returns the class that values represent
  def value_class
    format.target_class if format.respond_to?(:target_class)
  end

  def self.customized_class
    self.name =~ /^(.+)CustomField$/
    $1.constantize rescue nil
  end

  # to move in project_custom_field
  def self.for_all
    where(:is_for_all => true).order(:position).to_a
  end

  def type_name
    nil
  end

  # Returns the error messages for the given value
  # or an empty array if value is a valid value for the custom field
  def validate_custom_value(custom_value)
    value = custom_value.value
    errs = format.validate_custom_value(custom_value)

    unless errs.any?
      if value.is_a?(Array)
        if !multiple?
          errs << ::I18n.t('activerecord.errors.messages.invalid')
        end
        if is_required? && value.detect(&:present?).nil?
          errs << ::I18n.t('activerecord.errors.messages.blank')
        end
      else
        if is_required? && value.blank?
          errs << ::I18n.t('activerecord.errors.messages.blank')
        end
      end
    end

    errs
  end

  # Returns the error messages for the default custom field value
  def validate_field_value(value)
    validate_custom_value(CustomFieldValue.new(:custom_field => self, :value => value))
  end

  # Returns true if value is a valid value for the custom field
  def valid_field_value?(value)
    validate_field_value(value).empty?
  end

  def after_save_custom_value(custom_value)
    format.after_save_custom_value(self, custom_value)
  end

  def format_in?(*args)
    args.include?(field_format)
  end

  def self.human_attribute_name(attribute_key_name, *args)
    attr_name = attribute_key_name.to_s
    if attr_name == 'url_pattern'
      attr_name = "url"
    end
    super(attr_name, *args)
  end

  def css_classes
    "cf_#{id}"
  end

  protected

  # Removes multiple values for the custom field after setting the multiple attribute to false
  # We kepp the value with the highest id for each customized object
  def handle_multiplicity_change
    if !new_record? && multiple_before_last_save && !multiple
      ids = custom_values.
        where("EXISTS(SELECT 1 FROM #{CustomValue.table_name} cve WHERE cve.custom_field_id = #{CustomValue.table_name}.custom_field_id" +
          " AND cve.customized_type = #{CustomValue.table_name}.customized_type AND cve.customized_id = #{CustomValue.table_name}.customized_id" +
          " AND cve.id > #{CustomValue.table_name}.id)").
        pluck(:id)

      if ids.any?
        custom_values.where(:id => ids).delete_all
      end
    end
  end
end

require_dependency 'redmine/field_format'