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