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 @ 442:753f1380d6bc

History | View | Annotate | Download (32.1 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 130:db0caa9f0ff4 chris
    ## Original Redmine code: this truncates to the CR that is more
472
    ## than "length" characters from the start.
473
    # description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
474
    ## That's too much for us, and also we want to omit images and the
475
    ## like.  Truncate instead to the first CR that follows _any_
476
    ## non-blank text, and to the next word break beyond "length"
477
    ## characters if the result is still longer than that.
478
    description.gsub(/![^\s]+!/, '').gsub(/^(\s*[^\n\r]*).*$/m, '\1').gsub(/^(.{#{length}}\b).*$/m, '\1 ...').strip if description
479 0:513646585e45 Chris
  end
480 22:40f7cfd4df19 chris
481
  def css_classes
482
    s = 'project'
483
    s << ' root' if root?
484
    s << ' child' if child?
485
    s << (leaf? ? ' leaf' : ' parent')
486
    s
487
  end
488
489
  # The earliest start date of a project, based on it's issues and versions
490
  def start_date
491 117:af80e5618e9b Chris
    [
492
     issues.minimum('start_date'),
493
     shared_versions.collect(&:effective_date),
494
     shared_versions.collect(&:start_date)
495
    ].flatten.compact.min
496 22:40f7cfd4df19 chris
  end
497
498
  # The latest due date of an issue or version
499
  def due_date
500 117:af80e5618e9b Chris
    [
501
     issues.maximum('due_date'),
502
     shared_versions.collect(&:effective_date),
503
     shared_versions.collect {|v| v.fixed_issues.maximum('due_date')}
504
    ].flatten.compact.max
505 22:40f7cfd4df19 chris
  end
506
507
  def overdue?
508
    active? && !due_date.nil? && (due_date < Date.today)
509
  end
510
511
  # Returns the percent completed for this project, based on the
512
  # progress on it's versions.
513
  def completed_percent(options={:include_subprojects => false})
514
    if options.delete(:include_subprojects)
515
      total = self_and_descendants.collect(&:completed_percent).sum
516
517
      total / self_and_descendants.count
518
    else
519
      if versions.count > 0
520
        total = versions.collect(&:completed_pourcent).sum
521
522
        total / versions.count
523
      else
524
        100
525
      end
526
    end
527
  end
528 0:513646585e45 Chris
529
  # Return true if this project is allowed to do the specified action.
530
  # action can be:
531
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
532
  # * a permission Symbol (eg. :edit_project)
533
  def allows_to?(action)
534
    if action.is_a? Hash
535
      allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
536
    else
537
      allowed_permissions.include? action
538
    end
539
  end
540
541
  def module_enabled?(module_name)
542
    module_name = module_name.to_s
543
    enabled_modules.detect {|m| m.name == module_name}
544
  end
545
546
  def enabled_module_names=(module_names)
547
    if module_names && module_names.is_a?(Array)
548 117:af80e5618e9b Chris
      module_names = module_names.collect(&:to_s).reject(&:blank?)
549 441:cbce1fd3b1b7 Chris
      self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)}
550 0:513646585e45 Chris
    else
551
      enabled_modules.clear
552
    end
553
  end
554 117:af80e5618e9b Chris
555
  # Returns an array of the enabled modules names
556
  def enabled_module_names
557
    enabled_modules.collect(&:name)
558
  end
559
560
  safe_attributes 'name',
561
    'description',
562
    'homepage',
563
    'is_public',
564
    'identifier',
565
    'custom_field_values',
566
    'custom_fields',
567
    'tracker_ids',
568
    'issue_custom_field_ids'
569 22:40f7cfd4df19 chris
570 117:af80e5618e9b Chris
  safe_attributes 'enabled_module_names',
571
    :if => lambda {|project, user| project.new_record? || user.allowed_to?(:select_project_modules, project) }
572
573 22:40f7cfd4df19 chris
  # Returns an array of projects that are in this project's hierarchy
574
  #
575
  # Example: parents, children, siblings
576
  def hierarchy
577
    parents = project.self_and_ancestors || []
578
    descendants = project.descendants || []
579
    project_hierarchy = parents | descendants # Set union
580
  end
581 0:513646585e45 Chris
582
  # Returns an auto-generated project identifier based on the last identifier used
583
  def self.next_identifier
584
    p = Project.find(:first, :order => 'created_on DESC')
585
    p.nil? ? nil : p.identifier.to_s.succ
586
  end
587
588
  # Copies and saves the Project instance based on the +project+.
589
  # Duplicates the source project's:
590
  # * Wiki
591
  # * Versions
592
  # * Categories
593
  # * Issues
594
  # * Members
595
  # * Queries
596
  #
597
  # Accepts an +options+ argument to specify what to copy
598
  #
599
  # Examples:
600
  #   project.copy(1)                                    # => copies everything
601
  #   project.copy(1, :only => 'members')                # => copies members only
602
  #   project.copy(1, :only => ['members', 'versions'])  # => copies members and versions
603
  def copy(project, options={})
604
    project = project.is_a?(Project) ? project : Project.find(project)
605
606
    to_be_copied = %w(wiki versions issue_categories issues members queries boards)
607
    to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
608
609
    Project.transaction do
610
      if save
611
        reload
612
        to_be_copied.each do |name|
613
          send "copy_#{name}", project
614
        end
615
        Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
616
        save
617
      end
618
    end
619
  end
620
621
622
  # Copies +project+ and returns the new instance.  This will not save
623
  # the copy
624
  def self.copy_from(project)
625
    begin
626
      project = project.is_a?(Project) ? project : Project.find(project)
627
      if project
628
        # clear unique attributes
629
        attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
630
        copy = Project.new(attributes)
631
        copy.enabled_modules = project.enabled_modules
632
        copy.trackers = project.trackers
633
        copy.custom_values = project.custom_values.collect {|v| v.clone}
634
        copy.issue_custom_fields = project.issue_custom_fields
635
        return copy
636
      else
637
        return nil
638
      end
639
    rescue ActiveRecord::RecordNotFound
640
      return nil
641
    end
642
  end
643 37:94944d00e43c chris
644
  # Yields the given block for each project with its level in the tree
645
  def self.project_tree(projects, &block)
646
    ancestors = []
647
    projects.sort_by(&:lft).each do |project|
648
      while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
649
        ancestors.pop
650
      end
651
      yield project, ancestors.size
652
      ancestors << project
653
    end
654
  end
655 0:513646585e45 Chris
656
  private
657
658
  # Copies wiki from +project+
659
  def copy_wiki(project)
660
    # Check that the source project has a wiki first
661
    unless project.wiki.nil?
662
      self.wiki ||= Wiki.new
663
      wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
664
      wiki_pages_map = {}
665
      project.wiki.pages.each do |page|
666
        # Skip pages without content
667
        next if page.content.nil?
668
        new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
669
        new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
670
        new_wiki_page.content = new_wiki_content
671
        wiki.pages << new_wiki_page
672
        wiki_pages_map[page.id] = new_wiki_page
673
      end
674
      wiki.save
675
      # Reproduce page hierarchy
676
      project.wiki.pages.each do |page|
677
        if page.parent_id && wiki_pages_map[page.id]
678
          wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
679
          wiki_pages_map[page.id].save
680
        end
681
      end
682
    end
683
  end
684
685
  # Copies versions from +project+
686
  def copy_versions(project)
687
    project.versions.each do |version|
688
      new_version = Version.new
689
      new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
690
      self.versions << new_version
691
    end
692
  end
693
694
  # Copies issue categories from +project+
695
  def copy_issue_categories(project)
696
    project.issue_categories.each do |issue_category|
697
      new_issue_category = IssueCategory.new
698
      new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
699
      self.issue_categories << new_issue_category
700
    end
701
  end
702
703
  # Copies issues from +project+
704 441:cbce1fd3b1b7 Chris
  # Note: issues assigned to a closed version won't be copied due to validation rules
705 0:513646585e45 Chris
  def copy_issues(project)
706
    # Stores the source issue id as a key and the copied issues as the
707
    # value.  Used to map the two togeather for issue relations.
708
    issues_map = {}
709
710
    # Get issues sorted by root_id, lft so that parent issues
711
    # get copied before their children
712
    project.issues.find(:all, :order => 'root_id, lft').each do |issue|
713
      new_issue = Issue.new
714
      new_issue.copy_from(issue)
715
      new_issue.project = self
716
      # Reassign fixed_versions by name, since names are unique per
717
      # project and the versions for self are not yet saved
718
      if issue.fixed_version
719
        new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
720
      end
721
      # Reassign the category by name, since names are unique per
722
      # project and the categories for self are not yet saved
723
      if issue.category
724
        new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
725
      end
726
      # Parent issue
727
      if issue.parent_id
728
        if copied_parent = issues_map[issue.parent_id]
729
          new_issue.parent_issue_id = copied_parent.id
730
        end
731
      end
732
733
      self.issues << new_issue
734 117:af80e5618e9b Chris
      if new_issue.new_record?
735
        logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info
736
      else
737
        issues_map[issue.id] = new_issue unless new_issue.new_record?
738
      end
739 0:513646585e45 Chris
    end
740
741
    # Relations after in case issues related each other
742
    project.issues.each do |issue|
743
      new_issue = issues_map[issue.id]
744 117:af80e5618e9b Chris
      unless new_issue
745
        # Issue was not copied
746
        next
747
      end
748 0:513646585e45 Chris
749
      # Relations
750
      issue.relations_from.each do |source_relation|
751
        new_issue_relation = IssueRelation.new
752
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
753
        new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
754
        if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
755
          new_issue_relation.issue_to = source_relation.issue_to
756
        end
757
        new_issue.relations_from << new_issue_relation
758
      end
759
760
      issue.relations_to.each do |source_relation|
761
        new_issue_relation = IssueRelation.new
762
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
763
        new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
764
        if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
765
          new_issue_relation.issue_from = source_relation.issue_from
766
        end
767
        new_issue.relations_to << new_issue_relation
768
      end
769
    end
770
  end
771
772
  # Copies members from +project+
773
  def copy_members(project)
774 117:af80e5618e9b Chris
    # Copy users first, then groups to handle members with inherited and given roles
775
    members_to_copy = []
776
    members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)}
777
    members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)}
778
779
    members_to_copy.each do |member|
780 0:513646585e45 Chris
      new_member = Member.new
781
      new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
782
      # only copy non inherited roles
783
      # inherited roles will be added when copying the group membership
784
      role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
785
      next if role_ids.empty?
786
      new_member.role_ids = role_ids
787
      new_member.project = self
788
      self.members << new_member
789
    end
790
  end
791
792
  # Copies queries from +project+
793
  def copy_queries(project)
794
    project.queries.each do |query|
795
      new_query = Query.new
796
      new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
797
      new_query.sort_criteria = query.sort_criteria if query.sort_criteria
798
      new_query.project = self
799
      self.queries << new_query
800
    end
801
  end
802
803
  # Copies boards from +project+
804
  def copy_boards(project)
805
    project.boards.each do |board|
806
      new_board = Board.new
807
      new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
808
      new_board.project = self
809
      self.boards << new_board
810
    end
811
  end
812
813
  def allowed_permissions
814
    @allowed_permissions ||= begin
815
      module_names = enabled_modules.all(:select => :name).collect {|m| m.name}
816
      Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
817
    end
818
  end
819
820
  def allowed_actions
821
    @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
822
  end
823
824
  # Returns all the active Systemwide and project specific activities
825
  def active_activities
826
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
827
828
    if overridden_activity_ids.empty?
829
      return TimeEntryActivity.shared.active
830
    else
831
      return system_activities_and_project_overrides
832
    end
833
  end
834
835
  # Returns all the Systemwide and project specific activities
836
  # (inactive and active)
837
  def all_activities
838
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
839
840
    if overridden_activity_ids.empty?
841
      return TimeEntryActivity.shared
842
    else
843
      return system_activities_and_project_overrides(true)
844
    end
845
  end
846
847
  # Returns the systemwide active activities merged with the project specific overrides
848
  def system_activities_and_project_overrides(include_inactive=false)
849
    if include_inactive
850
      return TimeEntryActivity.shared.
851
        find(:all,
852
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
853
        self.time_entry_activities
854
    else
855
      return TimeEntryActivity.shared.active.
856
        find(:all,
857
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
858
        self.time_entry_activities.active
859
    end
860
  end
861
862
  # Archives subprojects recursively
863
  def archive!
864
    children.each do |subproject|
865
      subproject.send :archive!
866
    end
867
    update_attribute :status, STATUS_ARCHIVED
868
  end
869
end