PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/app/models/project.rb

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