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