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 @ 1358:b8f94812d737

History | View | Annotate | Download (35.7 KB)

1
# Redmine - project management software
2
# Copyright (C) 2006-2012  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
  include Redmine::SafeAttributes
20

    
21
  # Project statuses
22
  STATUS_ACTIVE     = 1
23
  STATUS_CLOSED     = 5
24
  STATUS_ARCHIVED   = 9
25

    
26
  # Maximum length for project identifiers
27
  IDENTIFIER_MAX_LENGTH = 100
28

    
29
  # Specific overidden Activities
30
  has_many :time_entry_activities
31
  has_many :members, :include => [:principal, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
32
  has_many :memberships, :class_name => 'Member'
33
  has_many :member_principals, :class_name => 'Member',
34
                               :include => :principal,
35
                               :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
36
  has_many :users, :through => :members
37
  has_many :principals, :through => :member_principals, :source => :principal
38

    
39
  has_many :enabled_modules, :dependent => :delete_all
40
  has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
41
  has_many :issues, :dependent => :destroy, :include => [:status, :tracker]
42
  has_many :issue_changes, :through => :issues, :source => :journals
43
  has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
44
  has_many :time_entries, :dependent => :delete_all
45
  has_many :queries, :dependent => :delete_all
46
  has_many :documents, :dependent => :destroy
47
  has_many :news, :dependent => :destroy, :include => :author
48
  has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
49
  has_many :boards, :dependent => :destroy, :order => "position ASC"
50
  has_one :repository, :conditions => ["is_default = ?", true]
51
  has_many :repositories, :dependent => :destroy
52
  has_many :changesets, :through => :repository
53
  has_one :wiki, :dependent => :destroy
54
  # Custom field for the project issues
55
  has_and_belongs_to_many :issue_custom_fields,
56
                          :class_name => 'IssueCustomField',
57
                          :order => "#{CustomField.table_name}.position",
58
                          :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
59
                          :association_foreign_key => 'custom_field_id'
60

    
61
  acts_as_nested_set :order => 'name', :dependent => :destroy
62
  acts_as_attachable :view_permission => :view_files,
63
                     :delete_permission => :manage_files
64

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

    
71
  attr_protected :status
72

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

    
84
  after_save :update_position_under_parent, :if => Proc.new {|project| project.name_changed?}
85
  before_destroy :delete_all_members
86

    
87
  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] } }
88
  scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
89
  scope :status, lambda {|arg| arg.blank? ? {} : {:conditions => {:status => arg.to_i}} }
90
  scope :all_public, { :conditions => { :is_public => true } }
91
  scope :visible, lambda {|*args| {:conditions => Project.visible_condition(args.shift || User.current, *args) }}
92
  scope :visible_roots, lambda { { :conditions => Project.root_visible_by(User.current) } }
93
  scope :allowed_to, lambda {|*args| 
94
    user = User.current
95
    permission = nil
96
    if args.first.is_a?(Symbol)
97
      permission = args.shift
98
    else
99
      user = args.shift
100
      permission = args.shift
101
    end
102
    { :conditions => Project.allowed_to_condition(user, permission, *args) }
103
  }
104
  scope :like, lambda {|arg|
105
    if arg.blank?
106
      {}
107
    else
108
      pattern = "%#{arg.to_s.strip.downcase}%"
109
      {:conditions => ["LOWER(identifier) LIKE :p OR LOWER(name) LIKE :p", {:p => pattern}]}
110
    end
111
  }
112

    
113
  def initialize(attributes=nil, *args)
114
    super
115

    
116
    initialized = (attributes || {}).stringify_keys
117
    if !initialized.key?('identifier') && Setting.sequential_project_identifiers?
118
      self.identifier = Project.next_identifier
119
    end
120
    if !initialized.key?('is_public')
121
      self.is_public = Setting.default_projects_public?
122
    end
123
    if !initialized.key?('enabled_module_names')
124
      self.enabled_module_names = Setting.default_projects_modules
125
    end
126
    if !initialized.key?('trackers') && !initialized.key?('tracker_ids')
127
      self.trackers = Tracker.sorted.all
128
    end
129
  end
130

    
131
  def identifier=(identifier)
132
    super unless identifier_frozen?
133
  end
134

    
135
  def identifier_frozen?
136
    errors[:identifier].blank? && !(new_record? || identifier.blank?)
137
  end
138

    
139
  # returns latest created projects
140
  # non public projects will be returned only if user is a member of those
141
  def self.latest(user=nil, count=5)
142
    visible(user).find(:all, :limit => count, :order => "created_on DESC")        
143
  end        
144

    
145
  # Returns true if the project is visible to +user+ or to the current user.
146
  def visible?(user=User.current)
147
    user.allowed_to?(:view_project, self)
148
  end
149

    
150
  # Returns a SQL conditions string used to find all projects visible by the specified user.
151
  #
152
  # Examples:
153
  #   Project.visible_condition(admin)        => "projects.status = 1"
154
  #   Project.visible_condition(normal_user)  => "((projects.status = 1) AND (projects.is_public = 1 OR projects.id IN (1,3,4)))"
155
  #   Project.visible_condition(anonymous)    => "((projects.status = 1) AND (projects.is_public = 1))"
156
  def self.visible_condition(user, options={})
157
    allowed_to_condition(user, :view_project, options)
158
  end
159

    
160
  def self.root_visible_by(user=nil)
161
    return "#{Project.table_name}.parent_id IS NULL AND " + visible_condition(user)
162
  end
163
  
164
  # Returns a SQL conditions string used to find all projects for which +user+ has the given +permission+
165
  #
166
  # Valid options:
167
  # * :project => limit the condition to project
168
  # * :with_subprojects => limit the condition to project and its subprojects
169
  # * :member => limit the condition to the user projects
170
  def self.allowed_to_condition(user, permission, options={})
171
    perm = Redmine::AccessControl.permission(permission)
172
    base_statement = (perm && perm.read? ? "#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED}" : "#{Project.table_name}.status = #{Project::STATUS_ACTIVE}")
173
    if perm && perm.project_module
174
      # If the permission belongs to a project module, make sure the module is enabled
175
      base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
176
    end
177
    if options[:project]
178
      project_statement = "#{Project.table_name}.id = #{options[:project].id}"
179
      project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
180
      base_statement = "(#{project_statement}) AND (#{base_statement})"
181
    end
182

    
183
    if user.admin?
184
      base_statement
185
    else
186
      statement_by_role = {}
187
      unless options[:member]
188
        role = user.logged? ? Role.non_member : Role.anonymous
189
        if role.allowed_to?(permission)
190
          statement_by_role[role] = "#{Project.table_name}.is_public = #{connection.quoted_true}"
191
        end
192
      end
193
      if user.logged?
194
        user.projects_by_role.each do |role, projects|
195
          if role.allowed_to?(permission) && projects.any?
196
            statement_by_role[role] = "#{Project.table_name}.id IN (#{projects.collect(&:id).join(',')})"
197
          end
198
        end
199
      end
200
      if statement_by_role.empty?
201
        "1=0"
202
      else
203
        if block_given?
204
          statement_by_role.each do |role, statement|
205
            if s = yield(role, user)
206
              statement_by_role[role] = "(#{statement} AND (#{s}))"
207
            end
208
          end
209
        end
210
        "((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))"
211
      end
212
    end
213
  end
214

    
215
  # Returns the Systemwide and project specific activities
216
  def activities(include_inactive=false)
217
    if include_inactive
218
      return all_activities
219
    else
220
      return active_activities
221
    end
222
  end
223

    
224
  # Will create a new Project specific Activity or update an existing one
225
  #
226
  # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
227
  # does not successfully save.
228
  def update_or_create_time_entry_activity(id, activity_hash)
229
    if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
230
      self.create_time_entry_activity_if_needed(activity_hash)
231
    else
232
      activity = project.time_entry_activities.find_by_id(id.to_i)
233
      activity.update_attributes(activity_hash) if activity
234
    end
235
  end
236

    
237
  # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
238
  #
239
  # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
240
  # does not successfully save.
241
  def create_time_entry_activity_if_needed(activity)
242
    if activity['parent_id']
243

    
244
      parent_activity = TimeEntryActivity.find(activity['parent_id'])
245
      activity['name'] = parent_activity.name
246
      activity['position'] = parent_activity.position
247

    
248
      if Enumeration.overridding_change?(activity, parent_activity)
249
        project_activity = self.time_entry_activities.create(activity)
250

    
251
        if project_activity.new_record?
252
          raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
253
        else
254
          self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
255
        end
256
      end
257
    end
258
  end
259

    
260
  # Returns a :conditions SQL string that can be used to find the issues associated with this project.
261
  #
262
  # Examples:
263
  #   project.project_condition(true)  => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
264
  #   project.project_condition(false) => "projects.id = 1"
265
  def project_condition(with_subprojects)
266
    cond = "#{Project.table_name}.id = #{id}"
267
    cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
268
    cond
269
  end
270

    
271
  def self.find(*args)
272
    if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
273
      project = find_by_identifier(*args)
274
      raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
275
      project
276
    else
277
      super
278
    end
279
  end
280

    
281
  def self.find_by_param(*args)
282
    self.find(*args)
283
  end
284

    
285
  def reload(*args)
286
    @shared_versions = nil
287
    @rolled_up_versions = nil
288
    @rolled_up_trackers = nil
289
    @all_issue_custom_fields = nil
290
    @all_time_entry_custom_fields = nil
291
    @to_param = nil
292
    @allowed_parents = nil
293
    @allowed_permissions = nil
294
    @actions_allowed = nil
295
    super
296
  end
297

    
298
  def to_param
299
    # id is used for projects with a numeric identifier (compatibility)
300
    @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id.to_s : identifier)
301
  end
302

    
303
  def active?
304
    self.status == STATUS_ACTIVE
305
  end
306

    
307
  def archived?
308
    self.status == STATUS_ARCHIVED
309
  end
310

    
311
  # Archives the project and its descendants
312
  def archive
313
    # Check that there is no issue of a non descendant project that is assigned
314
    # to one of the project or descendant versions
315
    v_ids = self_and_descendants.collect {|p| p.version_ids}.flatten
316
    if v_ids.any? && Issue.find(:first, :include => :project,
317
                                        :conditions => ["(#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?)" +
318
                                                        " AND #{Issue.table_name}.fixed_version_id IN (?)", lft, rgt, v_ids])
319
      return false
320
    end
321
    Project.transaction do
322
      archive!
323
    end
324
    true
325
  end
326

    
327
  # Unarchives the project
328
  # All its ancestors must be active
329
  def unarchive
330
    return false if ancestors.detect {|a| !a.active?}
331
    update_attribute :status, STATUS_ACTIVE
332
  end
333

    
334
  def close
335
    self_and_descendants.status(STATUS_ACTIVE).update_all :status => STATUS_CLOSED
336
  end
337

    
338
  def reopen
339
    self_and_descendants.status(STATUS_CLOSED).update_all :status => STATUS_ACTIVE
340
  end
341

    
342
  # Returns an array of projects the project can be moved to
343
  # by the current user
344
  def allowed_parents
345
    return @allowed_parents if @allowed_parents
346
    @allowed_parents = Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_subprojects))
347
    @allowed_parents = @allowed_parents - self_and_descendants
348
    if User.current.allowed_to?(:add_project, nil, :global => true) || (!new_record? && parent.nil?)
349
      @allowed_parents << nil
350
    end
351
    unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
352
      @allowed_parents << parent
353
    end
354
    @allowed_parents
355
  end
356

    
357
  # Sets the parent of the project with authorization check
358
  def set_allowed_parent!(p)
359
    unless p.nil? || p.is_a?(Project)
360
      if p.to_s.blank?
361
        p = nil
362
      else
363
        p = Project.find_by_id(p)
364
        return false unless p
365
      end
366
    end
367
    if p.nil?
368
      if !new_record? && allowed_parents.empty?
369
        return false
370
      end
371
    elsif !allowed_parents.include?(p)
372
      return false
373
    end
374
    set_parent!(p)
375
  end
376

    
377
  # Sets the parent of the project
378
  # Argument can be either a Project, a String, a Fixnum or nil
379
  def set_parent!(p)
380
    unless p.nil? || p.is_a?(Project)
381
      if p.to_s.blank?
382
        p = nil
383
      else
384
        p = Project.find_by_id(p)
385
        return false unless p
386
      end
387
    end
388
    if p == parent && !p.nil?
389
      # Nothing to do
390
      true
391
    elsif p.nil? || (p.active? && move_possible?(p))
392
      set_or_update_position_under(p)
393
      Issue.update_versions_from_hierarchy_change(self)
394
      true
395
    else
396
      # Can not move to the given target
397
      false
398
    end
399
  end
400

    
401
  # Recalculates all lft and rgt values based on project names
402
  # Unlike Project.rebuild!, these values are recalculated even if the tree "looks" valid
403
  # Used in BuildProjectsTree migration
404
  def self.rebuild_tree!
405
    transaction do
406
      update_all "lft = NULL, rgt = NULL"
407
      rebuild!(false)
408
    end
409
  end
410

    
411
  # Returns an array of the trackers used by the project and its active sub projects
412
  def rolled_up_trackers
413
    @rolled_up_trackers ||=
414
      Tracker.find(:all, :joins => :projects,
415
                         :select => "DISTINCT #{Tracker.table_name}.*",
416
                         :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> #{STATUS_ARCHIVED}", lft, rgt],
417
                         :order => "#{Tracker.table_name}.position")
418
  end
419

    
420
  # Closes open and locked project versions that are completed
421
  def close_completed_versions
422
    Version.transaction do
423
      versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version|
424
        if version.completed?
425
          version.update_attribute(:status, 'closed')
426
        end
427
      end
428
    end
429
  end
430

    
431
  # Returns a scope of the Versions on subprojects
432
  def rolled_up_versions
433
    @rolled_up_versions ||=
434
      Version.scoped(:include => :project,
435
                     :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> #{STATUS_ARCHIVED}", lft, rgt])
436
  end
437

    
438
  # Returns a scope of the Versions used by the project
439
  def shared_versions
440
    if new_record?
441
      Version.scoped(:include => :project,
442
                     :conditions => "#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED} AND #{Version.table_name}.sharing = 'system'")
443
    else
444
      @shared_versions ||= begin
445
        r = root? ? self : root
446
        Version.scoped(:include => :project,
447
                       :conditions => "#{Project.table_name}.id = #{id}" +
448
                                      " OR (#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED} AND (" +
449
                                          " #{Version.table_name}.sharing = 'system'" +
450
                                          " OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" +
451
                                          " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
452
                                          " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
453
                                          "))")
454
      end
455
    end
456
  end
457

    
458
  # Returns a hash of project users grouped by role
459
  def users_by_role
460
    members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
461
      m.roles.each do |r|
462
        h[r] ||= []
463
        h[r] << m.user
464
      end
465
      h
466
    end
467
  end
468

    
469
  # Deletes all project's members
470
  def delete_all_members
471
    me, mr = Member.table_name, MemberRole.table_name
472
    connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
473
    Member.delete_all(['project_id = ?', id])
474
  end
475

    
476
  # Users/groups issues can be assigned to
477
  def assignable_users
478
    assignable = Setting.issue_group_assignment? ? member_principals : members
479
    assignable.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.principal}.sort
480
  end
481

    
482
  # Returns the mail adresses of users that should be always notified on project events
483
  def recipients
484
    notified_users.collect {|user| user.mail}
485
  end
486

    
487
  # Returns the users that should be notified on project events
488
  def notified_users
489
    # TODO: User part should be extracted to User#notify_about?
490
    members.select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}.collect {|m| m.principal}
491
  end
492

    
493
  # Returns an array of all custom fields enabled for project issues
494
  # (explictly associated custom fields and custom fields enabled for all projects)
495
  def all_issue_custom_fields
496
    @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
497
  end
498

    
499
  # Returns an array of all custom fields enabled for project time entries
500
  # (explictly associated custom fields and custom fields enabled for all projects)
501
  def all_time_entry_custom_fields
502
    @all_time_entry_custom_fields ||= (TimeEntryCustomField.for_all + time_entry_custom_fields).uniq.sort
503
  end
504

    
505
  def project
506
    self
507
  end
508

    
509
  def <=>(project)
510
    name.downcase <=> project.name.downcase
511
  end
512

    
513
  def to_s
514
    name
515
  end
516

    
517
  # Returns a short description of the projects (first lines)
518
  def short_description(length = 200)
519

    
520
    ## The short description is used in lists, e.g. Latest projects,
521
    ## My projects etc.  It should be no more than a line or two with
522
    ## no text formatting.
523

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

    
528
    ## That can leave too much text for us, and also we want to omit
529
    ## images and the like.  Truncate instead to the first CR that
530
    ## follows _any_ non-blank text, and to the next word break beyond
531
    ## "length" characters if the result is still longer than that.
532
    ##
533
    description.gsub(/![^\s]+!/, '').gsub(/^(\s*[^\n\r]*).*$/m, '\1').gsub(/^(.{#{length}}[^\.;:,-]*).*$/m, '\1 ...').strip if description
534
  end
535

    
536
  def css_classes
537
    s = 'project'
538
    s << ' root' if root?
539
    s << ' child' if child?
540
    s << (leaf? ? ' leaf' : ' parent')
541
    unless active?
542
      if archived?
543
        s << ' archived'
544
      else
545
        s << ' closed'
546
      end
547
    end
548
    s
549
  end
550

    
551
  # The earliest start date of a project, based on it's issues and versions
552
  def start_date
553
    [
554
     issues.minimum('start_date'),
555
     shared_versions.collect(&:effective_date),
556
     shared_versions.collect(&:start_date)
557
    ].flatten.compact.min
558
  end
559

    
560
  # The latest due date of an issue or version
561
  def due_date
562
    [
563
     issues.maximum('due_date'),
564
     shared_versions.collect(&:effective_date),
565
     shared_versions.collect {|v| v.fixed_issues.maximum('due_date')}
566
    ].flatten.compact.max
567
  end
568

    
569
  def overdue?
570
    active? && !due_date.nil? && (due_date < Date.today)
571
  end
572

    
573
  # Returns the percent completed for this project, based on the
574
  # progress on it's versions.
575
  def completed_percent(options={:include_subprojects => false})
576
    if options.delete(:include_subprojects)
577
      total = self_and_descendants.collect(&:completed_percent).sum
578

    
579
      total / self_and_descendants.count
580
    else
581
      if versions.count > 0
582
        total = versions.collect(&:completed_pourcent).sum
583

    
584
        total / versions.count
585
      else
586
        100
587
      end
588
    end
589
  end
590

    
591
  # Return true if this project allows to do the specified action.
592
  # action can be:
593
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
594
  # * a permission Symbol (eg. :edit_project)
595
  def allows_to?(action)
596
    if archived?
597
      # No action allowed on archived projects
598
      return false
599
    end
600
    unless active? || Redmine::AccessControl.read_action?(action)
601
      # No write action allowed on closed projects
602
      return false
603
    end
604
    # No action allowed on disabled modules
605
    if action.is_a? Hash
606
      allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
607
    else
608
      allowed_permissions.include? action
609
    end
610
  end
611

    
612
  def module_enabled?(module_name)
613
    module_name = module_name.to_s
614
    enabled_modules.detect {|m| m.name == module_name}
615
  end
616

    
617
  def enabled_module_names=(module_names)
618
    if module_names && module_names.is_a?(Array)
619
      module_names = module_names.collect(&:to_s).reject(&:blank?)
620
      self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)}
621
    else
622
      enabled_modules.clear
623
    end
624
  end
625

    
626
  # Returns an array of the enabled modules names
627
  def enabled_module_names
628
    enabled_modules.collect(&:name)
629
  end
630

    
631
  # Enable a specific module
632
  #
633
  # Examples:
634
  #   project.enable_module!(:issue_tracking)
635
  #   project.enable_module!("issue_tracking")
636
  def enable_module!(name)
637
    enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name)
638
  end
639

    
640
  # Disable a module if it exists
641
  #
642
  # Examples:
643
  #   project.disable_module!(:issue_tracking)
644
  #   project.disable_module!("issue_tracking")
645
  #   project.disable_module!(project.enabled_modules.first)
646
  def disable_module!(target)
647
    target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target)
648
    target.destroy unless target.blank?
649
  end
650

    
651
  safe_attributes 'name',
652
    'description',
653
    'homepage',
654
    'is_public',
655
    'identifier',
656
    'custom_field_values',
657
    'custom_fields',
658
    'tracker_ids',
659
    'issue_custom_field_ids',
660
    'has_welcome_page'
661

    
662
  safe_attributes 'enabled_module_names',
663
    :if => lambda {|project, user| project.new_record? || user.allowed_to?(:select_project_modules, project) }
664

    
665
  # Returns an array of projects that are in this project's hierarchy
666
  #
667
  # Example: parents, children, siblings
668
  def hierarchy
669
    parents = project.self_and_ancestors || []
670
    descendants = project.descendants || []
671
    project_hierarchy = parents | descendants # Set union
672
  end
673

    
674
  # Returns an auto-generated project identifier based on the last identifier used
675
  def self.next_identifier
676
    p = Project.find(:first, :order => 'created_on DESC')
677
    p.nil? ? nil : p.identifier.to_s.succ
678
  end
679

    
680
  # Copies and saves the Project instance based on the +project+.
681
  # Duplicates the source project's:
682
  # * Wiki
683
  # * Versions
684
  # * Categories
685
  # * Issues
686
  # * Members
687
  # * Queries
688
  #
689
  # Accepts an +options+ argument to specify what to copy
690
  #
691
  # Examples:
692
  #   project.copy(1)                                    # => copies everything
693
  #   project.copy(1, :only => 'members')                # => copies members only
694
  #   project.copy(1, :only => ['members', 'versions'])  # => copies members and versions
695
  def copy(project, options={})
696
    project = project.is_a?(Project) ? project : Project.find(project)
697

    
698
    to_be_copied = %w(wiki versions issue_categories issues members queries boards)
699
    to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
700

    
701
    Project.transaction do
702
      if save
703
        reload
704
        to_be_copied.each do |name|
705
          send "copy_#{name}", project
706
        end
707
        Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
708
        save
709
      end
710
    end
711
  end
712

    
713

    
714
  # Copies +project+ and returns the new instance.  This will not save
715
  # the copy
716
  def self.copy_from(project)
717
    begin
718
      project = project.is_a?(Project) ? project : Project.find(project)
719
      if project
720
        # clear unique attributes
721
        attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
722
        copy = Project.new(attributes)
723
        copy.enabled_modules = project.enabled_modules
724
        copy.trackers = project.trackers
725
        copy.custom_values = project.custom_values.collect {|v| v.clone}
726
        copy.issue_custom_fields = project.issue_custom_fields
727
        return copy
728
      else
729
        return nil
730
      end
731
    rescue ActiveRecord::RecordNotFound
732
      return nil
733
    end
734
  end
735

    
736
  # Yields the given block for each project with its level in the tree
737
  def self.project_tree(projects, &block)
738
    ancestors = []
739
    projects.sort_by(&:lft).each do |project|
740
      while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
741
        ancestors.pop
742
      end
743
      yield project, ancestors.size
744
      ancestors << project
745
    end
746
  end
747

    
748
  private
749

    
750
  # Copies wiki from +project+
751
  def copy_wiki(project)
752
    # Check that the source project has a wiki first
753
    unless project.wiki.nil?
754
      wiki = self.wiki || Wiki.new
755
      wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
756
      wiki_pages_map = {}
757
      project.wiki.pages.each do |page|
758
        # Skip pages without content
759
        next if page.content.nil?
760
        new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
761
        new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
762
        new_wiki_page.content = new_wiki_content
763
        wiki.pages << new_wiki_page
764
        wiki_pages_map[page.id] = new_wiki_page
765
      end
766

    
767
      self.wiki = wiki
768
      wiki.save
769
      # Reproduce page hierarchy
770
      project.wiki.pages.each do |page|
771
        if page.parent_id && wiki_pages_map[page.id]
772
          wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
773
          wiki_pages_map[page.id].save
774
        end
775
      end
776
    end
777
  end
778

    
779
  # Copies versions from +project+
780
  def copy_versions(project)
781
    project.versions.each do |version|
782
      new_version = Version.new
783
      new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
784
      self.versions << new_version
785
    end
786
  end
787

    
788
  # Copies issue categories from +project+
789
  def copy_issue_categories(project)
790
    project.issue_categories.each do |issue_category|
791
      new_issue_category = IssueCategory.new
792
      new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
793
      self.issue_categories << new_issue_category
794
    end
795
  end
796

    
797
  # Copies issues from +project+
798
  def copy_issues(project)
799
    # Stores the source issue id as a key and the copied issues as the
800
    # value.  Used to map the two togeather for issue relations.
801
    issues_map = {}
802

    
803
    # Store status and reopen locked/closed versions
804
    version_statuses = versions.reject(&:open?).map {|version| [version, version.status]}
805
    version_statuses.each do |version, status|
806
      version.update_attribute :status, 'open'
807
    end
808

    
809
    # Get issues sorted by root_id, lft so that parent issues
810
    # get copied before their children
811
    project.issues.find(:all, :order => 'root_id, lft').each do |issue|
812
      new_issue = Issue.new
813
      new_issue.copy_from(issue, :subtasks => false, :link => false)
814
      new_issue.project = self
815
      # Reassign fixed_versions by name, since names are unique per project
816
      if issue.fixed_version && issue.fixed_version.project == project
817
        new_issue.fixed_version = self.versions.detect {|v| v.name == issue.fixed_version.name}
818
      end
819
      # Reassign the category by name, since names are unique per project
820
      if issue.category
821
        new_issue.category = self.issue_categories.detect {|c| c.name == issue.category.name}
822
      end
823
      # Parent issue
824
      if issue.parent_id
825
        if copied_parent = issues_map[issue.parent_id]
826
          new_issue.parent_issue_id = copied_parent.id
827
        end
828
      end
829

    
830
      self.issues << new_issue
831
      if new_issue.new_record?
832
        logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info
833
      else
834
        issues_map[issue.id] = new_issue unless new_issue.new_record?
835
      end
836
    end
837

    
838
    # Restore locked/closed version statuses
839
    version_statuses.each do |version, status|
840
      version.update_attribute :status, status
841
    end
842

    
843
    # Relations after in case issues related each other
844
    project.issues.each do |issue|
845
      new_issue = issues_map[issue.id]
846
      unless new_issue
847
        # Issue was not copied
848
        next
849
      end
850

    
851
      # Relations
852
      issue.relations_from.each do |source_relation|
853
        new_issue_relation = IssueRelation.new
854
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
855
        new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
856
        if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
857
          new_issue_relation.issue_to = source_relation.issue_to
858
        end
859
        new_issue.relations_from << new_issue_relation
860
      end
861

    
862
      issue.relations_to.each do |source_relation|
863
        new_issue_relation = IssueRelation.new
864
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
865
        new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
866
        if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
867
          new_issue_relation.issue_from = source_relation.issue_from
868
        end
869
        new_issue.relations_to << new_issue_relation
870
      end
871
    end
872
  end
873

    
874
  # Copies members from +project+
875
  def copy_members(project)
876
    # Copy users first, then groups to handle members with inherited and given roles
877
    members_to_copy = []
878
    members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)}
879
    members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)}
880

    
881
    members_to_copy.each do |member|
882
      new_member = Member.new
883
      new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
884
      # only copy non inherited roles
885
      # inherited roles will be added when copying the group membership
886
      role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
887
      next if role_ids.empty?
888
      new_member.role_ids = role_ids
889
      new_member.project = self
890
      self.members << new_member
891
    end
892
  end
893

    
894
  # Copies queries from +project+
895
  def copy_queries(project)
896
    project.queries.each do |query|
897
      new_query = ::Query.new
898
      new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
899
      new_query.sort_criteria = query.sort_criteria if query.sort_criteria
900
      new_query.project = self
901
      new_query.user_id = query.user_id
902
      self.queries << new_query
903
    end
904
  end
905

    
906
  # Copies boards from +project+
907
  def copy_boards(project)
908
    project.boards.each do |board|
909
      new_board = Board.new
910
      new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
911
      new_board.project = self
912
      self.boards << new_board
913
    end
914
  end
915

    
916
  def allowed_permissions
917
    @allowed_permissions ||= begin
918
      module_names = enabled_modules.all(:select => :name).collect {|m| m.name}
919
      Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
920
    end
921
  end
922

    
923
  def allowed_actions
924
    @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
925
  end
926

    
927
  # Returns all the active Systemwide and project specific activities
928
  def active_activities
929
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
930

    
931
    if overridden_activity_ids.empty?
932
      return TimeEntryActivity.shared.active
933
    else
934
      return system_activities_and_project_overrides
935
    end
936
  end
937

    
938
  # Returns all the Systemwide and project specific activities
939
  # (inactive and active)
940
  def all_activities
941
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
942

    
943
    if overridden_activity_ids.empty?
944
      return TimeEntryActivity.shared
945
    else
946
      return system_activities_and_project_overrides(true)
947
    end
948
  end
949

    
950
  # Returns the systemwide active activities merged with the project specific overrides
951
  def system_activities_and_project_overrides(include_inactive=false)
952
    if include_inactive
953
      return TimeEntryActivity.shared.
954
        find(:all,
955
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
956
        self.time_entry_activities
957
    else
958
      return TimeEntryActivity.shared.active.
959
        find(:all,
960
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
961
        self.time_entry_activities.active
962
    end
963
  end
964

    
965
  # Archives subprojects recursively
966
  def archive!
967
    children.each do |subproject|
968
      subproject.send :archive!
969
    end
970
    update_attribute :status, STATUS_ARCHIVED
971
  end
972

    
973
  def update_position_under_parent
974
    set_or_update_position_under(parent)
975
  end
976

    
977
  # Inserts/moves the project so that target's children or root projects stay alphabetically sorted
978
  def set_or_update_position_under(target_parent)
979
    sibs = (target_parent.nil? ? self.class.roots : target_parent.children)
980
    to_be_inserted_before = sibs.sort_by {|c| c.name.to_s.downcase}.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
981

    
982
    if to_be_inserted_before
983
      move_to_left_of(to_be_inserted_before)
984
    elsif target_parent.nil?
985
      if sibs.empty?
986
        # move_to_root adds the project in first (ie. left) position
987
        move_to_root
988
      else
989
        move_to_right_of(sibs.last) unless self == sibs.last
990
      end
991
    else
992
      # move_to_child_of adds the project in last (ie.right) position
993
      move_to_child_of(target_parent)
994
    end
995
  end
996
end