To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / project.rb @ 437:102056ec2de9

History | View | Annotate | Download (30.3 KB)

1
# redMine - project management software
2
# Copyright (C) 2006  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
# 
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
# 
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

    
18
class Project < ActiveRecord::Base
19
  # Project statuses
20
  STATUS_ACTIVE     = 1
21
  STATUS_ARCHIVED   = 9
22
  
23
  # Maximum length for project identifiers
24
  IDENTIFIER_MAX_LENGTH = 100
25
  
26
  # Specific overidden Activities
27
  has_many :time_entry_activities
28
  has_many :members, :include => [:user, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
29
  has_many :memberships, :class_name => 'Member'
30
  has_many :member_principals, :class_name => 'Member', 
31
                               :include => :principal,
32
                               :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
33
  has_many :users, :through => :members
34
  has_many :principals, :through => :member_principals, :source => :principal
35
  
36
  has_many :enabled_modules, :dependent => :delete_all
37
  has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
38
  has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
39
  has_many :issue_changes, :through => :issues, :source => :journals
40
  has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
41
  has_many :time_entries, :dependent => :delete_all
42
  has_many :queries, :dependent => :delete_all
43
  has_many :documents, :dependent => :destroy
44
  has_many :news, :dependent => :delete_all, :include => :author
45
  has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
46
  has_many :boards, :dependent => :destroy, :order => "position ASC"
47
  has_one :repository, :dependent => :destroy
48
  has_many :changesets, :through => :repository
49
  has_one :wiki, :dependent => :destroy
50
  # Custom field for the project issues
51
  has_and_belongs_to_many :issue_custom_fields, 
52
                          :class_name => 'IssueCustomField',
53
                          :order => "#{CustomField.table_name}.position",
54
                          :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
55
                          :association_foreign_key => 'custom_field_id'
56
                          
57
  acts_as_nested_set :order => 'name'
58
  acts_as_attachable :view_permission => :view_files,
59
                     :delete_permission => :manage_files
60

    
61
  acts_as_customizable
62
  acts_as_searchable :columns => ['name', 'identifier', 'description'], :project_key => 'id', :permission => nil
63
  acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
64
                :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o}},
65
                :author => nil
66

    
67
  attr_protected :status, :enabled_module_names
68
  
69
  validates_presence_of :name, :identifier
70
  validates_uniqueness_of :identifier
71
  validates_associated :repository, :wiki
72
  validates_length_of :name, :maximum => 255
73
  validates_length_of :homepage, :maximum => 255
74
  validates_length_of :identifier, :in => 1..IDENTIFIER_MAX_LENGTH
75
  # donwcase letters, digits, dashes but not digits only
76
  validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? }
77
  # reserved words
78
  validates_exclusion_of :identifier, :in => %w( new )
79

    
80
  before_destroy :delete_all_members, :destroy_children
81

    
82
  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] } }
83
  named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
84
  named_scope :all_public, { :conditions => { :is_public => true } }
85
  named_scope :visible, lambda { { :conditions => Project.visible_by(User.current) } }
86
  named_scope :visible_roots, lambda { { :conditions => Project.root_visible_by(User.current) } }
87
  
88
  def identifier=(identifier)
89
    super unless identifier_frozen?
90
  end
91
  
92
  def identifier_frozen?
93
    errors[:identifier].nil? && !(new_record? || identifier.blank?)
94
  end
95

    
96
  # returns latest created projects
97
  # non public projects will be returned only if user is a member of those
98
  def self.latest(user=nil, count=5)
99
    find(:all, :limit => count, :conditions => visible_by(user), :order => "created_on DESC")        
100
  end        
101

    
102
  # Returns a SQL :conditions string used to find all active projects for the specified user.
103
  #
104
  # Examples:
105
  #     Projects.visible_by(admin)        => "projects.status = 1"
106
  #     Projects.visible_by(normal_user)  => "projects.status = 1 AND projects.is_public = 1"
107
  def self.visible_by(user=nil)
108
    user ||= User.current
109
    if user && user.admin?
110
      return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
111
    elsif user && user.memberships.any?
112
      return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND (#{Project.table_name}.is_public = #{connection.quoted_true} or #{Project.table_name}.id IN (#{user.memberships.collect{|m| m.project_id}.join(',')}))"
113
    else
114
      return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND #{Project.table_name}.is_public = #{connection.quoted_true}"
115
    end
116
  end
117
  
118
  def self.root_visible_by(user=nil)
119
    return "#{Project.table_name}.parent_id IS NULL AND " + visible_by(user)
120
  end
121
  
122
  def self.allowed_to_condition(user, permission, options={})
123
    statements = []
124
    base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
125
    if perm = Redmine::AccessControl.permission(permission)
126
      unless perm.project_module.nil?
127
        # If the permission belongs to a project module, make sure the module is enabled
128
        base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
129
      end
130
    end
131
    if options[:project]
132
      project_statement = "#{Project.table_name}.id = #{options[:project].id}"
133
      project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
134
      base_statement = "(#{project_statement}) AND (#{base_statement})"
135
    end
136
    if user.admin?
137
      # no restriction
138
    else
139
      statements << "1=0"
140
      if user.logged?
141
        if Role.non_member.allowed_to?(permission) && !options[:member]
142
          statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
143
        end
144
        allowed_project_ids = user.memberships.select {|m| m.roles.detect {|role| role.allowed_to?(permission)}}.collect {|m| m.project_id}
145
        statements << "#{Project.table_name}.id IN (#{allowed_project_ids.join(',')})" if allowed_project_ids.any?
146
      else
147
        if Role.anonymous.allowed_to?(permission) && !options[:member]
148
          # anonymous user allowed on public project
149
          statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
150
        end 
151
      end
152
    end
153
    statements.empty? ? base_statement : "((#{base_statement}) AND (#{statements.join(' OR ')}))"
154
  end
155

    
156
  # Returns the Systemwide and project specific activities
157
  def activities(include_inactive=false)
158
    if include_inactive
159
      return all_activities
160
    else
161
      return active_activities
162
    end
163
  end
164

    
165
  # Will create a new Project specific Activity or update an existing one
166
  #
167
  # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
168
  # does not successfully save.
169
  def update_or_create_time_entry_activity(id, activity_hash)
170
    if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
171
      self.create_time_entry_activity_if_needed(activity_hash)
172
    else
173
      activity = project.time_entry_activities.find_by_id(id.to_i)
174
      activity.update_attributes(activity_hash) if activity
175
    end
176
  end
177
  
178
  # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
179
  #
180
  # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
181
  # does not successfully save.
182
  def create_time_entry_activity_if_needed(activity)
183
    if activity['parent_id']
184
    
185
      parent_activity = TimeEntryActivity.find(activity['parent_id'])
186
      activity['name'] = parent_activity.name
187
      activity['position'] = parent_activity.position
188

    
189
      if Enumeration.overridding_change?(activity, parent_activity)
190
        project_activity = self.time_entry_activities.create(activity)
191

    
192
        if project_activity.new_record?
193
          raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
194
        else
195
          self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
196
        end
197
      end
198
    end
199
  end
200

    
201
  # Returns a :conditions SQL string that can be used to find the issues associated with this project.
202
  #
203
  # Examples:
204
  #   project.project_condition(true)  => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
205
  #   project.project_condition(false) => "projects.id = 1"
206
  def project_condition(with_subprojects)
207
    cond = "#{Project.table_name}.id = #{id}"
208
    cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
209
    cond
210
  end
211
  
212
  def self.find(*args)
213
    if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
214
      project = find_by_identifier(*args)
215
      raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
216
      project
217
    else
218
      super
219
    end
220
  end
221
 
222
  def to_param
223
    # id is used for projects with a numeric identifier (compatibility)
224
    @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier)
225
  end
226
  
227
  def active?
228
    self.status == STATUS_ACTIVE
229
  end
230
  
231
  def archived?
232
    self.status == STATUS_ARCHIVED
233
  end
234
  
235
  # Archives the project and its descendants
236
  def archive
237
    # Check that there is no issue of a non descendant project that is assigned
238
    # to one of the project or descendant versions
239
    v_ids = self_and_descendants.collect {|p| p.version_ids}.flatten
240
    if v_ids.any? && Issue.find(:first, :include => :project,
241
                                        :conditions => ["(#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?)" +
242
                                                        " AND #{Issue.table_name}.fixed_version_id IN (?)", lft, rgt, v_ids])
243
      return false
244
    end
245
    Project.transaction do
246
      archive!
247
    end
248
    true
249
  end
250
  
251
  # Unarchives the project
252
  # All its ancestors must be active
253
  def unarchive
254
    return false if ancestors.detect {|a| !a.active?}
255
    update_attribute :status, STATUS_ACTIVE
256
  end
257
  
258
  # Returns an array of projects the project can be moved to
259
  # by the current user
260
  def allowed_parents
261
    return @allowed_parents if @allowed_parents
262
    @allowed_parents = Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_subprojects))
263
    @allowed_parents = @allowed_parents - self_and_descendants
264
    if User.current.allowed_to?(:add_project, nil, :global => true) || (!new_record? && parent.nil?)
265
      @allowed_parents << nil
266
    end
267
    unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
268
      @allowed_parents << parent
269
    end
270
    @allowed_parents
271
  end
272
  
273
  # Sets the parent of the project with authorization check
274
  def set_allowed_parent!(p)
275
    unless p.nil? || p.is_a?(Project)
276
      if p.to_s.blank?
277
        p = nil
278
      else
279
        p = Project.find_by_id(p)
280
        return false unless p
281
      end
282
    end
283
    if p.nil?
284
      if !new_record? && allowed_parents.empty?
285
        return false
286
      end
287
    elsif !allowed_parents.include?(p)
288
      return false
289
    end
290
    set_parent!(p)
291
  end
292
  
293
  # Sets the parent of the project
294
  # Argument can be either a Project, a String, a Fixnum or nil
295
  def set_parent!(p)
296
    unless p.nil? || p.is_a?(Project)
297
      if p.to_s.blank?
298
        p = nil
299
      else
300
        p = Project.find_by_id(p)
301
        return false unless p
302
      end
303
    end
304
    if p == parent && !p.nil?
305
      # Nothing to do
306
      true
307
    elsif p.nil? || (p.active? && move_possible?(p))
308
      # Insert the project so that target's children or root projects stay alphabetically sorted
309
      sibs = (p.nil? ? self.class.roots : p.children)
310
      to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
311
      if to_be_inserted_before
312
        move_to_left_of(to_be_inserted_before)
313
      elsif p.nil?
314
        if sibs.empty?
315
          # move_to_root adds the project in first (ie. left) position
316
          move_to_root
317
        else
318
          move_to_right_of(sibs.last) unless self == sibs.last
319
        end
320
      else
321
        # move_to_child_of adds the project in last (ie.right) position
322
        move_to_child_of(p)
323
      end
324
      Issue.update_versions_from_hierarchy_change(self)
325
      true
326
    else
327
      # Can not move to the given target
328
      false
329
    end
330
  end
331
  
332
  # Returns an array of the trackers used by the project and its active sub projects
333
  def rolled_up_trackers
334
    @rolled_up_trackers ||=
335
      Tracker.find(:all, :include => :projects,
336
                         :select => "DISTINCT #{Tracker.table_name}.*",
337
                         :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
338
                         :order => "#{Tracker.table_name}.position")
339
  end
340
  
341
  # Closes open and locked project versions that are completed
342
  def close_completed_versions
343
    Version.transaction do
344
      versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version|
345
        if version.completed?
346
          version.update_attribute(:status, 'closed')
347
        end
348
      end
349
    end
350
  end
351

    
352
  # Returns a scope of the Versions on subprojects
353
  def rolled_up_versions
354
    @rolled_up_versions ||=
355
      Version.scoped(:include => :project,
356
                     :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt])
357
  end
358
  
359
  # Returns a scope of the Versions used by the project
360
  def shared_versions
361
    @shared_versions ||= 
362
      Version.scoped(:include => :project,
363
                     :conditions => "#{Project.table_name}.id = #{id}" +
364
                                    " OR (#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND (" +
365
                                          " #{Version.table_name}.sharing = 'system'" +
366
                                          " OR (#{Project.table_name}.lft >= #{root.lft} AND #{Project.table_name}.rgt <= #{root.rgt} AND #{Version.table_name}.sharing = 'tree')" +
367
                                          " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
368
                                          " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
369
                                          "))")
370
  end
371

    
372
  # Returns a hash of project users grouped by role
373
  def users_by_role
374
    members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
375
      m.roles.each do |r|
376
        h[r] ||= []
377
        h[r] << m.user
378
      end
379
      h
380
    end
381
  end
382
  
383
  # Deletes all project's members
384
  def delete_all_members
385
    me, mr = Member.table_name, MemberRole.table_name
386
    connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
387
    Member.delete_all(['project_id = ?', id])
388
  end
389
  
390
  # Users issues can be assigned to
391
  def assignable_users
392
    members.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.user}.sort
393
  end
394
  
395
  # Returns the mail adresses of users that should be always notified on project events
396
  def recipients
397
    notified_users.collect {|user| user.mail}
398
  end
399
  
400
  # Returns the users that should be notified on project events
401
  def notified_users
402
    # TODO: User part should be extracted to User#notify_about?
403
    members.select {|m| m.mail_notification? || m.user.mail_notification == 'all'}.collect {|m| m.user}
404
  end
405
  
406
  # Returns an array of all custom fields enabled for project issues
407
  # (explictly associated custom fields and custom fields enabled for all projects)
408
  def all_issue_custom_fields
409
    @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
410
  end
411
  
412
  def project
413
    self
414
  end
415
  
416
  def <=>(project)
417
    name.downcase <=> project.name.downcase
418
  end
419
  
420
  def to_s
421
    name
422
  end
423
  
424
  # Returns a short description of the projects (first lines)
425
  def short_description(length = 255)
426

    
427
    ## The short description is used in lists, e.g. Latest projects,
428
    ## My projects etc.  It should be no more than a line or two with
429
    ## no text formatting.
430

    
431
    ## Original Redmine code: this truncates to the CR that is more
432
    ## than "length" characters from the start.
433
    # description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
434

    
435
    ## That can leave too much text for us, and also we want to omit
436
    ## images and the like.  Truncate instead to the first CR that
437
    ## follows _any_ non-blank text, and to the next word break beyond
438
    ## "length" characters if the result is still longer than that.
439
    ##
440
    description.gsub(/![^\s]+!/, '').gsub(/^(\s*[^\n\r]*).*$/m, '\1').gsub(/^(.{#{length}}\b).*$/m, '\1 ...').strip if description
441
  end
442

    
443
  def css_classes
444
    s = 'project'
445
    s << ' root' if root?
446
    s << ' child' if child?
447
    s << (leaf? ? ' leaf' : ' parent')
448
    s
449
  end
450

    
451
  # The earliest start date of a project, based on it's issues and versions
452
  def start_date
453
    if module_enabled?(:issue_tracking)
454
      [
455
       issues.minimum('start_date'),
456
       shared_versions.collect(&:effective_date),
457
       shared_versions.collect {|v| v.fixed_issues.minimum('start_date')}
458
      ].flatten.compact.min
459
    end
460
  end
461

    
462
  # The latest due date of an issue or version
463
  def due_date
464
    if module_enabled?(:issue_tracking)
465
      [
466
       issues.maximum('due_date'),
467
       shared_versions.collect(&:effective_date),
468
       shared_versions.collect {|v| v.fixed_issues.maximum('due_date')}
469
      ].flatten.compact.max
470
    end
471
  end
472

    
473
  def overdue?
474
    active? && !due_date.nil? && (due_date < Date.today)
475
  end
476

    
477
  # Returns the percent completed for this project, based on the
478
  # progress on it's versions.
479
  def completed_percent(options={:include_subprojects => false})
480
    if options.delete(:include_subprojects)
481
      total = self_and_descendants.collect(&:completed_percent).sum
482

    
483
      total / self_and_descendants.count
484
    else
485
      if versions.count > 0
486
        total = versions.collect(&:completed_pourcent).sum
487

    
488
        total / versions.count
489
      else
490
        100
491
      end
492
    end
493
  end
494
  
495
  # Return true if this project is allowed to do the specified action.
496
  # action can be:
497
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
498
  # * a permission Symbol (eg. :edit_project)
499
  def allows_to?(action)
500
    if action.is_a? Hash
501
      allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
502
    else
503
      allowed_permissions.include? action
504
    end
505
  end
506
  
507
  def module_enabled?(module_name)
508
    module_name = module_name.to_s
509
    enabled_modules.detect {|m| m.name == module_name}
510
  end
511
  
512
  def enabled_module_names=(module_names)
513
    if module_names && module_names.is_a?(Array)
514
      module_names = module_names.collect(&:to_s)
515
      # remove disabled modules
516
      enabled_modules.each {|mod| mod.destroy unless module_names.include?(mod.name)}
517
      # add new modules
518
      module_names.reject {|name| module_enabled?(name)}.each {|name| enabled_modules << EnabledModule.new(:name => name)}
519
    else
520
      enabled_modules.clear
521
    end
522
  end
523

    
524
  # Returns an array of projects that are in this project's hierarchy
525
  #
526
  # Example: parents, children, siblings
527
  def hierarchy
528
    parents = project.self_and_ancestors || []
529
    descendants = project.descendants || []
530
    project_hierarchy = parents | descendants # Set union
531
  end
532
  
533
  # Returns an auto-generated project identifier based on the last identifier used
534
  def self.next_identifier
535
    p = Project.find(:first, :order => 'created_on DESC')
536
    p.nil? ? nil : p.identifier.to_s.succ
537
  end
538

    
539
  # Copies and saves the Project instance based on the +project+.
540
  # Duplicates the source project's:
541
  # * Wiki
542
  # * Versions
543
  # * Categories
544
  # * Issues
545
  # * Members
546
  # * Queries
547
  #
548
  # Accepts an +options+ argument to specify what to copy
549
  #
550
  # Examples:
551
  #   project.copy(1)                                    # => copies everything
552
  #   project.copy(1, :only => 'members')                # => copies members only
553
  #   project.copy(1, :only => ['members', 'versions'])  # => copies members and versions
554
  def copy(project, options={})
555
    project = project.is_a?(Project) ? project : Project.find(project)
556
    
557
    to_be_copied = %w(wiki versions issue_categories issues members queries boards)
558
    to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
559
    
560
    Project.transaction do
561
      if save
562
        reload
563
        to_be_copied.each do |name|
564
          send "copy_#{name}", project
565
        end
566
        Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
567
        save
568
      end
569
    end
570
  end
571

    
572
  
573
  # Copies +project+ and returns the new instance.  This will not save
574
  # the copy
575
  def self.copy_from(project)
576
    begin
577
      project = project.is_a?(Project) ? project : Project.find(project)
578
      if project
579
        # clear unique attributes
580
        attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
581
        copy = Project.new(attributes)
582
        copy.enabled_modules = project.enabled_modules
583
        copy.trackers = project.trackers
584
        copy.custom_values = project.custom_values.collect {|v| v.clone}
585
        copy.issue_custom_fields = project.issue_custom_fields
586
        return copy
587
      else
588
        return nil
589
      end
590
    rescue ActiveRecord::RecordNotFound
591
      return nil
592
    end
593
  end
594

    
595
  # Yields the given block for each project with its level in the tree
596
  def self.project_tree(projects, &block)
597
    ancestors = []
598
    projects.sort_by(&:lft).each do |project|
599
      while (ancestors.any? && !project.is_descendant_of?(ancestors.last)) 
600
        ancestors.pop
601
      end
602
      yield project, ancestors.size
603
      ancestors << project
604
    end
605
  end
606
  
607
  private
608
  
609
  # Destroys children before destroying self
610
  def destroy_children
611
    children.each do |child|
612
      child.destroy
613
    end
614
  end
615
  
616
  # Copies wiki from +project+
617
  def copy_wiki(project)
618
    # Check that the source project has a wiki first
619
    unless project.wiki.nil?
620
      self.wiki ||= Wiki.new
621
      wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
622
      wiki_pages_map = {}
623
      project.wiki.pages.each do |page|
624
        # Skip pages without content
625
        next if page.content.nil?
626
        new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
627
        new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
628
        new_wiki_page.content = new_wiki_content
629
        wiki.pages << new_wiki_page
630
        wiki_pages_map[page.id] = new_wiki_page
631
      end
632
      wiki.save
633
      # Reproduce page hierarchy
634
      project.wiki.pages.each do |page|
635
        if page.parent_id && wiki_pages_map[page.id]
636
          wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
637
          wiki_pages_map[page.id].save
638
        end
639
      end
640
    end
641
  end
642

    
643
  # Copies versions from +project+
644
  def copy_versions(project)
645
    project.versions.each do |version|
646
      new_version = Version.new
647
      new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
648
      self.versions << new_version
649
    end
650
  end
651

    
652
  # Copies issue categories from +project+
653
  def copy_issue_categories(project)
654
    project.issue_categories.each do |issue_category|
655
      new_issue_category = IssueCategory.new
656
      new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
657
      self.issue_categories << new_issue_category
658
    end
659
  end
660
  
661
  # Copies issues from +project+
662
  def copy_issues(project)
663
    # Stores the source issue id as a key and the copied issues as the
664
    # value.  Used to map the two togeather for issue relations.
665
    issues_map = {}
666
    
667
    # Get issues sorted by root_id, lft so that parent issues
668
    # get copied before their children
669
    project.issues.find(:all, :order => 'root_id, lft').each do |issue|
670
      new_issue = Issue.new
671
      new_issue.copy_from(issue)
672
      new_issue.project = self
673
      # Reassign fixed_versions by name, since names are unique per
674
      # project and the versions for self are not yet saved
675
      if issue.fixed_version
676
        new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
677
      end
678
      # Reassign the category by name, since names are unique per
679
      # project and the categories for self are not yet saved
680
      if issue.category
681
        new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
682
      end
683
      # Parent issue
684
      if issue.parent_id
685
        if copied_parent = issues_map[issue.parent_id]
686
          new_issue.parent_issue_id = copied_parent.id
687
        end
688
      end
689
      
690
      self.issues << new_issue
691
      issues_map[issue.id] = new_issue
692
    end
693

    
694
    # Relations after in case issues related each other
695
    project.issues.each do |issue|
696
      new_issue = issues_map[issue.id]
697
      
698
      # Relations
699
      issue.relations_from.each do |source_relation|
700
        new_issue_relation = IssueRelation.new
701
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
702
        new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
703
        if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
704
          new_issue_relation.issue_to = source_relation.issue_to
705
        end
706
        new_issue.relations_from << new_issue_relation
707
      end
708
      
709
      issue.relations_to.each do |source_relation|
710
        new_issue_relation = IssueRelation.new
711
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
712
        new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
713
        if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
714
          new_issue_relation.issue_from = source_relation.issue_from
715
        end
716
        new_issue.relations_to << new_issue_relation
717
      end
718
    end
719
  end
720

    
721
  # Copies members from +project+
722
  def copy_members(project)
723
    project.memberships.each do |member|
724
      new_member = Member.new
725
      new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
726
      # only copy non inherited roles
727
      # inherited roles will be added when copying the group membership
728
      role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
729
      next if role_ids.empty?
730
      new_member.role_ids = role_ids
731
      new_member.project = self
732
      self.members << new_member
733
    end
734
  end
735

    
736
  # Copies queries from +project+
737
  def copy_queries(project)
738
    project.queries.each do |query|
739
      new_query = Query.new
740
      new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
741
      new_query.sort_criteria = query.sort_criteria if query.sort_criteria
742
      new_query.project = self
743
      self.queries << new_query
744
    end
745
  end
746

    
747
  # Copies boards from +project+
748
  def copy_boards(project)
749
    project.boards.each do |board|
750
      new_board = Board.new
751
      new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
752
      new_board.project = self
753
      self.boards << new_board
754
    end
755
  end
756
  
757
  def allowed_permissions
758
    @allowed_permissions ||= begin
759
      module_names = enabled_modules.all(:select => :name).collect {|m| m.name}
760
      Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
761
    end
762
  end
763

    
764
  def allowed_actions
765
    @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
766
  end
767

    
768
  # Returns all the active Systemwide and project specific activities
769
  def active_activities
770
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
771
    
772
    if overridden_activity_ids.empty?
773
      return TimeEntryActivity.shared.active
774
    else
775
      return system_activities_and_project_overrides
776
    end
777
  end
778

    
779
  # Returns all the Systemwide and project specific activities
780
  # (inactive and active)
781
  def all_activities
782
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
783

    
784
    if overridden_activity_ids.empty?
785
      return TimeEntryActivity.shared
786
    else
787
      return system_activities_and_project_overrides(true)
788
    end
789
  end
790

    
791
  # Returns the systemwide active activities merged with the project specific overrides
792
  def system_activities_and_project_overrides(include_inactive=false)
793
    if include_inactive
794
      return TimeEntryActivity.shared.
795
        find(:all,
796
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
797
        self.time_entry_activities
798
    else
799
      return TimeEntryActivity.shared.active.
800
        find(:all,
801
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
802
        self.time_entry_activities.active
803
    end
804
  end
805
  
806
  # Archives subprojects recursively
807
  def archive!
808
    children.each do |subproject|
809
      subproject.send :archive!
810
    end
811
    update_attribute :status, STATUS_ARCHIVED
812
  end
813
end