Project

General

Profile

Defect #26691 » project.rb

jwjw yy, 2017-08-15 03:27

 
1
# Redmine - project management software
2
# Copyright (C) 2006-2016  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
  include Redmine::NestedSet::ProjectNestedSet
21

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

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

    
30
  # Specific overridden Activities
31
  has_many :time_entry_activities
32
  has_many :memberships, :class_name => 'Member', :inverse_of => :project
33
  # Memberships of active users only
34
  has_many :members,
35
           lambda { joins(:principal).where(:users => {:type => 'User', :status => Principal::STATUS_ACTIVE}) }
36
  has_many :enabled_modules, :dependent => :delete_all
37
  has_and_belongs_to_many :trackers, lambda {order(:position)}
38
  has_many :issues, :dependent => :destroy
39
  has_many :issue_changes, :through => :issues, :source => :journals
40
  has_many :versions, lambda {order("#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC")}, :dependent => :destroy
41
  belongs_to :default_version, :class_name => 'Version'
42
  has_many :time_entries, :dependent => :destroy
43
  has_many :queries, :class_name => 'IssueQuery', :dependent => :delete_all
44
  has_many :documents, :dependent => :destroy
45
  has_many :news, lambda {includes(:author)}, :dependent => :destroy
46
  has_many :issue_categories, lambda {order("#{IssueCategory.table_name}.name")}, :dependent => :delete_all
47
  has_many :boards, lambda {order("position ASC")}, :dependent => :destroy
48
  has_one :repository, lambda {where(["is_default = ?", true])}
49
  has_many :repositories, :dependent => :destroy
50
  has_many :changesets, :through => :repository
51
  has_one :wiki, :dependent => :destroy
52
  # Custom field for the project issues
53
  has_and_belongs_to_many :issue_custom_fields,
54
                          lambda {order("#{CustomField.table_name}.position")},
55
                          :class_name => 'IssueCustomField',
56
                          :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
57
                          :association_foreign_key => 'custom_field_id'
58

    
59
  acts_as_attachable :view_permission => :view_files,
60
                     :edit_permission => :manage_files,
61
                     :delete_permission => :manage_files
62

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

    
69
  attr_protected :status
70

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

    
82
  after_save :update_inherited_members, :if => Proc.new {|project| project.inherit_members_changed?}
83
  after_save :remove_inherited_member_roles, :add_inherited_member_roles, :if => Proc.new {|project| project.parent_id_changed?}
84
  after_update :update_versions_from_hierarchy_change, :if => Proc.new {|project| project.parent_id_changed?}
85
  before_destroy :delete_all_members
86
  
87
  attr_accessor :cached_start_date
88
  
89
  attr_accessor :cached_due_date
90

    
91
  scope :has_module, lambda {|mod|
92
    where("#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s)
93
  }
94
  scope :active, lambda { where(:status => STATUS_ACTIVE) }
95
  scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) }
96
  scope :all_public, lambda { where(:is_public => true) }
97
  scope :visible, lambda {|*args| where(Project.visible_condition(args.shift || User.current, *args)) }
98
  scope :allowed_to, lambda {|*args|
99
    user = User.current
100
    permission = nil
101
    if args.first.is_a?(Symbol)
102
      permission = args.shift
103
    else
104
      user = args.shift
105
      permission = args.shift
106
    end
107
    where(Project.allowed_to_condition(user, permission, *args))
108
  }
109
  scope :like, lambda {|arg|
110
    if arg.blank?
111
      where(nil)
112
    else
113
      pattern = "%#{arg.to_s.strip.downcase}%"
114
      where("LOWER(identifier) LIKE :p OR LOWER(name) LIKE :p", :p => pattern)
115
    end
116
  }
117
  scope :sorted, lambda {order(:lft)}
118
  scope :having_trackers, lambda {
119
    where("#{Project.table_name}.id IN (SELECT DISTINCT project_id FROM #{table_name_prefix}projects_trackers#{table_name_suffix})")
120
  }
121

    
122
  def initialize(attributes=nil, *args)
123
    super
124

    
125
    initialized = (attributes || {}).stringify_keys
126
    if !initialized.key?('identifier') && Setting.sequential_project_identifiers?
127
      self.identifier = Project.next_identifier
128
    end
129
    if !initialized.key?('is_public')
130
      self.is_public = Setting.default_projects_public?
131
    end
132
    if !initialized.key?('enabled_module_names')
133
      self.enabled_module_names = Setting.default_projects_modules
134
    end
135
    if !initialized.key?('trackers') && !initialized.key?('tracker_ids')
136
      default = Setting.default_projects_tracker_ids
137
      if default.is_a?(Array)
138
        self.trackers = Tracker.where(:id => default.map(&:to_i)).sorted.to_a
139
      else
140
        self.trackers = Tracker.sorted.to_a
141
      end
142
    end
143
  end
144

    
145
  def identifier=(identifier)
146
    super unless identifier_frozen?
147
  end
148

    
149
  def identifier_frozen?
150
    errors[:identifier].blank? && !(new_record? || identifier.blank?)
151
  end
152

    
153
  # returns latest created projects
154
  # non public projects will be returned only if user is a member of those
155
  def self.latest(user=nil, count=5)
156
    visible(user).limit(count).
157
      order(:created_on => :desc).
158
      where("#{table_name}.created_on >= ?", 30.days.ago).
159
      to_a
160
  end
161

    
162
  # Returns true if the project is visible to +user+ or to the current user.
163
  def visible?(user=User.current)
164
    user.allowed_to?(:view_project, self)
165
  end
166

    
167
  # Returns a SQL conditions string used to find all projects visible by the specified user.
168
  #
169
  # Examples:
170
  #   Project.visible_condition(admin)        => "projects.status = 1"
171
  #   Project.visible_condition(normal_user)  => "((projects.status = 1) AND (projects.is_public = 1 OR projects.id IN (1,3,4)))"
172
  #   Project.visible_condition(anonymous)    => "((projects.status = 1) AND (projects.is_public = 1))"
173
  def self.visible_condition(user, options={})
174
    allowed_to_condition(user, :view_project, options)
175
  end
176

    
177
  # Returns a SQL conditions string used to find all projects for which +user+ has the given +permission+
178
  #
179
  # Valid options:
180
  # * :project => limit the condition to project
181
  # * :with_subprojects => limit the condition to project and its subprojects
182
  # * :member => limit the condition to the user projects
183
  def self.allowed_to_condition(user, permission, options={})
184
    perm = Redmine::AccessControl.permission(permission)
185
    base_statement = (perm && perm.read? ? "#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED}" : "#{Project.table_name}.status = #{Project::STATUS_ACTIVE}")
186
    if perm && perm.project_module
187
      # If the permission belongs to a project module, make sure the module is enabled
188
      base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
189
    end
190
    if project = options[:project]
191
      project_statement = project.project_condition(options[:with_subprojects])
192
      base_statement = "(#{project_statement}) AND (#{base_statement})"
193
    end
194

    
195
    if user.admin?
196
      base_statement
197
    else
198
      statement_by_role = {}
199
      unless options[:member]
200
        role = user.builtin_role
201
        if role.allowed_to?(permission)
202
          s = "#{Project.table_name}.is_public = #{connection.quoted_true}"
203
          if user.id
204
            group = role.anonymous? ? Group.anonymous : Group.non_member
205
            principal_ids = [user.id, group.id].compact
206
            s = "(#{s} AND #{Project.table_name}.id NOT IN (SELECT project_id FROM #{Member.table_name} WHERE user_id IN (#{principal_ids.join(',')})))"
207
          end
208
          statement_by_role[role] = s
209
        end
210
      end
211
      user.project_ids_by_role.each do |role, project_ids|
212
        if role.allowed_to?(permission) && project_ids.any?
213
          statement_by_role[role] = "#{Project.table_name}.id IN (#{project_ids.join(',')})"
214
        end
215
      end
216
      if statement_by_role.empty?
217
        "1=0"
218
      else
219
        if block_given?
220
          statement_by_role.each do |role, statement|
221
            if s = yield(role, user)
222
              statement_by_role[role] = "(#{statement} AND (#{s}))"
223
            end
224
          end
225
        end
226
        "((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))"
227
      end
228
    end
229
  end
230

    
231
  def override_roles(role)
232
    @override_members ||= memberships.
233
      joins(:principal).
234
      where(:users => {:type => ['GroupAnonymous', 'GroupNonMember']}).to_a
235

    
236
    group_class = role.anonymous? ? GroupAnonymous : GroupNonMember
237
    member = @override_members.detect {|m| m.principal.is_a? group_class}
238
    member ? member.roles.to_a : [role]
239
  end
240

    
241
  def principals
242
    @principals ||= Principal.active.joins(:members).where("#{Member.table_name}.project_id = ?", id).distinct
243
  end
244

    
245
  def users
246
    @users ||= User.active.joins(:members).where("#{Member.table_name}.project_id = ?", id).distinct
247
  end
248

    
249
  # Returns the Systemwide and project specific activities
250
  def activities(include_inactive=false)
251
    t = TimeEntryActivity.table_name
252
    scope = TimeEntryActivity.where("#{t}.project_id IS NULL OR #{t}.project_id = ?", id)
253

    
254
    overridden_activity_ids = self.time_entry_activities.pluck(:parent_id).compact
255
    if overridden_activity_ids.any?
256
      scope = scope.where("#{t}.id NOT IN (?)", overridden_activity_ids)
257
    end
258
    unless include_inactive
259
      scope = scope.active
260
    end
261
    scope
262
  end
263

    
264
  # Will create a new Project specific Activity or update an existing one
265
  #
266
  # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
267
  # does not successfully save.
268
  def update_or_create_time_entry_activity(id, activity_hash)
269
    if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
270
      self.create_time_entry_activity_if_needed(activity_hash)
271
    else
272
      activity = project.time_entry_activities.find_by_id(id.to_i)
273
      activity.update_attributes(activity_hash) if activity
274
    end
275
  end
276

    
277
  # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
278
  #
279
  # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
280
  # does not successfully save.
281
  def create_time_entry_activity_if_needed(activity)
282
    if activity['parent_id']
283
      parent_activity = TimeEntryActivity.find(activity['parent_id'])
284
      activity['name'] = parent_activity.name
285
      activity['position'] = parent_activity.position
286
      if Enumeration.overriding_change?(activity, parent_activity)
287
        project_activity = self.time_entry_activities.create(activity)
288
        if project_activity.new_record?
289
          raise ActiveRecord::Rollback, "Overriding TimeEntryActivity was not successfully saved"
290
        else
291
          self.time_entries.
292
            where(:activity_id => parent_activity.id).
293
            update_all(:activity_id => project_activity.id)
294
        end
295
      end
296
    end
297
  end
298

    
299
  # Returns a :conditions SQL string that can be used to find the issues associated with this project.
300
  #
301
  # Examples:
302
  #   project.project_condition(true)  => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
303
  #   project.project_condition(false) => "projects.id = 1"
304
  def project_condition(with_subprojects)
305
    cond = "#{Project.table_name}.id = #{id}"
306
    cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
307
    cond
308
  end
309

    
310
  def self.find(*args)
311
    if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
312
      project = find_by_identifier(*args)
313
      raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
314
      project
315
    else
316
      super
317
    end
318
  end
319

    
320
  def self.find_by_param(*args)
321
    self.find(*args)
322
  end
323

    
324
  alias :base_reload :reload
325
  def reload(*args)
326
    @principals = nil
327
    @users = nil
328
    @shared_versions = nil
329
    @rolled_up_versions = nil
330
    @rolled_up_trackers = nil
331
    @all_issue_custom_fields = nil
332
    @all_time_entry_custom_fields = nil
333
    @to_param = nil
334
    @allowed_parents = nil
335
    @allowed_permissions = nil
336
    @actions_allowed = nil
337
    @start_date = nil
338
    @due_date = nil
339
    @override_members = nil
340
    @assignable_users = nil
341
    base_reload(*args)
342
  end
343

    
344
  def to_param
345
    if new_record?
346
      nil
347
    else
348
      # id is used for projects with a numeric identifier (compatibility)
349
      @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id.to_s : identifier)
350
    end
351
  end
352

    
353
  def active?
354
    self.status == STATUS_ACTIVE
355
  end
356

    
357
  def closed?
358
    self.status == STATUS_CLOSED
359
  end
360

    
361
  def archived?
362
    self.status == STATUS_ARCHIVED
363
  end
364

    
365
  # Archives the project and its descendants
366
  def archive
367
    # Check that there is no issue of a non descendant project that is assigned
368
    # to one of the project or descendant versions
369
    version_ids = self_and_descendants.joins(:versions).pluck("#{Version.table_name}.id")
370

    
371
    if version_ids.any? &&
372
      Issue.
373
        includes(:project).
374
        where("#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?", lft, rgt).
375
        where(:fixed_version_id => version_ids).
376
        exists?
377
      return false
378
    end
379
    Project.transaction do
380
      archive!
381
    end
382
    true
383
  end
384

    
385
  # Unarchives the project
386
  # All its ancestors must be active
387
  def unarchive
388
    return false if ancestors.detect {|a| a.archived?}
389
    new_status = STATUS_ACTIVE
390
    if parent
391
      new_status = parent.status
392
    end
393
    update_attribute :status, new_status
394
  end
395

    
396
  def close
397
    self_and_descendants.status(STATUS_ACTIVE).update_all :status => STATUS_CLOSED
398
  end
399

    
400
  def reopen
401
    self_and_descendants.status(STATUS_CLOSED).update_all :status => STATUS_ACTIVE
402
  end
403

    
404
  # Returns an array of projects the project can be moved to
405
  # by the current user
406
  def allowed_parents(user=User.current)
407
    return @allowed_parents if @allowed_parents
408
    @allowed_parents = Project.allowed_to(user, :add_subprojects).to_a
409
    @allowed_parents = @allowed_parents - self_and_descendants
410
    if user.allowed_to?(:add_project, nil, :global => true) || (!new_record? && parent.nil?)
411
      @allowed_parents << nil
412
    end
413
    unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
414
      @allowed_parents << parent
415
    end
416
    @allowed_parents
417
  end
418

    
419
  # Sets the parent of the project with authorization check
420
  def set_allowed_parent!(p)
421
    ActiveSupport::Deprecation.warn "Project#set_allowed_parent! is deprecated and will be removed in Redmine 4, use #safe_attributes= instead."
422
    p = p.id if p.is_a?(Project)
423
    send :safe_attributes, {:project_id => p}
424
    save
425
  end
426

    
427
  # Sets the parent of the project and saves the project
428
  # Argument can be either a Project, a String, a Fixnum or nil
429
  def set_parent!(p)
430
    if p.is_a?(Project)
431
      self.parent = p
432
    else
433
      self.parent_id = p
434
    end
435
    save
436
  end
437

    
438
  # Returns a scope of the trackers used by the project and its active sub projects
439
  def rolled_up_trackers(include_subprojects=true)
440
    if include_subprojects
441
      @rolled_up_trackers ||= rolled_up_trackers_base_scope.
442
          where("#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ?", lft, rgt)
443
    else
444
      rolled_up_trackers_base_scope.
445
        where(:projects => {:id => id})
446
    end
447
  end
448

    
449
  def rolled_up_trackers_base_scope
450
    Tracker.
451
      joins(projects: :enabled_modules).
452
      where("#{Project.table_name}.status <> ?", STATUS_ARCHIVED).
453
      where(:enabled_modules => {:name => 'issue_tracking'}).
454
      distinct.
455
      sorted
456
  end
457

    
458
  # Closes open and locked project versions that are completed
459
  def close_completed_versions
460
    Version.transaction do
461
      versions.where(:status => %w(open locked)).each do |version|
462
        if version.completed?
463
          version.update_attribute(:status, 'closed')
464
        end
465
      end
466
    end
467
  end
468

    
469
  # Returns a scope of the Versions on subprojects
470
  def rolled_up_versions
471
    @rolled_up_versions ||=
472
      Version.
473
        joins(:project).
474
        where("#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> ?", lft, rgt, STATUS_ARCHIVED)
475
  end
476

    
477
  # Returns a scope of the Versions used by the project
478
  def shared_versions
479
    if new_record?
480
      Version.
481
        joins(:project).
482
        preload(:project).
483
        where("#{Project.table_name}.status <> ? AND #{Version.table_name}.sharing = 'system'", STATUS_ARCHIVED)
484
    else
485
      @shared_versions ||= begin
486
        r = root? ? self : root
487
        Version.
488
          joins(:project).
489
          preload(:project).
490
          where("#{Project.table_name}.id = #{id}" +
491
                  " OR (#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED} AND (" +
492
                    " #{Version.table_name}.sharing = 'system'" +
493
                    " OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" +
494
                    " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
495
                    " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
496
                  "))")
497
      end
498
    end
499
  end
500

    
501
  # Returns a hash of project users grouped by role
502
  def users_by_role
503
    members.includes(:user, :roles).inject({}) do |h, m|
504
      m.roles.each do |r|
505
        h[r] ||= []
506
        h[r] << m.user
507
      end
508
      h
509
    end
510
  end
511

    
512
  # Adds user as a project member with the default role
513
  # Used for when a non-admin user creates a project
514
  def add_default_member(user)
515
    role = self.class.default_member_role
516
    member = Member.new(:project => self, :principal => user, :roles => [role])
517
    self.members << member
518
    member
519
  end
520

    
521
	# Default role that is given to non-admin users that
522
	# create a project
523
  def self.default_member_role
524
    Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first
525
  end
526

    
527
  # Deletes all project's members
528
  def delete_all_members
529
    me, mr = Member.table_name, MemberRole.table_name
530
    self.class.connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
531
    Member.where(:project_id => id).delete_all
532
  end
533

    
534
  # Return a Principal scope of users/groups issues can be assigned to
535
  def assignable_users(tracker=nil)
536
    return @assignable_users[tracker] if @assignable_users && @assignable_users[tracker]
537

    
538
    types = ['User']
539
    types << 'Group' if Setting.issue_group_assignment?
540

    
541
    scope = Principal.
542
      active.
543
      joins(:members => :roles).
544
      where(:type => types, :members => {:project_id => id}, :roles => {:assignable => true}).
545
      distinct.
546
      sorted
547

    
548
    if tracker
549
      # Rejects users that cannot the view the tracker
550
      roles = Role.where(:assignable => true).select {|role| role.permissions_tracker?(:view_issues, tracker)}
551
      scope = scope.where(:roles => {:id => roles.map(&:id)})
552
    end
553

    
554
    @assignable_users ||= {}
555
    @assignable_users[tracker] = scope
556
  end
557

    
558
  # Returns the mail addresses of users that should be always notified on project events
559
  def recipients
560
    notified_users.collect {|user| user.mail}
561
  end
562

    
563
  # Returns the users that should be notified on project events
564
  def notified_users
565
    # TODO: User part should be extracted to User#notify_about?
566
    members.preload(:principal).select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}.collect {|m| m.principal}
567
  end
568

    
569
  # Returns a scope of all custom fields enabled for project issues
570
  # (explicitly associated custom fields and custom fields enabled for all projects)
571
  def all_issue_custom_fields
572
    if new_record?
573
      @all_issue_custom_fields ||= IssueCustomField.
574
        sorted.
575
        where("is_for_all = ? OR id IN (?)", true, issue_custom_field_ids)
576
    else
577
      @all_issue_custom_fields ||= IssueCustomField.
578
        sorted.
579
        where("is_for_all = ? OR id IN (SELECT DISTINCT cfp.custom_field_id" +
580
          " FROM #{table_name_prefix}custom_fields_projects#{table_name_suffix} cfp" +
581
          " WHERE cfp.project_id = ?)", true, id)
582
    end
583
  end
584

    
585
  def project
586
    self
587
  end
588

    
589
  def <=>(project)
590
    name.casecmp(project.name)
591
  end
592

    
593
  def to_s
594
    name
595
  end
596

    
597
  # Returns a short description of the projects (first lines)
598
  def short_description(length = 255)
599
    description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
600
  end
601

    
602
  def css_classes
603
    s = 'project'
604
    s << ' root' if root?
605
    s << ' child' if child?
606
    s << (leaf? ? ' leaf' : ' parent')
607
    unless active?
608
      if archived?
609
        s << ' archived'
610
      else
611
        s << ' closed'
612
      end
613
    end
614
    s
615
  end
616

    
617
  # The earliest start date of a project, based on it's issues and versions
618
  def start_date
619
    #@start_date ||= [
620
    # issues.minimum('start_date'),
621
    # shared_versions.minimum('effective_date'),
622
    # Issue.fixed_version(shared_versions).minimum('start_date')
623
    #].compact.min
624
    @start_date = cached_start_date || issues.minimum('start_date')
625
  end
626

    
627
  # The latest due date of an issue or version
628
  def due_date
629
    @due_date = cached_due_date|| issues.maximum('due_date')
630
    #@due_date ||= [
631
    # issues.maximum('due_date') ,
632
    # shared_versions.maximum('effective_date'),
633
    # Issue.fixed_version(shared_versions).maximum('due_date')
634
    #].compact.max
635
  end
636

    
637
  def overdue?
638
    active? && !due_date.nil?  && (due_date < User.current.today)
639
  end
640

    
641
  # Returns the percent completed for this project, based on the
642
  # progress on it's versions.
643
  def completed_percent(options={:include_subprojects => false})
644
    if options.delete(:include_subprojects)
645
      total = self_and_descendants.collect(&:completed_percent).sum
646

    
647
      total / self_and_descendants.count
648
    else
649
      if versions.count > 0
650
        total = versions.collect(&:completed_percent).sum
651

    
652
        total / versions.count
653
      else
654
        100
655
      end
656
    end
657
  end
658

    
659
  # Return true if this project allows to do the specified action.
660
  # action can be:
661
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
662
  # * a permission Symbol (eg. :edit_project)
663
  def allows_to?(action)
664
    if archived?
665
      # No action allowed on archived projects
666
      return false
667
    end
668
    unless active? || Redmine::AccessControl.read_action?(action)
669
      # No write action allowed on closed projects
670
      return false
671
    end
672
    # No action allowed on disabled modules
673
    if action.is_a? Hash
674
      allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
675
    else
676
      allowed_permissions.include? action
677
    end
678
  end
679

    
680
  # Return the enabled module with the given name
681
  # or nil if the module is not enabled for the project
682
  def enabled_module(name)
683
    name = name.to_s
684
    enabled_modules.detect {|m| m.name == name}
685
  end
686

    
687
  # Return true if the module with the given name is enabled
688
  def module_enabled?(name)
689
    enabled_module(name).present?
690
  end
691

    
692
  def enabled_module_names=(module_names)
693
    if module_names && module_names.is_a?(Array)
694
      module_names = module_names.collect(&:to_s).reject(&:blank?)
695
      self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)}
696
    else
697
      enabled_modules.clear
698
    end
699
  end
700

    
701
  # Returns an array of the enabled modules names
702
  def enabled_module_names
703
    enabled_modules.collect(&:name)
704
  end
705

    
706
  # Enable a specific module
707
  #
708
  # Examples:
709
  #   project.enable_module!(:issue_tracking)
710
  #   project.enable_module!("issue_tracking")
711
  def enable_module!(name)
712
    enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name)
713
  end
714

    
715
  # Disable a module if it exists
716
  #
717
  # Examples:
718
  #   project.disable_module!(:issue_tracking)
719
  #   project.disable_module!("issue_tracking")
720
  #   project.disable_module!(project.enabled_modules.first)
721
  def disable_module!(target)
722
    target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target)
723
    target.destroy unless target.blank?
724
  end
725

    
726
  safe_attributes 'name',
727
    'description',
728
    'homepage',
729
    'is_public',
730
    'identifier',
731
    'custom_field_values',
732
    'custom_fields',
733
    'tracker_ids',
734
    'issue_custom_field_ids',
735
    'parent_id',
736
    'default_version_id'
737

    
738
  safe_attributes 'enabled_module_names',
739
    :if => lambda {|project, user|
740
        if project.new_record?
741
          if user.admin?
742
            true
743
          else
744
            default_member_role.has_permission?(:select_project_modules)
745
          end
746
        else
747
          user.allowed_to?(:select_project_modules, project)
748
        end
749
      }
750

    
751
  safe_attributes 'inherit_members',
752
    :if => lambda {|project, user| project.parent.nil? || project.parent.visible?(user)}
753

    
754
  def safe_attributes=(attrs, user=User.current)
755
    return unless attrs.is_a?(Hash)
756
    attrs = attrs.deep_dup
757

    
758
    @unallowed_parent_id = nil
759
    if new_record? || attrs.key?('parent_id')
760
      parent_id_param = attrs['parent_id'].to_s
761
      if new_record? || parent_id_param != parent_id.to_s
762
        p = parent_id_param.present? ? Project.find_by_id(parent_id_param) : nil
763
        unless allowed_parents(user).include?(p)
764
          attrs.delete('parent_id')
765
          @unallowed_parent_id = true
766
        end
767
      end
768
    end
769

    
770
    super(attrs, user)
771
  end
772

    
773
  # Returns an auto-generated project identifier based on the last identifier used
774
  def self.next_identifier
775
    p = Project.order('id DESC').first
776
    p.nil? ? nil : p.identifier.to_s.succ
777
  end
778

    
779
  # Copies and saves the Project instance based on the +project+.
780
  # Duplicates the source project's:
781
  # * Wiki
782
  # * Versions
783
  # * Categories
784
  # * Issues
785
  # * Members
786
  # * Queries
787
  #
788
  # Accepts an +options+ argument to specify what to copy
789
  #
790
  # Examples:
791
  #   project.copy(1)                                    # => copies everything
792
  #   project.copy(1, :only => 'members')                # => copies members only
793
  #   project.copy(1, :only => ['members', 'versions'])  # => copies members and versions
794
  def copy(project, options={})
795
    project = project.is_a?(Project) ? project : Project.find(project)
796

    
797
    to_be_copied = %w(members wiki versions issue_categories issues queries boards)
798
    to_be_copied = to_be_copied & Array.wrap(options[:only]) unless options[:only].nil?
799

    
800
    Project.transaction do
801
      if save
802
        reload
803
        to_be_copied.each do |name|
804
          send "copy_#{name}", project
805
        end
806
        Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
807
        save
808
      else
809
        false
810
      end
811
    end
812
  end
813

    
814
  def member_principals
815
    ActiveSupport::Deprecation.warn "Project#member_principals is deprecated and will be removed in Redmine 4.0. Use #memberships.active instead."
816
    memberships.active
817
  end
818

    
819
  # Returns a new unsaved Project instance with attributes copied from +project+
820
  def self.copy_from(project)
821
    project = project.is_a?(Project) ? project : Project.find(project)
822
    # clear unique attributes
823
    attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
824
    copy = Project.new(attributes)
825
    copy.enabled_module_names = project.enabled_module_names
826
    copy.trackers = project.trackers
827
    copy.custom_values = project.custom_values.collect {|v| v.clone}
828
    copy.issue_custom_fields = project.issue_custom_fields
829
    copy
830
  end
831

    
832
  # Yields the given block for each project with its level in the tree
833
  def self.project_tree(projects, options={}, &block)
834

    
835
    start_dates = Issue.where(project_id: projects).group(:project_id).minimum(:start_date)
836
    due_dates = Issue.where(project_id: projects).group(:project_id).maximum(:due_date)
837
    projects.each do |project|
838
      if start_dates[project.id]
839
        project.cached_start_date = Date.new(start_dates[project.id])
840
      else
841
        project.cached_start_date = Time.now.to_date
842
      end
843
      if due_dates[project.id]
844
        project.cached_due_date = Date.new(due_dates[project.id])
845
      else
846
        project.cached_due_date = Time.now.to_date
847
      end
848
      
849
    end
850

    
851
    ancestors = []
852
    if options[:init_level] && projects.first
853
      ancestors = projects.first.ancestors.to_a
854
    end
855
    projects.sort_by(&:lft).each do |project|
856
      while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
857
        ancestors.pop
858
      end
859
      yield project, ancestors.size
860
      ancestors << project
861
    end
862
  end
863

    
864
  private
865

    
866
  def update_inherited_members
867
    if parent
868
      if inherit_members? && !inherit_members_was
869
        remove_inherited_member_roles
870
        add_inherited_member_roles
871
      elsif !inherit_members? && inherit_members_was
872
        remove_inherited_member_roles
873
      end
874
    end
875
  end
876

    
877
  def remove_inherited_member_roles
878
    member_roles = MemberRole.where(:member_id => membership_ids).to_a
879
    member_role_ids = member_roles.map(&:id)
880
    member_roles.each do |member_role|
881
      if member_role.inherited_from && !member_role_ids.include?(member_role.inherited_from)
882
        member_role.destroy
883
      end
884
    end
885
  end
886

    
887
  def add_inherited_member_roles
888
    if inherit_members? && parent
889
      parent.memberships.each do |parent_member|
890
        member = Member.find_or_new(self.id, parent_member.user_id)
891
        parent_member.member_roles.each do |parent_member_role|
892
          member.member_roles << MemberRole.new(:role => parent_member_role.role, :inherited_from => parent_member_role.id)
893
        end
894
        member.save!
895
      end
896
      memberships.reset
897
    end
898
  end
899

    
900
  def update_versions_from_hierarchy_change
901
    Issue.update_versions_from_hierarchy_change(self)
902
  end
903

    
904
  def validate_parent
905
    if @unallowed_parent_id
906
      errors.add(:parent_id, :invalid)
907
    elsif parent_id_changed?
908
      unless parent.nil? || (parent.active? && move_possible?(parent))
909
        errors.add(:parent_id, :invalid)
910
      end
911
    end
912
  end
913

    
914
  # Copies wiki from +project+
915
  def copy_wiki(project)
916
    # Check that the source project has a wiki first
917
    unless project.wiki.nil?
918
      wiki = self.wiki || Wiki.new
919
      wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
920
      wiki_pages_map = {}
921
      project.wiki.pages.each do |page|
922
        # Skip pages without content
923
        next if page.content.nil?
924
        new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
925
        new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
926
        new_wiki_page.content = new_wiki_content
927
        wiki.pages << new_wiki_page
928
        wiki_pages_map[page.id] = new_wiki_page
929
      end
930

    
931
      self.wiki = wiki
932
      wiki.save
933
      # Reproduce page hierarchy
934
      project.wiki.pages.each do |page|
935
        if page.parent_id && wiki_pages_map[page.id]
936
          wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
937
          wiki_pages_map[page.id].save
938
        end
939
      end
940
    end
941
  end
942

    
943
  # Copies versions from +project+
944
  def copy_versions(project)
945
    project.versions.each do |version|
946
      new_version = Version.new
947
      new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
948
      self.versions << new_version
949
    end
950
  end
951

    
952
  # Copies issue categories from +project+
953
  def copy_issue_categories(project)
954
    project.issue_categories.each do |issue_category|
955
      new_issue_category = IssueCategory.new
956
      new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
957
      self.issue_categories << new_issue_category
958
    end
959
  end
960

    
961
  # Copies issues from +project+
962
  def copy_issues(project)
963
    # Stores the source issue id as a key and the copied issues as the
964
    # value.  Used to map the two together for issue relations.
965
    issues_map = {}
966

    
967
    # Store status and reopen locked/closed versions
968
    version_statuses = versions.reject(&:open?).map {|version| [version, version.status]}
969
    version_statuses.each do |version, status|
970
      version.update_attribute :status, 'open'
971
    end
972

    
973
    # Get issues sorted by root_id, lft so that parent issues
974
    # get copied before their children
975
    project.issues.reorder('root_id, lft').each do |issue|
976
      new_issue = Issue.new
977
      new_issue.copy_from(issue, :subtasks => false, :link => false)
978
      new_issue.project = self
979
      # Changing project resets the custom field values
980
      # TODO: handle this in Issue#project=
981
      new_issue.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
982
      # Reassign fixed_versions by name, since names are unique per project
983
      if issue.fixed_version && issue.fixed_version.project == project
984
        new_issue.fixed_version = self.versions.detect {|v| v.name == issue.fixed_version.name}
985
      end
986
      # Reassign version custom field values
987
      new_issue.custom_field_values.each do |custom_value|
988
        if custom_value.custom_field.field_format == 'version' && custom_value.value.present?
989
          versions = Version.where(:id => custom_value.value).to_a
990
          new_value = versions.map do |version|
991
            if version.project == project
992
              self.versions.detect {|v| v.name == version.name}.try(:id)
993
            else
994
              version.id
995
            end
996
          end
997
          new_value.compact!
998
          new_value = new_value.first unless custom_value.custom_field.multiple?
999
          custom_value.value = new_value
1000
        end
1001
      end
1002
      # Reassign the category by name, since names are unique per project
1003
      if issue.category
1004
        new_issue.category = self.issue_categories.detect {|c| c.name == issue.category.name}
1005
      end
1006
      # Parent issue
1007
      if issue.parent_id
1008
        if copied_parent = issues_map[issue.parent_id]
1009
          new_issue.parent_issue_id = copied_parent.id
1010
        end
1011
      end
1012

    
1013
      self.issues << new_issue
1014
      if new_issue.new_record?
1015
        logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info?
1016
      else
1017
        issues_map[issue.id] = new_issue unless new_issue.new_record?
1018
      end
1019
    end
1020

    
1021
    # Restore locked/closed version statuses
1022
    version_statuses.each do |version, status|
1023
      version.update_attribute :status, status
1024
    end
1025

    
1026
    # Relations after in case issues related each other
1027
    project.issues.each do |issue|
1028
      new_issue = issues_map[issue.id]
1029
      unless new_issue
1030
        # Issue was not copied
1031
        next
1032
      end
1033

    
1034
      # Relations
1035
      issue.relations_from.each do |source_relation|
1036
        new_issue_relation = IssueRelation.new
1037
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
1038
        new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
1039
        if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
1040
          new_issue_relation.issue_to = source_relation.issue_to
1041
        end
1042
        new_issue.relations_from << new_issue_relation
1043
      end
1044

    
1045
      issue.relations_to.each do |source_relation|
1046
        new_issue_relation = IssueRelation.new
1047
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
1048
        new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
1049
        if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
1050
          new_issue_relation.issue_from = source_relation.issue_from
1051
        end
1052
        new_issue.relations_to << new_issue_relation
1053
      end
1054
    end
1055
  end
1056

    
1057
  # Copies members from +project+
1058
  def copy_members(project)
1059
    # Copy users first, then groups to handle members with inherited and given roles
1060
    members_to_copy = []
1061
    members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)}
1062
    members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)}
1063

    
1064
    members_to_copy.each do |member|
1065
      new_member = Member.new
1066
      new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
1067
      # only copy non inherited roles
1068
      # inherited roles will be added when copying the group membership
1069
      role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
1070
      next if role_ids.empty?
1071
      new_member.role_ids = role_ids
1072
      new_member.project = self
1073
      self.members << new_member
1074
    end
1075
  end
1076

    
1077
  # Copies queries from +project+
1078
  def copy_queries(project)
1079
    project.queries.each do |query|
1080
      new_query = IssueQuery.new
1081
      new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria", "user_id", "type")
1082
      new_query.sort_criteria = query.sort_criteria if query.sort_criteria
1083
      new_query.project = self
1084
      new_query.user_id = query.user_id
1085
      new_query.role_ids = query.role_ids if query.visibility == IssueQuery::VISIBILITY_ROLES
1086
      self.queries << new_query
1087
    end
1088
  end
1089

    
1090
  # Copies boards from +project+
1091
  def copy_boards(project)
1092
    project.boards.each do |board|
1093
      new_board = Board.new
1094
      new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
1095
      new_board.project = self
1096
      self.boards << new_board
1097
    end
1098
  end
1099

    
1100
  def allowed_permissions
1101
    @allowed_permissions ||= begin
1102
      module_names = enabled_modules.loaded? ? enabled_modules.map(&:name) : enabled_modules.pluck(:name)
1103
      Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
1104
    end
1105
  end
1106

    
1107
  def allowed_actions
1108
    @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
1109
  end
1110

    
1111
  # Archives subprojects recursively
1112
  def archive!
1113
    children.each do |subproject|
1114
      subproject.send :archive!
1115
    end
1116
    update_attribute :status, STATUS_ARCHIVED
1117
  end
1118
end
(1-1/2)