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