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 36KB

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