annotate app/models/project.rb @ 1474:c4436fec34bf bug_494

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