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