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