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