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