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