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

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