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 @ 443:350acce374a2

History | View | Annotate | Download (32.2 KB)

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