Chris@441: # Redmine - project management software Chris@441: # Copyright (C) 2006-2011 Jean-Philippe Lang Chris@0: # Chris@0: # This program is free software; you can redistribute it and/or Chris@0: # modify it under the terms of the GNU General Public License Chris@0: # as published by the Free Software Foundation; either version 2 Chris@0: # of the License, or (at your option) any later version. Chris@0: # Chris@0: # This program is distributed in the hope that it will be useful, Chris@0: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@0: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@0: # GNU General Public License for more details. Chris@0: # Chris@0: # You should have received a copy of the GNU General Public License Chris@0: # along with this program; if not, write to the Free Software Chris@0: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@0: Chris@0: class Project < ActiveRecord::Base Chris@117: include Redmine::SafeAttributes Chris@117: Chris@0: # Project statuses Chris@0: STATUS_ACTIVE = 1 Chris@0: STATUS_ARCHIVED = 9 Chris@0: chris@37: # Maximum length for project identifiers chris@37: IDENTIFIER_MAX_LENGTH = 100 chris@37: Chris@0: # Specific overidden Activities Chris@0: has_many :time_entry_activities Chris@0: has_many :members, :include => [:user, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}" Chris@0: has_many :memberships, :class_name => 'Member' Chris@0: has_many :member_principals, :class_name => 'Member', Chris@0: :include => :principal, Chris@0: :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})" Chris@0: has_many :users, :through => :members Chris@0: has_many :principals, :through => :member_principals, :source => :principal Chris@0: Chris@0: has_many :enabled_modules, :dependent => :delete_all Chris@0: has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position" Chris@0: has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker] Chris@0: has_many :issue_changes, :through => :issues, :source => :journals Chris@0: has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC" Chris@0: has_many :time_entries, :dependent => :delete_all Chris@0: has_many :queries, :dependent => :delete_all Chris@0: has_many :documents, :dependent => :destroy Chris@441: has_many :news, :dependent => :destroy, :include => :author Chris@0: has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name" Chris@0: has_many :boards, :dependent => :destroy, :order => "position ASC" Chris@0: has_one :repository, :dependent => :destroy Chris@0: has_many :changesets, :through => :repository Chris@0: has_one :wiki, :dependent => :destroy Chris@0: # Custom field for the project issues Chris@0: has_and_belongs_to_many :issue_custom_fields, Chris@0: :class_name => 'IssueCustomField', Chris@0: :order => "#{CustomField.table_name}.position", Chris@0: :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}", Chris@0: :association_foreign_key => 'custom_field_id' Chris@0: Chris@441: acts_as_nested_set :order => 'name', :dependent => :destroy Chris@0: acts_as_attachable :view_permission => :view_files, Chris@0: :delete_permission => :manage_files Chris@0: Chris@0: acts_as_customizable Chris@0: acts_as_searchable :columns => ['name', 'identifier', 'description'], :project_key => 'id', :permission => nil Chris@0: acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"}, Chris@0: :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o}}, Chris@0: :author => nil Chris@0: Chris@117: attr_protected :status Chris@0: Chris@0: validates_presence_of :name, :identifier chris@37: validates_uniqueness_of :identifier Chris@0: validates_associated :repository, :wiki chris@37: validates_length_of :name, :maximum => 255 Chris@0: validates_length_of :homepage, :maximum => 255 chris@37: validates_length_of :identifier, :in => 1..IDENTIFIER_MAX_LENGTH Chris@0: # donwcase letters, digits, dashes but not digits only Chris@0: validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? } Chris@0: # reserved words Chris@0: validates_exclusion_of :identifier, :in => %w( new ) Chris@0: Chris@441: before_destroy :delete_all_members Chris@0: Chris@0: 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: named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"} Chris@0: named_scope :all_public, { :conditions => { :is_public => true } } Chris@441: named_scope :visible, lambda {|*args| {:conditions => Project.visible_condition(args.shift || User.current, *args) }} chris@205: named_scope :visible_roots, lambda { { :conditions => Project.root_visible_by(User.current) } } Chris@0: Chris@117: def initialize(attributes = nil) Chris@117: super Chris@117: Chris@117: initialized = (attributes || {}).stringify_keys Chris@117: if !initialized.key?('identifier') && Setting.sequential_project_identifiers? Chris@117: self.identifier = Project.next_identifier Chris@117: end Chris@117: if !initialized.key?('is_public') Chris@117: self.is_public = Setting.default_projects_public? Chris@117: end Chris@117: if !initialized.key?('enabled_module_names') Chris@117: self.enabled_module_names = Setting.default_projects_modules Chris@117: end Chris@117: if !initialized.key?('trackers') && !initialized.key?('tracker_ids') Chris@117: self.trackers = Tracker.all Chris@117: end Chris@117: end Chris@117: Chris@0: def identifier=(identifier) Chris@0: super unless identifier_frozen? Chris@0: end Chris@0: Chris@0: def identifier_frozen? Chris@0: errors[:identifier].nil? && !(new_record? || identifier.blank?) Chris@0: end Chris@0: Chris@0: # returns latest created projects Chris@0: # non public projects will be returned only if user is a member of those Chris@0: def self.latest(user=nil, count=5) Chris@441: visible(user).find(:all, :limit => count, :order => "created_on DESC") Chris@0: end Chris@0: Chris@507: # Returns true if the project is visible to +user+ or to the current user. Chris@507: def visible?(user=User.current) Chris@507: user.allowed_to?(:view_project, self) Chris@507: end Chris@507: Chris@441: def self.visible_by(user=nil) Chris@441: ActiveSupport::Deprecation.warn "Project.visible_by is deprecated and will be removed in Redmine 1.3.0. Use Project.visible_condition instead." Chris@441: visible_condition(user || User.current) Chris@441: end Chris@441: Chris@441: # Returns a SQL conditions string used to find all projects visible by the specified user. Chris@0: # Chris@0: # Examples: Chris@441: # Project.visible_condition(admin) => "projects.status = 1" Chris@441: # Project.visible_condition(normal_user) => "((projects.status = 1) AND (projects.is_public = 1 OR projects.id IN (1,3,4)))" Chris@441: # Project.visible_condition(anonymous) => "((projects.status = 1) AND (projects.is_public = 1))" Chris@441: def self.visible_condition(user, options={}) Chris@441: allowed_to_condition(user, :view_project, options) Chris@0: end Chris@0: chris@205: def self.root_visible_by(user=nil) chris@205: return "#{Project.table_name}.parent_id IS NULL AND " + visible_by(user) chris@205: end chris@205: Chris@441: # Returns a SQL conditions string used to find all projects for which +user+ has the given +permission+ Chris@441: # Chris@441: # Valid options: Chris@441: # * :project => limit the condition to project Chris@441: # * :with_subprojects => limit the condition to project and its subprojects Chris@441: # * :member => limit the condition to the user projects Chris@0: def self.allowed_to_condition(user, permission, options={}) Chris@0: base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}" Chris@0: if perm = Redmine::AccessControl.permission(permission) Chris@0: unless perm.project_module.nil? Chris@0: # If the permission belongs to a project module, make sure the module is enabled Chris@0: 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: end Chris@0: end Chris@0: if options[:project] Chris@0: project_statement = "#{Project.table_name}.id = #{options[:project].id}" Chris@0: project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects] Chris@0: base_statement = "(#{project_statement}) AND (#{base_statement})" Chris@0: end Chris@441: Chris@0: if user.admin? Chris@441: base_statement Chris@0: else Chris@441: statement_by_role = {} Chris@441: unless options[:member] Chris@441: role = user.logged? ? Role.non_member : Role.anonymous Chris@441: if role.allowed_to?(permission) Chris@441: statement_by_role[role] = "#{Project.table_name}.is_public = #{connection.quoted_true}" Chris@441: end Chris@441: end Chris@0: if user.logged? Chris@441: user.projects_by_role.each do |role, projects| Chris@441: if role.allowed_to?(permission) Chris@441: statement_by_role[role] = "#{Project.table_name}.id IN (#{projects.collect(&:id).join(',')})" Chris@441: end Chris@0: end Chris@441: end Chris@441: if statement_by_role.empty? Chris@441: "1=0" Chris@0: else Chris@441: if block_given? Chris@441: statement_by_role.each do |role, statement| Chris@441: if s = yield(role, user) Chris@441: statement_by_role[role] = "(#{statement} AND (#{s}))" Chris@441: end Chris@441: end Chris@441: end Chris@441: "((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))" Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: # Returns the Systemwide and project specific activities Chris@0: def activities(include_inactive=false) Chris@0: if include_inactive Chris@0: return all_activities Chris@0: else Chris@0: return active_activities Chris@0: end Chris@0: end Chris@0: Chris@0: # Will create a new Project specific Activity or update an existing one Chris@0: # Chris@0: # This will raise a ActiveRecord::Rollback if the TimeEntryActivity Chris@0: # does not successfully save. Chris@0: def update_or_create_time_entry_activity(id, activity_hash) Chris@0: if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id') Chris@0: self.create_time_entry_activity_if_needed(activity_hash) Chris@0: else Chris@0: activity = project.time_entry_activities.find_by_id(id.to_i) Chris@0: activity.update_attributes(activity_hash) if activity Chris@0: end Chris@0: end Chris@0: Chris@0: # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity Chris@0: # Chris@0: # This will raise a ActiveRecord::Rollback if the TimeEntryActivity Chris@0: # does not successfully save. Chris@0: def create_time_entry_activity_if_needed(activity) Chris@0: if activity['parent_id'] Chris@0: Chris@0: parent_activity = TimeEntryActivity.find(activity['parent_id']) Chris@0: activity['name'] = parent_activity.name Chris@0: activity['position'] = parent_activity.position Chris@0: Chris@0: if Enumeration.overridding_change?(activity, parent_activity) Chris@0: project_activity = self.time_entry_activities.create(activity) Chris@0: Chris@0: if project_activity.new_record? Chris@0: raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved" Chris@0: else Chris@0: self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id]) Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: # Returns a :conditions SQL string that can be used to find the issues associated with this project. Chris@0: # Chris@0: # Examples: Chris@0: # project.project_condition(true) => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))" Chris@0: # project.project_condition(false) => "projects.id = 1" Chris@0: def project_condition(with_subprojects) Chris@0: cond = "#{Project.table_name}.id = #{id}" Chris@0: cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects Chris@0: cond Chris@0: end Chris@0: Chris@0: def self.find(*args) Chris@0: if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/) Chris@0: project = find_by_identifier(*args) Chris@0: raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil? Chris@0: project Chris@0: else Chris@0: super Chris@0: end Chris@0: end Chris@0: Chris@0: def to_param Chris@0: # id is used for projects with a numeric identifier (compatibility) Chris@0: @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier) Chris@0: end Chris@0: Chris@0: def active? Chris@0: self.status == STATUS_ACTIVE Chris@0: end Chris@0: chris@37: def archived? chris@37: self.status == STATUS_ARCHIVED chris@37: end chris@37: Chris@0: # Archives the project and its descendants Chris@0: def archive Chris@0: # Check that there is no issue of a non descendant project that is assigned Chris@0: # to one of the project or descendant versions Chris@0: v_ids = self_and_descendants.collect {|p| p.version_ids}.flatten Chris@0: if v_ids.any? && Issue.find(:first, :include => :project, Chris@0: :conditions => ["(#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?)" + Chris@0: " AND #{Issue.table_name}.fixed_version_id IN (?)", lft, rgt, v_ids]) Chris@0: return false Chris@0: end Chris@0: Project.transaction do Chris@0: archive! Chris@0: end Chris@0: true Chris@0: end Chris@0: Chris@0: # Unarchives the project Chris@0: # All its ancestors must be active Chris@0: def unarchive Chris@0: return false if ancestors.detect {|a| !a.active?} Chris@0: update_attribute :status, STATUS_ACTIVE Chris@0: end Chris@0: Chris@0: # Returns an array of projects the project can be moved to Chris@0: # by the current user Chris@0: def allowed_parents Chris@0: return @allowed_parents if @allowed_parents Chris@0: @allowed_parents = Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_subprojects)) Chris@0: @allowed_parents = @allowed_parents - self_and_descendants Chris@0: if User.current.allowed_to?(:add_project, nil, :global => true) || (!new_record? && parent.nil?) Chris@0: @allowed_parents << nil Chris@0: end Chris@0: unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent) Chris@0: @allowed_parents << parent Chris@0: end Chris@0: @allowed_parents Chris@0: end Chris@0: Chris@0: # Sets the parent of the project with authorization check Chris@0: def set_allowed_parent!(p) Chris@0: unless p.nil? || p.is_a?(Project) Chris@0: if p.to_s.blank? Chris@0: p = nil Chris@0: else Chris@0: p = Project.find_by_id(p) Chris@0: return false unless p Chris@0: end Chris@0: end Chris@0: if p.nil? Chris@0: if !new_record? && allowed_parents.empty? Chris@0: return false Chris@0: end Chris@0: elsif !allowed_parents.include?(p) Chris@0: return false Chris@0: end Chris@0: set_parent!(p) Chris@0: end Chris@0: Chris@0: # Sets the parent of the project Chris@0: # Argument can be either a Project, a String, a Fixnum or nil Chris@0: def set_parent!(p) Chris@0: unless p.nil? || p.is_a?(Project) Chris@0: if p.to_s.blank? Chris@0: p = nil Chris@0: else Chris@0: p = Project.find_by_id(p) Chris@0: return false unless p Chris@0: end Chris@0: end Chris@0: if p == parent && !p.nil? Chris@0: # Nothing to do Chris@0: true Chris@0: elsif p.nil? || (p.active? && move_possible?(p)) Chris@0: # Insert the project so that target's children or root projects stay alphabetically sorted Chris@0: sibs = (p.nil? ? self.class.roots : p.children) Chris@0: to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase } Chris@0: if to_be_inserted_before Chris@0: move_to_left_of(to_be_inserted_before) Chris@0: elsif p.nil? Chris@0: if sibs.empty? Chris@0: # move_to_root adds the project in first (ie. left) position Chris@0: move_to_root Chris@0: else Chris@0: move_to_right_of(sibs.last) unless self == sibs.last Chris@0: end Chris@0: else Chris@0: # move_to_child_of adds the project in last (ie.right) position Chris@0: move_to_child_of(p) Chris@0: end Chris@0: Issue.update_versions_from_hierarchy_change(self) Chris@0: true Chris@0: else Chris@0: # Can not move to the given target Chris@0: false Chris@0: end Chris@0: end Chris@0: Chris@0: # Returns an array of the trackers used by the project and its active sub projects Chris@0: def rolled_up_trackers Chris@0: @rolled_up_trackers ||= Chris@441: Tracker.find(:all, :joins => :projects, Chris@0: :select => "DISTINCT #{Tracker.table_name}.*", Chris@0: :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt], Chris@0: :order => "#{Tracker.table_name}.position") Chris@0: end Chris@0: Chris@0: # Closes open and locked project versions that are completed Chris@0: def close_completed_versions Chris@0: Version.transaction do Chris@0: versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version| Chris@0: if version.completed? Chris@0: version.update_attribute(:status, 'closed') Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: # Returns a scope of the Versions on subprojects Chris@0: def rolled_up_versions Chris@0: @rolled_up_versions ||= Chris@0: Version.scoped(:include => :project, Chris@0: :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt]) Chris@0: end Chris@0: Chris@0: # Returns a scope of the Versions used by the project Chris@0: def shared_versions Chris@441: @shared_versions ||= begin Chris@441: r = root? ? self : root Chris@0: Version.scoped(:include => :project, Chris@0: :conditions => "#{Project.table_name}.id = #{id}" + Chris@0: " OR (#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND (" + Chris@0: " #{Version.table_name}.sharing = 'system'" + Chris@441: " OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" + Chris@0: " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" + Chris@0: " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" + Chris@0: "))") Chris@441: end Chris@0: end Chris@0: Chris@0: # Returns a hash of project users grouped by role Chris@0: def users_by_role Chris@0: members.find(:all, :include => [:user, :roles]).inject({}) do |h, m| Chris@0: m.roles.each do |r| Chris@0: h[r] ||= [] Chris@0: h[r] << m.user Chris@0: end Chris@0: h Chris@0: end Chris@0: end Chris@0: Chris@0: # Deletes all project's members Chris@0: def delete_all_members Chris@0: me, mr = Member.table_name, MemberRole.table_name Chris@0: connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})") Chris@0: Member.delete_all(['project_id = ?', id]) Chris@0: end Chris@0: Chris@0: # Users issues can be assigned to Chris@0: def assignable_users Chris@0: members.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.user}.sort Chris@0: end Chris@0: Chris@0: # Returns the mail adresses of users that should be always notified on project events Chris@0: def recipients chris@37: notified_users.collect {|user| user.mail} Chris@0: end Chris@0: Chris@0: # Returns the users that should be notified on project events Chris@0: def notified_users chris@37: # TODO: User part should be extracted to User#notify_about? chris@37: members.select {|m| m.mail_notification? || m.user.mail_notification == 'all'}.collect {|m| m.user} Chris@0: end Chris@0: Chris@0: # Returns an array of all custom fields enabled for project issues Chris@0: # (explictly associated custom fields and custom fields enabled for all projects) Chris@0: def all_issue_custom_fields Chris@0: @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort Chris@0: end Chris@441: Chris@441: # Returns an array of all custom fields enabled for project time entries Chris@441: # (explictly associated custom fields and custom fields enabled for all projects) Chris@441: def all_time_entry_custom_fields Chris@441: @all_time_entry_custom_fields ||= (TimeEntryCustomField.for_all + time_entry_custom_fields).uniq.sort Chris@441: end Chris@0: Chris@0: def project Chris@0: self Chris@0: end Chris@0: Chris@0: def <=>(project) Chris@0: name.downcase <=> project.name.downcase Chris@0: end Chris@0: Chris@0: def to_s Chris@0: name Chris@0: end Chris@0: Chris@0: # Returns a short description of the projects (first lines) Chris@0: def short_description(length = 255) chris@335: chris@335: ## The short description is used in lists, e.g. Latest projects, chris@335: ## My projects etc. It should be no more than a line or two with chris@335: ## no text formatting. chris@335: chris@130: ## Original Redmine code: this truncates to the CR that is more chris@130: ## than "length" characters from the start. chris@130: # description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description chris@335: chris@335: ## That can leave too much text for us, and also we want to omit chris@335: ## images and the like. Truncate instead to the first CR that chris@335: ## follows _any_ non-blank text, and to the next word break beyond chris@335: ## "length" characters if the result is still longer than that. chris@335: ## chris@130: description.gsub(/![^\s]+!/, '').gsub(/^(\s*[^\n\r]*).*$/m, '\1').gsub(/^(.{#{length}}\b).*$/m, '\1 ...').strip if description Chris@0: end chris@22: chris@22: def css_classes chris@22: s = 'project' chris@22: s << ' root' if root? chris@22: s << ' child' if child? chris@22: s << (leaf? ? ' leaf' : ' parent') chris@22: s chris@22: end chris@22: chris@22: # The earliest start date of a project, based on it's issues and versions chris@22: def start_date Chris@117: [ Chris@117: issues.minimum('start_date'), Chris@117: shared_versions.collect(&:effective_date), Chris@117: shared_versions.collect(&:start_date) Chris@117: ].flatten.compact.min chris@22: end chris@22: chris@22: # The latest due date of an issue or version chris@22: def due_date Chris@117: [ Chris@117: issues.maximum('due_date'), Chris@117: shared_versions.collect(&:effective_date), Chris@117: shared_versions.collect {|v| v.fixed_issues.maximum('due_date')} Chris@117: ].flatten.compact.max chris@22: end chris@22: chris@22: def overdue? chris@22: active? && !due_date.nil? && (due_date < Date.today) chris@22: end chris@22: chris@22: # Returns the percent completed for this project, based on the chris@22: # progress on it's versions. chris@22: def completed_percent(options={:include_subprojects => false}) chris@22: if options.delete(:include_subprojects) chris@22: total = self_and_descendants.collect(&:completed_percent).sum chris@22: chris@22: total / self_and_descendants.count chris@22: else chris@22: if versions.count > 0 chris@22: total = versions.collect(&:completed_pourcent).sum chris@22: chris@22: total / versions.count chris@22: else chris@22: 100 chris@22: end chris@22: end chris@22: end Chris@0: Chris@0: # Return true if this project is allowed to do the specified action. Chris@0: # action can be: Chris@0: # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit') Chris@0: # * a permission Symbol (eg. :edit_project) Chris@0: def allows_to?(action) Chris@0: if action.is_a? Hash Chris@0: allowed_actions.include? "#{action[:controller]}/#{action[:action]}" Chris@0: else Chris@0: allowed_permissions.include? action Chris@0: end Chris@0: end Chris@0: Chris@0: def module_enabled?(module_name) Chris@0: module_name = module_name.to_s Chris@0: enabled_modules.detect {|m| m.name == module_name} Chris@0: end Chris@0: Chris@0: def enabled_module_names=(module_names) Chris@0: if module_names && module_names.is_a?(Array) Chris@117: module_names = module_names.collect(&:to_s).reject(&:blank?) Chris@441: self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)} Chris@0: else Chris@0: enabled_modules.clear Chris@0: end Chris@0: end Chris@117: Chris@117: # Returns an array of the enabled modules names Chris@117: def enabled_module_names Chris@117: enabled_modules.collect(&:name) Chris@117: end Chris@507: Chris@507: # Enable a specific module Chris@507: # Chris@507: # Examples: Chris@507: # project.enable_module!(:issue_tracking) Chris@507: # project.enable_module!("issue_tracking") Chris@507: def enable_module!(name) Chris@507: enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name) Chris@507: end Chris@507: Chris@507: # Disable a module if it exists Chris@507: # Chris@507: # Examples: Chris@507: # project.disable_module!(:issue_tracking) Chris@507: # project.disable_module!("issue_tracking") Chris@507: # project.disable_module!(project.enabled_modules.first) Chris@507: def disable_module!(target) Chris@507: target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target) Chris@507: target.destroy unless target.blank? Chris@507: end Chris@507: Chris@117: safe_attributes 'name', Chris@117: 'description', Chris@117: 'homepage', Chris@117: 'is_public', Chris@117: 'identifier', Chris@117: 'custom_field_values', Chris@117: 'custom_fields', Chris@117: 'tracker_ids', Chris@117: 'issue_custom_field_ids' chris@22: Chris@117: safe_attributes 'enabled_module_names', Chris@117: :if => lambda {|project, user| project.new_record? || user.allowed_to?(:select_project_modules, project) } Chris@117: chris@22: # Returns an array of projects that are in this project's hierarchy chris@22: # chris@22: # Example: parents, children, siblings chris@22: def hierarchy chris@22: parents = project.self_and_ancestors || [] chris@22: descendants = project.descendants || [] chris@22: project_hierarchy = parents | descendants # Set union chris@22: end Chris@0: Chris@0: # Returns an auto-generated project identifier based on the last identifier used Chris@0: def self.next_identifier Chris@0: p = Project.find(:first, :order => 'created_on DESC') Chris@0: p.nil? ? nil : p.identifier.to_s.succ Chris@0: end Chris@0: Chris@0: # Copies and saves the Project instance based on the +project+. Chris@0: # Duplicates the source project's: Chris@0: # * Wiki Chris@0: # * Versions Chris@0: # * Categories Chris@0: # * Issues Chris@0: # * Members Chris@0: # * Queries Chris@0: # Chris@0: # Accepts an +options+ argument to specify what to copy Chris@0: # Chris@0: # Examples: Chris@0: # project.copy(1) # => copies everything Chris@0: # project.copy(1, :only => 'members') # => copies members only Chris@0: # project.copy(1, :only => ['members', 'versions']) # => copies members and versions Chris@0: def copy(project, options={}) Chris@0: project = project.is_a?(Project) ? project : Project.find(project) Chris@0: Chris@0: to_be_copied = %w(wiki versions issue_categories issues members queries boards) Chris@0: to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil? Chris@0: Chris@0: Project.transaction do Chris@0: if save Chris@0: reload Chris@0: to_be_copied.each do |name| Chris@0: send "copy_#{name}", project Chris@0: end Chris@0: Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self) Chris@0: save Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: Chris@0: # Copies +project+ and returns the new instance. This will not save Chris@0: # the copy Chris@0: def self.copy_from(project) Chris@0: begin Chris@0: project = project.is_a?(Project) ? project : Project.find(project) Chris@0: if project Chris@0: # clear unique attributes Chris@0: attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt') Chris@0: copy = Project.new(attributes) Chris@0: copy.enabled_modules = project.enabled_modules Chris@0: copy.trackers = project.trackers Chris@0: copy.custom_values = project.custom_values.collect {|v| v.clone} Chris@0: copy.issue_custom_fields = project.issue_custom_fields Chris@0: return copy Chris@0: else Chris@0: return nil Chris@0: end Chris@0: rescue ActiveRecord::RecordNotFound Chris@0: return nil Chris@0: end Chris@0: end chris@37: chris@37: # Yields the given block for each project with its level in the tree chris@37: def self.project_tree(projects, &block) chris@37: ancestors = [] chris@37: projects.sort_by(&:lft).each do |project| chris@37: while (ancestors.any? && !project.is_descendant_of?(ancestors.last)) chris@37: ancestors.pop chris@37: end chris@37: yield project, ancestors.size chris@37: ancestors << project chris@37: end chris@37: end Chris@0: Chris@0: private Chris@0: Chris@0: # Copies wiki from +project+ Chris@0: def copy_wiki(project) Chris@0: # Check that the source project has a wiki first Chris@0: unless project.wiki.nil? Chris@0: self.wiki ||= Wiki.new Chris@0: wiki.attributes = project.wiki.attributes.dup.except("id", "project_id") Chris@0: wiki_pages_map = {} Chris@0: project.wiki.pages.each do |page| Chris@0: # Skip pages without content Chris@0: next if page.content.nil? Chris@0: new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on")) Chris@0: new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id")) Chris@0: new_wiki_page.content = new_wiki_content Chris@0: wiki.pages << new_wiki_page Chris@0: wiki_pages_map[page.id] = new_wiki_page Chris@0: end Chris@0: wiki.save Chris@0: # Reproduce page hierarchy Chris@0: project.wiki.pages.each do |page| Chris@0: if page.parent_id && wiki_pages_map[page.id] Chris@0: wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id] Chris@0: wiki_pages_map[page.id].save Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: # Copies versions from +project+ Chris@0: def copy_versions(project) Chris@0: project.versions.each do |version| Chris@0: new_version = Version.new Chris@0: new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on") Chris@0: self.versions << new_version Chris@0: end Chris@0: end Chris@0: Chris@0: # Copies issue categories from +project+ Chris@0: def copy_issue_categories(project) Chris@0: project.issue_categories.each do |issue_category| Chris@0: new_issue_category = IssueCategory.new Chris@0: new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id") Chris@0: self.issue_categories << new_issue_category Chris@0: end Chris@0: end Chris@0: Chris@0: # Copies issues from +project+ Chris@441: # Note: issues assigned to a closed version won't be copied due to validation rules Chris@0: def copy_issues(project) Chris@0: # Stores the source issue id as a key and the copied issues as the Chris@0: # value. Used to map the two togeather for issue relations. Chris@0: issues_map = {} Chris@0: Chris@0: # Get issues sorted by root_id, lft so that parent issues Chris@0: # get copied before their children Chris@0: project.issues.find(:all, :order => 'root_id, lft').each do |issue| Chris@0: new_issue = Issue.new Chris@0: new_issue.copy_from(issue) Chris@0: new_issue.project = self Chris@0: # Reassign fixed_versions by name, since names are unique per Chris@0: # project and the versions for self are not yet saved Chris@0: if issue.fixed_version Chris@0: new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first Chris@0: end Chris@0: # Reassign the category by name, since names are unique per Chris@0: # project and the categories for self are not yet saved Chris@0: if issue.category Chris@0: new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first Chris@0: end Chris@0: # Parent issue Chris@0: if issue.parent_id Chris@0: if copied_parent = issues_map[issue.parent_id] Chris@0: new_issue.parent_issue_id = copied_parent.id Chris@0: end Chris@0: end Chris@0: Chris@0: self.issues << new_issue Chris@117: if new_issue.new_record? Chris@117: logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info Chris@117: else Chris@117: issues_map[issue.id] = new_issue unless new_issue.new_record? Chris@117: end Chris@0: end Chris@0: Chris@0: # Relations after in case issues related each other Chris@0: project.issues.each do |issue| Chris@0: new_issue = issues_map[issue.id] Chris@117: unless new_issue Chris@117: # Issue was not copied Chris@117: next Chris@117: end Chris@0: Chris@0: # Relations Chris@0: issue.relations_from.each do |source_relation| Chris@0: new_issue_relation = IssueRelation.new Chris@0: new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id") Chris@0: new_issue_relation.issue_to = issues_map[source_relation.issue_to_id] Chris@0: if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations? Chris@0: new_issue_relation.issue_to = source_relation.issue_to Chris@0: end Chris@0: new_issue.relations_from << new_issue_relation Chris@0: end Chris@0: Chris@0: issue.relations_to.each do |source_relation| Chris@0: new_issue_relation = IssueRelation.new Chris@0: new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id") Chris@0: new_issue_relation.issue_from = issues_map[source_relation.issue_from_id] Chris@0: if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations? Chris@0: new_issue_relation.issue_from = source_relation.issue_from Chris@0: end Chris@0: new_issue.relations_to << new_issue_relation Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: # Copies members from +project+ Chris@0: def copy_members(project) Chris@117: # Copy users first, then groups to handle members with inherited and given roles Chris@117: members_to_copy = [] Chris@117: members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)} Chris@117: members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)} Chris@117: Chris@117: members_to_copy.each do |member| Chris@0: new_member = Member.new Chris@0: new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on") Chris@0: # only copy non inherited roles Chris@0: # inherited roles will be added when copying the group membership Chris@0: role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id) Chris@0: next if role_ids.empty? Chris@0: new_member.role_ids = role_ids Chris@0: new_member.project = self Chris@0: self.members << new_member Chris@0: end Chris@0: end Chris@0: Chris@0: # Copies queries from +project+ Chris@0: def copy_queries(project) Chris@0: project.queries.each do |query| Chris@0: new_query = Query.new Chris@0: new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria") Chris@0: new_query.sort_criteria = query.sort_criteria if query.sort_criteria Chris@0: new_query.project = self Chris@0: self.queries << new_query Chris@0: end Chris@0: end Chris@0: Chris@0: # Copies boards from +project+ Chris@0: def copy_boards(project) Chris@0: project.boards.each do |board| Chris@0: new_board = Board.new Chris@0: new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id") Chris@0: new_board.project = self Chris@0: self.boards << new_board Chris@0: end Chris@0: end Chris@0: Chris@0: def allowed_permissions Chris@0: @allowed_permissions ||= begin Chris@0: module_names = enabled_modules.all(:select => :name).collect {|m| m.name} Chris@0: Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name} Chris@0: end Chris@0: end Chris@0: Chris@0: def allowed_actions Chris@0: @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten Chris@0: end Chris@0: Chris@0: # Returns all the active Systemwide and project specific activities Chris@0: def active_activities Chris@0: overridden_activity_ids = self.time_entry_activities.collect(&:parent_id) Chris@0: Chris@0: if overridden_activity_ids.empty? Chris@0: return TimeEntryActivity.shared.active Chris@0: else Chris@0: return system_activities_and_project_overrides Chris@0: end Chris@0: end Chris@0: Chris@0: # Returns all the Systemwide and project specific activities Chris@0: # (inactive and active) Chris@0: def all_activities Chris@0: overridden_activity_ids = self.time_entry_activities.collect(&:parent_id) Chris@0: Chris@0: if overridden_activity_ids.empty? Chris@0: return TimeEntryActivity.shared Chris@0: else Chris@0: return system_activities_and_project_overrides(true) Chris@0: end Chris@0: end Chris@0: Chris@0: # Returns the systemwide active activities merged with the project specific overrides Chris@0: def system_activities_and_project_overrides(include_inactive=false) Chris@0: if include_inactive Chris@0: return TimeEntryActivity.shared. Chris@0: find(:all, Chris@0: :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) + Chris@0: self.time_entry_activities Chris@0: else Chris@0: return TimeEntryActivity.shared.active. Chris@0: find(:all, Chris@0: :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) + Chris@0: self.time_entry_activities.active Chris@0: end Chris@0: end Chris@0: Chris@0: # Archives subprojects recursively Chris@0: def archive! Chris@0: children.each do |subproject| Chris@0: subproject.send :archive! Chris@0: end Chris@0: update_attribute :status, STATUS_ARCHIVED Chris@0: end Chris@0: end