##// END OF EJS Templates
'Assigned to' drop down list is now sorted by user's lastname....
Jean-Philippe Lang -
r926:81ada666bb54
parent child
Show More
@@ -1,195 +1,195
1 1 # redMine - project management software
2 2 # Copyright (C) 2006 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class Project < ActiveRecord::Base
19 19 # Project statuses
20 20 STATUS_ACTIVE = 1
21 21 STATUS_ARCHIVED = 9
22 22
23 23 has_many :members, :dependent => :delete_all, :include => :user, :conditions => "#{User.table_name}.status=#{User::STATUS_ACTIVE}"
24 24 has_many :users, :through => :members
25 25 has_many :custom_values, :dependent => :delete_all, :as => :customized
26 26 has_many :enabled_modules, :dependent => :delete_all
27 27 has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
28 28 has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
29 29 has_many :issue_changes, :through => :issues, :source => :journals
30 30 has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
31 31 has_many :time_entries, :dependent => :delete_all
32 32 has_many :queries, :dependent => :delete_all
33 33 has_many :documents, :dependent => :destroy
34 34 has_many :news, :dependent => :delete_all, :include => :author
35 35 has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
36 36 has_many :boards, :order => "position ASC"
37 37 has_one :repository, :dependent => :destroy
38 38 has_many :changesets, :through => :repository
39 39 has_one :wiki, :dependent => :destroy
40 40 # Custom field for the project issues
41 41 has_and_belongs_to_many :custom_fields,
42 42 :class_name => 'IssueCustomField',
43 43 :order => "#{CustomField.table_name}.position",
44 44 :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
45 45 :association_foreign_key => 'custom_field_id'
46 46
47 47 acts_as_tree :order => "name", :counter_cache => true
48 48
49 49 acts_as_searchable :columns => ['name', 'description'], :project_key => 'id'
50 50 acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
51 51 :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o.id}}
52 52
53 53 attr_protected :status, :enabled_module_names
54 54
55 55 validates_presence_of :name, :description, :identifier
56 56 validates_uniqueness_of :name, :identifier
57 57 validates_associated :custom_values, :on => :update
58 58 validates_associated :repository, :wiki
59 59 validates_length_of :name, :maximum => 30
60 60 validates_format_of :name, :with => /^[\w\s\'\-]*$/i
61 61 validates_length_of :description, :maximum => 255
62 62 validates_length_of :homepage, :maximum => 60
63 63 validates_length_of :identifier, :in => 3..12
64 64 validates_format_of :identifier, :with => /^[a-z0-9\-]*$/
65 65
66 66 def identifier=(identifier)
67 67 super unless identifier_frozen?
68 68 end
69 69
70 70 def identifier_frozen?
71 71 errors[:identifier].nil? && !(new_record? || identifier.blank?)
72 72 end
73 73
74 74 def issues_with_subprojects(include_subprojects=false)
75 75 conditions = nil
76 76 if include_subprojects && !active_children.empty?
77 77 ids = [id] + active_children.collect {|c| c.id}
78 78 conditions = ["#{Issue.table_name}.project_id IN (#{ids.join(',')})"]
79 79 end
80 80 conditions ||= ["#{Issue.table_name}.project_id = ?", id]
81 81 Issue.with_scope :find => { :conditions => conditions } do
82 82 yield
83 83 end
84 84 end
85 85
86 86 # Return all issues status changes for the project between the 2 given dates
87 87 def issues_status_changes(from, to)
88 88 Journal.find(:all, :include => [:issue, :details, :user],
89 89 :conditions => ["#{Journal.table_name}.journalized_type = 'Issue'" +
90 90 " AND #{Issue.table_name}.project_id = ?" +
91 91 " AND #{JournalDetail.table_name}.prop_key = 'status_id'" +
92 92 " AND #{Journal.table_name}.created_on BETWEEN ? AND ?",
93 93 id, from, to+1])
94 94 end
95 95
96 96 # returns latest created projects
97 97 # non public projects will be returned only if user is a member of those
98 98 def self.latest(user=nil, count=5)
99 99 find(:all, :limit => count, :conditions => visible_by(user), :order => "created_on DESC")
100 100 end
101 101
102 102 def self.visible_by(user=nil)
103 103 if user && user.admin?
104 104 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
105 105 elsif user && user.memberships.any?
106 106 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND (#{Project.table_name}.is_public = #{connection.quoted_true} or #{Project.table_name}.id IN (#{user.memberships.collect{|m| m.project_id}.join(',')}))"
107 107 else
108 108 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND #{Project.table_name}.is_public = #{connection.quoted_true}"
109 109 end
110 110 end
111 111
112 112 def active?
113 113 self.status == STATUS_ACTIVE
114 114 end
115 115
116 116 def archive
117 117 # Archive subprojects if any
118 118 children.each do |subproject|
119 119 subproject.archive
120 120 end
121 121 update_attribute :status, STATUS_ARCHIVED
122 122 end
123 123
124 124 def unarchive
125 125 return false if parent && !parent.active?
126 126 update_attribute :status, STATUS_ACTIVE
127 127 end
128 128
129 129 def active_children
130 130 children.select {|child| child.active?}
131 131 end
132 132
133 133 # Users issues can be assigned to
134 134 def assignable_users
135 members.select {|m| m.role.assignable?}.collect {|m| m.user}
135 members.select {|m| m.role.assignable?}.collect {|m| m.user}.sort
136 136 end
137 137
138 138 # Returns the mail adresses of users that should be always notified on project events
139 139 def recipients
140 140 members.select {|m| m.mail_notification? || m.user.mail_notification?}.collect {|m| m.user.mail}
141 141 end
142 142
143 143 # Returns an array of all custom fields enabled for project issues
144 144 # (explictly associated custom fields and custom fields enabled for all projects)
145 145 def custom_fields_for_issues(tracker)
146 146 all_custom_fields.select {|c| tracker.custom_fields.include? c }
147 147 end
148 148
149 149 def all_custom_fields
150 150 @all_custom_fields ||= (IssueCustomField.for_all + custom_fields).uniq
151 151 end
152 152
153 153 def <=>(project)
154 154 name.downcase <=> project.name.downcase
155 155 end
156 156
157 157 def allows_to?(action)
158 158 if action.is_a? Hash
159 159 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
160 160 else
161 161 allowed_permissions.include? action
162 162 end
163 163 end
164 164
165 165 def module_enabled?(module_name)
166 166 module_name = module_name.to_s
167 167 enabled_modules.detect {|m| m.name == module_name}
168 168 end
169 169
170 170 def enabled_module_names=(module_names)
171 171 enabled_modules.clear
172 172 module_names = [] unless module_names && module_names.is_a?(Array)
173 173 module_names.each do |name|
174 174 enabled_modules << EnabledModule.new(:name => name.to_s)
175 175 end
176 176 end
177 177
178 178 protected
179 179 def validate
180 180 errors.add(parent_id, " must be a root project") if parent and parent.parent
181 181 errors.add_to_base("A project with subprojects can't be a subproject") if parent and children.size > 0
182 182 end
183 183
184 184 private
185 185 def allowed_permissions
186 186 @allowed_permissions ||= begin
187 187 module_names = enabled_modules.collect {|m| m.name}
188 188 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
189 189 end
190 190 end
191 191
192 192 def allowed_actions
193 193 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
194 194 end
195 195 end
@@ -1,344 +1,344
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class QueryColumn
19 19 attr_accessor :name, :sortable
20 20 include GLoc
21 21
22 22 def initialize(name, options={})
23 23 self.name = name
24 24 self.sortable = options[:sortable]
25 25 end
26 26
27 27 def caption
28 28 set_language_if_valid(User.current.language)
29 29 l("field_#{name}")
30 30 end
31 31 end
32 32
33 33 class QueryCustomFieldColumn < QueryColumn
34 34
35 35 def initialize(custom_field)
36 36 self.name = "cf_#{custom_field.id}".to_sym
37 37 self.sortable = false
38 38 @cf = custom_field
39 39 end
40 40
41 41 def caption
42 42 @cf.name
43 43 end
44 44
45 45 def custom_field
46 46 @cf
47 47 end
48 48 end
49 49
50 50 class Query < ActiveRecord::Base
51 51 belongs_to :project
52 52 belongs_to :user
53 53 serialize :filters
54 54 serialize :column_names
55 55
56 56 attr_protected :project, :user
57 57 attr_accessor :executed_by
58 58
59 59 validates_presence_of :name, :on => :save
60 60 validates_length_of :name, :maximum => 255
61 61
62 62 @@operators = { "=" => :label_equals,
63 63 "!" => :label_not_equals,
64 64 "o" => :label_open_issues,
65 65 "c" => :label_closed_issues,
66 66 "!*" => :label_none,
67 67 "*" => :label_all,
68 68 ">=" => '>=',
69 69 "<=" => '<=',
70 70 "<t+" => :label_in_less_than,
71 71 ">t+" => :label_in_more_than,
72 72 "t+" => :label_in,
73 73 "t" => :label_today,
74 74 "w" => :label_this_week,
75 75 ">t-" => :label_less_than_ago,
76 76 "<t-" => :label_more_than_ago,
77 77 "t-" => :label_ago,
78 78 "~" => :label_contains,
79 79 "!~" => :label_not_contains }
80 80
81 81 cattr_reader :operators
82 82
83 83 @@operators_by_filter_type = { :list => [ "=", "!" ],
84 84 :list_status => [ "o", "=", "!", "c", "*" ],
85 85 :list_optional => [ "=", "!", "!*", "*" ],
86 86 :list_one_or_more => [ "*", "=" ],
87 87 :date => [ "<t+", ">t+", "t+", "t", "w", ">t-", "<t-", "t-" ],
88 88 :date_past => [ ">t-", "<t-", "t-", "t", "w" ],
89 89 :string => [ "=", "~", "!", "!~" ],
90 90 :text => [ "~", "!~" ],
91 91 :integer => [ "=", ">=", "<=" ] }
92 92
93 93 cattr_reader :operators_by_filter_type
94 94
95 95 @@available_columns = [
96 96 QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position"),
97 97 QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position"),
98 98 QueryColumn.new(:priority, :sortable => "#{Enumeration.table_name}.position"),
99 99 QueryColumn.new(:subject),
100 100 QueryColumn.new(:assigned_to, :sortable => "#{User.table_name}.lastname"),
101 101 QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on"),
102 102 QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name"),
103 103 QueryColumn.new(:fixed_version),
104 104 QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
105 105 QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
106 106 QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
107 107 QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio"),
108 108 QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on"),
109 109 ]
110 110 cattr_reader :available_columns
111 111
112 112 def initialize(attributes = nil)
113 113 super attributes
114 114 self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
115 115 @executed_by = User.current.logged? ? User.current : nil
116 116 set_language_if_valid(executed_by.language) if executed_by
117 117 end
118 118
119 119 def validate
120 120 filters.each_key do |field|
121 121 errors.add label_for(field), :activerecord_error_blank unless
122 122 # filter requires one or more values
123 123 (values_for(field) and !values_for(field).first.empty?) or
124 124 # filter doesn't require any value
125 125 ["o", "c", "!*", "*", "t", "w"].include? operator_for(field)
126 126 end if filters
127 127 end
128 128
129 129 def editable_by?(user)
130 130 return false unless user
131 131 return true if !is_public && self.user_id == user.id
132 132 is_public && user.allowed_to?(:manage_public_queries, project)
133 133 end
134 134
135 135 def available_filters
136 136 return @available_filters if @available_filters
137 137 @available_filters = { "status_id" => { :type => :list_status, :order => 1, :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } },
138 138 "tracker_id" => { :type => :list, :order => 2, :values => Tracker.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } },
139 139 "priority_id" => { :type => :list, :order => 3, :values => Enumeration.find(:all, :conditions => ['opt=?','IPRI']).collect{|s| [s.name, s.id.to_s] } },
140 140 "subject" => { :type => :text, :order => 8 },
141 141 "created_on" => { :type => :date_past, :order => 9 },
142 142 "updated_on" => { :type => :date_past, :order => 10 },
143 143 "start_date" => { :type => :date, :order => 11 },
144 144 "due_date" => { :type => :date, :order => 12 },
145 145 "done_ratio" => { :type => :integer, :order => 13 }}
146 146
147 147 user_values = []
148 148 user_values << ["<< #{l(:label_me)} >>", "me"] if executed_by
149 149 if project
150 user_values += project.users.collect{|s| [s.name, s.id.to_s] }
150 user_values += project.users.sort.collect{|s| [s.name, s.id.to_s] }
151 151 elsif executed_by
152 152 # members of the user's projects
153 153 user_values += executed_by.projects.collect(&:users).flatten.uniq.sort.collect{|s| [s.name, s.id.to_s] }
154 154 end
155 155 @available_filters["assigned_to_id"] = { :type => :list_optional, :order => 4, :values => user_values } unless user_values.empty?
156 156 @available_filters["author_id"] = { :type => :list, :order => 5, :values => user_values } unless user_values.empty?
157 157
158 158 if project
159 159 # project specific filters
160 160 @available_filters["category_id"] = { :type => :list_optional, :order => 6, :values => @project.issue_categories.collect{|s| [s.name, s.id.to_s] } }
161 161 @available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => @project.versions.sort.collect{|s| [s.name, s.id.to_s] } }
162 162 unless @project.active_children.empty?
163 163 @available_filters["subproject_id"] = { :type => :list_one_or_more, :order => 13, :values => @project.active_children.collect{|s| [s.name, s.id.to_s] } }
164 164 end
165 165 @project.all_custom_fields.select(&:is_filter?).each do |field|
166 166 case field.field_format
167 167 when "text"
168 168 options = { :type => :text, :order => 20 }
169 169 when "list"
170 170 options = { :type => :list_optional, :values => field.possible_values, :order => 20}
171 171 when "date"
172 172 options = { :type => :date, :order => 20 }
173 173 when "bool"
174 174 options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 }
175 175 else
176 176 options = { :type => :string, :order => 20 }
177 177 end
178 178 @available_filters["cf_#{field.id}"] = options.merge({ :name => field.name })
179 179 end
180 180 # remove category filter if no category defined
181 181 @available_filters.delete "category_id" if @available_filters["category_id"][:values].empty?
182 182 end
183 183 @available_filters
184 184 end
185 185
186 186 def add_filter(field, operator, values)
187 187 # values must be an array
188 188 return unless values and values.is_a? Array # and !values.first.empty?
189 189 # check if field is defined as an available filter
190 190 if available_filters.has_key? field
191 191 filter_options = available_filters[field]
192 192 # check if operator is allowed for that filter
193 193 #if @@operators_by_filter_type[filter_options[:type]].include? operator
194 194 # allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]})
195 195 # filters[field] = {:operator => operator, :values => allowed_values } if (allowed_values.first and !allowed_values.first.empty?) or ["o", "c", "!*", "*", "t"].include? operator
196 196 #end
197 197 filters[field] = {:operator => operator, :values => values }
198 198 end
199 199 end
200 200
201 201 def add_short_filter(field, expression)
202 202 return unless expression
203 203 parms = expression.scan(/^(o|c|\!|\*)?(.*)$/).first
204 204 add_filter field, (parms[0] || "="), [parms[1] || ""]
205 205 end
206 206
207 207 def has_filter?(field)
208 208 filters and filters[field]
209 209 end
210 210
211 211 def operator_for(field)
212 212 has_filter?(field) ? filters[field][:operator] : nil
213 213 end
214 214
215 215 def values_for(field)
216 216 has_filter?(field) ? filters[field][:values] : nil
217 217 end
218 218
219 219 def label_for(field)
220 220 label = @available_filters[field][:name] if @available_filters.has_key?(field)
221 221 label ||= field.gsub(/\_id$/, "")
222 222 end
223 223
224 224 def available_columns
225 225 return @available_columns if @available_columns
226 226 @available_columns = Query.available_columns
227 227 @available_columns += (project ?
228 228 project.custom_fields :
229 229 IssueCustomField.find(:all, :conditions => {:is_for_all => true})
230 230 ).collect {|cf| QueryCustomFieldColumn.new(cf) }
231 231 end
232 232
233 233 def columns
234 234 if has_default_columns?
235 235 available_columns.select {|c| Setting.issue_list_default_columns.include?(c.name.to_s) }
236 236 else
237 237 # preserve the column_names order
238 238 column_names.collect {|name| available_columns.find {|col| col.name == name}}.compact
239 239 end
240 240 end
241 241
242 242 def column_names=(names)
243 243 names = names.select {|n| n.is_a?(Symbol) || !n.blank? } if names
244 244 names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym } if names
245 245 write_attribute(:column_names, names)
246 246 end
247 247
248 248 def has_column?(column)
249 249 column_names && column_names.include?(column.name)
250 250 end
251 251
252 252 def has_default_columns?
253 253 column_names.nil? || column_names.empty?
254 254 end
255 255
256 256 def statement
257 257 # project/subprojects clause
258 258 clause = ''
259 259 if project && has_filter?("subproject_id")
260 260 subproject_ids = []
261 261 if operator_for("subproject_id") == "="
262 262 subproject_ids = values_for("subproject_id").each(&:to_i)
263 263 else
264 264 subproject_ids = project.active_children.collect{|p| p.id}
265 265 end
266 266 clause << "#{Issue.table_name}.project_id IN (%d,%s)" % [project.id, subproject_ids.join(",")] if project
267 267 elsif project
268 268 clause << "#{Issue.table_name}.project_id=%d" % project.id
269 269 else
270 270 clause << Project.visible_by(executed_by)
271 271 end
272 272
273 273 # filters clauses
274 274 filters_clauses = []
275 275 filters.each_key do |field|
276 276 next if field == "subproject_id"
277 277 v = values_for(field).clone
278 278 next unless v and !v.empty?
279 279
280 280 sql = ''
281 281 if field =~ /^cf_(\d+)$/
282 282 # custom field
283 283 db_table = CustomValue.table_name
284 284 db_field = 'value'
285 285 sql << "#{Issue.table_name}.id IN (SELECT #{db_table}.customized_id FROM #{db_table} where #{db_table}.customized_type='Issue' AND #{db_table}.customized_id=#{Issue.table_name}.id AND #{db_table}.custom_field_id=#{$1} AND "
286 286 else
287 287 # regular field
288 288 db_table = Issue.table_name
289 289 db_field = field
290 290 sql << '('
291 291 end
292 292
293 293 # "me" value subsitution
294 294 if %w(assigned_to_id author_id).include?(field)
295 295 v.push(executed_by ? executed_by.id.to_s : "0") if v.delete("me")
296 296 end
297 297
298 298 case operator_for field
299 299 when "="
300 300 sql = sql + "#{db_table}.#{db_field} IN (" + v.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
301 301 when "!"
302 302 sql = sql + "#{db_table}.#{db_field} NOT IN (" + v.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
303 303 when "!*"
304 304 sql = sql + "#{db_table}.#{db_field} IS NULL"
305 305 when "*"
306 306 sql = sql + "#{db_table}.#{db_field} IS NOT NULL"
307 307 when ">="
308 308 sql = sql + "#{db_table}.#{db_field} >= #{v.first.to_i}"
309 309 when "<="
310 310 sql = sql + "#{db_table}.#{db_field} <= #{v.first.to_i}"
311 311 when "o"
312 312 sql = sql + "#{IssueStatus.table_name}.is_closed=#{connection.quoted_false}" if field == "status_id"
313 313 when "c"
314 314 sql = sql + "#{IssueStatus.table_name}.is_closed=#{connection.quoted_true}" if field == "status_id"
315 315 when ">t-"
316 316 sql = sql + "#{db_table}.#{db_field} BETWEEN '%s' AND '%s'" % [connection.quoted_date((Date.today - v.first.to_i).to_time), connection.quoted_date((Date.today + 1).to_time)]
317 317 when "<t-"
318 318 sql = sql + "#{db_table}.#{db_field} <= '%s'" % connection.quoted_date((Date.today - v.first.to_i).to_time)
319 319 when "t-"
320 320 sql = sql + "#{db_table}.#{db_field} BETWEEN '%s' AND '%s'" % [connection.quoted_date((Date.today - v.first.to_i).to_time), connection.quoted_date((Date.today - v.first.to_i + 1).to_time)]
321 321 when ">t+"
322 322 sql = sql + "#{db_table}.#{db_field} >= '%s'" % connection.quoted_date((Date.today + v.first.to_i).to_time)
323 323 when "<t+"
324 324 sql = sql + "#{db_table}.#{db_field} BETWEEN '%s' AND '%s'" % [connection.quoted_date(Date.today.to_time), connection.quoted_date((Date.today + v.first.to_i + 1).to_time)]
325 325 when "t+"
326 326 sql = sql + "#{db_table}.#{db_field} BETWEEN '%s' AND '%s'" % [connection.quoted_date((Date.today + v.first.to_i).to_time), connection.quoted_date((Date.today + v.first.to_i + 1).to_time)]
327 327 when "t"
328 328 sql = sql + "#{db_table}.#{db_field} BETWEEN '%s' AND '%s'" % [connection.quoted_date(Date.today.to_time), connection.quoted_date((Date.today+1).to_time)]
329 329 when "w"
330 330 sql = sql + "#{db_table}.#{db_field} BETWEEN '%s' AND '%s'" % [connection.quoted_date(Time.now.at_beginning_of_week), connection.quoted_date(Time.now.next_week.yesterday)]
331 331 when "~"
332 332 sql = sql + "#{db_table}.#{db_field} LIKE '%#{connection.quote_string(v.first)}%'"
333 333 when "!~"
334 334 sql = sql + "#{db_table}.#{db_field} NOT LIKE '%#{connection.quote_string(v.first)}%'"
335 335 end
336 336 sql << ')'
337 337 filters_clauses << sql
338 338 end if filters and valid?
339 339
340 340 clause << ' AND ' unless clause.empty?
341 341 clause << filters_clauses.join(' AND ') unless filters_clauses.empty?
342 342 clause
343 343 end
344 344 end
@@ -1,255 +1,255
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require "digest/sha1"
19 19
20 20 class User < ActiveRecord::Base
21 21 # Account statuses
22 22 STATUS_ANONYMOUS = 0
23 23 STATUS_ACTIVE = 1
24 24 STATUS_REGISTERED = 2
25 25 STATUS_LOCKED = 3
26 26
27 27 has_many :memberships, :class_name => 'Member', :include => [ :project, :role ], :conditions => "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}", :order => "#{Project.table_name}.name", :dependent => :delete_all
28 28 has_many :projects, :through => :memberships
29 29 has_many :custom_values, :dependent => :delete_all, :as => :customized
30 30 has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify
31 31 has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
32 32 has_one :rss_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='feeds'"
33 33 belongs_to :auth_source
34 34
35 35 attr_accessor :password, :password_confirmation
36 36 attr_accessor :last_before_login_on
37 37 # Prevents unauthorized assignments
38 38 attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
39 39
40 40 validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
41 41 validates_uniqueness_of :login, :mail
42 42 # Login must contain lettres, numbers, underscores only
43 43 validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
44 44 validates_length_of :login, :maximum => 30
45 45 validates_format_of :firstname, :lastname, :with => /^[\w\s\'\-]*$/i
46 46 validates_length_of :firstname, :lastname, :maximum => 30
47 47 validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_nil => true
48 48 validates_length_of :mail, :maximum => 60, :allow_nil => true
49 49 validates_length_of :password, :minimum => 4, :allow_nil => true
50 50 validates_confirmation_of :password, :allow_nil => true
51 51 validates_associated :custom_values, :on => :update
52 52
53 53 def before_create
54 54 self.mail_notification = false
55 55 true
56 56 end
57 57
58 58 def before_save
59 59 # update hashed_password if password was set
60 60 self.hashed_password = User.hash_password(self.password) if self.password
61 61 end
62 62
63 63 def self.active
64 64 with_scope :find => { :conditions => [ "status = ?", STATUS_ACTIVE ] } do
65 65 yield
66 66 end
67 67 end
68 68
69 69 def self.find_active(*args)
70 70 active do
71 71 find(*args)
72 72 end
73 73 end
74 74
75 75 # Returns the user that matches provided login and password, or nil
76 76 def self.try_to_login(login, password)
77 77 user = find(:first, :conditions => ["login=?", login])
78 78 if user
79 79 # user is already in local database
80 80 return nil if !user.active?
81 81 if user.auth_source
82 82 # user has an external authentication method
83 83 return nil unless user.auth_source.authenticate(login, password)
84 84 else
85 85 # authentication with local password
86 86 return nil unless User.hash_password(password) == user.hashed_password
87 87 end
88 88 else
89 89 # user is not yet registered, try to authenticate with available sources
90 90 attrs = AuthSource.authenticate(login, password)
91 91 if attrs
92 92 onthefly = new(*attrs)
93 93 onthefly.login = login
94 94 onthefly.language = Setting.default_language
95 95 if onthefly.save
96 96 user = find(:first, :conditions => ["login=?", login])
97 97 logger.info("User '#{user.login}' created on the fly.") if logger
98 98 end
99 99 end
100 100 end
101 101 user.update_attribute(:last_login_on, Time.now) if user
102 102 user
103 103
104 104 rescue => text
105 105 raise text
106 106 end
107 107
108 108 # Return user's full name for display
109 109 def name
110 110 "#{firstname} #{lastname}"
111 111 end
112 112
113 113 def active?
114 114 self.status == STATUS_ACTIVE
115 115 end
116 116
117 117 def registered?
118 118 self.status == STATUS_REGISTERED
119 119 end
120 120
121 121 def locked?
122 122 self.status == STATUS_LOCKED
123 123 end
124 124
125 125 def check_password?(clear_password)
126 126 User.hash_password(clear_password) == self.hashed_password
127 127 end
128 128
129 129 def pref
130 130 self.preference ||= UserPreference.new(:user => self)
131 131 end
132 132
133 133 def time_zone
134 134 self.pref.time_zone.nil? ? nil : TimeZone[self.pref.time_zone]
135 135 end
136 136
137 137 # Return user's RSS key (a 40 chars long string), used to access feeds
138 138 def rss_key
139 139 token = self.rss_token || Token.create(:user => self, :action => 'feeds')
140 140 token.value
141 141 end
142 142
143 143 # Return an array of project ids for which the user has explicitly turned mail notifications on
144 144 def notified_projects_ids
145 145 @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
146 146 end
147 147
148 148 def notified_project_ids=(ids)
149 149 Member.update_all("mail_notification = #{connection.quoted_false}", ['user_id = ?', id])
150 150 Member.update_all("mail_notification = #{connection.quoted_true}", ['user_id = ? AND project_id IN (?)', id, ids]) if ids && !ids.empty?
151 151 @notified_projects_ids = nil
152 152 notified_projects_ids
153 153 end
154 154
155 155 def self.find_by_rss_key(key)
156 156 token = Token.find_by_value(key)
157 157 token && token.user.active? ? token.user : nil
158 158 end
159 159
160 160 def self.find_by_autologin_key(key)
161 161 token = Token.find_by_action_and_value('autologin', key)
162 162 token && (token.created_on > Setting.autologin.to_i.day.ago) && token.user.active? ? token.user : nil
163 163 end
164 164
165 165 def <=>(user)
166 lastname == user.lastname ? firstname <=> user.firstname : lastname <=> user.lastname
166 user.nil? ? -1 : (lastname == user.lastname ? firstname <=> user.firstname : lastname <=> user.lastname)
167 167 end
168 168
169 169 def to_s
170 170 name
171 171 end
172 172
173 173 def logged?
174 174 true
175 175 end
176 176
177 177 # Return user's role for project
178 178 def role_for_project(project)
179 179 # No role on archived projects
180 180 return nil unless project && project.active?
181 181 if logged?
182 182 # Find project membership
183 183 membership = memberships.detect {|m| m.project_id == project.id}
184 184 if membership
185 185 membership.role
186 186 else
187 187 @role_non_member ||= Role.non_member
188 188 end
189 189 else
190 190 @role_anonymous ||= Role.anonymous
191 191 end
192 192 end
193 193
194 194 # Return true if the user is a member of project
195 195 def member_of?(project)
196 196 role_for_project(project).member?
197 197 end
198 198
199 199 # Return true if the user is allowed to do the specified action on project
200 200 # action can be:
201 201 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
202 202 # * a permission Symbol (eg. :edit_project)
203 203 def allowed_to?(action, project)
204 204 # No action allowed on archived projects
205 205 return false unless project.active?
206 206 # No action allowed on disabled modules
207 207 return false unless project.allows_to?(action)
208 208 # Admin users are authorized for anything else
209 209 return true if admin?
210 210
211 211 role = role_for_project(project)
212 212 return false unless role
213 213 role.allowed_to?(action) && (project.is_public? || role.member?)
214 214 end
215 215
216 216 def self.current=(user)
217 217 @current_user = user
218 218 end
219 219
220 220 def self.current
221 221 @current_user ||= User.anonymous
222 222 end
223 223
224 224 def self.anonymous
225 225 return @anonymous_user if @anonymous_user
226 226 anonymous_user = AnonymousUser.find(:first)
227 227 if anonymous_user.nil?
228 228 anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
229 229 raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
230 230 end
231 231 @anonymous_user = anonymous_user
232 232 end
233 233
234 234 private
235 235 # Return password digest
236 236 def self.hash_password(clear_password)
237 237 Digest::SHA1.hexdigest(clear_password || "")
238 238 end
239 239 end
240 240
241 241 class AnonymousUser < User
242 242
243 243 def validate_on_create
244 244 # There should be only one AnonymousUser in the database
245 245 errors.add_to_base 'An anonymous user already exists.' if AnonymousUser.find(:first)
246 246 end
247 247
248 248 # Overrides a few properties
249 249 def logged?; false end
250 250 def admin; false end
251 251 def name; 'Anonymous' end
252 252 def mail; nil end
253 253 def time_zone; nil end
254 254 def rss_key; nil end
255 255 end
General Comments 0
You need to be logged in to leave comments. Login now