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