##// END OF EJS Templates
Speedup remove_inherited_roles (#22850)....
Jean-Philippe Lang -
r15501:ddf249d7b055
parent child
Show More
@@ -0,0 +1,5
1 class AddIndexOnMemberRolesInheritedFrom < ActiveRecord::Migration
2 def change
3 add_index :member_roles, :inherited_from
4 end
5 end
@@ -1,80 +1,77
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class MemberRole < ActiveRecord::Base
19 19 belongs_to :member
20 20 belongs_to :role
21 21
22 22 after_destroy :remove_member_if_empty
23 23
24 24 after_create :add_role_to_group_users, :add_role_to_subprojects
25 25 after_destroy :remove_inherited_roles
26 26
27 27 validates_presence_of :role
28 28 validate :validate_role_member
29 29 attr_protected :id
30 30
31 31 def validate_role_member
32 32 errors.add :role_id, :invalid if role && !role.member?
33 33 end
34 34
35 35 def inherited?
36 36 !inherited_from.nil?
37 37 end
38 38
39 39 # Destroys the MemberRole without destroying its Member if it doesn't have
40 40 # any other roles
41 41 def destroy_without_member_removal
42 42 @member_removal = false
43 43 destroy
44 44 end
45 45
46 46 private
47 47
48 48 def remove_member_if_empty
49 49 if @member_removal != false && member.roles.empty?
50 50 member.destroy
51 51 end
52 52 end
53 53
54 54 def add_role_to_group_users
55 55 if member.principal.is_a?(Group) && !inherited?
56 56 member.principal.users.each do |user|
57 57 user_member = Member.find_or_new(member.project_id, user.id)
58 58 user_member.member_roles << MemberRole.new(:role => role, :inherited_from => id)
59 59 user_member.save!
60 60 end
61 61 end
62 62 end
63 63
64 64 def add_role_to_subprojects
65 65 member.project.children.each do |subproject|
66 66 if subproject.inherit_members?
67 67 child_member = Member.find_or_new(subproject.id, member.user_id)
68 68 child_member.member_roles << MemberRole.new(:role => role, :inherited_from => id)
69 69 child_member.save!
70 70 end
71 71 end
72 72 end
73 73
74 74 def remove_inherited_roles
75 MemberRole.where(:inherited_from => id).group_by(&:member).
76 each do |member, member_roles|
77 member_roles.each(&:destroy)
78 end
75 MemberRole.where(:inherited_from => id).destroy_all
79 76 end
80 77 end
@@ -1,1087 +1,1087
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class Project < ActiveRecord::Base
19 19 include Redmine::SafeAttributes
20 20 include Redmine::NestedSet::ProjectNestedSet
21 21
22 22 # Project statuses
23 23 STATUS_ACTIVE = 1
24 24 STATUS_CLOSED = 5
25 25 STATUS_ARCHIVED = 9
26 26
27 27 # Maximum length for project identifiers
28 28 IDENTIFIER_MAX_LENGTH = 100
29 29
30 30 # Specific overridden Activities
31 31 has_many :time_entry_activities
32 32 has_many :memberships, :class_name => 'Member', :inverse_of => :project
33 33 # Memberships of active users only
34 34 has_many :members,
35 35 lambda { joins(:principal).where(:users => {:type => 'User', :status => Principal::STATUS_ACTIVE}) }
36 36 has_many :enabled_modules, :dependent => :delete_all
37 37 has_and_belongs_to_many :trackers, lambda {order(:position)}
38 38 has_many :issues, :dependent => :destroy
39 39 has_many :issue_changes, :through => :issues, :source => :journals
40 40 has_many :versions, lambda {order("#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC")}, :dependent => :destroy
41 41 belongs_to :default_version, :class_name => 'Version'
42 42 has_many :time_entries, :dependent => :destroy
43 43 has_many :queries, :class_name => 'IssueQuery', :dependent => :delete_all
44 44 has_many :documents, :dependent => :destroy
45 45 has_many :news, lambda {includes(:author)}, :dependent => :destroy
46 46 has_many :issue_categories, lambda {order("#{IssueCategory.table_name}.name")}, :dependent => :delete_all
47 47 has_many :boards, lambda {order("position ASC")}, :dependent => :destroy
48 48 has_one :repository, lambda {where(["is_default = ?", true])}
49 49 has_many :repositories, :dependent => :destroy
50 50 has_many :changesets, :through => :repository
51 51 has_one :wiki, :dependent => :destroy
52 52 # Custom field for the project issues
53 53 has_and_belongs_to_many :issue_custom_fields,
54 54 lambda {order("#{CustomField.table_name}.position")},
55 55 :class_name => 'IssueCustomField',
56 56 :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
57 57 :association_foreign_key => 'custom_field_id'
58 58
59 59 acts_as_attachable :view_permission => :view_files,
60 60 :edit_permission => :manage_files,
61 61 :delete_permission => :manage_files
62 62
63 63 acts_as_customizable
64 64 acts_as_searchable :columns => ['name', 'identifier', 'description'], :project_key => "#{Project.table_name}.id", :permission => nil
65 65 acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
66 66 :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o}},
67 67 :author => nil
68 68
69 69 attr_protected :status
70 70
71 71 validates_presence_of :name, :identifier
72 72 validates_uniqueness_of :identifier, :if => Proc.new {|p| p.identifier_changed?}
73 73 validates_length_of :name, :maximum => 255
74 74 validates_length_of :homepage, :maximum => 255
75 75 validates_length_of :identifier, :in => 1..IDENTIFIER_MAX_LENGTH
76 76 # downcase letters, digits, dashes but not digits only
77 77 validates_format_of :identifier, :with => /\A(?!\d+$)[a-z0-9\-_]*\z/, :if => Proc.new { |p| p.identifier_changed? }
78 78 # reserved words
79 79 validates_exclusion_of :identifier, :in => %w( new )
80 80 validate :validate_parent
81 81
82 82 after_save :update_inherited_members, :if => Proc.new {|project| project.inherit_members_changed?}
83 83 after_save :remove_inherited_member_roles, :add_inherited_member_roles, :if => Proc.new {|project| project.parent_id_changed?}
84 84 after_update :update_versions_from_hierarchy_change, :if => Proc.new {|project| project.parent_id_changed?}
85 85 before_destroy :delete_all_members
86 86
87 87 scope :has_module, lambda {|mod|
88 88 where("#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s)
89 89 }
90 90 scope :active, lambda { where(:status => STATUS_ACTIVE) }
91 91 scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) }
92 92 scope :all_public, lambda { where(:is_public => true) }
93 93 scope :visible, lambda {|*args| where(Project.visible_condition(args.shift || User.current, *args)) }
94 94 scope :allowed_to, lambda {|*args|
95 95 user = User.current
96 96 permission = nil
97 97 if args.first.is_a?(Symbol)
98 98 permission = args.shift
99 99 else
100 100 user = args.shift
101 101 permission = args.shift
102 102 end
103 103 where(Project.allowed_to_condition(user, permission, *args))
104 104 }
105 105 scope :like, lambda {|arg|
106 106 if arg.blank?
107 107 where(nil)
108 108 else
109 109 pattern = "%#{arg.to_s.strip.downcase}%"
110 110 where("LOWER(identifier) LIKE :p OR LOWER(name) LIKE :p", :p => pattern)
111 111 end
112 112 }
113 113 scope :sorted, lambda {order(:lft)}
114 114 scope :having_trackers, lambda {
115 115 where("#{Project.table_name}.id IN (SELECT DISTINCT project_id FROM #{table_name_prefix}projects_trackers#{table_name_suffix})")
116 116 }
117 117
118 118 def initialize(attributes=nil, *args)
119 119 super
120 120
121 121 initialized = (attributes || {}).stringify_keys
122 122 if !initialized.key?('identifier') && Setting.sequential_project_identifiers?
123 123 self.identifier = Project.next_identifier
124 124 end
125 125 if !initialized.key?('is_public')
126 126 self.is_public = Setting.default_projects_public?
127 127 end
128 128 if !initialized.key?('enabled_module_names')
129 129 self.enabled_module_names = Setting.default_projects_modules
130 130 end
131 131 if !initialized.key?('trackers') && !initialized.key?('tracker_ids')
132 132 default = Setting.default_projects_tracker_ids
133 133 if default.is_a?(Array)
134 134 self.trackers = Tracker.where(:id => default.map(&:to_i)).sorted.to_a
135 135 else
136 136 self.trackers = Tracker.sorted.to_a
137 137 end
138 138 end
139 139 end
140 140
141 141 def identifier=(identifier)
142 142 super unless identifier_frozen?
143 143 end
144 144
145 145 def identifier_frozen?
146 146 errors[:identifier].blank? && !(new_record? || identifier.blank?)
147 147 end
148 148
149 149 # returns latest created projects
150 150 # non public projects will be returned only if user is a member of those
151 151 def self.latest(user=nil, count=5)
152 152 visible(user).limit(count).
153 153 order(:created_on => :desc).
154 154 where("#{table_name}.created_on >= ?", 30.days.ago).
155 155 to_a
156 156 end
157 157
158 158 # Returns true if the project is visible to +user+ or to the current user.
159 159 def visible?(user=User.current)
160 160 user.allowed_to?(:view_project, self)
161 161 end
162 162
163 163 # Returns a SQL conditions string used to find all projects visible by the specified user.
164 164 #
165 165 # Examples:
166 166 # Project.visible_condition(admin) => "projects.status = 1"
167 167 # Project.visible_condition(normal_user) => "((projects.status = 1) AND (projects.is_public = 1 OR projects.id IN (1,3,4)))"
168 168 # Project.visible_condition(anonymous) => "((projects.status = 1) AND (projects.is_public = 1))"
169 169 def self.visible_condition(user, options={})
170 170 allowed_to_condition(user, :view_project, options)
171 171 end
172 172
173 173 # Returns a SQL conditions string used to find all projects for which +user+ has the given +permission+
174 174 #
175 175 # Valid options:
176 176 # * :project => limit the condition to project
177 177 # * :with_subprojects => limit the condition to project and its subprojects
178 178 # * :member => limit the condition to the user projects
179 179 def self.allowed_to_condition(user, permission, options={})
180 180 perm = Redmine::AccessControl.permission(permission)
181 181 base_statement = (perm && perm.read? ? "#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED}" : "#{Project.table_name}.status = #{Project::STATUS_ACTIVE}")
182 182 if perm && perm.project_module
183 183 # If the permission belongs to a project module, make sure the module is enabled
184 184 base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
185 185 end
186 186 if project = options[:project]
187 187 project_statement = project.project_condition(options[:with_subprojects])
188 188 base_statement = "(#{project_statement}) AND (#{base_statement})"
189 189 end
190 190
191 191 if user.admin?
192 192 base_statement
193 193 else
194 194 statement_by_role = {}
195 195 unless options[:member]
196 196 role = user.builtin_role
197 197 if role.allowed_to?(permission)
198 198 s = "#{Project.table_name}.is_public = #{connection.quoted_true}"
199 199 if user.id
200 200 group = role.anonymous? ? Group.anonymous : Group.non_member
201 201 principal_ids = [user.id, group.id].compact
202 202 s = "(#{s} AND #{Project.table_name}.id NOT IN (SELECT project_id FROM #{Member.table_name} WHERE user_id IN (#{principal_ids.join(',')})))"
203 203 end
204 204 statement_by_role[role] = s
205 205 end
206 206 end
207 207 user.projects_by_role.each do |role, projects|
208 208 if role.allowed_to?(permission) && projects.any?
209 209 statement_by_role[role] = "#{Project.table_name}.id IN (#{projects.collect(&:id).join(',')})"
210 210 end
211 211 end
212 212 if statement_by_role.empty?
213 213 "1=0"
214 214 else
215 215 if block_given?
216 216 statement_by_role.each do |role, statement|
217 217 if s = yield(role, user)
218 218 statement_by_role[role] = "(#{statement} AND (#{s}))"
219 219 end
220 220 end
221 221 end
222 222 "((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))"
223 223 end
224 224 end
225 225 end
226 226
227 227 def override_roles(role)
228 228 @override_members ||= memberships.
229 229 joins(:principal).
230 230 where(:users => {:type => ['GroupAnonymous', 'GroupNonMember']}).to_a
231 231
232 232 group_class = role.anonymous? ? GroupAnonymous : GroupNonMember
233 233 member = @override_members.detect {|m| m.principal.is_a? group_class}
234 234 member ? member.roles.to_a : [role]
235 235 end
236 236
237 237 def principals
238 238 @principals ||= Principal.active.joins(:members).where("#{Member.table_name}.project_id = ?", id).distinct
239 239 end
240 240
241 241 def users
242 242 @users ||= User.active.joins(:members).where("#{Member.table_name}.project_id = ?", id).distinct
243 243 end
244 244
245 245 # Returns the Systemwide and project specific activities
246 246 def activities(include_inactive=false)
247 247 t = TimeEntryActivity.table_name
248 248 scope = TimeEntryActivity.where("#{t}.project_id IS NULL OR #{t}.project_id = ?", id)
249 249
250 250 overridden_activity_ids = self.time_entry_activities.pluck(:parent_id).compact
251 251 if overridden_activity_ids.any?
252 252 scope = scope.where("#{t}.id NOT IN (?)", overridden_activity_ids)
253 253 end
254 254 unless include_inactive
255 255 scope = scope.active
256 256 end
257 257 scope
258 258 end
259 259
260 260 # Will create a new Project specific Activity or update an existing one
261 261 #
262 262 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
263 263 # does not successfully save.
264 264 def update_or_create_time_entry_activity(id, activity_hash)
265 265 if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
266 266 self.create_time_entry_activity_if_needed(activity_hash)
267 267 else
268 268 activity = project.time_entry_activities.find_by_id(id.to_i)
269 269 activity.update_attributes(activity_hash) if activity
270 270 end
271 271 end
272 272
273 273 # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
274 274 #
275 275 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
276 276 # does not successfully save.
277 277 def create_time_entry_activity_if_needed(activity)
278 278 if activity['parent_id']
279 279 parent_activity = TimeEntryActivity.find(activity['parent_id'])
280 280 activity['name'] = parent_activity.name
281 281 activity['position'] = parent_activity.position
282 282 if Enumeration.overriding_change?(activity, parent_activity)
283 283 project_activity = self.time_entry_activities.create(activity)
284 284 if project_activity.new_record?
285 285 raise ActiveRecord::Rollback, "Overriding TimeEntryActivity was not successfully saved"
286 286 else
287 287 self.time_entries.
288 288 where(:activity_id => parent_activity.id).
289 289 update_all(:activity_id => project_activity.id)
290 290 end
291 291 end
292 292 end
293 293 end
294 294
295 295 # Returns a :conditions SQL string that can be used to find the issues associated with this project.
296 296 #
297 297 # Examples:
298 298 # project.project_condition(true) => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
299 299 # project.project_condition(false) => "projects.id = 1"
300 300 def project_condition(with_subprojects)
301 301 cond = "#{Project.table_name}.id = #{id}"
302 302 cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
303 303 cond
304 304 end
305 305
306 306 def self.find(*args)
307 307 if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
308 308 project = find_by_identifier(*args)
309 309 raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
310 310 project
311 311 else
312 312 super
313 313 end
314 314 end
315 315
316 316 def self.find_by_param(*args)
317 317 self.find(*args)
318 318 end
319 319
320 320 alias :base_reload :reload
321 321 def reload(*args)
322 322 @principals = nil
323 323 @users = nil
324 324 @shared_versions = nil
325 325 @rolled_up_versions = nil
326 326 @rolled_up_trackers = nil
327 327 @all_issue_custom_fields = nil
328 328 @all_time_entry_custom_fields = nil
329 329 @to_param = nil
330 330 @allowed_parents = nil
331 331 @allowed_permissions = nil
332 332 @actions_allowed = nil
333 333 @start_date = nil
334 334 @due_date = nil
335 335 @override_members = nil
336 336 @assignable_users = nil
337 337 base_reload(*args)
338 338 end
339 339
340 340 def to_param
341 341 if new_record?
342 342 nil
343 343 else
344 344 # id is used for projects with a numeric identifier (compatibility)
345 345 @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id.to_s : identifier)
346 346 end
347 347 end
348 348
349 349 def active?
350 350 self.status == STATUS_ACTIVE
351 351 end
352 352
353 353 def archived?
354 354 self.status == STATUS_ARCHIVED
355 355 end
356 356
357 357 # Archives the project and its descendants
358 358 def archive
359 359 # Check that there is no issue of a non descendant project that is assigned
360 360 # to one of the project or descendant versions
361 361 version_ids = self_and_descendants.joins(:versions).pluck("#{Version.table_name}.id")
362 362
363 363 if version_ids.any? &&
364 364 Issue.
365 365 includes(:project).
366 366 where("#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?", lft, rgt).
367 367 where(:fixed_version_id => version_ids).
368 368 exists?
369 369 return false
370 370 end
371 371 Project.transaction do
372 372 archive!
373 373 end
374 374 true
375 375 end
376 376
377 377 # Unarchives the project
378 378 # All its ancestors must be active
379 379 def unarchive
380 380 return false if ancestors.detect {|a| !a.active?}
381 381 update_attribute :status, STATUS_ACTIVE
382 382 end
383 383
384 384 def close
385 385 self_and_descendants.status(STATUS_ACTIVE).update_all :status => STATUS_CLOSED
386 386 end
387 387
388 388 def reopen
389 389 self_and_descendants.status(STATUS_CLOSED).update_all :status => STATUS_ACTIVE
390 390 end
391 391
392 392 # Returns an array of projects the project can be moved to
393 393 # by the current user
394 394 def allowed_parents(user=User.current)
395 395 return @allowed_parents if @allowed_parents
396 396 @allowed_parents = Project.allowed_to(user, :add_subprojects).to_a
397 397 @allowed_parents = @allowed_parents - self_and_descendants
398 398 if user.allowed_to?(:add_project, nil, :global => true) || (!new_record? && parent.nil?)
399 399 @allowed_parents << nil
400 400 end
401 401 unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
402 402 @allowed_parents << parent
403 403 end
404 404 @allowed_parents
405 405 end
406 406
407 407 # Sets the parent of the project with authorization check
408 408 def set_allowed_parent!(p)
409 409 ActiveSupport::Deprecation.warn "Project#set_allowed_parent! is deprecated and will be removed in Redmine 4, use #safe_attributes= instead."
410 410 p = p.id if p.is_a?(Project)
411 411 send :safe_attributes, {:project_id => p}
412 412 save
413 413 end
414 414
415 415 # Sets the parent of the project and saves the project
416 416 # Argument can be either a Project, a String, a Fixnum or nil
417 417 def set_parent!(p)
418 418 if p.is_a?(Project)
419 419 self.parent = p
420 420 else
421 421 self.parent_id = p
422 422 end
423 423 save
424 424 end
425 425
426 426 # Returns a scope of the trackers used by the project and its active sub projects
427 427 def rolled_up_trackers(include_subprojects=true)
428 428 if include_subprojects
429 429 @rolled_up_trackers ||= rolled_up_trackers_base_scope.
430 430 where("#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ?", lft, rgt)
431 431 else
432 432 rolled_up_trackers_base_scope.
433 433 where(:projects => {:id => id})
434 434 end
435 435 end
436 436
437 437 def rolled_up_trackers_base_scope
438 438 Tracker.
439 439 joins(projects: :enabled_modules).
440 440 where("#{Project.table_name}.status <> ?", STATUS_ARCHIVED).
441 441 where(:enabled_modules => {:name => 'issue_tracking'}).
442 442 distinct.
443 443 sorted
444 444 end
445 445
446 446 # Closes open and locked project versions that are completed
447 447 def close_completed_versions
448 448 Version.transaction do
449 449 versions.where(:status => %w(open locked)).each do |version|
450 450 if version.completed?
451 451 version.update_attribute(:status, 'closed')
452 452 end
453 453 end
454 454 end
455 455 end
456 456
457 457 # Returns a scope of the Versions on subprojects
458 458 def rolled_up_versions
459 459 @rolled_up_versions ||=
460 460 Version.
461 461 joins(:project).
462 462 where("#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> ?", lft, rgt, STATUS_ARCHIVED)
463 463 end
464 464
465 465 # Returns a scope of the Versions used by the project
466 466 def shared_versions
467 467 if new_record?
468 468 Version.
469 469 joins(:project).
470 470 preload(:project).
471 471 where("#{Project.table_name}.status <> ? AND #{Version.table_name}.sharing = 'system'", STATUS_ARCHIVED)
472 472 else
473 473 @shared_versions ||= begin
474 474 r = root? ? self : root
475 475 Version.
476 476 joins(:project).
477 477 preload(:project).
478 478 where("#{Project.table_name}.id = #{id}" +
479 479 " OR (#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED} AND (" +
480 480 " #{Version.table_name}.sharing = 'system'" +
481 481 " OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" +
482 482 " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
483 483 " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
484 484 "))")
485 485 end
486 486 end
487 487 end
488 488
489 489 # Returns a hash of project users grouped by role
490 490 def users_by_role
491 491 members.includes(:user, :roles).inject({}) do |h, m|
492 492 m.roles.each do |r|
493 493 h[r] ||= []
494 494 h[r] << m.user
495 495 end
496 496 h
497 497 end
498 498 end
499 499
500 500 # Adds user as a project member with the default role
501 501 # Used for when a non-admin user creates a project
502 502 def add_default_member(user)
503 503 role = self.class.default_member_role
504 504 member = Member.new(:project => self, :principal => user, :roles => [role])
505 505 self.members << member
506 506 member
507 507 end
508 508
509 509 # Default role that is given to non-admin users that
510 510 # create a project
511 511 def self.default_member_role
512 512 Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first
513 513 end
514 514
515 515 # Deletes all project's members
516 516 def delete_all_members
517 517 me, mr = Member.table_name, MemberRole.table_name
518 518 self.class.connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
519 519 Member.where(:project_id => id).delete_all
520 520 end
521 521
522 522 # Return a Principal scope of users/groups issues can be assigned to
523 523 def assignable_users(tracker=nil)
524 524 return @assignable_users[tracker] if @assignable_users && @assignable_users[tracker]
525 525
526 526 types = ['User']
527 527 types << 'Group' if Setting.issue_group_assignment?
528 528
529 529 scope = Principal.
530 530 active.
531 531 joins(:members => :roles).
532 532 where(:type => types, :members => {:project_id => id}, :roles => {:assignable => true}).
533 533 distinct.
534 534 sorted
535 535
536 536 if tracker
537 537 # Rejects users that cannot the view the tracker
538 538 roles = Role.where(:assignable => true).select {|role| role.permissions_tracker?(:view_issues, tracker)}
539 539 scope = scope.where(:roles => {:id => roles.map(&:id)})
540 540 end
541 541
542 542 @assignable_users ||= {}
543 543 @assignable_users[tracker] = scope
544 544 end
545 545
546 546 # Returns the mail addresses of users that should be always notified on project events
547 547 def recipients
548 548 notified_users.collect {|user| user.mail}
549 549 end
550 550
551 551 # Returns the users that should be notified on project events
552 552 def notified_users
553 553 # TODO: User part should be extracted to User#notify_about?
554 554 members.preload(:principal).select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}.collect {|m| m.principal}
555 555 end
556 556
557 557 # Returns a scope of all custom fields enabled for project issues
558 558 # (explicitly associated custom fields and custom fields enabled for all projects)
559 559 def all_issue_custom_fields
560 560 if new_record?
561 561 @all_issue_custom_fields ||= IssueCustomField.
562 562 sorted.
563 563 where("is_for_all = ? OR id IN (?)", true, issue_custom_field_ids)
564 564 else
565 565 @all_issue_custom_fields ||= IssueCustomField.
566 566 sorted.
567 567 where("is_for_all = ? OR id IN (SELECT DISTINCT cfp.custom_field_id" +
568 568 " FROM #{table_name_prefix}custom_fields_projects#{table_name_suffix} cfp" +
569 569 " WHERE cfp.project_id = ?)", true, id)
570 570 end
571 571 end
572 572
573 573 def project
574 574 self
575 575 end
576 576
577 577 def <=>(project)
578 578 name.casecmp(project.name)
579 579 end
580 580
581 581 def to_s
582 582 name
583 583 end
584 584
585 585 # Returns a short description of the projects (first lines)
586 586 def short_description(length = 255)
587 587 description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
588 588 end
589 589
590 590 def css_classes
591 591 s = 'project'
592 592 s << ' root' if root?
593 593 s << ' child' if child?
594 594 s << (leaf? ? ' leaf' : ' parent')
595 595 unless active?
596 596 if archived?
597 597 s << ' archived'
598 598 else
599 599 s << ' closed'
600 600 end
601 601 end
602 602 s
603 603 end
604 604
605 605 # The earliest start date of a project, based on it's issues and versions
606 606 def start_date
607 607 @start_date ||= [
608 608 issues.minimum('start_date'),
609 609 shared_versions.minimum('effective_date'),
610 610 Issue.fixed_version(shared_versions).minimum('start_date')
611 611 ].compact.min
612 612 end
613 613
614 614 # The latest due date of an issue or version
615 615 def due_date
616 616 @due_date ||= [
617 617 issues.maximum('due_date'),
618 618 shared_versions.maximum('effective_date'),
619 619 Issue.fixed_version(shared_versions).maximum('due_date')
620 620 ].compact.max
621 621 end
622 622
623 623 def overdue?
624 624 active? && !due_date.nil? && (due_date < User.current.today)
625 625 end
626 626
627 627 # Returns the percent completed for this project, based on the
628 628 # progress on it's versions.
629 629 def completed_percent(options={:include_subprojects => false})
630 630 if options.delete(:include_subprojects)
631 631 total = self_and_descendants.collect(&:completed_percent).sum
632 632
633 633 total / self_and_descendants.count
634 634 else
635 635 if versions.count > 0
636 636 total = versions.collect(&:completed_percent).sum
637 637
638 638 total / versions.count
639 639 else
640 640 100
641 641 end
642 642 end
643 643 end
644 644
645 645 # Return true if this project allows to do the specified action.
646 646 # action can be:
647 647 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
648 648 # * a permission Symbol (eg. :edit_project)
649 649 def allows_to?(action)
650 650 if archived?
651 651 # No action allowed on archived projects
652 652 return false
653 653 end
654 654 unless active? || Redmine::AccessControl.read_action?(action)
655 655 # No write action allowed on closed projects
656 656 return false
657 657 end
658 658 # No action allowed on disabled modules
659 659 if action.is_a? Hash
660 660 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
661 661 else
662 662 allowed_permissions.include? action
663 663 end
664 664 end
665 665
666 666 # Return the enabled module with the given name
667 667 # or nil if the module is not enabled for the project
668 668 def enabled_module(name)
669 669 name = name.to_s
670 670 enabled_modules.detect {|m| m.name == name}
671 671 end
672 672
673 673 # Return true if the module with the given name is enabled
674 674 def module_enabled?(name)
675 675 enabled_module(name).present?
676 676 end
677 677
678 678 def enabled_module_names=(module_names)
679 679 if module_names && module_names.is_a?(Array)
680 680 module_names = module_names.collect(&:to_s).reject(&:blank?)
681 681 self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)}
682 682 else
683 683 enabled_modules.clear
684 684 end
685 685 end
686 686
687 687 # Returns an array of the enabled modules names
688 688 def enabled_module_names
689 689 enabled_modules.collect(&:name)
690 690 end
691 691
692 692 # Enable a specific module
693 693 #
694 694 # Examples:
695 695 # project.enable_module!(:issue_tracking)
696 696 # project.enable_module!("issue_tracking")
697 697 def enable_module!(name)
698 698 enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name)
699 699 end
700 700
701 701 # Disable a module if it exists
702 702 #
703 703 # Examples:
704 704 # project.disable_module!(:issue_tracking)
705 705 # project.disable_module!("issue_tracking")
706 706 # project.disable_module!(project.enabled_modules.first)
707 707 def disable_module!(target)
708 708 target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target)
709 709 target.destroy unless target.blank?
710 710 end
711 711
712 712 safe_attributes 'name',
713 713 'description',
714 714 'homepage',
715 715 'is_public',
716 716 'identifier',
717 717 'custom_field_values',
718 718 'custom_fields',
719 719 'tracker_ids',
720 720 'issue_custom_field_ids',
721 721 'parent_id',
722 722 'default_version_id'
723 723
724 724 safe_attributes 'enabled_module_names',
725 725 :if => lambda {|project, user|
726 726 if project.new_record?
727 727 if user.admin?
728 728 true
729 729 else
730 730 default_member_role.has_permission?(:select_project_modules)
731 731 end
732 732 else
733 733 user.allowed_to?(:select_project_modules, project)
734 734 end
735 735 }
736 736
737 737 safe_attributes 'inherit_members',
738 738 :if => lambda {|project, user| project.parent.nil? || project.parent.visible?(user)}
739 739
740 740 def safe_attributes=(attrs, user=User.current)
741 741 return unless attrs.is_a?(Hash)
742 742 attrs = attrs.deep_dup
743 743
744 744 @unallowed_parent_id = nil
745 745 if new_record? || attrs.key?('parent_id')
746 746 parent_id_param = attrs['parent_id'].to_s
747 747 if new_record? || parent_id_param != parent_id.to_s
748 748 p = parent_id_param.present? ? Project.find_by_id(parent_id_param) : nil
749 749 unless allowed_parents(user).include?(p)
750 750 attrs.delete('parent_id')
751 751 @unallowed_parent_id = true
752 752 end
753 753 end
754 754 end
755 755
756 756 super(attrs, user)
757 757 end
758 758
759 759 # Returns an auto-generated project identifier based on the last identifier used
760 760 def self.next_identifier
761 761 p = Project.order('id DESC').first
762 762 p.nil? ? nil : p.identifier.to_s.succ
763 763 end
764 764
765 765 # Copies and saves the Project instance based on the +project+.
766 766 # Duplicates the source project's:
767 767 # * Wiki
768 768 # * Versions
769 769 # * Categories
770 770 # * Issues
771 771 # * Members
772 772 # * Queries
773 773 #
774 774 # Accepts an +options+ argument to specify what to copy
775 775 #
776 776 # Examples:
777 777 # project.copy(1) # => copies everything
778 778 # project.copy(1, :only => 'members') # => copies members only
779 779 # project.copy(1, :only => ['members', 'versions']) # => copies members and versions
780 780 def copy(project, options={})
781 781 project = project.is_a?(Project) ? project : Project.find(project)
782 782
783 783 to_be_copied = %w(wiki versions issue_categories issues members queries boards)
784 784 to_be_copied = to_be_copied & Array.wrap(options[:only]) unless options[:only].nil?
785 785
786 786 Project.transaction do
787 787 if save
788 788 reload
789 789 to_be_copied.each do |name|
790 790 send "copy_#{name}", project
791 791 end
792 792 Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
793 793 save
794 794 else
795 795 false
796 796 end
797 797 end
798 798 end
799 799
800 800 def member_principals
801 801 ActiveSupport::Deprecation.warn "Project#member_principals is deprecated and will be removed in Redmine 4.0. Use #memberships.active instead."
802 802 memberships.active
803 803 end
804 804
805 805 # Returns a new unsaved Project instance with attributes copied from +project+
806 806 def self.copy_from(project)
807 807 project = project.is_a?(Project) ? project : Project.find(project)
808 808 # clear unique attributes
809 809 attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
810 810 copy = Project.new(attributes)
811 811 copy.enabled_module_names = project.enabled_module_names
812 812 copy.trackers = project.trackers
813 813 copy.custom_values = project.custom_values.collect {|v| v.clone}
814 814 copy.issue_custom_fields = project.issue_custom_fields
815 815 copy
816 816 end
817 817
818 818 # Yields the given block for each project with its level in the tree
819 819 def self.project_tree(projects, options={}, &block)
820 820 ancestors = []
821 821 if options[:init_level] && projects.first
822 822 ancestors = projects.first.ancestors.to_a
823 823 end
824 824 projects.sort_by(&:lft).each do |project|
825 825 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
826 826 ancestors.pop
827 827 end
828 828 yield project, ancestors.size
829 829 ancestors << project
830 830 end
831 831 end
832 832
833 833 private
834 834
835 835 def update_inherited_members
836 836 if parent
837 837 if inherit_members? && !inherit_members_was
838 838 remove_inherited_member_roles
839 839 add_inherited_member_roles
840 840 elsif !inherit_members? && inherit_members_was
841 841 remove_inherited_member_roles
842 842 end
843 843 end
844 844 end
845 845
846 846 def remove_inherited_member_roles
847 member_roles = memberships.map(&:member_roles).flatten
847 member_roles = MemberRole.where(:member_id => membership_ids).to_a
848 848 member_role_ids = member_roles.map(&:id)
849 849 member_roles.each do |member_role|
850 850 if member_role.inherited_from && !member_role_ids.include?(member_role.inherited_from)
851 851 member_role.destroy
852 852 end
853 853 end
854 854 end
855 855
856 856 def add_inherited_member_roles
857 857 if inherit_members? && parent
858 858 parent.memberships.each do |parent_member|
859 859 member = Member.find_or_new(self.id, parent_member.user_id)
860 860 parent_member.member_roles.each do |parent_member_role|
861 861 member.member_roles << MemberRole.new(:role => parent_member_role.role, :inherited_from => parent_member_role.id)
862 862 end
863 863 member.save!
864 864 end
865 865 memberships.reset
866 866 end
867 867 end
868 868
869 869 def update_versions_from_hierarchy_change
870 870 Issue.update_versions_from_hierarchy_change(self)
871 871 end
872 872
873 873 def validate_parent
874 874 if @unallowed_parent_id
875 875 errors.add(:parent_id, :invalid)
876 876 elsif parent_id_changed?
877 877 unless parent.nil? || (parent.active? && move_possible?(parent))
878 878 errors.add(:parent_id, :invalid)
879 879 end
880 880 end
881 881 end
882 882
883 883 # Copies wiki from +project+
884 884 def copy_wiki(project)
885 885 # Check that the source project has a wiki first
886 886 unless project.wiki.nil?
887 887 wiki = self.wiki || Wiki.new
888 888 wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
889 889 wiki_pages_map = {}
890 890 project.wiki.pages.each do |page|
891 891 # Skip pages without content
892 892 next if page.content.nil?
893 893 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
894 894 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
895 895 new_wiki_page.content = new_wiki_content
896 896 wiki.pages << new_wiki_page
897 897 wiki_pages_map[page.id] = new_wiki_page
898 898 end
899 899
900 900 self.wiki = wiki
901 901 wiki.save
902 902 # Reproduce page hierarchy
903 903 project.wiki.pages.each do |page|
904 904 if page.parent_id && wiki_pages_map[page.id]
905 905 wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
906 906 wiki_pages_map[page.id].save
907 907 end
908 908 end
909 909 end
910 910 end
911 911
912 912 # Copies versions from +project+
913 913 def copy_versions(project)
914 914 project.versions.each do |version|
915 915 new_version = Version.new
916 916 new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
917 917 self.versions << new_version
918 918 end
919 919 end
920 920
921 921 # Copies issue categories from +project+
922 922 def copy_issue_categories(project)
923 923 project.issue_categories.each do |issue_category|
924 924 new_issue_category = IssueCategory.new
925 925 new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
926 926 self.issue_categories << new_issue_category
927 927 end
928 928 end
929 929
930 930 # Copies issues from +project+
931 931 def copy_issues(project)
932 932 # Stores the source issue id as a key and the copied issues as the
933 933 # value. Used to map the two together for issue relations.
934 934 issues_map = {}
935 935
936 936 # Store status and reopen locked/closed versions
937 937 version_statuses = versions.reject(&:open?).map {|version| [version, version.status]}
938 938 version_statuses.each do |version, status|
939 939 version.update_attribute :status, 'open'
940 940 end
941 941
942 942 # Get issues sorted by root_id, lft so that parent issues
943 943 # get copied before their children
944 944 project.issues.reorder('root_id, lft').each do |issue|
945 945 new_issue = Issue.new
946 946 new_issue.copy_from(issue, :subtasks => false, :link => false)
947 947 new_issue.project = self
948 948 # Changing project resets the custom field values
949 949 # TODO: handle this in Issue#project=
950 950 new_issue.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
951 951 # Reassign fixed_versions by name, since names are unique per project
952 952 if issue.fixed_version && issue.fixed_version.project == project
953 953 new_issue.fixed_version = self.versions.detect {|v| v.name == issue.fixed_version.name}
954 954 end
955 955 # Reassign version custom field values
956 956 new_issue.custom_field_values.each do |custom_value|
957 957 if custom_value.custom_field.field_format == 'version' && custom_value.value.present?
958 958 versions = Version.where(:id => custom_value.value).to_a
959 959 new_value = versions.map do |version|
960 960 if version.project == project
961 961 self.versions.detect {|v| v.name == version.name}.try(:id)
962 962 else
963 963 version.id
964 964 end
965 965 end
966 966 new_value.compact!
967 967 new_value = new_value.first unless custom_value.custom_field.multiple?
968 968 custom_value.value = new_value
969 969 end
970 970 end
971 971 # Reassign the category by name, since names are unique per project
972 972 if issue.category
973 973 new_issue.category = self.issue_categories.detect {|c| c.name == issue.category.name}
974 974 end
975 975 # Parent issue
976 976 if issue.parent_id
977 977 if copied_parent = issues_map[issue.parent_id]
978 978 new_issue.parent_issue_id = copied_parent.id
979 979 end
980 980 end
981 981
982 982 self.issues << new_issue
983 983 if new_issue.new_record?
984 984 logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info?
985 985 else
986 986 issues_map[issue.id] = new_issue unless new_issue.new_record?
987 987 end
988 988 end
989 989
990 990 # Restore locked/closed version statuses
991 991 version_statuses.each do |version, status|
992 992 version.update_attribute :status, status
993 993 end
994 994
995 995 # Relations after in case issues related each other
996 996 project.issues.each do |issue|
997 997 new_issue = issues_map[issue.id]
998 998 unless new_issue
999 999 # Issue was not copied
1000 1000 next
1001 1001 end
1002 1002
1003 1003 # Relations
1004 1004 issue.relations_from.each do |source_relation|
1005 1005 new_issue_relation = IssueRelation.new
1006 1006 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
1007 1007 new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
1008 1008 if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
1009 1009 new_issue_relation.issue_to = source_relation.issue_to
1010 1010 end
1011 1011 new_issue.relations_from << new_issue_relation
1012 1012 end
1013 1013
1014 1014 issue.relations_to.each do |source_relation|
1015 1015 new_issue_relation = IssueRelation.new
1016 1016 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
1017 1017 new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
1018 1018 if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
1019 1019 new_issue_relation.issue_from = source_relation.issue_from
1020 1020 end
1021 1021 new_issue.relations_to << new_issue_relation
1022 1022 end
1023 1023 end
1024 1024 end
1025 1025
1026 1026 # Copies members from +project+
1027 1027 def copy_members(project)
1028 1028 # Copy users first, then groups to handle members with inherited and given roles
1029 1029 members_to_copy = []
1030 1030 members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)}
1031 1031 members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)}
1032 1032
1033 1033 members_to_copy.each do |member|
1034 1034 new_member = Member.new
1035 1035 new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
1036 1036 # only copy non inherited roles
1037 1037 # inherited roles will be added when copying the group membership
1038 1038 role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
1039 1039 next if role_ids.empty?
1040 1040 new_member.role_ids = role_ids
1041 1041 new_member.project = self
1042 1042 self.members << new_member
1043 1043 end
1044 1044 end
1045 1045
1046 1046 # Copies queries from +project+
1047 1047 def copy_queries(project)
1048 1048 project.queries.each do |query|
1049 1049 new_query = IssueQuery.new
1050 1050 new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria", "user_id", "type")
1051 1051 new_query.sort_criteria = query.sort_criteria if query.sort_criteria
1052 1052 new_query.project = self
1053 1053 new_query.user_id = query.user_id
1054 1054 new_query.role_ids = query.role_ids if query.visibility == IssueQuery::VISIBILITY_ROLES
1055 1055 self.queries << new_query
1056 1056 end
1057 1057 end
1058 1058
1059 1059 # Copies boards from +project+
1060 1060 def copy_boards(project)
1061 1061 project.boards.each do |board|
1062 1062 new_board = Board.new
1063 1063 new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
1064 1064 new_board.project = self
1065 1065 self.boards << new_board
1066 1066 end
1067 1067 end
1068 1068
1069 1069 def allowed_permissions
1070 1070 @allowed_permissions ||= begin
1071 1071 module_names = enabled_modules.loaded? ? enabled_modules.map(&:name) : enabled_modules.pluck(:name)
1072 1072 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
1073 1073 end
1074 1074 end
1075 1075
1076 1076 def allowed_actions
1077 1077 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
1078 1078 end
1079 1079
1080 1080 # Archives subprojects recursively
1081 1081 def archive!
1082 1082 children.each do |subproject|
1083 1083 subproject.send :archive!
1084 1084 end
1085 1085 update_attribute :status, STATUS_ARCHIVED
1086 1086 end
1087 1087 end
General Comments 0
You need to be logged in to leave comments. Login now