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 @ 913:b502ad91d302

History | View | Annotate | Download (32.8 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 909:cbb26bc654de Chris
#
9 0:513646585e45 Chris
# 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 909:cbb26bc654de Chris
#
14 0:513646585e45 Chris
# 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 909:cbb26bc654de Chris
21 0:513646585e45 Chris
  # Project statuses
22
  STATUS_ACTIVE     = 1
23
  STATUS_ARCHIVED   = 9
24 909:cbb26bc654de Chris
25 37:94944d00e43c chris
  # Maximum length for project identifiers
26
  IDENTIFIER_MAX_LENGTH = 100
27 909:cbb26bc654de Chris
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 909:cbb26bc654de Chris
  has_many :member_principals, :class_name => 'Member',
33 0:513646585e45 Chris
                               :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 909:cbb26bc654de Chris
38 0:513646585e45 Chris
  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 909:cbb26bc654de Chris
  has_and_belongs_to_many :issue_custom_fields,
54 0:513646585e45 Chris
                          :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 909:cbb26bc654de Chris
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 909:cbb26bc654de Chris
71 0:513646585e45 Chris
  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 909:cbb26bc654de Chris
90 117:af80e5618e9b Chris
  def initialize(attributes = nil)
91
    super
92 909:cbb26bc654de Chris
93 117:af80e5618e9b Chris
    initialized = (attributes || {}).stringify_keys
94 909:cbb26bc654de Chris
    if !initialized.key?('identifier') && Setting.sequential_project_identifiers?
95 117:af80e5618e9b Chris
      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 909:cbb26bc654de Chris
108 0:513646585e45 Chris
  def identifier=(identifier)
109
    super unless identifier_frozen?
110
  end
111 909:cbb26bc654de Chris
112 0:513646585e45 Chris
  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 507:0c939c159af4 Chris
  # Returns true if the project is visible to +user+ or to the current user.
123
  def visible?(user=User.current)
124
    user.allowed_to?(:view_project, self)
125
  end
126 909:cbb26bc654de Chris
127 441:cbce1fd3b1b7 Chris
  # 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 909:cbb26bc654de Chris
137 205:05f9a2a9c753 chris
  def self.root_visible_by(user=nil)
138 913:b502ad91d302 luis
    return "#{Project.table_name}.parent_id IS NULL AND " + visible_condition(user)
139 205:05f9a2a9c753 chris
  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 909:cbb26bc654de 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 909:cbb26bc654de Chris
215 0:513646585e45 Chris
  # 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 909:cbb26bc654de Chris
222 0:513646585e45 Chris
      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 909:cbb26bc654de Chris
249 0:513646585e45 Chris
  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 909:cbb26bc654de Chris
259 0:513646585e45 Chris
  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 909:cbb26bc654de Chris
264 0:513646585e45 Chris
  def active?
265
    self.status == STATUS_ACTIVE
266
  end
267 909:cbb26bc654de Chris
268 37:94944d00e43c chris
  def archived?
269
    self.status == STATUS_ARCHIVED
270
  end
271 909:cbb26bc654de Chris
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 909:cbb26bc654de Chris
288 0:513646585e45 Chris
  # 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 909:cbb26bc654de Chris
295 0:513646585e45 Chris
  # 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 909:cbb26bc654de Chris
310 0:513646585e45 Chris
  # 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 909:cbb26bc654de Chris
330 0:513646585e45 Chris
  # 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 909:cbb26bc654de Chris
369 0:513646585e45 Chris
  # 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 909:cbb26bc654de Chris
378 0:513646585e45 Chris
  # 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 909:cbb26bc654de Chris
396 0:513646585e45 Chris
  # 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 909:cbb26bc654de Chris
422 0:513646585e45 Chris
  # 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 909:cbb26bc654de Chris
429
  # Users/groups issues can be assigned to
430 0:513646585e45 Chris
  def assignable_users
431 909:cbb26bc654de Chris
    assignable = Setting.issue_group_assignment? ? member_principals : members
432
    assignable.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.principal}.sort
433 0:513646585e45 Chris
  end
434 909:cbb26bc654de Chris
435 0:513646585e45 Chris
  # Returns the mail adresses of users that should be always notified on project events
436
  def recipients
437 37:94944d00e43c chris
    notified_users.collect {|user| user.mail}
438 0:513646585e45 Chris
  end
439 909:cbb26bc654de Chris
440 0:513646585e45 Chris
  # Returns the users that should be notified on project events
441
  def notified_users
442 37:94944d00e43c chris
    # TODO: User part should be extracted to User#notify_about?
443
    members.select {|m| m.mail_notification? || m.user.mail_notification == 'all'}.collect {|m| m.user}
444 0:513646585e45 Chris
  end
445 909:cbb26bc654de Chris
446 0:513646585e45 Chris
  # Returns an array of all custom fields enabled for project issues
447
  # (explictly associated custom fields and custom fields enabled for all projects)
448
  def all_issue_custom_fields
449
    @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
450
  end
451 441:cbce1fd3b1b7 Chris
452
  # Returns an array of all custom fields enabled for project time entries
453
  # (explictly associated custom fields and custom fields enabled for all projects)
454
  def all_time_entry_custom_fields
455
    @all_time_entry_custom_fields ||= (TimeEntryCustomField.for_all + time_entry_custom_fields).uniq.sort
456
  end
457 909:cbb26bc654de Chris
458 0:513646585e45 Chris
  def project
459
    self
460
  end
461 909:cbb26bc654de Chris
462 0:513646585e45 Chris
  def <=>(project)
463
    name.downcase <=> project.name.downcase
464
  end
465 909:cbb26bc654de Chris
466 0:513646585e45 Chris
  def to_s
467
    name
468
  end
469 909:cbb26bc654de Chris
470 0:513646585e45 Chris
  # Returns a short description of the projects (first lines)
471
  def short_description(length = 255)
472 335:7acd282bee3c chris
473
    ## The short description is used in lists, e.g. Latest projects,
474
    ## My projects etc.  It should be no more than a line or two with
475
    ## no text formatting.
476
477 130:db0caa9f0ff4 chris
    ## Original Redmine code: this truncates to the CR that is more
478
    ## than "length" characters from the start.
479
    # description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
480 335:7acd282bee3c chris
481
    ## That can leave too much text for us, and also we want to omit
482
    ## images and the like.  Truncate instead to the first CR that
483
    ## follows _any_ non-blank text, and to the next word break beyond
484
    ## "length" characters if the result is still longer than that.
485
    ##
486 130:db0caa9f0ff4 chris
    description.gsub(/![^\s]+!/, '').gsub(/^(\s*[^\n\r]*).*$/m, '\1').gsub(/^(.{#{length}}\b).*$/m, '\1 ...').strip if description
487 0:513646585e45 Chris
  end
488 22:40f7cfd4df19 chris
489
  def css_classes
490
    s = 'project'
491
    s << ' root' if root?
492
    s << ' child' if child?
493
    s << (leaf? ? ' leaf' : ' parent')
494
    s
495
  end
496
497
  # The earliest start date of a project, based on it's issues and versions
498
  def start_date
499 117:af80e5618e9b Chris
    [
500
     issues.minimum('start_date'),
501
     shared_versions.collect(&:effective_date),
502
     shared_versions.collect(&:start_date)
503
    ].flatten.compact.min
504 22:40f7cfd4df19 chris
  end
505
506
  # The latest due date of an issue or version
507
  def due_date
508 117:af80e5618e9b Chris
    [
509
     issues.maximum('due_date'),
510
     shared_versions.collect(&:effective_date),
511
     shared_versions.collect {|v| v.fixed_issues.maximum('due_date')}
512
    ].flatten.compact.max
513 22:40f7cfd4df19 chris
  end
514
515
  def overdue?
516
    active? && !due_date.nil? && (due_date < Date.today)
517
  end
518
519
  # Returns the percent completed for this project, based on the
520
  # progress on it's versions.
521
  def completed_percent(options={:include_subprojects => false})
522
    if options.delete(:include_subprojects)
523
      total = self_and_descendants.collect(&:completed_percent).sum
524
525
      total / self_and_descendants.count
526
    else
527
      if versions.count > 0
528
        total = versions.collect(&:completed_pourcent).sum
529
530
        total / versions.count
531
      else
532
        100
533
      end
534
    end
535
  end
536 909:cbb26bc654de Chris
537 0:513646585e45 Chris
  # Return true if this project is allowed to do the specified action.
538
  # action can be:
539
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
540
  # * a permission Symbol (eg. :edit_project)
541
  def allows_to?(action)
542
    if action.is_a? Hash
543
      allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
544
    else
545
      allowed_permissions.include? action
546
    end
547
  end
548 909:cbb26bc654de Chris
549 0:513646585e45 Chris
  def module_enabled?(module_name)
550
    module_name = module_name.to_s
551
    enabled_modules.detect {|m| m.name == module_name}
552
  end
553 909:cbb26bc654de Chris
554 0:513646585e45 Chris
  def enabled_module_names=(module_names)
555
    if module_names && module_names.is_a?(Array)
556 117:af80e5618e9b Chris
      module_names = module_names.collect(&:to_s).reject(&:blank?)
557 441:cbce1fd3b1b7 Chris
      self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)}
558 0:513646585e45 Chris
    else
559
      enabled_modules.clear
560
    end
561
  end
562 909:cbb26bc654de Chris
563 117:af80e5618e9b Chris
  # Returns an array of the enabled modules names
564
  def enabled_module_names
565
    enabled_modules.collect(&:name)
566
  end
567 507:0c939c159af4 Chris
568
  # Enable a specific module
569
  #
570
  # Examples:
571
  #   project.enable_module!(:issue_tracking)
572
  #   project.enable_module!("issue_tracking")
573
  def enable_module!(name)
574
    enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name)
575
  end
576
577
  # Disable a module if it exists
578
  #
579
  # Examples:
580
  #   project.disable_module!(:issue_tracking)
581
  #   project.disable_module!("issue_tracking")
582
  #   project.disable_module!(project.enabled_modules.first)
583
  def disable_module!(target)
584
    target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target)
585
    target.destroy unless target.blank?
586
  end
587
588 117:af80e5618e9b Chris
  safe_attributes 'name',
589
    'description',
590
    'homepage',
591
    'is_public',
592
    'identifier',
593
    'custom_field_values',
594
    'custom_fields',
595
    'tracker_ids',
596 680:65abc6b39292 chris
    'issue_custom_field_ids',
597
    'has_welcome_page'
598 22:40f7cfd4df19 chris
599 117:af80e5618e9b Chris
  safe_attributes 'enabled_module_names',
600
    :if => lambda {|project, user| project.new_record? || user.allowed_to?(:select_project_modules, project) }
601 909:cbb26bc654de Chris
602 22:40f7cfd4df19 chris
  # Returns an array of projects that are in this project's hierarchy
603
  #
604
  # Example: parents, children, siblings
605
  def hierarchy
606
    parents = project.self_and_ancestors || []
607
    descendants = project.descendants || []
608
    project_hierarchy = parents | descendants # Set union
609
  end
610 909:cbb26bc654de Chris
611 0:513646585e45 Chris
  # Returns an auto-generated project identifier based on the last identifier used
612
  def self.next_identifier
613
    p = Project.find(:first, :order => 'created_on DESC')
614
    p.nil? ? nil : p.identifier.to_s.succ
615
  end
616
617
  # Copies and saves the Project instance based on the +project+.
618
  # Duplicates the source project's:
619
  # * Wiki
620
  # * Versions
621
  # * Categories
622
  # * Issues
623
  # * Members
624
  # * Queries
625
  #
626
  # Accepts an +options+ argument to specify what to copy
627
  #
628
  # Examples:
629
  #   project.copy(1)                                    # => copies everything
630
  #   project.copy(1, :only => 'members')                # => copies members only
631
  #   project.copy(1, :only => ['members', 'versions'])  # => copies members and versions
632
  def copy(project, options={})
633
    project = project.is_a?(Project) ? project : Project.find(project)
634 909:cbb26bc654de Chris
635 0:513646585e45 Chris
    to_be_copied = %w(wiki versions issue_categories issues members queries boards)
636
    to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
637 909:cbb26bc654de Chris
638 0:513646585e45 Chris
    Project.transaction do
639
      if save
640
        reload
641
        to_be_copied.each do |name|
642
          send "copy_#{name}", project
643
        end
644
        Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
645
        save
646
      end
647
    end
648
  end
649
650 909:cbb26bc654de Chris
651 0:513646585e45 Chris
  # Copies +project+ and returns the new instance.  This will not save
652
  # the copy
653
  def self.copy_from(project)
654
    begin
655
      project = project.is_a?(Project) ? project : Project.find(project)
656
      if project
657
        # clear unique attributes
658
        attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
659
        copy = Project.new(attributes)
660
        copy.enabled_modules = project.enabled_modules
661
        copy.trackers = project.trackers
662
        copy.custom_values = project.custom_values.collect {|v| v.clone}
663
        copy.issue_custom_fields = project.issue_custom_fields
664
        return copy
665
      else
666
        return nil
667
      end
668
    rescue ActiveRecord::RecordNotFound
669
      return nil
670
    end
671
  end
672 37:94944d00e43c chris
673
  # Yields the given block for each project with its level in the tree
674
  def self.project_tree(projects, &block)
675
    ancestors = []
676
    projects.sort_by(&:lft).each do |project|
677 909:cbb26bc654de Chris
      while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
678 37:94944d00e43c chris
        ancestors.pop
679
      end
680
      yield project, ancestors.size
681
      ancestors << project
682
    end
683
  end
684 909:cbb26bc654de Chris
685 0:513646585e45 Chris
  private
686 909:cbb26bc654de Chris
687 0:513646585e45 Chris
  # Copies wiki from +project+
688
  def copy_wiki(project)
689
    # Check that the source project has a wiki first
690
    unless project.wiki.nil?
691
      self.wiki ||= Wiki.new
692
      wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
693
      wiki_pages_map = {}
694
      project.wiki.pages.each do |page|
695
        # Skip pages without content
696
        next if page.content.nil?
697
        new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
698
        new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
699
        new_wiki_page.content = new_wiki_content
700
        wiki.pages << new_wiki_page
701
        wiki_pages_map[page.id] = new_wiki_page
702
      end
703
      wiki.save
704
      # Reproduce page hierarchy
705
      project.wiki.pages.each do |page|
706
        if page.parent_id && wiki_pages_map[page.id]
707
          wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
708
          wiki_pages_map[page.id].save
709
        end
710
      end
711
    end
712
  end
713
714
  # Copies versions from +project+
715
  def copy_versions(project)
716
    project.versions.each do |version|
717
      new_version = Version.new
718
      new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
719
      self.versions << new_version
720
    end
721
  end
722
723
  # Copies issue categories from +project+
724
  def copy_issue_categories(project)
725
    project.issue_categories.each do |issue_category|
726
      new_issue_category = IssueCategory.new
727
      new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
728
      self.issue_categories << new_issue_category
729
    end
730
  end
731 909:cbb26bc654de Chris
732 0:513646585e45 Chris
  # Copies issues from +project+
733 441:cbce1fd3b1b7 Chris
  # Note: issues assigned to a closed version won't be copied due to validation rules
734 0:513646585e45 Chris
  def copy_issues(project)
735
    # Stores the source issue id as a key and the copied issues as the
736
    # value.  Used to map the two togeather for issue relations.
737
    issues_map = {}
738 909:cbb26bc654de Chris
739 0:513646585e45 Chris
    # Get issues sorted by root_id, lft so that parent issues
740
    # get copied before their children
741
    project.issues.find(:all, :order => 'root_id, lft').each do |issue|
742
      new_issue = Issue.new
743
      new_issue.copy_from(issue)
744
      new_issue.project = self
745
      # Reassign fixed_versions by name, since names are unique per
746
      # project and the versions for self are not yet saved
747
      if issue.fixed_version
748
        new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
749
      end
750
      # Reassign the category by name, since names are unique per
751
      # project and the categories for self are not yet saved
752
      if issue.category
753
        new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
754
      end
755
      # Parent issue
756
      if issue.parent_id
757
        if copied_parent = issues_map[issue.parent_id]
758
          new_issue.parent_issue_id = copied_parent.id
759
        end
760
      end
761 909:cbb26bc654de Chris
762 0:513646585e45 Chris
      self.issues << new_issue
763 117:af80e5618e9b Chris
      if new_issue.new_record?
764
        logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info
765
      else
766
        issues_map[issue.id] = new_issue unless new_issue.new_record?
767
      end
768 0:513646585e45 Chris
    end
769
770
    # Relations after in case issues related each other
771
    project.issues.each do |issue|
772
      new_issue = issues_map[issue.id]
773 117:af80e5618e9b Chris
      unless new_issue
774
        # Issue was not copied
775
        next
776
      end
777 909:cbb26bc654de Chris
778 0:513646585e45 Chris
      # Relations
779
      issue.relations_from.each do |source_relation|
780
        new_issue_relation = IssueRelation.new
781
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
782
        new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
783
        if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
784
          new_issue_relation.issue_to = source_relation.issue_to
785
        end
786
        new_issue.relations_from << new_issue_relation
787
      end
788 909:cbb26bc654de Chris
789 0:513646585e45 Chris
      issue.relations_to.each do |source_relation|
790
        new_issue_relation = IssueRelation.new
791
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
792
        new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
793
        if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
794
          new_issue_relation.issue_from = source_relation.issue_from
795
        end
796
        new_issue.relations_to << new_issue_relation
797
      end
798
    end
799
  end
800
801
  # Copies members from +project+
802
  def copy_members(project)
803 117:af80e5618e9b Chris
    # Copy users first, then groups to handle members with inherited and given roles
804
    members_to_copy = []
805
    members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)}
806
    members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)}
807 909:cbb26bc654de Chris
808 117:af80e5618e9b Chris
    members_to_copy.each do |member|
809 0:513646585e45 Chris
      new_member = Member.new
810
      new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
811
      # only copy non inherited roles
812
      # inherited roles will be added when copying the group membership
813
      role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
814
      next if role_ids.empty?
815
      new_member.role_ids = role_ids
816
      new_member.project = self
817
      self.members << new_member
818
    end
819
  end
820
821
  # Copies queries from +project+
822
  def copy_queries(project)
823
    project.queries.each do |query|
824
      new_query = Query.new
825
      new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
826
      new_query.sort_criteria = query.sort_criteria if query.sort_criteria
827
      new_query.project = self
828 909:cbb26bc654de Chris
      new_query.user_id = query.user_id
829 0:513646585e45 Chris
      self.queries << new_query
830
    end
831
  end
832
833
  # Copies boards from +project+
834
  def copy_boards(project)
835
    project.boards.each do |board|
836
      new_board = Board.new
837
      new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
838
      new_board.project = self
839
      self.boards << new_board
840
    end
841
  end
842 909:cbb26bc654de Chris
843 0:513646585e45 Chris
  def allowed_permissions
844
    @allowed_permissions ||= begin
845
      module_names = enabled_modules.all(:select => :name).collect {|m| m.name}
846
      Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
847
    end
848
  end
849
850
  def allowed_actions
851
    @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
852
  end
853
854
  # Returns all the active Systemwide and project specific activities
855
  def active_activities
856
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
857 909:cbb26bc654de Chris
858 0:513646585e45 Chris
    if overridden_activity_ids.empty?
859
      return TimeEntryActivity.shared.active
860
    else
861
      return system_activities_and_project_overrides
862
    end
863
  end
864
865
  # Returns all the Systemwide and project specific activities
866
  # (inactive and active)
867
  def all_activities
868
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
869
870
    if overridden_activity_ids.empty?
871
      return TimeEntryActivity.shared
872
    else
873
      return system_activities_and_project_overrides(true)
874
    end
875
  end
876
877
  # Returns the systemwide active activities merged with the project specific overrides
878
  def system_activities_and_project_overrides(include_inactive=false)
879
    if include_inactive
880
      return TimeEntryActivity.shared.
881
        find(:all,
882
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
883
        self.time_entry_activities
884
    else
885
      return TimeEntryActivity.shared.active.
886
        find(:all,
887
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
888
        self.time_entry_activities.active
889
    end
890
  end
891 909:cbb26bc654de Chris
892 0:513646585e45 Chris
  # Archives subprojects recursively
893
  def archive!
894
    children.each do |subproject|
895
      subproject.send :archive!
896
    end
897
    update_attribute :status, STATUS_ARCHIVED
898
  end
899
end