Chris@441: # Redmine - project management software Chris@1494: # Copyright (C) 2006-2014 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@909: # 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@909: # 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@909: Chris@0: # Project statuses Chris@0: STATUS_ACTIVE = 1 Chris@1115: STATUS_CLOSED = 5 Chris@0: STATUS_ARCHIVED = 9 Chris@909: chris@37: # Maximum length for project identifiers chris@37: IDENTIFIER_MAX_LENGTH = 100 Chris@909: Chris@0: # Specific overidden Activities Chris@0: has_many :time_entry_activities Chris@1464: has_many :members, :include => [:principal, :roles], :conditions => "#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{Principal::STATUS_ACTIVE}" Chris@0: has_many :memberships, :class_name => 'Member' Chris@909: has_many :member_principals, :class_name => 'Member', Chris@0: :include => :principal, Chris@1464: :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{Principal::STATUS_ACTIVE})" Chris@909: Chris@0: has_many :enabled_modules, :dependent => :delete_all Chris@0: has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position" Chris@1115: has_many :issues, :dependent => :destroy, :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@1517: has_many :time_entries, :dependent => :destroy Chris@1464: has_many :queries, :class_name => 'IssueQuery', :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@1115: has_one :repository, :conditions => ["is_default = ?", true] Chris@1115: has_many :repositories, :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@909: 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@909: Chris@1517: acts_as_nested_set :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@909: 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@1464: validates_format_of :identifier, :with => /\A(?!\d+$)[a-z0-9\-_]*\z/, :if => Proc.new { |p| p.identifier_changed? } Chris@0: # reserved words Chris@0: validates_exclusion_of :identifier, :in => %w( new ) Chris@0: Chris@1115: after_save :update_position_under_parent, :if => Proc.new {|project| project.name_changed?} Chris@1464: after_save :update_inherited_members, :if => Proc.new {|project| project.inherit_members_changed?} Chris@441: before_destroy :delete_all_members Chris@0: Chris@1464: scope :has_module, lambda {|mod| Chris@1464: where("#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s) Chris@1464: } Chris@1464: scope :active, lambda { where(:status => STATUS_ACTIVE) } Chris@1464: scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) } Chris@1464: scope :all_public, lambda { where(:is_public => true) } Chris@1464: scope :visible, lambda {|*args| where(Project.visible_condition(args.shift || User.current, *args)) } Chris@1484: scope :visible_roots, lambda {|*args| where(Project.root_visible_by(args.shift || User.current, *args)) } Chris@1464: scope :allowed_to, lambda {|*args| Chris@1115: user = User.current Chris@1115: permission = nil Chris@1115: if args.first.is_a?(Symbol) Chris@1115: permission = args.shift Chris@1115: else Chris@1115: user = args.shift Chris@1115: permission = args.shift Chris@1115: end Chris@1464: where(Project.allowed_to_condition(user, permission, *args)) Chris@1115: } Chris@1115: scope :like, lambda {|arg| Chris@1115: if arg.blank? Chris@1464: where(nil) Chris@1115: else Chris@1115: pattern = "%#{arg.to_s.strip.downcase}%" Chris@1464: where("LOWER(identifier) LIKE :p OR LOWER(name) LIKE :p", :p => pattern) Chris@1115: end Chris@1115: } Chris@909: Chris@1115: def initialize(attributes=nil, *args) Chris@117: super Chris@909: Chris@117: initialized = (attributes || {}).stringify_keys Chris@909: 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@1464: default = Setting.default_projects_tracker_ids Chris@1464: if default.is_a?(Array) Chris@1464: self.trackers = Tracker.where(:id => default.map(&:to_i)).sorted.all Chris@1464: else Chris@1464: self.trackers = Tracker.sorted.all Chris@1464: end Chris@117: end Chris@117: end Chris@909: Chris@0: def identifier=(identifier) Chris@0: super unless identifier_frozen? Chris@0: end Chris@909: Chris@0: def identifier_frozen? Chris@1115: errors[:identifier].blank? && !(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@1464: visible(user).limit(count).order("created_on DESC").all Chris@1464: 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@909: 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@909: Chris@1501: def self.root_visible_by(user, options={}) Chris@1501: return "#{Project.table_name}.parent_id IS NULL AND " + visible_condition(user, options) 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@1115: perm = Redmine::AccessControl.permission(permission) Chris@1115: base_statement = (perm && perm.read? ? "#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED}" : "#{Project.table_name}.status = #{Project::STATUS_ACTIVE}") Chris@1115: if perm && perm.project_module Chris@1115: # If the permission belongs to a project module, make sure the module is enabled Chris@1115: 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: 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@909: Chris@0: if user.admin? Chris@441: base_statement Chris@0: else Chris@441: statement_by_role = {} Chris@441: unless options[:member] Chris@1464: role = user.builtin_role 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@1115: if role.allowed_to?(permission) && projects.any? 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@1464: def principals Chris@1464: @principals ||= Principal.active.joins(:members).where("#{Member.table_name}.project_id = ?", id).uniq Chris@1464: end Chris@1464: Chris@1464: def users Chris@1464: @users ||= User.active.joins(:members).where("#{Member.table_name}.project_id = ?", id).uniq Chris@1464: end Chris@1464: 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@909: 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: parent_activity = TimeEntryActivity.find(activity['parent_id']) Chris@0: activity['name'] = parent_activity.name Chris@0: activity['position'] = parent_activity.position Chris@0: if Enumeration.overridding_change?(activity, parent_activity) Chris@0: project_activity = self.time_entry_activities.create(activity) Chris@0: if project_activity.new_record? Chris@0: raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved" Chris@0: else Chris@1517: self.time_entries. Chris@1517: where(["activity_id = ?", parent_activity.id]). Chris@1517: update_all("activity_id = #{project_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@909: 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@909: Chris@1115: def self.find_by_param(*args) Chris@1115: self.find(*args) Chris@1115: end Chris@1115: Chris@1464: alias :base_reload :reload Chris@1115: def reload(*args) Chris@1464: @principals = nil Chris@1464: @users = nil Chris@1115: @shared_versions = nil Chris@1115: @rolled_up_versions = nil Chris@1115: @rolled_up_trackers = nil Chris@1115: @all_issue_custom_fields = nil Chris@1115: @all_time_entry_custom_fields = nil Chris@1115: @to_param = nil Chris@1115: @allowed_parents = nil Chris@1115: @allowed_permissions = nil Chris@1115: @actions_allowed = nil Chris@1464: @start_date = nil Chris@1464: @due_date = nil Chris@1464: base_reload(*args) Chris@1115: end Chris@1115: Chris@0: def to_param Chris@0: # id is used for projects with a numeric identifier (compatibility) Chris@929: @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id.to_s : identifier) Chris@0: end Chris@909: Chris@0: def active? Chris@0: self.status == STATUS_ACTIVE Chris@0: end Chris@909: chris@37: def archived? chris@37: self.status == STATUS_ARCHIVED chris@37: end Chris@909: 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@1464: if v_ids.any? && Chris@1464: Issue. Chris@1464: includes(:project). Chris@1464: where("#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?", lft, rgt). Chris@1464: where("#{Issue.table_name}.fixed_version_id IN (?)", v_ids). Chris@1464: exists? 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@909: 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@909: Chris@1115: def close Chris@1115: self_and_descendants.status(STATUS_ACTIVE).update_all :status => STATUS_CLOSED Chris@1115: end Chris@1115: Chris@1115: def reopen Chris@1115: self_and_descendants.status(STATUS_CLOSED).update_all :status => STATUS_ACTIVE Chris@1115: end Chris@1115: 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@1464: @allowed_parents = Project.where(Project.allowed_to_condition(User.current, :add_subprojects)).all 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@909: 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@909: 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@1115: set_or_update_position_under(p) 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@909: Chris@1115: # Recalculates all lft and rgt values based on project names Chris@1115: # Unlike Project.rebuild!, these values are recalculated even if the tree "looks" valid Chris@1115: # Used in BuildProjectsTree migration Chris@1115: def self.rebuild_tree! Chris@1115: transaction do Chris@1115: update_all "lft = NULL, rgt = NULL" Chris@1115: rebuild!(false) Chris@1517: all.each { |p| p.set_or_update_position_under(p.parent) } Chris@1115: end Chris@1115: end Chris@1115: 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@1464: Tracker. Chris@1464: joins(:projects). Chris@1464: joins("JOIN #{EnabledModule.table_name} ON #{EnabledModule.table_name}.project_id = #{Project.table_name}.id AND #{EnabledModule.table_name}.name = 'issue_tracking'"). Chris@1464: select("DISTINCT #{Tracker.table_name}.*"). Chris@1464: where("#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> #{STATUS_ARCHIVED}", lft, rgt). Chris@1464: sorted. Chris@1464: all Chris@0: end Chris@909: Chris@0: # Closes open and locked project versions that are completed Chris@0: def close_completed_versions Chris@0: Version.transaction do Chris@1517: versions.where(: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@1464: Version. Chris@1464: includes(:project). Chris@1464: where("#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> ?", lft, rgt, STATUS_ARCHIVED) Chris@0: end Chris@909: Chris@0: # Returns a scope of the Versions used by the project Chris@0: def shared_versions Chris@929: if new_record? Chris@1464: Version. Chris@1464: includes(:project). Chris@1464: where("#{Project.table_name}.status <> ? AND #{Version.table_name}.sharing = 'system'", STATUS_ARCHIVED) Chris@929: else Chris@929: @shared_versions ||= begin Chris@929: r = root? ? self : root Chris@1464: Version. Chris@1464: includes(:project). Chris@1464: where("#{Project.table_name}.id = #{id}" + Chris@1464: " OR (#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED} AND (" + Chris@1464: " #{Version.table_name}.sharing = 'system'" + Chris@1464: " OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" + Chris@1464: " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" + Chris@1464: " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" + Chris@1464: "))") Chris@929: end 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@1517: members.includes(: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@909: 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@909: Chris@909: # Users/groups issues can be assigned to Chris@0: 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@0: end Chris@909: 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@909: 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@1115: members.select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}.collect {|m| m.principal} Chris@0: end Chris@909: Chris@1464: # Returns a scope 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@1464: @all_issue_custom_fields ||= IssueCustomField. Chris@1464: sorted. Chris@1464: where("is_for_all = ? OR id IN (SELECT DISTINCT cfp.custom_field_id" + Chris@1464: " FROM #{table_name_prefix}custom_fields_projects#{table_name_suffix} cfp" + Chris@1464: " WHERE cfp.project_id = ?)", true, id) 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@909: Chris@0: def project Chris@0: self Chris@0: end Chris@909: Chris@0: def <=>(project) Chris@0: name.downcase <=> project.name.downcase Chris@0: end Chris@909: Chris@0: def to_s Chris@0: name Chris@0: end Chris@909: Chris@0: # Returns a short description of the projects (first lines) chris@1215: def short_description(length = 200) 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@1215: description.gsub(/![^\s]+!/, '').gsub(/^(\s*[^\n\r]*).*$/m, '\1').gsub(/^(.{#{length}}[^\.;:,-]*).*$/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@1115: unless active? Chris@1115: if archived? Chris@1115: s << ' archived' Chris@1115: else Chris@1115: s << ' closed' Chris@1115: end Chris@1115: end 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@1464: @start_date ||= [ Chris@117: issues.minimum('start_date'), Chris@1464: shared_versions.minimum('effective_date'), Chris@1464: Issue.fixed_version(shared_versions).minimum('start_date') Chris@1464: ].compact.min chris@22: end chris@22: chris@22: # The latest due date of an issue or version chris@22: def due_date Chris@1464: @due_date ||= [ Chris@117: issues.maximum('due_date'), Chris@1464: shared_versions.maximum('effective_date'), Chris@1464: Issue.fixed_version(shared_versions).maximum('due_date') Chris@1464: ].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@1464: total = versions.collect(&:completed_percent).sum chris@22: chris@22: total / versions.count chris@22: else chris@22: 100 chris@22: end chris@22: end chris@22: end Chris@909: Chris@1115: # Return true if this project allows 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@1115: if archived? Chris@1115: # No action allowed on archived projects Chris@1115: return false Chris@1115: end Chris@1115: unless active? || Redmine::AccessControl.read_action?(action) Chris@1115: # No write action allowed on closed projects Chris@1115: return false Chris@1115: end Chris@1115: # No action allowed on disabled modules 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@909: 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@0: end Chris@909: 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@909: 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@680: 'issue_custom_field_ids', chris@680: 'has_welcome_page' 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@909: Chris@1464: safe_attributes 'inherit_members', Chris@1464: :if => lambda {|project, user| project.parent.nil? || project.parent.visible?(user)} Chris@1464: 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@909: Chris@0: # Returns an auto-generated project identifier based on the last identifier used Chris@0: def self.next_identifier Chris@1464: p = Project.order('id DESC').first 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@909: 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@909: 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@1464: # Returns a new unsaved Project instance with attributes copied from +project+ Chris@0: def self.copy_from(project) Chris@1464: project = project.is_a?(Project) ? project : Project.find(project) Chris@1464: # clear unique attributes Chris@1464: attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt') Chris@1464: copy = Project.new(attributes) Chris@1464: copy.enabled_modules = project.enabled_modules Chris@1464: copy.trackers = project.trackers Chris@1464: copy.custom_values = project.custom_values.collect {|v| v.clone} Chris@1464: copy.issue_custom_fields = project.issue_custom_fields Chris@1464: copy 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@909: 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@909: Chris@0: private Chris@909: Chris@1464: def after_parent_changed(parent_was) Chris@1464: remove_inherited_member_roles Chris@1464: add_inherited_member_roles Chris@1464: end Chris@1464: Chris@1464: def update_inherited_members Chris@1464: if parent Chris@1464: if inherit_members? && !inherit_members_was Chris@1464: remove_inherited_member_roles Chris@1464: add_inherited_member_roles Chris@1464: elsif !inherit_members? && inherit_members_was Chris@1464: remove_inherited_member_roles Chris@1464: end Chris@1464: end Chris@1464: end Chris@1464: Chris@1464: def remove_inherited_member_roles Chris@1464: member_roles = memberships.map(&:member_roles).flatten Chris@1464: member_role_ids = member_roles.map(&:id) Chris@1464: member_roles.each do |member_role| Chris@1464: if member_role.inherited_from && !member_role_ids.include?(member_role.inherited_from) Chris@1464: member_role.destroy Chris@1464: end Chris@1464: end Chris@1464: end Chris@1464: Chris@1464: def add_inherited_member_roles Chris@1464: if inherit_members? && parent Chris@1464: parent.memberships.each do |parent_member| Chris@1464: member = Member.find_or_new(self.id, parent_member.user_id) Chris@1464: parent_member.member_roles.each do |parent_member_role| Chris@1464: member.member_roles << MemberRole.new(:role => parent_member_role.role, :inherited_from => parent_member_role.id) Chris@1464: end Chris@1464: member.save! Chris@1464: end Chris@1464: end Chris@1464: end Chris@1464: 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@1294: wiki = 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@1294: Chris@1294: self.wiki = wiki 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@909: Chris@0: # Copies issues from +project+ 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@909: Chris@1115: # Store status and reopen locked/closed versions Chris@1115: version_statuses = versions.reject(&:open?).map {|version| [version, version.status]} Chris@1115: version_statuses.each do |version, status| Chris@1115: version.update_attribute :status, 'open' Chris@1115: end Chris@1115: Chris@0: # Get issues sorted by root_id, lft so that parent issues Chris@0: # get copied before their children Chris@1517: project.issues.reorder('root_id, lft').each do |issue| Chris@0: new_issue = Issue.new Chris@1115: new_issue.copy_from(issue, :subtasks => false, :link => false) Chris@0: new_issue.project = self Chris@1464: # Changing project resets the custom field values Chris@1464: # TODO: handle this in Issue#project= Chris@1464: new_issue.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h} Chris@1115: # Reassign fixed_versions by name, since names are unique per project Chris@1115: if issue.fixed_version && issue.fixed_version.project == project Chris@1115: new_issue.fixed_version = self.versions.detect {|v| v.name == issue.fixed_version.name} Chris@0: end Chris@1115: # Reassign the category by name, since names are unique per project Chris@0: if issue.category Chris@1115: new_issue.category = self.issue_categories.detect {|c| c.name == issue.category.name} 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@909: 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@1115: # Restore locked/closed version statuses Chris@1115: version_statuses.each do |version, status| Chris@1115: version.update_attribute :status, status Chris@1115: end Chris@1115: 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@909: 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@909: 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@909: 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@1464: new_query = IssueQuery.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@909: new_query.user_id = query.user_id 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@909: Chris@0: def allowed_permissions Chris@0: @allowed_permissions ||= begin Chris@1464: module_names = enabled_modules.loaded? ? enabled_modules.map(&:name) : enabled_modules.pluck(: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@909: 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@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@0: end Chris@1517: scope Chris@0: end Chris@909: 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@1115: Chris@1115: def update_position_under_parent Chris@1115: set_or_update_position_under(parent) Chris@1115: end Chris@1115: Chris@1517: public Chris@1517: Chris@1115: # Inserts/moves the project so that target's children or root projects stay alphabetically sorted Chris@1115: def set_or_update_position_under(target_parent) Chris@1464: parent_was = parent Chris@1115: sibs = (target_parent.nil? ? self.class.roots : target_parent.children) Chris@1115: 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@1115: Chris@1115: if to_be_inserted_before Chris@1115: move_to_left_of(to_be_inserted_before) Chris@1115: elsif target_parent.nil? Chris@1115: if sibs.empty? Chris@1115: # move_to_root adds the project in first (ie. left) position Chris@1115: move_to_root Chris@1115: else Chris@1115: move_to_right_of(sibs.last) unless self == sibs.last Chris@1115: end Chris@1115: else Chris@1115: # move_to_child_of adds the project in last (ie.right) position Chris@1115: move_to_child_of(target_parent) Chris@1115: end Chris@1464: if parent_was != target_parent Chris@1464: after_parent_changed(parent_was) Chris@1464: end Chris@1115: end Chris@0: end