##// END OF EJS Templates
Load roles when loading project members....
Jean-Philippe Lang -
r2964:d73fb1fab896
parent child
Show More
@@ -1,607 +1,607
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 # Specific overidden Activities
23 # Specific overidden Activities
24 has_many :time_entry_activities do
24 has_many :time_entry_activities do
25 def active
25 def active
26 find(:all, :conditions => {:active => true})
26 find(:all, :conditions => {:active => true})
27 end
27 end
28 end
28 end
29 has_many :members, :include => :user, :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
29 has_many :members, :include => [:user, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
30 has_many :member_principals, :class_name => 'Member',
30 has_many :member_principals, :class_name => 'Member',
31 :include => :principal,
31 :include => :principal,
32 :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
32 :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
33 has_many :users, :through => :members
33 has_many :users, :through => :members
34 has_many :principals, :through => :member_principals, :source => :principal
34 has_many :principals, :through => :member_principals, :source => :principal
35
35
36 has_many :enabled_modules, :dependent => :delete_all
36 has_many :enabled_modules, :dependent => :delete_all
37 has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
37 has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
38 has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
38 has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
39 has_many :issue_changes, :through => :issues, :source => :journals
39 has_many :issue_changes, :through => :issues, :source => :journals
40 has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
40 has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
41 has_many :time_entries, :dependent => :delete_all
41 has_many :time_entries, :dependent => :delete_all
42 has_many :queries, :dependent => :delete_all
42 has_many :queries, :dependent => :delete_all
43 has_many :documents, :dependent => :destroy
43 has_many :documents, :dependent => :destroy
44 has_many :news, :dependent => :delete_all, :include => :author
44 has_many :news, :dependent => :delete_all, :include => :author
45 has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
45 has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
46 has_many :boards, :dependent => :destroy, :order => "position ASC"
46 has_many :boards, :dependent => :destroy, :order => "position ASC"
47 has_one :repository, :dependent => :destroy
47 has_one :repository, :dependent => :destroy
48 has_many :changesets, :through => :repository
48 has_many :changesets, :through => :repository
49 has_one :wiki, :dependent => :destroy
49 has_one :wiki, :dependent => :destroy
50 # Custom field for the project issues
50 # Custom field for the project issues
51 has_and_belongs_to_many :issue_custom_fields,
51 has_and_belongs_to_many :issue_custom_fields,
52 :class_name => 'IssueCustomField',
52 :class_name => 'IssueCustomField',
53 :order => "#{CustomField.table_name}.position",
53 :order => "#{CustomField.table_name}.position",
54 :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
54 :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
55 :association_foreign_key => 'custom_field_id'
55 :association_foreign_key => 'custom_field_id'
56
56
57 acts_as_nested_set :order => 'name', :dependent => :destroy
57 acts_as_nested_set :order => 'name', :dependent => :destroy
58 acts_as_attachable :view_permission => :view_files,
58 acts_as_attachable :view_permission => :view_files,
59 :delete_permission => :manage_files
59 :delete_permission => :manage_files
60
60
61 acts_as_customizable
61 acts_as_customizable
62 acts_as_searchable :columns => ['name', 'description'], :project_key => 'id', :permission => nil
62 acts_as_searchable :columns => ['name', 'description'], :project_key => 'id', :permission => nil
63 acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
63 acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
64 :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o.id}},
64 :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o.id}},
65 :author => nil
65 :author => nil
66
66
67 attr_protected :status, :enabled_module_names
67 attr_protected :status, :enabled_module_names
68
68
69 validates_presence_of :name, :identifier
69 validates_presence_of :name, :identifier
70 validates_uniqueness_of :name, :identifier
70 validates_uniqueness_of :name, :identifier
71 validates_associated :repository, :wiki
71 validates_associated :repository, :wiki
72 validates_length_of :name, :maximum => 30
72 validates_length_of :name, :maximum => 30
73 validates_length_of :homepage, :maximum => 255
73 validates_length_of :homepage, :maximum => 255
74 validates_length_of :identifier, :in => 1..20
74 validates_length_of :identifier, :in => 1..20
75 # donwcase letters, digits, dashes but not digits only
75 # donwcase letters, digits, dashes but not digits only
76 validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? }
76 validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? }
77 # reserved words
77 # reserved words
78 validates_exclusion_of :identifier, :in => %w( new )
78 validates_exclusion_of :identifier, :in => %w( new )
79
79
80 before_destroy :delete_all_members
80 before_destroy :delete_all_members
81
81
82 named_scope :has_module, lambda { |mod| { :conditions => ["#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s] } }
82 named_scope :has_module, lambda { |mod| { :conditions => ["#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s] } }
83 named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
83 named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
84 named_scope :all_public, { :conditions => { :is_public => true } }
84 named_scope :all_public, { :conditions => { :is_public => true } }
85 named_scope :visible, lambda { { :conditions => Project.visible_by(User.current) } }
85 named_scope :visible, lambda { { :conditions => Project.visible_by(User.current) } }
86
86
87 def identifier=(identifier)
87 def identifier=(identifier)
88 super unless identifier_frozen?
88 super unless identifier_frozen?
89 end
89 end
90
90
91 def identifier_frozen?
91 def identifier_frozen?
92 errors[:identifier].nil? && !(new_record? || identifier.blank?)
92 errors[:identifier].nil? && !(new_record? || identifier.blank?)
93 end
93 end
94
94
95 # returns latest created projects
95 # returns latest created projects
96 # non public projects will be returned only if user is a member of those
96 # non public projects will be returned only if user is a member of those
97 def self.latest(user=nil, count=5)
97 def self.latest(user=nil, count=5)
98 find(:all, :limit => count, :conditions => visible_by(user), :order => "created_on DESC")
98 find(:all, :limit => count, :conditions => visible_by(user), :order => "created_on DESC")
99 end
99 end
100
100
101 # Returns a SQL :conditions string used to find all active projects for the specified user.
101 # Returns a SQL :conditions string used to find all active projects for the specified user.
102 #
102 #
103 # Examples:
103 # Examples:
104 # Projects.visible_by(admin) => "projects.status = 1"
104 # Projects.visible_by(admin) => "projects.status = 1"
105 # Projects.visible_by(normal_user) => "projects.status = 1 AND projects.is_public = 1"
105 # Projects.visible_by(normal_user) => "projects.status = 1 AND projects.is_public = 1"
106 def self.visible_by(user=nil)
106 def self.visible_by(user=nil)
107 user ||= User.current
107 user ||= User.current
108 if user && user.admin?
108 if user && user.admin?
109 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
109 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
110 elsif user && user.memberships.any?
110 elsif user && user.memberships.any?
111 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(',')}))"
111 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(',')}))"
112 else
112 else
113 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND #{Project.table_name}.is_public = #{connection.quoted_true}"
113 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND #{Project.table_name}.is_public = #{connection.quoted_true}"
114 end
114 end
115 end
115 end
116
116
117 def self.allowed_to_condition(user, permission, options={})
117 def self.allowed_to_condition(user, permission, options={})
118 statements = []
118 statements = []
119 base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
119 base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
120 if perm = Redmine::AccessControl.permission(permission)
120 if perm = Redmine::AccessControl.permission(permission)
121 unless perm.project_module.nil?
121 unless perm.project_module.nil?
122 # If the permission belongs to a project module, make sure the module is enabled
122 # If the permission belongs to a project module, make sure the module is enabled
123 base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
123 base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
124 end
124 end
125 end
125 end
126 if options[:project]
126 if options[:project]
127 project_statement = "#{Project.table_name}.id = #{options[:project].id}"
127 project_statement = "#{Project.table_name}.id = #{options[:project].id}"
128 project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
128 project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
129 base_statement = "(#{project_statement}) AND (#{base_statement})"
129 base_statement = "(#{project_statement}) AND (#{base_statement})"
130 end
130 end
131 if user.admin?
131 if user.admin?
132 # no restriction
132 # no restriction
133 else
133 else
134 statements << "1=0"
134 statements << "1=0"
135 if user.logged?
135 if user.logged?
136 if Role.non_member.allowed_to?(permission) && !options[:member]
136 if Role.non_member.allowed_to?(permission) && !options[:member]
137 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
137 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
138 end
138 end
139 allowed_project_ids = user.memberships.select {|m| m.roles.detect {|role| role.allowed_to?(permission)}}.collect {|m| m.project_id}
139 allowed_project_ids = user.memberships.select {|m| m.roles.detect {|role| role.allowed_to?(permission)}}.collect {|m| m.project_id}
140 statements << "#{Project.table_name}.id IN (#{allowed_project_ids.join(',')})" if allowed_project_ids.any?
140 statements << "#{Project.table_name}.id IN (#{allowed_project_ids.join(',')})" if allowed_project_ids.any?
141 else
141 else
142 if Role.anonymous.allowed_to?(permission) && !options[:member]
142 if Role.anonymous.allowed_to?(permission) && !options[:member]
143 # anonymous user allowed on public project
143 # anonymous user allowed on public project
144 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
144 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
145 end
145 end
146 end
146 end
147 end
147 end
148 statements.empty? ? base_statement : "((#{base_statement}) AND (#{statements.join(' OR ')}))"
148 statements.empty? ? base_statement : "((#{base_statement}) AND (#{statements.join(' OR ')}))"
149 end
149 end
150
150
151 # Returns the Systemwide and project specific activities
151 # Returns the Systemwide and project specific activities
152 def activities(include_inactive=false)
152 def activities(include_inactive=false)
153 if include_inactive
153 if include_inactive
154 return all_activities
154 return all_activities
155 else
155 else
156 return active_activities
156 return active_activities
157 end
157 end
158 end
158 end
159
159
160 # Will create a new Project specific Activity or update an existing one
160 # Will create a new Project specific Activity or update an existing one
161 #
161 #
162 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
162 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
163 # does not successfully save.
163 # does not successfully save.
164 def update_or_create_time_entry_activity(id, activity_hash)
164 def update_or_create_time_entry_activity(id, activity_hash)
165 if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
165 if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
166 self.create_time_entry_activity_if_needed(activity_hash)
166 self.create_time_entry_activity_if_needed(activity_hash)
167 else
167 else
168 activity = project.time_entry_activities.find_by_id(id.to_i)
168 activity = project.time_entry_activities.find_by_id(id.to_i)
169 activity.update_attributes(activity_hash) if activity
169 activity.update_attributes(activity_hash) if activity
170 end
170 end
171 end
171 end
172
172
173 # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
173 # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
174 #
174 #
175 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
175 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
176 # does not successfully save.
176 # does not successfully save.
177 def create_time_entry_activity_if_needed(activity)
177 def create_time_entry_activity_if_needed(activity)
178 if activity['parent_id']
178 if activity['parent_id']
179
179
180 parent_activity = TimeEntryActivity.find(activity['parent_id'])
180 parent_activity = TimeEntryActivity.find(activity['parent_id'])
181 activity['name'] = parent_activity.name
181 activity['name'] = parent_activity.name
182 activity['position'] = parent_activity.position
182 activity['position'] = parent_activity.position
183
183
184 if Enumeration.overridding_change?(activity, parent_activity)
184 if Enumeration.overridding_change?(activity, parent_activity)
185 project_activity = self.time_entry_activities.create(activity)
185 project_activity = self.time_entry_activities.create(activity)
186
186
187 if project_activity.new_record?
187 if project_activity.new_record?
188 raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
188 raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
189 else
189 else
190 self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
190 self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
191 end
191 end
192 end
192 end
193 end
193 end
194 end
194 end
195
195
196 # Returns a :conditions SQL string that can be used to find the issues associated with this project.
196 # Returns a :conditions SQL string that can be used to find the issues associated with this project.
197 #
197 #
198 # Examples:
198 # Examples:
199 # project.project_condition(true) => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
199 # project.project_condition(true) => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
200 # project.project_condition(false) => "projects.id = 1"
200 # project.project_condition(false) => "projects.id = 1"
201 def project_condition(with_subprojects)
201 def project_condition(with_subprojects)
202 cond = "#{Project.table_name}.id = #{id}"
202 cond = "#{Project.table_name}.id = #{id}"
203 cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
203 cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
204 cond
204 cond
205 end
205 end
206
206
207 def self.find(*args)
207 def self.find(*args)
208 if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
208 if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
209 project = find_by_identifier(*args)
209 project = find_by_identifier(*args)
210 raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
210 raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
211 project
211 project
212 else
212 else
213 super
213 super
214 end
214 end
215 end
215 end
216
216
217 def to_param
217 def to_param
218 # id is used for projects with a numeric identifier (compatibility)
218 # id is used for projects with a numeric identifier (compatibility)
219 @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier)
219 @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier)
220 end
220 end
221
221
222 def active?
222 def active?
223 self.status == STATUS_ACTIVE
223 self.status == STATUS_ACTIVE
224 end
224 end
225
225
226 # Archives the project and its descendants recursively
226 # Archives the project and its descendants recursively
227 def archive
227 def archive
228 # Archive subprojects if any
228 # Archive subprojects if any
229 children.each do |subproject|
229 children.each do |subproject|
230 subproject.archive
230 subproject.archive
231 end
231 end
232 update_attribute :status, STATUS_ARCHIVED
232 update_attribute :status, STATUS_ARCHIVED
233 end
233 end
234
234
235 # Unarchives the project
235 # Unarchives the project
236 # All its ancestors must be active
236 # All its ancestors must be active
237 def unarchive
237 def unarchive
238 return false if ancestors.detect {|a| !a.active?}
238 return false if ancestors.detect {|a| !a.active?}
239 update_attribute :status, STATUS_ACTIVE
239 update_attribute :status, STATUS_ACTIVE
240 end
240 end
241
241
242 # Returns an array of projects the project can be moved to
242 # Returns an array of projects the project can be moved to
243 # by the current user
243 # by the current user
244 def allowed_parents
244 def allowed_parents
245 return @allowed_parents if @allowed_parents
245 return @allowed_parents if @allowed_parents
246 @allowed_parents = (Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_project, :member => true)) - self_and_descendants)
246 @allowed_parents = (Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_project, :member => true)) - self_and_descendants)
247 unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
247 unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
248 @allowed_parents << parent
248 @allowed_parents << parent
249 end
249 end
250 @allowed_parents
250 @allowed_parents
251 end
251 end
252
252
253 # Sets the parent of the project with authorization check
253 # Sets the parent of the project with authorization check
254 def set_allowed_parent!(p)
254 def set_allowed_parent!(p)
255 unless p.nil? || p.is_a?(Project)
255 unless p.nil? || p.is_a?(Project)
256 if p.to_s.blank?
256 if p.to_s.blank?
257 p = nil
257 p = nil
258 else
258 else
259 p = Project.find_by_id(p)
259 p = Project.find_by_id(p)
260 return false unless p
260 return false unless p
261 end
261 end
262 end
262 end
263 if p.nil?
263 if p.nil?
264 if !new_record? && allowed_parents.empty?
264 if !new_record? && allowed_parents.empty?
265 return false
265 return false
266 end
266 end
267 elsif !allowed_parents.include?(p)
267 elsif !allowed_parents.include?(p)
268 return false
268 return false
269 end
269 end
270 set_parent!(p)
270 set_parent!(p)
271 end
271 end
272
272
273 # Sets the parent of the project
273 # Sets the parent of the project
274 # Argument can be either a Project, a String, a Fixnum or nil
274 # Argument can be either a Project, a String, a Fixnum or nil
275 def set_parent!(p)
275 def set_parent!(p)
276 unless p.nil? || p.is_a?(Project)
276 unless p.nil? || p.is_a?(Project)
277 if p.to_s.blank?
277 if p.to_s.blank?
278 p = nil
278 p = nil
279 else
279 else
280 p = Project.find_by_id(p)
280 p = Project.find_by_id(p)
281 return false unless p
281 return false unless p
282 end
282 end
283 end
283 end
284 if p == parent && !p.nil?
284 if p == parent && !p.nil?
285 # Nothing to do
285 # Nothing to do
286 true
286 true
287 elsif p.nil? || (p.active? && move_possible?(p))
287 elsif p.nil? || (p.active? && move_possible?(p))
288 # Insert the project so that target's children or root projects stay alphabetically sorted
288 # Insert the project so that target's children or root projects stay alphabetically sorted
289 sibs = (p.nil? ? self.class.roots : p.children)
289 sibs = (p.nil? ? self.class.roots : p.children)
290 to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
290 to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
291 if to_be_inserted_before
291 if to_be_inserted_before
292 move_to_left_of(to_be_inserted_before)
292 move_to_left_of(to_be_inserted_before)
293 elsif p.nil?
293 elsif p.nil?
294 if sibs.empty?
294 if sibs.empty?
295 # move_to_root adds the project in first (ie. left) position
295 # move_to_root adds the project in first (ie. left) position
296 move_to_root
296 move_to_root
297 else
297 else
298 move_to_right_of(sibs.last) unless self == sibs.last
298 move_to_right_of(sibs.last) unless self == sibs.last
299 end
299 end
300 else
300 else
301 # move_to_child_of adds the project in last (ie.right) position
301 # move_to_child_of adds the project in last (ie.right) position
302 move_to_child_of(p)
302 move_to_child_of(p)
303 end
303 end
304 true
304 true
305 else
305 else
306 # Can not move to the given target
306 # Can not move to the given target
307 false
307 false
308 end
308 end
309 end
309 end
310
310
311 # Returns an array of the trackers used by the project and its active sub projects
311 # Returns an array of the trackers used by the project and its active sub projects
312 def rolled_up_trackers
312 def rolled_up_trackers
313 @rolled_up_trackers ||=
313 @rolled_up_trackers ||=
314 Tracker.find(:all, :include => :projects,
314 Tracker.find(:all, :include => :projects,
315 :select => "DISTINCT #{Tracker.table_name}.*",
315 :select => "DISTINCT #{Tracker.table_name}.*",
316 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
316 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
317 :order => "#{Tracker.table_name}.position")
317 :order => "#{Tracker.table_name}.position")
318 end
318 end
319
319
320 # Closes open and locked project versions that are completed
320 # Closes open and locked project versions that are completed
321 def close_completed_versions
321 def close_completed_versions
322 Version.transaction do
322 Version.transaction do
323 versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version|
323 versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version|
324 if version.completed?
324 if version.completed?
325 version.update_attribute(:status, 'closed')
325 version.update_attribute(:status, 'closed')
326 end
326 end
327 end
327 end
328 end
328 end
329 end
329 end
330
330
331 # Returns a hash of project users grouped by role
331 # Returns a hash of project users grouped by role
332 def users_by_role
332 def users_by_role
333 members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
333 members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
334 m.roles.each do |r|
334 m.roles.each do |r|
335 h[r] ||= []
335 h[r] ||= []
336 h[r] << m.user
336 h[r] << m.user
337 end
337 end
338 h
338 h
339 end
339 end
340 end
340 end
341
341
342 # Deletes all project's members
342 # Deletes all project's members
343 def delete_all_members
343 def delete_all_members
344 me, mr = Member.table_name, MemberRole.table_name
344 me, mr = Member.table_name, MemberRole.table_name
345 connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
345 connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
346 Member.delete_all(['project_id = ?', id])
346 Member.delete_all(['project_id = ?', id])
347 end
347 end
348
348
349 # Users issues can be assigned to
349 # Users issues can be assigned to
350 def assignable_users
350 def assignable_users
351 members.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.user}.sort
351 members.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.user}.sort
352 end
352 end
353
353
354 # Returns the mail adresses of users that should be always notified on project events
354 # Returns the mail adresses of users that should be always notified on project events
355 def recipients
355 def recipients
356 members.select {|m| m.mail_notification? || m.user.mail_notification?}.collect {|m| m.user.mail}
356 members.select {|m| m.mail_notification? || m.user.mail_notification?}.collect {|m| m.user.mail}
357 end
357 end
358
358
359 # Returns an array of all custom fields enabled for project issues
359 # Returns an array of all custom fields enabled for project issues
360 # (explictly associated custom fields and custom fields enabled for all projects)
360 # (explictly associated custom fields and custom fields enabled for all projects)
361 def all_issue_custom_fields
361 def all_issue_custom_fields
362 @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
362 @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
363 end
363 end
364
364
365 def project
365 def project
366 self
366 self
367 end
367 end
368
368
369 def <=>(project)
369 def <=>(project)
370 name.downcase <=> project.name.downcase
370 name.downcase <=> project.name.downcase
371 end
371 end
372
372
373 def to_s
373 def to_s
374 name
374 name
375 end
375 end
376
376
377 # Returns a short description of the projects (first lines)
377 # Returns a short description of the projects (first lines)
378 def short_description(length = 255)
378 def short_description(length = 255)
379 description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
379 description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
380 end
380 end
381
381
382 # Return true if this project is allowed to do the specified action.
382 # Return true if this project is allowed to do the specified action.
383 # action can be:
383 # action can be:
384 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
384 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
385 # * a permission Symbol (eg. :edit_project)
385 # * a permission Symbol (eg. :edit_project)
386 def allows_to?(action)
386 def allows_to?(action)
387 if action.is_a? Hash
387 if action.is_a? Hash
388 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
388 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
389 else
389 else
390 allowed_permissions.include? action
390 allowed_permissions.include? action
391 end
391 end
392 end
392 end
393
393
394 def module_enabled?(module_name)
394 def module_enabled?(module_name)
395 module_name = module_name.to_s
395 module_name = module_name.to_s
396 enabled_modules.detect {|m| m.name == module_name}
396 enabled_modules.detect {|m| m.name == module_name}
397 end
397 end
398
398
399 def enabled_module_names=(module_names)
399 def enabled_module_names=(module_names)
400 if module_names && module_names.is_a?(Array)
400 if module_names && module_names.is_a?(Array)
401 module_names = module_names.collect(&:to_s)
401 module_names = module_names.collect(&:to_s)
402 # remove disabled modules
402 # remove disabled modules
403 enabled_modules.each {|mod| mod.destroy unless module_names.include?(mod.name)}
403 enabled_modules.each {|mod| mod.destroy unless module_names.include?(mod.name)}
404 # add new modules
404 # add new modules
405 module_names.reject {|name| module_enabled?(name)}.each {|name| enabled_modules << EnabledModule.new(:name => name)}
405 module_names.reject {|name| module_enabled?(name)}.each {|name| enabled_modules << EnabledModule.new(:name => name)}
406 else
406 else
407 enabled_modules.clear
407 enabled_modules.clear
408 end
408 end
409 end
409 end
410
410
411 # Returns an auto-generated project identifier based on the last identifier used
411 # Returns an auto-generated project identifier based on the last identifier used
412 def self.next_identifier
412 def self.next_identifier
413 p = Project.find(:first, :order => 'created_on DESC')
413 p = Project.find(:first, :order => 'created_on DESC')
414 p.nil? ? nil : p.identifier.to_s.succ
414 p.nil? ? nil : p.identifier.to_s.succ
415 end
415 end
416
416
417 # Copies and saves the Project instance based on the +project+.
417 # Copies and saves the Project instance based on the +project+.
418 # Duplicates the source project's:
418 # Duplicates the source project's:
419 # * Wiki
419 # * Wiki
420 # * Versions
420 # * Versions
421 # * Categories
421 # * Categories
422 # * Issues
422 # * Issues
423 # * Members
423 # * Members
424 # * Queries
424 # * Queries
425 #
425 #
426 # Accepts an +options+ argument to specify what to copy
426 # Accepts an +options+ argument to specify what to copy
427 #
427 #
428 # Examples:
428 # Examples:
429 # project.copy(1) # => copies everything
429 # project.copy(1) # => copies everything
430 # project.copy(1, :only => 'members') # => copies members only
430 # project.copy(1, :only => 'members') # => copies members only
431 # project.copy(1, :only => ['members', 'versions']) # => copies members and versions
431 # project.copy(1, :only => ['members', 'versions']) # => copies members and versions
432 def copy(project, options={})
432 def copy(project, options={})
433 project = project.is_a?(Project) ? project : Project.find(project)
433 project = project.is_a?(Project) ? project : Project.find(project)
434
434
435 to_be_copied = %w(wiki versions issue_categories issues members queries boards)
435 to_be_copied = %w(wiki versions issue_categories issues members queries boards)
436 to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
436 to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
437
437
438 Project.transaction do
438 Project.transaction do
439 if save
439 if save
440 reload
440 reload
441 to_be_copied.each do |name|
441 to_be_copied.each do |name|
442 send "copy_#{name}", project
442 send "copy_#{name}", project
443 end
443 end
444 Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
444 Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
445 save
445 save
446 end
446 end
447 end
447 end
448 end
448 end
449
449
450
450
451 # Copies +project+ and returns the new instance. This will not save
451 # Copies +project+ and returns the new instance. This will not save
452 # the copy
452 # the copy
453 def self.copy_from(project)
453 def self.copy_from(project)
454 begin
454 begin
455 project = project.is_a?(Project) ? project : Project.find(project)
455 project = project.is_a?(Project) ? project : Project.find(project)
456 if project
456 if project
457 # clear unique attributes
457 # clear unique attributes
458 attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
458 attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
459 copy = Project.new(attributes)
459 copy = Project.new(attributes)
460 copy.enabled_modules = project.enabled_modules
460 copy.enabled_modules = project.enabled_modules
461 copy.trackers = project.trackers
461 copy.trackers = project.trackers
462 copy.custom_values = project.custom_values.collect {|v| v.clone}
462 copy.custom_values = project.custom_values.collect {|v| v.clone}
463 copy.issue_custom_fields = project.issue_custom_fields
463 copy.issue_custom_fields = project.issue_custom_fields
464 return copy
464 return copy
465 else
465 else
466 return nil
466 return nil
467 end
467 end
468 rescue ActiveRecord::RecordNotFound
468 rescue ActiveRecord::RecordNotFound
469 return nil
469 return nil
470 end
470 end
471 end
471 end
472
472
473 private
473 private
474
474
475 # Copies wiki from +project+
475 # Copies wiki from +project+
476 def copy_wiki(project)
476 def copy_wiki(project)
477 # Check that the source project has a wiki first
477 # Check that the source project has a wiki first
478 unless project.wiki.nil?
478 unless project.wiki.nil?
479 self.wiki ||= Wiki.new
479 self.wiki ||= Wiki.new
480 wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
480 wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
481 project.wiki.pages.each do |page|
481 project.wiki.pages.each do |page|
482 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
482 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
483 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
483 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
484 new_wiki_page.content = new_wiki_content
484 new_wiki_page.content = new_wiki_content
485 wiki.pages << new_wiki_page
485 wiki.pages << new_wiki_page
486 end
486 end
487 end
487 end
488 end
488 end
489
489
490 # Copies versions from +project+
490 # Copies versions from +project+
491 def copy_versions(project)
491 def copy_versions(project)
492 project.versions.each do |version|
492 project.versions.each do |version|
493 new_version = Version.new
493 new_version = Version.new
494 new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
494 new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
495 self.versions << new_version
495 self.versions << new_version
496 end
496 end
497 end
497 end
498
498
499 # Copies issue categories from +project+
499 # Copies issue categories from +project+
500 def copy_issue_categories(project)
500 def copy_issue_categories(project)
501 project.issue_categories.each do |issue_category|
501 project.issue_categories.each do |issue_category|
502 new_issue_category = IssueCategory.new
502 new_issue_category = IssueCategory.new
503 new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
503 new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
504 self.issue_categories << new_issue_category
504 self.issue_categories << new_issue_category
505 end
505 end
506 end
506 end
507
507
508 # Copies issues from +project+
508 # Copies issues from +project+
509 def copy_issues(project)
509 def copy_issues(project)
510 project.issues.each do |issue|
510 project.issues.each do |issue|
511 new_issue = Issue.new
511 new_issue = Issue.new
512 new_issue.copy_from(issue)
512 new_issue.copy_from(issue)
513 # Reassign fixed_versions by name, since names are unique per
513 # Reassign fixed_versions by name, since names are unique per
514 # project and the versions for self are not yet saved
514 # project and the versions for self are not yet saved
515 if issue.fixed_version
515 if issue.fixed_version
516 new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
516 new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
517 end
517 end
518 # Reassign the category by name, since names are unique per
518 # Reassign the category by name, since names are unique per
519 # project and the categories for self are not yet saved
519 # project and the categories for self are not yet saved
520 if issue.category
520 if issue.category
521 new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
521 new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
522 end
522 end
523 self.issues << new_issue
523 self.issues << new_issue
524 end
524 end
525 end
525 end
526
526
527 # Copies members from +project+
527 # Copies members from +project+
528 def copy_members(project)
528 def copy_members(project)
529 project.members.each do |member|
529 project.members.each do |member|
530 new_member = Member.new
530 new_member = Member.new
531 new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
531 new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
532 new_member.role_ids = member.role_ids.dup
532 new_member.role_ids = member.role_ids.dup
533 new_member.project = self
533 new_member.project = self
534 self.members << new_member
534 self.members << new_member
535 end
535 end
536 end
536 end
537
537
538 # Copies queries from +project+
538 # Copies queries from +project+
539 def copy_queries(project)
539 def copy_queries(project)
540 project.queries.each do |query|
540 project.queries.each do |query|
541 new_query = Query.new
541 new_query = Query.new
542 new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
542 new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
543 new_query.sort_criteria = query.sort_criteria if query.sort_criteria
543 new_query.sort_criteria = query.sort_criteria if query.sort_criteria
544 new_query.project = self
544 new_query.project = self
545 self.queries << new_query
545 self.queries << new_query
546 end
546 end
547 end
547 end
548
548
549 # Copies boards from +project+
549 # Copies boards from +project+
550 def copy_boards(project)
550 def copy_boards(project)
551 project.boards.each do |board|
551 project.boards.each do |board|
552 new_board = Board.new
552 new_board = Board.new
553 new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
553 new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
554 new_board.project = self
554 new_board.project = self
555 self.boards << new_board
555 self.boards << new_board
556 end
556 end
557 end
557 end
558
558
559 def allowed_permissions
559 def allowed_permissions
560 @allowed_permissions ||= begin
560 @allowed_permissions ||= begin
561 module_names = enabled_modules.collect {|m| m.name}
561 module_names = enabled_modules.collect {|m| m.name}
562 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
562 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
563 end
563 end
564 end
564 end
565
565
566 def allowed_actions
566 def allowed_actions
567 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
567 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
568 end
568 end
569
569
570 # Returns all the active Systemwide and project specific activities
570 # Returns all the active Systemwide and project specific activities
571 def active_activities
571 def active_activities
572 overridden_activity_ids = self.time_entry_activities.active.collect(&:parent_id)
572 overridden_activity_ids = self.time_entry_activities.active.collect(&:parent_id)
573
573
574 if overridden_activity_ids.empty?
574 if overridden_activity_ids.empty?
575 return TimeEntryActivity.active
575 return TimeEntryActivity.active
576 else
576 else
577 return system_activities_and_project_overrides
577 return system_activities_and_project_overrides
578 end
578 end
579 end
579 end
580
580
581 # Returns all the Systemwide and project specific activities
581 # Returns all the Systemwide and project specific activities
582 # (inactive and active)
582 # (inactive and active)
583 def all_activities
583 def all_activities
584 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
584 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
585
585
586 if overridden_activity_ids.empty?
586 if overridden_activity_ids.empty?
587 return TimeEntryActivity.all
587 return TimeEntryActivity.all
588 else
588 else
589 return system_activities_and_project_overrides(true)
589 return system_activities_and_project_overrides(true)
590 end
590 end
591 end
591 end
592
592
593 # Returns the systemwide active activities merged with the project specific overrides
593 # Returns the systemwide active activities merged with the project specific overrides
594 def system_activities_and_project_overrides(include_inactive=false)
594 def system_activities_and_project_overrides(include_inactive=false)
595 if include_inactive
595 if include_inactive
596 return TimeEntryActivity.all.
596 return TimeEntryActivity.all.
597 find(:all,
597 find(:all,
598 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
598 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
599 self.time_entry_activities
599 self.time_entry_activities
600 else
600 else
601 return TimeEntryActivity.active.
601 return TimeEntryActivity.active.
602 find(:all,
602 find(:all,
603 :conditions => ["id NOT IN (?)", self.time_entry_activities.active.collect(&:parent_id)]) +
603 :conditions => ["id NOT IN (?)", self.time_entry_activities.active.collect(&:parent_id)]) +
604 self.time_entry_activities.active
604 self.time_entry_activities.active
605 end
605 end
606 end
606 end
607 end
607 end
General Comments 0
You need to be logged in to leave comments. Login now