You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

project.rb 34KB

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