Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

project.rb 42KB

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