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

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