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 @ 441:cbce1fd3b1b7

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