##// END OF EJS Templates
Rails 3.1 compatibility....
Jean-Philippe Lang -
r8953:64d843a4d715
parent child
Show More
@@ -1,123 +1,126
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
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
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.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class AttachmentsController < ApplicationController
18 class AttachmentsController < ApplicationController
19 before_filter :find_project, :except => :upload
19 before_filter :find_project, :except => :upload
20 before_filter :file_readable, :read_authorize, :only => [:show, :download]
20 before_filter :file_readable, :read_authorize, :only => [:show, :download]
21 before_filter :delete_authorize, :only => :destroy
21 before_filter :delete_authorize, :only => :destroy
22 before_filter :authorize_global, :only => :upload
22 before_filter :authorize_global, :only => :upload
23
23
24 accept_api_auth :show, :download, :upload
24 accept_api_auth :show, :download, :upload
25
25
26 def show
26 def show
27 respond_to do |format|
27 respond_to do |format|
28 format.html {
28 format.html {
29 if @attachment.is_diff?
29 if @attachment.is_diff?
30 @diff = File.new(@attachment.diskfile, "rb").read
30 @diff = File.new(@attachment.diskfile, "rb").read
31 @diff_type = params[:type] || User.current.pref[:diff_type] || 'inline'
31 @diff_type = params[:type] || User.current.pref[:diff_type] || 'inline'
32 @diff_type = 'inline' unless %w(inline sbs).include?(@diff_type)
32 @diff_type = 'inline' unless %w(inline sbs).include?(@diff_type)
33 # Save diff type as user preference
33 # Save diff type as user preference
34 if User.current.logged? && @diff_type != User.current.pref[:diff_type]
34 if User.current.logged? && @diff_type != User.current.pref[:diff_type]
35 User.current.pref[:diff_type] = @diff_type
35 User.current.pref[:diff_type] = @diff_type
36 User.current.preference.save
36 User.current.preference.save
37 end
37 end
38 render :action => 'diff'
38 render :action => 'diff'
39 elsif @attachment.is_text? && @attachment.filesize <= Setting.file_max_size_displayed.to_i.kilobyte
39 elsif @attachment.is_text? && @attachment.filesize <= Setting.file_max_size_displayed.to_i.kilobyte
40 @content = File.new(@attachment.diskfile, "rb").read
40 @content = File.new(@attachment.diskfile, "rb").read
41 render :action => 'file'
41 render :action => 'file'
42 else
42 else
43 download
43 download
44 end
44 end
45 }
45 }
46 format.api
46 format.api
47 end
47 end
48 end
48 end
49
49
50 def download
50 def download
51 if @attachment.container.is_a?(Version) || @attachment.container.is_a?(Project)
51 if @attachment.container.is_a?(Version) || @attachment.container.is_a?(Project)
52 @attachment.increment_download
52 @attachment.increment_download
53 end
53 end
54
54
55 # images are sent inline
55 # images are sent inline
56 send_file @attachment.diskfile, :filename => filename_for_content_disposition(@attachment.filename),
56 send_file @attachment.diskfile, :filename => filename_for_content_disposition(@attachment.filename),
57 :type => detect_content_type(@attachment),
57 :type => detect_content_type(@attachment),
58 :disposition => (@attachment.image? ? 'inline' : 'attachment')
58 :disposition => (@attachment.image? ? 'inline' : 'attachment')
59
59
60 end
60 end
61
61
62 def upload
62 def upload
63 # Make sure that API users get used to set this content type
63 # Make sure that API users get used to set this content type
64 # as it won't trigger Rails' automatic parsing of the request body for parameters
64 # as it won't trigger Rails' automatic parsing of the request body for parameters
65 unless request.content_type == 'application/octet-stream'
65 unless request.content_type == 'application/octet-stream'
66 render :nothing => true, :status => 406
66 render :nothing => true, :status => 406
67 return
67 return
68 end
68 end
69
69
70 @attachment = Attachment.new(:file => request.body)
70 @attachment = Attachment.new(:file => request.body)
71 @attachment.author = User.current
71 @attachment.author = User.current
72 @attachment.filename = Redmine::Utils.random_hex(16)
72 @attachment.filename = Redmine::Utils.random_hex(16)
73
73
74 if @attachment.save
74 if @attachment.save
75 respond_to do |format|
75 respond_to do |format|
76 format.api { render :action => 'upload', :status => :created }
76 format.api { render :action => 'upload', :status => :created }
77 end
77 end
78 else
78 else
79 respond_to do |format|
79 respond_to do |format|
80 format.api { render_validation_errors(@attachment) }
80 format.api { render_validation_errors(@attachment) }
81 end
81 end
82 end
82 end
83 end
83 end
84
84
85 def destroy
85 def destroy
86 if @attachment.container.respond_to?(:init_journal)
87 @attachment.container.init_journal(User.current)
88 end
86 # Make sure association callbacks are called
89 # Make sure association callbacks are called
87 @attachment.container.attachments.delete(@attachment)
90 @attachment.container.attachments.delete(@attachment)
88 redirect_to :back
91 redirect_to :back
89 rescue ::ActionController::RedirectBackError
92 rescue ::ActionController::RedirectBackError
90 redirect_to :controller => 'projects', :action => 'show', :id => @project
93 redirect_to :controller => 'projects', :action => 'show', :id => @project
91 end
94 end
92
95
93 private
96 private
94 def find_project
97 def find_project
95 @attachment = Attachment.find(params[:id])
98 @attachment = Attachment.find(params[:id])
96 # Show 404 if the filename in the url is wrong
99 # Show 404 if the filename in the url is wrong
97 raise ActiveRecord::RecordNotFound if params[:filename] && params[:filename] != @attachment.filename
100 raise ActiveRecord::RecordNotFound if params[:filename] && params[:filename] != @attachment.filename
98 @project = @attachment.project
101 @project = @attachment.project
99 rescue ActiveRecord::RecordNotFound
102 rescue ActiveRecord::RecordNotFound
100 render_404
103 render_404
101 end
104 end
102
105
103 # Checks that the file exists and is readable
106 # Checks that the file exists and is readable
104 def file_readable
107 def file_readable
105 @attachment.readable? ? true : render_404
108 @attachment.readable? ? true : render_404
106 end
109 end
107
110
108 def read_authorize
111 def read_authorize
109 @attachment.visible? ? true : deny_access
112 @attachment.visible? ? true : deny_access
110 end
113 end
111
114
112 def delete_authorize
115 def delete_authorize
113 @attachment.deletable? ? true : deny_access
116 @attachment.deletable? ? true : deny_access
114 end
117 end
115
118
116 def detect_content_type(attachment)
119 def detect_content_type(attachment)
117 content_type = attachment.content_type
120 content_type = attachment.content_type
118 if content_type.blank?
121 if content_type.blank?
119 content_type = Redmine::MimeType.of(attachment.filename)
122 content_type = Redmine::MimeType.of(attachment.filename)
120 end
123 end
121 content_type.to_s
124 content_type.to_s
122 end
125 end
123 end
126 end
@@ -1,1078 +1,1077
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
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
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.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class Issue < ActiveRecord::Base
18 class Issue < ActiveRecord::Base
19 include Redmine::SafeAttributes
19 include Redmine::SafeAttributes
20
20
21 belongs_to :project
21 belongs_to :project
22 belongs_to :tracker
22 belongs_to :tracker
23 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
23 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
24 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
24 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
25 belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
25 belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
26 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
26 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
27 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
27 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
28 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
28 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
29
29
30 has_many :journals, :as => :journalized, :dependent => :destroy
30 has_many :journals, :as => :journalized, :dependent => :destroy
31 has_many :time_entries, :dependent => :delete_all
31 has_many :time_entries, :dependent => :delete_all
32 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
32 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
33
33
34 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
34 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
35 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
35 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
36
36
37 acts_as_nested_set :scope => 'root_id', :dependent => :destroy
37 acts_as_nested_set :scope => 'root_id', :dependent => :destroy
38 acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
38 acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
39 acts_as_customizable
39 acts_as_customizable
40 acts_as_watchable
40 acts_as_watchable
41 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
41 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
42 :include => [:project, :journals],
42 :include => [:project, :journals],
43 # sort by id so that limited eager loading doesn't break with postgresql
43 # sort by id so that limited eager loading doesn't break with postgresql
44 :order_column => "#{table_name}.id"
44 :order_column => "#{table_name}.id"
45 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
45 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
46 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
46 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
47 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
47 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
48
48
49 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
49 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
50 :author_key => :author_id
50 :author_key => :author_id
51
51
52 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
52 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
53
53
54 attr_reader :current_journal
54 attr_reader :current_journal
55
55
56 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
56 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
57
57
58 validates_length_of :subject, :maximum => 255
58 validates_length_of :subject, :maximum => 255
59 validates_inclusion_of :done_ratio, :in => 0..100
59 validates_inclusion_of :done_ratio, :in => 0..100
60 validates_numericality_of :estimated_hours, :allow_nil => true
60 validates_numericality_of :estimated_hours, :allow_nil => true
61 validate :validate_issue
61 validate :validate_issue
62
62
63 named_scope :visible, lambda {|*args| { :include => :project,
63 named_scope :visible, lambda {|*args| { :include => :project,
64 :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
64 :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
65
65
66 named_scope :open, lambda {|*args|
66 named_scope :open, lambda {|*args|
67 is_closed = args.size > 0 ? !args.first : false
67 is_closed = args.size > 0 ? !args.first : false
68 {:conditions => ["#{IssueStatus.table_name}.is_closed = ?", is_closed], :include => :status}
68 {:conditions => ["#{IssueStatus.table_name}.is_closed = ?", is_closed], :include => :status}
69 }
69 }
70
70
71 named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
71 named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
72 named_scope :with_limit, lambda { |limit| { :limit => limit} }
72 named_scope :with_limit, lambda { |limit| { :limit => limit} }
73 named_scope :on_active_project, :include => [:status, :project, :tracker],
73 named_scope :on_active_project, :include => [:status, :project, :tracker],
74 :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
74 :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
75
75
76 before_create :default_assign
76 before_create :default_assign
77 before_save :close_duplicates, :update_done_ratio_from_issue_status
77 before_save :close_duplicates, :update_done_ratio_from_issue_status
78 after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
78 after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
79 after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
79 after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
80 after_destroy :update_parent_attributes
80 after_destroy :update_parent_attributes
81
81
82 # Returns a SQL conditions string used to find all issues visible by the specified user
82 # Returns a SQL conditions string used to find all issues visible by the specified user
83 def self.visible_condition(user, options={})
83 def self.visible_condition(user, options={})
84 Project.allowed_to_condition(user, :view_issues, options) do |role, user|
84 Project.allowed_to_condition(user, :view_issues, options) do |role, user|
85 case role.issues_visibility
85 case role.issues_visibility
86 when 'all'
86 when 'all'
87 nil
87 nil
88 when 'default'
88 when 'default'
89 user_ids = [user.id] + user.groups.map(&:id)
89 user_ids = [user.id] + user.groups.map(&:id)
90 "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
90 "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
91 when 'own'
91 when 'own'
92 user_ids = [user.id] + user.groups.map(&:id)
92 user_ids = [user.id] + user.groups.map(&:id)
93 "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
93 "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
94 else
94 else
95 '1=0'
95 '1=0'
96 end
96 end
97 end
97 end
98 end
98 end
99
99
100 # Returns true if usr or current user is allowed to view the issue
100 # Returns true if usr or current user is allowed to view the issue
101 def visible?(usr=nil)
101 def visible?(usr=nil)
102 (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
102 (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
103 case role.issues_visibility
103 case role.issues_visibility
104 when 'all'
104 when 'all'
105 true
105 true
106 when 'default'
106 when 'default'
107 !self.is_private? || self.author == user || user.is_or_belongs_to?(assigned_to)
107 !self.is_private? || self.author == user || user.is_or_belongs_to?(assigned_to)
108 when 'own'
108 when 'own'
109 self.author == user || user.is_or_belongs_to?(assigned_to)
109 self.author == user || user.is_or_belongs_to?(assigned_to)
110 else
110 else
111 false
111 false
112 end
112 end
113 end
113 end
114 end
114 end
115
115
116 def initialize(attributes=nil, *args)
116 def initialize(attributes=nil, *args)
117 super
117 super
118 if new_record?
118 if new_record?
119 # set default values for new records only
119 # set default values for new records only
120 self.status ||= IssueStatus.default
120 self.status ||= IssueStatus.default
121 self.priority ||= IssuePriority.default
121 self.priority ||= IssuePriority.default
122 self.watcher_user_ids = []
122 self.watcher_user_ids = []
123 end
123 end
124 end
124 end
125
125
126 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
126 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
127 def available_custom_fields
127 def available_custom_fields
128 (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
128 (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
129 end
129 end
130
130
131 # Copies attributes from another issue, arg can be an id or an Issue
131 # Copies attributes from another issue, arg can be an id or an Issue
132 def copy_from(arg, options={})
132 def copy_from(arg, options={})
133 issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
133 issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
134 self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
134 self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
135 self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
135 self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
136 self.status = issue.status
136 self.status = issue.status
137 self.author = User.current
137 self.author = User.current
138 unless options[:attachments] == false
138 unless options[:attachments] == false
139 self.attachments = issue.attachments.map do |attachement|
139 self.attachments = issue.attachments.map do |attachement|
140 attachement.copy(:container => self)
140 attachement.copy(:container => self)
141 end
141 end
142 end
142 end
143 @copied_from = issue
143 @copied_from = issue
144 self
144 self
145 end
145 end
146
146
147 # Returns an unsaved copy of the issue
147 # Returns an unsaved copy of the issue
148 def copy(attributes=nil)
148 def copy(attributes=nil)
149 copy = self.class.new.copy_from(self)
149 copy = self.class.new.copy_from(self)
150 copy.attributes = attributes if attributes
150 copy.attributes = attributes if attributes
151 copy
151 copy
152 end
152 end
153
153
154 # Returns true if the issue is a copy
154 # Returns true if the issue is a copy
155 def copy?
155 def copy?
156 @copied_from.present?
156 @copied_from.present?
157 end
157 end
158
158
159 # Moves/copies an issue to a new project and tracker
159 # Moves/copies an issue to a new project and tracker
160 # Returns the moved/copied issue on success, false on failure
160 # Returns the moved/copied issue on success, false on failure
161 def move_to_project(new_project, new_tracker=nil, options={})
161 def move_to_project(new_project, new_tracker=nil, options={})
162 ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
162 ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
163
163
164 if options[:copy]
164 if options[:copy]
165 issue = self.copy
165 issue = self.copy
166 else
166 else
167 issue = self
167 issue = self
168 end
168 end
169
169
170 issue.init_journal(User.current, options[:notes])
170 issue.init_journal(User.current, options[:notes])
171
171
172 # Preserve previous behaviour
172 # Preserve previous behaviour
173 # #move_to_project doesn't change tracker automatically
173 # #move_to_project doesn't change tracker automatically
174 issue.send :project=, new_project, true
174 issue.send :project=, new_project, true
175 if new_tracker
175 if new_tracker
176 issue.tracker = new_tracker
176 issue.tracker = new_tracker
177 end
177 end
178 # Allow bulk setting of attributes on the issue
178 # Allow bulk setting of attributes on the issue
179 if options[:attributes]
179 if options[:attributes]
180 issue.attributes = options[:attributes]
180 issue.attributes = options[:attributes]
181 end
181 end
182
182
183 issue.save ? issue : false
183 issue.save ? issue : false
184 end
184 end
185
185
186 def status_id=(sid)
186 def status_id=(sid)
187 self.status = nil
187 self.status = nil
188 write_attribute(:status_id, sid)
188 write_attribute(:status_id, sid)
189 end
189 end
190
190
191 def priority_id=(pid)
191 def priority_id=(pid)
192 self.priority = nil
192 self.priority = nil
193 write_attribute(:priority_id, pid)
193 write_attribute(:priority_id, pid)
194 end
194 end
195
195
196 def category_id=(cid)
196 def category_id=(cid)
197 self.category = nil
197 self.category = nil
198 write_attribute(:category_id, cid)
198 write_attribute(:category_id, cid)
199 end
199 end
200
200
201 def fixed_version_id=(vid)
201 def fixed_version_id=(vid)
202 self.fixed_version = nil
202 self.fixed_version = nil
203 write_attribute(:fixed_version_id, vid)
203 write_attribute(:fixed_version_id, vid)
204 end
204 end
205
205
206 def tracker_id=(tid)
206 def tracker_id=(tid)
207 self.tracker = nil
207 self.tracker = nil
208 result = write_attribute(:tracker_id, tid)
208 result = write_attribute(:tracker_id, tid)
209 @custom_field_values = nil
209 @custom_field_values = nil
210 result
210 result
211 end
211 end
212
212
213 def project_id=(project_id)
213 def project_id=(project_id)
214 if project_id.to_s != self.project_id.to_s
214 if project_id.to_s != self.project_id.to_s
215 self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
215 self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
216 end
216 end
217 end
217 end
218
218
219 def project=(project, keep_tracker=false)
219 def project=(project, keep_tracker=false)
220 project_was = self.project
220 project_was = self.project
221 write_attribute(:project_id, project ? project.id : nil)
221 write_attribute(:project_id, project ? project.id : nil)
222 association_instance_set('project', project)
222 association_instance_set('project', project)
223 if project_was && project && project_was != project
223 if project_was && project && project_was != project
224 unless keep_tracker || project.trackers.include?(tracker)
224 unless keep_tracker || project.trackers.include?(tracker)
225 self.tracker = project.trackers.first
225 self.tracker = project.trackers.first
226 end
226 end
227 # Reassign to the category with same name if any
227 # Reassign to the category with same name if any
228 if category
228 if category
229 self.category = project.issue_categories.find_by_name(category.name)
229 self.category = project.issue_categories.find_by_name(category.name)
230 end
230 end
231 # Keep the fixed_version if it's still valid in the new_project
231 # Keep the fixed_version if it's still valid in the new_project
232 if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
232 if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
233 self.fixed_version = nil
233 self.fixed_version = nil
234 end
234 end
235 if parent && parent.project_id != project_id
235 if parent && parent.project_id != project_id
236 self.parent_issue_id = nil
236 self.parent_issue_id = nil
237 end
237 end
238 @custom_field_values = nil
238 @custom_field_values = nil
239 end
239 end
240 end
240 end
241
241
242 def description=(arg)
242 def description=(arg)
243 if arg.is_a?(String)
243 if arg.is_a?(String)
244 arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
244 arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
245 end
245 end
246 write_attribute(:description, arg)
246 write_attribute(:description, arg)
247 end
247 end
248
248
249 # Overrides attributes= so that project and tracker get assigned first
249 # Overrides attributes= so that project and tracker get assigned first
250 def attributes_with_project_and_tracker_first=(new_attributes, *args)
250 def attributes_with_project_and_tracker_first=(new_attributes, *args)
251 return if new_attributes.nil?
251 return if new_attributes.nil?
252 attrs = new_attributes.dup
252 attrs = new_attributes.dup
253 attrs.stringify_keys!
253 attrs.stringify_keys!
254
254
255 %w(project project_id tracker tracker_id).each do |attr|
255 %w(project project_id tracker tracker_id).each do |attr|
256 if attrs.has_key?(attr)
256 if attrs.has_key?(attr)
257 send "#{attr}=", attrs.delete(attr)
257 send "#{attr}=", attrs.delete(attr)
258 end
258 end
259 end
259 end
260 send :attributes_without_project_and_tracker_first=, attrs, *args
260 send :attributes_without_project_and_tracker_first=, attrs, *args
261 end
261 end
262 # Do not redefine alias chain on reload (see #4838)
262 # Do not redefine alias chain on reload (see #4838)
263 alias_method_chain(:attributes=, :project_and_tracker_first) unless method_defined?(:attributes_without_project_and_tracker_first=)
263 alias_method_chain(:attributes=, :project_and_tracker_first) unless method_defined?(:attributes_without_project_and_tracker_first=)
264
264
265 def estimated_hours=(h)
265 def estimated_hours=(h)
266 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
266 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
267 end
267 end
268
268
269 safe_attributes 'project_id',
269 safe_attributes 'project_id',
270 :if => lambda {|issue, user|
270 :if => lambda {|issue, user|
271 if issue.new_record?
271 if issue.new_record?
272 issue.copy?
272 issue.copy?
273 elsif user.allowed_to?(:move_issues, issue.project)
273 elsif user.allowed_to?(:move_issues, issue.project)
274 projects = Issue.allowed_target_projects_on_move(user)
274 projects = Issue.allowed_target_projects_on_move(user)
275 projects.include?(issue.project) && projects.size > 1
275 projects.include?(issue.project) && projects.size > 1
276 end
276 end
277 }
277 }
278
278
279 safe_attributes 'tracker_id',
279 safe_attributes 'tracker_id',
280 'status_id',
280 'status_id',
281 'category_id',
281 'category_id',
282 'assigned_to_id',
282 'assigned_to_id',
283 'priority_id',
283 'priority_id',
284 'fixed_version_id',
284 'fixed_version_id',
285 'subject',
285 'subject',
286 'description',
286 'description',
287 'start_date',
287 'start_date',
288 'due_date',
288 'due_date',
289 'done_ratio',
289 'done_ratio',
290 'estimated_hours',
290 'estimated_hours',
291 'custom_field_values',
291 'custom_field_values',
292 'custom_fields',
292 'custom_fields',
293 'lock_version',
293 'lock_version',
294 :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
294 :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
295
295
296 safe_attributes 'status_id',
296 safe_attributes 'status_id',
297 'assigned_to_id',
297 'assigned_to_id',
298 'fixed_version_id',
298 'fixed_version_id',
299 'done_ratio',
299 'done_ratio',
300 'lock_version',
300 'lock_version',
301 :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
301 :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
302
302
303 safe_attributes 'watcher_user_ids',
303 safe_attributes 'watcher_user_ids',
304 :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
304 :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
305
305
306 safe_attributes 'is_private',
306 safe_attributes 'is_private',
307 :if => lambda {|issue, user|
307 :if => lambda {|issue, user|
308 user.allowed_to?(:set_issues_private, issue.project) ||
308 user.allowed_to?(:set_issues_private, issue.project) ||
309 (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
309 (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
310 }
310 }
311
311
312 safe_attributes 'parent_issue_id',
312 safe_attributes 'parent_issue_id',
313 :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
313 :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
314 user.allowed_to?(:manage_subtasks, issue.project)}
314 user.allowed_to?(:manage_subtasks, issue.project)}
315
315
316 # Safely sets attributes
316 # Safely sets attributes
317 # Should be called from controllers instead of #attributes=
317 # Should be called from controllers instead of #attributes=
318 # attr_accessible is too rough because we still want things like
318 # attr_accessible is too rough because we still want things like
319 # Issue.new(:project => foo) to work
319 # Issue.new(:project => foo) to work
320 def safe_attributes=(attrs, user=User.current)
320 def safe_attributes=(attrs, user=User.current)
321 return unless attrs.is_a?(Hash)
321 return unless attrs.is_a?(Hash)
322
322
323 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
323 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
324 attrs = delete_unsafe_attributes(attrs, user)
324 attrs = delete_unsafe_attributes(attrs, user)
325 return if attrs.empty?
325 return if attrs.empty?
326
326
327 # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
327 # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
328 if p = attrs.delete('project_id')
328 if p = attrs.delete('project_id')
329 if allowed_target_projects(user).collect(&:id).include?(p.to_i)
329 if allowed_target_projects(user).collect(&:id).include?(p.to_i)
330 self.project_id = p
330 self.project_id = p
331 end
331 end
332 end
332 end
333
333
334 if t = attrs.delete('tracker_id')
334 if t = attrs.delete('tracker_id')
335 self.tracker_id = t
335 self.tracker_id = t
336 end
336 end
337
337
338 if attrs['status_id']
338 if attrs['status_id']
339 unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
339 unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
340 attrs.delete('status_id')
340 attrs.delete('status_id')
341 end
341 end
342 end
342 end
343
343
344 unless leaf?
344 unless leaf?
345 attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
345 attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
346 end
346 end
347
347
348 if attrs['parent_issue_id'].present?
348 if attrs['parent_issue_id'].present?
349 attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
349 attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
350 end
350 end
351
351
352 # mass-assignment security bypass
352 # mass-assignment security bypass
353 self.send :attributes=, attrs, false
353 self.send :attributes=, attrs, false
354 end
354 end
355
355
356 def done_ratio
356 def done_ratio
357 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
357 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
358 status.default_done_ratio
358 status.default_done_ratio
359 else
359 else
360 read_attribute(:done_ratio)
360 read_attribute(:done_ratio)
361 end
361 end
362 end
362 end
363
363
364 def self.use_status_for_done_ratio?
364 def self.use_status_for_done_ratio?
365 Setting.issue_done_ratio == 'issue_status'
365 Setting.issue_done_ratio == 'issue_status'
366 end
366 end
367
367
368 def self.use_field_for_done_ratio?
368 def self.use_field_for_done_ratio?
369 Setting.issue_done_ratio == 'issue_field'
369 Setting.issue_done_ratio == 'issue_field'
370 end
370 end
371
371
372 def validate_issue
372 def validate_issue
373 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
373 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
374 errors.add :due_date, :not_a_date
374 errors.add :due_date, :not_a_date
375 end
375 end
376
376
377 if self.due_date and self.start_date and self.due_date < self.start_date
377 if self.due_date and self.start_date and self.due_date < self.start_date
378 errors.add :due_date, :greater_than_start_date
378 errors.add :due_date, :greater_than_start_date
379 end
379 end
380
380
381 if start_date && soonest_start && start_date < soonest_start
381 if start_date && soonest_start && start_date < soonest_start
382 errors.add :start_date, :invalid
382 errors.add :start_date, :invalid
383 end
383 end
384
384
385 if fixed_version
385 if fixed_version
386 if !assignable_versions.include?(fixed_version)
386 if !assignable_versions.include?(fixed_version)
387 errors.add :fixed_version_id, :inclusion
387 errors.add :fixed_version_id, :inclusion
388 elsif reopened? && fixed_version.closed?
388 elsif reopened? && fixed_version.closed?
389 errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
389 errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
390 end
390 end
391 end
391 end
392
392
393 # Checks that the issue can not be added/moved to a disabled tracker
393 # Checks that the issue can not be added/moved to a disabled tracker
394 if project && (tracker_id_changed? || project_id_changed?)
394 if project && (tracker_id_changed? || project_id_changed?)
395 unless project.trackers.include?(tracker)
395 unless project.trackers.include?(tracker)
396 errors.add :tracker_id, :inclusion
396 errors.add :tracker_id, :inclusion
397 end
397 end
398 end
398 end
399
399
400 # Checks parent issue assignment
400 # Checks parent issue assignment
401 if @parent_issue
401 if @parent_issue
402 if @parent_issue.project_id != project_id
402 if @parent_issue.project_id != project_id
403 errors.add :parent_issue_id, :not_same_project
403 errors.add :parent_issue_id, :not_same_project
404 elsif !new_record?
404 elsif !new_record?
405 # moving an existing issue
405 # moving an existing issue
406 if @parent_issue.root_id != root_id
406 if @parent_issue.root_id != root_id
407 # we can always move to another tree
407 # we can always move to another tree
408 elsif move_possible?(@parent_issue)
408 elsif move_possible?(@parent_issue)
409 # move accepted inside tree
409 # move accepted inside tree
410 else
410 else
411 errors.add :parent_issue_id, :not_a_valid_parent
411 errors.add :parent_issue_id, :not_a_valid_parent
412 end
412 end
413 end
413 end
414 end
414 end
415 end
415 end
416
416
417 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
417 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
418 # even if the user turns off the setting later
418 # even if the user turns off the setting later
419 def update_done_ratio_from_issue_status
419 def update_done_ratio_from_issue_status
420 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
420 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
421 self.done_ratio = status.default_done_ratio
421 self.done_ratio = status.default_done_ratio
422 end
422 end
423 end
423 end
424
424
425 def init_journal(user, notes = "")
425 def init_journal(user, notes = "")
426 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
426 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
427 if new_record?
427 if new_record?
428 @current_journal.notify = false
428 @current_journal.notify = false
429 else
429 else
430 @attributes_before_change = attributes.dup
430 @attributes_before_change = attributes.dup
431 @custom_values_before_change = {}
431 @custom_values_before_change = {}
432 self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
432 self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
433 end
433 end
434 # Make sure updated_on is updated when adding a note.
434 # Make sure updated_on is updated when adding a note.
435 updated_on_will_change!
435 updated_on_will_change!
436 @current_journal
436 @current_journal
437 end
437 end
438
438
439 # Returns the id of the last journal or nil
439 # Returns the id of the last journal or nil
440 def last_journal_id
440 def last_journal_id
441 if new_record?
441 if new_record?
442 nil
442 nil
443 else
443 else
444 journals.first(:order => "#{Journal.table_name}.id DESC").try(:id)
444 journals.first(:order => "#{Journal.table_name}.id DESC").try(:id)
445 end
445 end
446 end
446 end
447
447
448 # Return true if the issue is closed, otherwise false
448 # Return true if the issue is closed, otherwise false
449 def closed?
449 def closed?
450 self.status.is_closed?
450 self.status.is_closed?
451 end
451 end
452
452
453 # Return true if the issue is being reopened
453 # Return true if the issue is being reopened
454 def reopened?
454 def reopened?
455 if !new_record? && status_id_changed?
455 if !new_record? && status_id_changed?
456 status_was = IssueStatus.find_by_id(status_id_was)
456 status_was = IssueStatus.find_by_id(status_id_was)
457 status_new = IssueStatus.find_by_id(status_id)
457 status_new = IssueStatus.find_by_id(status_id)
458 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
458 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
459 return true
459 return true
460 end
460 end
461 end
461 end
462 false
462 false
463 end
463 end
464
464
465 # Return true if the issue is being closed
465 # Return true if the issue is being closed
466 def closing?
466 def closing?
467 if !new_record? && status_id_changed?
467 if !new_record? && status_id_changed?
468 status_was = IssueStatus.find_by_id(status_id_was)
468 status_was = IssueStatus.find_by_id(status_id_was)
469 status_new = IssueStatus.find_by_id(status_id)
469 status_new = IssueStatus.find_by_id(status_id)
470 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
470 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
471 return true
471 return true
472 end
472 end
473 end
473 end
474 false
474 false
475 end
475 end
476
476
477 # Returns true if the issue is overdue
477 # Returns true if the issue is overdue
478 def overdue?
478 def overdue?
479 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
479 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
480 end
480 end
481
481
482 # Is the amount of work done less than it should for the due date
482 # Is the amount of work done less than it should for the due date
483 def behind_schedule?
483 def behind_schedule?
484 return false if start_date.nil? || due_date.nil?
484 return false if start_date.nil? || due_date.nil?
485 done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
485 done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
486 return done_date <= Date.today
486 return done_date <= Date.today
487 end
487 end
488
488
489 # Does this issue have children?
489 # Does this issue have children?
490 def children?
490 def children?
491 !leaf?
491 !leaf?
492 end
492 end
493
493
494 # Users the issue can be assigned to
494 # Users the issue can be assigned to
495 def assignable_users
495 def assignable_users
496 users = project.assignable_users
496 users = project.assignable_users
497 users << author if author
497 users << author if author
498 users << assigned_to if assigned_to
498 users << assigned_to if assigned_to
499 users.uniq.sort
499 users.uniq.sort
500 end
500 end
501
501
502 # Versions that the issue can be assigned to
502 # Versions that the issue can be assigned to
503 def assignable_versions
503 def assignable_versions
504 @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
504 @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
505 end
505 end
506
506
507 # Returns true if this issue is blocked by another issue that is still open
507 # Returns true if this issue is blocked by another issue that is still open
508 def blocked?
508 def blocked?
509 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
509 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
510 end
510 end
511
511
512 # Returns an array of status that user is able to apply
512 # Returns an array of status that user is able to apply
513 def new_statuses_allowed_to(user=User.current, include_default=false)
513 def new_statuses_allowed_to(user=User.current, include_default=false)
514 statuses = status.find_new_statuses_allowed_to(
514 statuses = status.find_new_statuses_allowed_to(
515 user.admin ? Role.all : user.roles_for_project(project),
515 user.admin ? Role.all : user.roles_for_project(project),
516 tracker,
516 tracker,
517 author == user,
517 author == user,
518 assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
518 assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
519 )
519 )
520 statuses << status unless statuses.empty?
520 statuses << status unless statuses.empty?
521 statuses << IssueStatus.default if include_default
521 statuses << IssueStatus.default if include_default
522 statuses = statuses.uniq.sort
522 statuses = statuses.uniq.sort
523 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
523 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
524 end
524 end
525
525
526 def assigned_to_was
526 def assigned_to_was
527 if assigned_to_id_changed? && assigned_to_id_was.present?
527 if assigned_to_id_changed? && assigned_to_id_was.present?
528 @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
528 @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
529 end
529 end
530 end
530 end
531
531
532 # Returns the mail adresses of users that should be notified
532 # Returns the mail adresses of users that should be notified
533 def recipients
533 def recipients
534 notified = []
534 notified = []
535 # Author and assignee are always notified unless they have been
535 # Author and assignee are always notified unless they have been
536 # locked or don't want to be notified
536 # locked or don't want to be notified
537 notified << author if author
537 notified << author if author
538 if assigned_to
538 if assigned_to
539 notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
539 notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
540 end
540 end
541 if assigned_to_was
541 if assigned_to_was
542 notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
542 notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
543 end
543 end
544 notified = notified.select {|u| u.active? && u.notify_about?(self)}
544 notified = notified.select {|u| u.active? && u.notify_about?(self)}
545
545
546 notified += project.notified_users
546 notified += project.notified_users
547 notified.uniq!
547 notified.uniq!
548 # Remove users that can not view the issue
548 # Remove users that can not view the issue
549 notified.reject! {|user| !visible?(user)}
549 notified.reject! {|user| !visible?(user)}
550 notified.collect(&:mail)
550 notified.collect(&:mail)
551 end
551 end
552
552
553 # Returns the number of hours spent on this issue
553 # Returns the number of hours spent on this issue
554 def spent_hours
554 def spent_hours
555 @spent_hours ||= time_entries.sum(:hours) || 0
555 @spent_hours ||= time_entries.sum(:hours) || 0
556 end
556 end
557
557
558 # Returns the total number of hours spent on this issue and its descendants
558 # Returns the total number of hours spent on this issue and its descendants
559 #
559 #
560 # Example:
560 # Example:
561 # spent_hours => 0.0
561 # spent_hours => 0.0
562 # spent_hours => 50.2
562 # spent_hours => 50.2
563 def total_spent_hours
563 def total_spent_hours
564 @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
564 @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
565 :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
565 :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
566 end
566 end
567
567
568 def relations
568 def relations
569 @relations ||= (relations_from + relations_to).sort
569 @relations ||= (relations_from + relations_to).sort
570 end
570 end
571
571
572 # Preloads relations for a collection of issues
572 # Preloads relations for a collection of issues
573 def self.load_relations(issues)
573 def self.load_relations(issues)
574 if issues.any?
574 if issues.any?
575 relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
575 relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
576 issues.each do |issue|
576 issues.each do |issue|
577 issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
577 issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
578 end
578 end
579 end
579 end
580 end
580 end
581
581
582 # Preloads visible spent time for a collection of issues
582 # Preloads visible spent time for a collection of issues
583 def self.load_visible_spent_hours(issues, user=User.current)
583 def self.load_visible_spent_hours(issues, user=User.current)
584 if issues.any?
584 if issues.any?
585 hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
585 hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
586 issues.each do |issue|
586 issues.each do |issue|
587 issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
587 issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
588 end
588 end
589 end
589 end
590 end
590 end
591
591
592 # Finds an issue relation given its id.
592 # Finds an issue relation given its id.
593 def find_relation(relation_id)
593 def find_relation(relation_id)
594 IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
594 IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
595 end
595 end
596
596
597 def all_dependent_issues(except=[])
597 def all_dependent_issues(except=[])
598 except << self
598 except << self
599 dependencies = []
599 dependencies = []
600 relations_from.each do |relation|
600 relations_from.each do |relation|
601 if relation.issue_to && !except.include?(relation.issue_to)
601 if relation.issue_to && !except.include?(relation.issue_to)
602 dependencies << relation.issue_to
602 dependencies << relation.issue_to
603 dependencies += relation.issue_to.all_dependent_issues(except)
603 dependencies += relation.issue_to.all_dependent_issues(except)
604 end
604 end
605 end
605 end
606 dependencies
606 dependencies
607 end
607 end
608
608
609 # Returns an array of issues that duplicate this one
609 # Returns an array of issues that duplicate this one
610 def duplicates
610 def duplicates
611 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
611 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
612 end
612 end
613
613
614 # Returns the due date or the target due date if any
614 # Returns the due date or the target due date if any
615 # Used on gantt chart
615 # Used on gantt chart
616 def due_before
616 def due_before
617 due_date || (fixed_version ? fixed_version.effective_date : nil)
617 due_date || (fixed_version ? fixed_version.effective_date : nil)
618 end
618 end
619
619
620 # Returns the time scheduled for this issue.
620 # Returns the time scheduled for this issue.
621 #
621 #
622 # Example:
622 # Example:
623 # Start Date: 2/26/09, End Date: 3/04/09
623 # Start Date: 2/26/09, End Date: 3/04/09
624 # duration => 6
624 # duration => 6
625 def duration
625 def duration
626 (start_date && due_date) ? due_date - start_date : 0
626 (start_date && due_date) ? due_date - start_date : 0
627 end
627 end
628
628
629 def soonest_start
629 def soonest_start
630 @soonest_start ||= (
630 @soonest_start ||= (
631 relations_to.collect{|relation| relation.successor_soonest_start} +
631 relations_to.collect{|relation| relation.successor_soonest_start} +
632 ancestors.collect(&:soonest_start)
632 ancestors.collect(&:soonest_start)
633 ).compact.max
633 ).compact.max
634 end
634 end
635
635
636 def reschedule_after(date)
636 def reschedule_after(date)
637 return if date.nil?
637 return if date.nil?
638 if leaf?
638 if leaf?
639 if start_date.nil? || start_date < date
639 if start_date.nil? || start_date < date
640 self.start_date, self.due_date = date, date + duration
640 self.start_date, self.due_date = date, date + duration
641 begin
641 begin
642 save
642 save
643 rescue ActiveRecord::StaleObjectError
643 rescue ActiveRecord::StaleObjectError
644 reload
644 reload
645 self.start_date, self.due_date = date, date + duration
645 self.start_date, self.due_date = date, date + duration
646 save
646 save
647 end
647 end
648 end
648 end
649 else
649 else
650 leaves.each do |leaf|
650 leaves.each do |leaf|
651 leaf.reschedule_after(date)
651 leaf.reschedule_after(date)
652 end
652 end
653 end
653 end
654 end
654 end
655
655
656 def <=>(issue)
656 def <=>(issue)
657 if issue.nil?
657 if issue.nil?
658 -1
658 -1
659 elsif root_id != issue.root_id
659 elsif root_id != issue.root_id
660 (root_id || 0) <=> (issue.root_id || 0)
660 (root_id || 0) <=> (issue.root_id || 0)
661 else
661 else
662 (lft || 0) <=> (issue.lft || 0)
662 (lft || 0) <=> (issue.lft || 0)
663 end
663 end
664 end
664 end
665
665
666 def to_s
666 def to_s
667 "#{tracker} ##{id}: #{subject}"
667 "#{tracker} ##{id}: #{subject}"
668 end
668 end
669
669
670 # Returns a string of css classes that apply to the issue
670 # Returns a string of css classes that apply to the issue
671 def css_classes
671 def css_classes
672 s = "issue status-#{status.position} priority-#{priority.position}"
672 s = "issue status-#{status.position} priority-#{priority.position}"
673 s << ' closed' if closed?
673 s << ' closed' if closed?
674 s << ' overdue' if overdue?
674 s << ' overdue' if overdue?
675 s << ' child' if child?
675 s << ' child' if child?
676 s << ' parent' unless leaf?
676 s << ' parent' unless leaf?
677 s << ' private' if is_private?
677 s << ' private' if is_private?
678 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
678 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
679 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
679 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
680 s
680 s
681 end
681 end
682
682
683 # Saves an issue and a time_entry from the parameters
683 # Saves an issue and a time_entry from the parameters
684 def save_issue_with_child_records(params, existing_time_entry=nil)
684 def save_issue_with_child_records(params, existing_time_entry=nil)
685 Issue.transaction do
685 Issue.transaction do
686 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
686 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
687 @time_entry = existing_time_entry || TimeEntry.new
687 @time_entry = existing_time_entry || TimeEntry.new
688 @time_entry.project = project
688 @time_entry.project = project
689 @time_entry.issue = self
689 @time_entry.issue = self
690 @time_entry.user = User.current
690 @time_entry.user = User.current
691 @time_entry.spent_on = User.current.today
691 @time_entry.spent_on = User.current.today
692 @time_entry.attributes = params[:time_entry]
692 @time_entry.attributes = params[:time_entry]
693 self.time_entries << @time_entry
693 self.time_entries << @time_entry
694 end
694 end
695
695
696 # TODO: Rename hook
696 # TODO: Rename hook
697 Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
697 Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
698 if save
698 if save
699 # TODO: Rename hook
699 # TODO: Rename hook
700 Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
700 Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
701 else
701 else
702 raise ActiveRecord::Rollback
702 raise ActiveRecord::Rollback
703 end
703 end
704 end
704 end
705 end
705 end
706
706
707 # Unassigns issues from +version+ if it's no longer shared with issue's project
707 # Unassigns issues from +version+ if it's no longer shared with issue's project
708 def self.update_versions_from_sharing_change(version)
708 def self.update_versions_from_sharing_change(version)
709 # Update issues assigned to the version
709 # Update issues assigned to the version
710 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
710 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
711 end
711 end
712
712
713 # Unassigns issues from versions that are no longer shared
713 # Unassigns issues from versions that are no longer shared
714 # after +project+ was moved
714 # after +project+ was moved
715 def self.update_versions_from_hierarchy_change(project)
715 def self.update_versions_from_hierarchy_change(project)
716 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
716 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
717 # Update issues of the moved projects and issues assigned to a version of a moved project
717 # Update issues of the moved projects and issues assigned to a version of a moved project
718 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
718 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
719 end
719 end
720
720
721 def parent_issue_id=(arg)
721 def parent_issue_id=(arg)
722 parent_issue_id = arg.blank? ? nil : arg.to_i
722 parent_issue_id = arg.blank? ? nil : arg.to_i
723 if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
723 if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
724 @parent_issue.id
724 @parent_issue.id
725 else
725 else
726 @parent_issue = nil
726 @parent_issue = nil
727 nil
727 nil
728 end
728 end
729 end
729 end
730
730
731 def parent_issue_id
731 def parent_issue_id
732 if instance_variable_defined? :@parent_issue
732 if instance_variable_defined? :@parent_issue
733 @parent_issue.nil? ? nil : @parent_issue.id
733 @parent_issue.nil? ? nil : @parent_issue.id
734 else
734 else
735 parent_id
735 parent_id
736 end
736 end
737 end
737 end
738
738
739 # Extracted from the ReportsController.
739 # Extracted from the ReportsController.
740 def self.by_tracker(project)
740 def self.by_tracker(project)
741 count_and_group_by(:project => project,
741 count_and_group_by(:project => project,
742 :field => 'tracker_id',
742 :field => 'tracker_id',
743 :joins => Tracker.table_name)
743 :joins => Tracker.table_name)
744 end
744 end
745
745
746 def self.by_version(project)
746 def self.by_version(project)
747 count_and_group_by(:project => project,
747 count_and_group_by(:project => project,
748 :field => 'fixed_version_id',
748 :field => 'fixed_version_id',
749 :joins => Version.table_name)
749 :joins => Version.table_name)
750 end
750 end
751
751
752 def self.by_priority(project)
752 def self.by_priority(project)
753 count_and_group_by(:project => project,
753 count_and_group_by(:project => project,
754 :field => 'priority_id',
754 :field => 'priority_id',
755 :joins => IssuePriority.table_name)
755 :joins => IssuePriority.table_name)
756 end
756 end
757
757
758 def self.by_category(project)
758 def self.by_category(project)
759 count_and_group_by(:project => project,
759 count_and_group_by(:project => project,
760 :field => 'category_id',
760 :field => 'category_id',
761 :joins => IssueCategory.table_name)
761 :joins => IssueCategory.table_name)
762 end
762 end
763
763
764 def self.by_assigned_to(project)
764 def self.by_assigned_to(project)
765 count_and_group_by(:project => project,
765 count_and_group_by(:project => project,
766 :field => 'assigned_to_id',
766 :field => 'assigned_to_id',
767 :joins => User.table_name)
767 :joins => User.table_name)
768 end
768 end
769
769
770 def self.by_author(project)
770 def self.by_author(project)
771 count_and_group_by(:project => project,
771 count_and_group_by(:project => project,
772 :field => 'author_id',
772 :field => 'author_id',
773 :joins => User.table_name)
773 :joins => User.table_name)
774 end
774 end
775
775
776 def self.by_subproject(project)
776 def self.by_subproject(project)
777 ActiveRecord::Base.connection.select_all("select s.id as status_id,
777 ActiveRecord::Base.connection.select_all("select s.id as status_id,
778 s.is_closed as closed,
778 s.is_closed as closed,
779 #{Issue.table_name}.project_id as project_id,
779 #{Issue.table_name}.project_id as project_id,
780 count(#{Issue.table_name}.id) as total
780 count(#{Issue.table_name}.id) as total
781 from
781 from
782 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
782 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
783 where
783 where
784 #{Issue.table_name}.status_id=s.id
784 #{Issue.table_name}.status_id=s.id
785 and #{Issue.table_name}.project_id = #{Project.table_name}.id
785 and #{Issue.table_name}.project_id = #{Project.table_name}.id
786 and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
786 and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
787 and #{Issue.table_name}.project_id <> #{project.id}
787 and #{Issue.table_name}.project_id <> #{project.id}
788 group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
788 group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
789 end
789 end
790 # End ReportsController extraction
790 # End ReportsController extraction
791
791
792 # Returns an array of projects that user can assign the issue to
792 # Returns an array of projects that user can assign the issue to
793 def allowed_target_projects(user=User.current)
793 def allowed_target_projects(user=User.current)
794 if new_record?
794 if new_record?
795 Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
795 Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
796 else
796 else
797 self.class.allowed_target_projects_on_move(user)
797 self.class.allowed_target_projects_on_move(user)
798 end
798 end
799 end
799 end
800
800
801 # Returns an array of projects that user can move issues to
801 # Returns an array of projects that user can move issues to
802 def self.allowed_target_projects_on_move(user=User.current)
802 def self.allowed_target_projects_on_move(user=User.current)
803 projects = []
803 projects = []
804 if user.admin?
804 if user.admin?
805 # admin is allowed to move issues to any active (visible) project
805 # admin is allowed to move issues to any active (visible) project
806 projects = Project.visible(user).all
806 projects = Project.visible(user).all
807 elsif user.logged?
807 elsif user.logged?
808 if Role.non_member.allowed_to?(:move_issues)
808 if Role.non_member.allowed_to?(:move_issues)
809 projects = Project.visible(user).all
809 projects = Project.visible(user).all
810 else
810 else
811 user.memberships.each {|m| projects << m.project if m.roles.detect {|r| r.allowed_to?(:move_issues)}}
811 user.memberships.each {|m| projects << m.project if m.roles.detect {|r| r.allowed_to?(:move_issues)}}
812 end
812 end
813 end
813 end
814 projects
814 projects
815 end
815 end
816
816
817 private
817 private
818
818
819 def after_project_change
819 def after_project_change
820 # Update project_id on related time entries
820 # Update project_id on related time entries
821 TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
821 TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
822
822
823 # Delete issue relations
823 # Delete issue relations
824 unless Setting.cross_project_issue_relations?
824 unless Setting.cross_project_issue_relations?
825 relations_from.clear
825 relations_from.clear
826 relations_to.clear
826 relations_to.clear
827 end
827 end
828
828
829 # Move subtasks
829 # Move subtasks
830 children.each do |child|
830 children.each do |child|
831 # Change project and keep project
831 # Change project and keep project
832 child.send :project=, project, true
832 child.send :project=, project, true
833 unless child.save
833 unless child.save
834 raise ActiveRecord::Rollback
834 raise ActiveRecord::Rollback
835 end
835 end
836 end
836 end
837 end
837 end
838
838
839 def update_nested_set_attributes
839 def update_nested_set_attributes
840 if root_id.nil?
840 if root_id.nil?
841 # issue was just created
841 # issue was just created
842 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
842 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
843 set_default_left_and_right
843 set_default_left_and_right
844 Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
844 Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
845 if @parent_issue
845 if @parent_issue
846 move_to_child_of(@parent_issue)
846 move_to_child_of(@parent_issue)
847 end
847 end
848 reload
848 reload
849 elsif parent_issue_id != parent_id
849 elsif parent_issue_id != parent_id
850 former_parent_id = parent_id
850 former_parent_id = parent_id
851 # moving an existing issue
851 # moving an existing issue
852 if @parent_issue && @parent_issue.root_id == root_id
852 if @parent_issue && @parent_issue.root_id == root_id
853 # inside the same tree
853 # inside the same tree
854 move_to_child_of(@parent_issue)
854 move_to_child_of(@parent_issue)
855 else
855 else
856 # to another tree
856 # to another tree
857 unless root?
857 unless root?
858 move_to_right_of(root)
858 move_to_right_of(root)
859 reload
859 reload
860 end
860 end
861 old_root_id = root_id
861 old_root_id = root_id
862 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
862 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
863 target_maxright = nested_set_scope.maximum(right_column_name) || 0
863 target_maxright = nested_set_scope.maximum(right_column_name) || 0
864 offset = target_maxright + 1 - lft
864 offset = target_maxright + 1 - lft
865 Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
865 Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
866 ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
866 ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
867 self[left_column_name] = lft + offset
867 self[left_column_name] = lft + offset
868 self[right_column_name] = rgt + offset
868 self[right_column_name] = rgt + offset
869 if @parent_issue
869 if @parent_issue
870 move_to_child_of(@parent_issue)
870 move_to_child_of(@parent_issue)
871 end
871 end
872 end
872 end
873 reload
873 reload
874 # delete invalid relations of all descendants
874 # delete invalid relations of all descendants
875 self_and_descendants.each do |issue|
875 self_and_descendants.each do |issue|
876 issue.relations.each do |relation|
876 issue.relations.each do |relation|
877 relation.destroy unless relation.valid?
877 relation.destroy unless relation.valid?
878 end
878 end
879 end
879 end
880 # update former parent
880 # update former parent
881 recalculate_attributes_for(former_parent_id) if former_parent_id
881 recalculate_attributes_for(former_parent_id) if former_parent_id
882 end
882 end
883 remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
883 remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
884 end
884 end
885
885
886 def update_parent_attributes
886 def update_parent_attributes
887 recalculate_attributes_for(parent_id) if parent_id
887 recalculate_attributes_for(parent_id) if parent_id
888 end
888 end
889
889
890 def recalculate_attributes_for(issue_id)
890 def recalculate_attributes_for(issue_id)
891 if issue_id && p = Issue.find_by_id(issue_id)
891 if issue_id && p = Issue.find_by_id(issue_id)
892 # priority = highest priority of children
892 # priority = highest priority of children
893 if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
893 if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
894 p.priority = IssuePriority.find_by_position(priority_position)
894 p.priority = IssuePriority.find_by_position(priority_position)
895 end
895 end
896
896
897 # start/due dates = lowest/highest dates of children
897 # start/due dates = lowest/highest dates of children
898 p.start_date = p.children.minimum(:start_date)
898 p.start_date = p.children.minimum(:start_date)
899 p.due_date = p.children.maximum(:due_date)
899 p.due_date = p.children.maximum(:due_date)
900 if p.start_date && p.due_date && p.due_date < p.start_date
900 if p.start_date && p.due_date && p.due_date < p.start_date
901 p.start_date, p.due_date = p.due_date, p.start_date
901 p.start_date, p.due_date = p.due_date, p.start_date
902 end
902 end
903
903
904 # done ratio = weighted average ratio of leaves
904 # done ratio = weighted average ratio of leaves
905 unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
905 unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
906 leaves_count = p.leaves.count
906 leaves_count = p.leaves.count
907 if leaves_count > 0
907 if leaves_count > 0
908 average = p.leaves.average(:estimated_hours).to_f
908 average = p.leaves.average(:estimated_hours).to_f
909 if average == 0
909 if average == 0
910 average = 1
910 average = 1
911 end
911 end
912 done = p.leaves.sum("COALESCE(estimated_hours, #{average}) * (CASE WHEN is_closed = #{connection.quoted_true} THEN 100 ELSE COALESCE(done_ratio, 0) END)", :joins => :status).to_f
912 done = p.leaves.sum("COALESCE(estimated_hours, #{average}) * (CASE WHEN is_closed = #{connection.quoted_true} THEN 100 ELSE COALESCE(done_ratio, 0) END)", :joins => :status).to_f
913 progress = done / (average * leaves_count)
913 progress = done / (average * leaves_count)
914 p.done_ratio = progress.round
914 p.done_ratio = progress.round
915 end
915 end
916 end
916 end
917
917
918 # estimate = sum of leaves estimates
918 # estimate = sum of leaves estimates
919 p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
919 p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
920 p.estimated_hours = nil if p.estimated_hours == 0.0
920 p.estimated_hours = nil if p.estimated_hours == 0.0
921
921
922 # ancestors will be recursively updated
922 # ancestors will be recursively updated
923 p.save(false)
923 p.save(false)
924 end
924 end
925 end
925 end
926
926
927 # Update issues so their versions are not pointing to a
927 # Update issues so their versions are not pointing to a
928 # fixed_version that is not shared with the issue's project
928 # fixed_version that is not shared with the issue's project
929 def self.update_versions(conditions=nil)
929 def self.update_versions(conditions=nil)
930 # Only need to update issues with a fixed_version from
930 # Only need to update issues with a fixed_version from
931 # a different project and that is not systemwide shared
931 # a different project and that is not systemwide shared
932 Issue.scoped(:conditions => conditions).all(
932 Issue.scoped(:conditions => conditions).all(
933 :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
933 :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
934 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
934 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
935 " AND #{Version.table_name}.sharing <> 'system'",
935 " AND #{Version.table_name}.sharing <> 'system'",
936 :include => [:project, :fixed_version]
936 :include => [:project, :fixed_version]
937 ).each do |issue|
937 ).each do |issue|
938 next if issue.project.nil? || issue.fixed_version.nil?
938 next if issue.project.nil? || issue.fixed_version.nil?
939 unless issue.project.shared_versions.include?(issue.fixed_version)
939 unless issue.project.shared_versions.include?(issue.fixed_version)
940 issue.init_journal(User.current)
940 issue.init_journal(User.current)
941 issue.fixed_version = nil
941 issue.fixed_version = nil
942 issue.save
942 issue.save
943 end
943 end
944 end
944 end
945 end
945 end
946
946
947 # Callback on attachment deletion
947 # Callback on attachment deletion
948 def attachment_added(obj)
948 def attachment_added(obj)
949 if @current_journal && !obj.new_record?
949 if @current_journal && !obj.new_record?
950 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
950 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
951 end
951 end
952 end
952 end
953
953
954 # Callback on attachment deletion
954 # Callback on attachment deletion
955 def attachment_removed(obj)
955 def attachment_removed(obj)
956 journal = init_journal(User.current)
956 if @current_journal && !obj.new_record?
957 journal.details << JournalDetail.new(:property => 'attachment',
957 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :old_value => obj.filename)
958 :prop_key => obj.id,
958 @current_journal.save
959 :old_value => obj.filename)
959 end
960 journal.save
961 end
960 end
962
961
963 # Default assignment based on category
962 # Default assignment based on category
964 def default_assign
963 def default_assign
965 if assigned_to.nil? && category && category.assigned_to
964 if assigned_to.nil? && category && category.assigned_to
966 self.assigned_to = category.assigned_to
965 self.assigned_to = category.assigned_to
967 end
966 end
968 end
967 end
969
968
970 # Updates start/due dates of following issues
969 # Updates start/due dates of following issues
971 def reschedule_following_issues
970 def reschedule_following_issues
972 if start_date_changed? || due_date_changed?
971 if start_date_changed? || due_date_changed?
973 relations_from.each do |relation|
972 relations_from.each do |relation|
974 relation.set_issue_to_dates
973 relation.set_issue_to_dates
975 end
974 end
976 end
975 end
977 end
976 end
978
977
979 # Closes duplicates if the issue is being closed
978 # Closes duplicates if the issue is being closed
980 def close_duplicates
979 def close_duplicates
981 if closing?
980 if closing?
982 duplicates.each do |duplicate|
981 duplicates.each do |duplicate|
983 # Reload is need in case the duplicate was updated by a previous duplicate
982 # Reload is need in case the duplicate was updated by a previous duplicate
984 duplicate.reload
983 duplicate.reload
985 # Don't re-close it if it's already closed
984 # Don't re-close it if it's already closed
986 next if duplicate.closed?
985 next if duplicate.closed?
987 # Same user and notes
986 # Same user and notes
988 if @current_journal
987 if @current_journal
989 duplicate.init_journal(@current_journal.user, @current_journal.notes)
988 duplicate.init_journal(@current_journal.user, @current_journal.notes)
990 end
989 end
991 duplicate.update_attribute :status, self.status
990 duplicate.update_attribute :status, self.status
992 end
991 end
993 end
992 end
994 end
993 end
995
994
996 # Saves the changes in a Journal
995 # Saves the changes in a Journal
997 # Called after_save
996 # Called after_save
998 def create_journal
997 def create_journal
999 if @current_journal
998 if @current_journal
1000 # attributes changes
999 # attributes changes
1001 if @attributes_before_change
1000 if @attributes_before_change
1002 (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
1001 (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
1003 before = @attributes_before_change[c]
1002 before = @attributes_before_change[c]
1004 after = send(c)
1003 after = send(c)
1005 next if before == after || (before.blank? && after.blank?)
1004 next if before == after || (before.blank? && after.blank?)
1006 @current_journal.details << JournalDetail.new(:property => 'attr',
1005 @current_journal.details << JournalDetail.new(:property => 'attr',
1007 :prop_key => c,
1006 :prop_key => c,
1008 :old_value => before,
1007 :old_value => before,
1009 :value => after)
1008 :value => after)
1010 }
1009 }
1011 end
1010 end
1012 if @custom_values_before_change
1011 if @custom_values_before_change
1013 # custom fields changes
1012 # custom fields changes
1014 custom_field_values.each {|c|
1013 custom_field_values.each {|c|
1015 before = @custom_values_before_change[c.custom_field_id]
1014 before = @custom_values_before_change[c.custom_field_id]
1016 after = c.value
1015 after = c.value
1017 next if before == after || (before.blank? && after.blank?)
1016 next if before == after || (before.blank? && after.blank?)
1018
1017
1019 if before.is_a?(Array) || after.is_a?(Array)
1018 if before.is_a?(Array) || after.is_a?(Array)
1020 before = [before] unless before.is_a?(Array)
1019 before = [before] unless before.is_a?(Array)
1021 after = [after] unless after.is_a?(Array)
1020 after = [after] unless after.is_a?(Array)
1022
1021
1023 # values removed
1022 # values removed
1024 (before - after).reject(&:blank?).each do |value|
1023 (before - after).reject(&:blank?).each do |value|
1025 @current_journal.details << JournalDetail.new(:property => 'cf',
1024 @current_journal.details << JournalDetail.new(:property => 'cf',
1026 :prop_key => c.custom_field_id,
1025 :prop_key => c.custom_field_id,
1027 :old_value => value,
1026 :old_value => value,
1028 :value => nil)
1027 :value => nil)
1029 end
1028 end
1030 # values added
1029 # values added
1031 (after - before).reject(&:blank?).each do |value|
1030 (after - before).reject(&:blank?).each do |value|
1032 @current_journal.details << JournalDetail.new(:property => 'cf',
1031 @current_journal.details << JournalDetail.new(:property => 'cf',
1033 :prop_key => c.custom_field_id,
1032 :prop_key => c.custom_field_id,
1034 :old_value => nil,
1033 :old_value => nil,
1035 :value => value)
1034 :value => value)
1036 end
1035 end
1037 else
1036 else
1038 @current_journal.details << JournalDetail.new(:property => 'cf',
1037 @current_journal.details << JournalDetail.new(:property => 'cf',
1039 :prop_key => c.custom_field_id,
1038 :prop_key => c.custom_field_id,
1040 :old_value => before,
1039 :old_value => before,
1041 :value => after)
1040 :value => after)
1042 end
1041 end
1043 }
1042 }
1044 end
1043 end
1045 @current_journal.save
1044 @current_journal.save
1046 # reset current journal
1045 # reset current journal
1047 init_journal @current_journal.user, @current_journal.notes
1046 init_journal @current_journal.user, @current_journal.notes
1048 end
1047 end
1049 end
1048 end
1050
1049
1051 # Query generator for selecting groups of issue counts for a project
1050 # Query generator for selecting groups of issue counts for a project
1052 # based on specific criteria
1051 # based on specific criteria
1053 #
1052 #
1054 # Options
1053 # Options
1055 # * project - Project to search in.
1054 # * project - Project to search in.
1056 # * field - String. Issue field to key off of in the grouping.
1055 # * field - String. Issue field to key off of in the grouping.
1057 # * joins - String. The table name to join against.
1056 # * joins - String. The table name to join against.
1058 def self.count_and_group_by(options)
1057 def self.count_and_group_by(options)
1059 project = options.delete(:project)
1058 project = options.delete(:project)
1060 select_field = options.delete(:field)
1059 select_field = options.delete(:field)
1061 joins = options.delete(:joins)
1060 joins = options.delete(:joins)
1062
1061
1063 where = "#{Issue.table_name}.#{select_field}=j.id"
1062 where = "#{Issue.table_name}.#{select_field}=j.id"
1064
1063
1065 ActiveRecord::Base.connection.select_all("select s.id as status_id,
1064 ActiveRecord::Base.connection.select_all("select s.id as status_id,
1066 s.is_closed as closed,
1065 s.is_closed as closed,
1067 j.id as #{select_field},
1066 j.id as #{select_field},
1068 count(#{Issue.table_name}.id) as total
1067 count(#{Issue.table_name}.id) as total
1069 from
1068 from
1070 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
1069 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
1071 where
1070 where
1072 #{Issue.table_name}.status_id=s.id
1071 #{Issue.table_name}.status_id=s.id
1073 and #{where}
1072 and #{where}
1074 and #{Issue.table_name}.project_id=#{Project.table_name}.id
1073 and #{Issue.table_name}.project_id=#{Project.table_name}.id
1075 and #{visible_condition(User.current, :project => project)}
1074 and #{visible_condition(User.current, :project => project)}
1076 group by s.id, s.is_closed, j.id")
1075 group by s.id, s.is_closed, j.id")
1077 end
1076 end
1078 end
1077 end
@@ -1,313 +1,316
1 # encoding: utf-8
1 # encoding: utf-8
2 #
2 #
3 # Redmine - project management software
3 # Redmine - project management software
4 # Copyright (C) 2006-2011 Jean-Philippe Lang
4 # Copyright (C) 2006-2011 Jean-Philippe Lang
5 #
5 #
6 # This program is free software; you can redistribute it and/or
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
9 # of the License, or (at your option) any later version.
10 #
10 #
11 # This program is distributed in the hope that it will be useful,
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
14 # GNU General Public License for more details.
15 #
15 #
16 # You should have received a copy of the GNU General Public License
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
19
20 require File.expand_path('../../test_helper', __FILE__)
20 require File.expand_path('../../test_helper', __FILE__)
21 require 'attachments_controller'
21 require 'attachments_controller'
22
22
23 # Re-raise errors caught by the controller.
23 # Re-raise errors caught by the controller.
24 class AttachmentsController; def rescue_action(e) raise e end; end
24 class AttachmentsController; def rescue_action(e) raise e end; end
25
25
26 class AttachmentsControllerTest < ActionController::TestCase
26 class AttachmentsControllerTest < ActionController::TestCase
27 fixtures :users, :projects, :roles, :members, :member_roles,
27 fixtures :users, :projects, :roles, :members, :member_roles,
28 :enabled_modules, :issues, :trackers, :attachments,
28 :enabled_modules, :issues, :trackers, :attachments,
29 :versions, :wiki_pages, :wikis, :documents
29 :versions, :wiki_pages, :wikis, :documents
30
30
31 def setup
31 def setup
32 @controller = AttachmentsController.new
32 @controller = AttachmentsController.new
33 @request = ActionController::TestRequest.new
33 @request = ActionController::TestRequest.new
34 @response = ActionController::TestResponse.new
34 @response = ActionController::TestResponse.new
35 User.current = nil
35 User.current = nil
36 set_fixtures_attachments_directory
36 set_fixtures_attachments_directory
37 end
37 end
38
38
39 def teardown
39 def teardown
40 set_tmp_attachments_directory
40 set_tmp_attachments_directory
41 end
41 end
42
42
43 def test_show_diff
43 def test_show_diff
44 ['inline', 'sbs'].each do |dt|
44 ['inline', 'sbs'].each do |dt|
45 # 060719210727_changeset_utf8.diff
45 # 060719210727_changeset_utf8.diff
46 get :show, :id => 14, :type => dt
46 get :show, :id => 14, :type => dt
47 assert_response :success
47 assert_response :success
48 assert_template 'diff'
48 assert_template 'diff'
49 assert_equal 'text/html', @response.content_type
49 assert_equal 'text/html', @response.content_type
50 assert_tag 'th',
50 assert_tag 'th',
51 :attributes => {:class => /filename/},
51 :attributes => {:class => /filename/},
52 :content => /issues_controller.rb\t\(rΓ©vision 1484\)/
52 :content => /issues_controller.rb\t\(rΓ©vision 1484\)/
53 assert_tag 'td',
53 assert_tag 'td',
54 :attributes => {:class => /line-code/},
54 :attributes => {:class => /line-code/},
55 :content => /Demande créée avec succès/
55 :content => /Demande créée avec succès/
56 end
56 end
57 set_tmp_attachments_directory
57 set_tmp_attachments_directory
58 end
58 end
59
59
60 def test_show_diff_replcace_cannot_convert_content
60 def test_show_diff_replcace_cannot_convert_content
61 with_settings :repositories_encodings => 'UTF-8' do
61 with_settings :repositories_encodings => 'UTF-8' do
62 ['inline', 'sbs'].each do |dt|
62 ['inline', 'sbs'].each do |dt|
63 # 060719210727_changeset_iso8859-1.diff
63 # 060719210727_changeset_iso8859-1.diff
64 get :show, :id => 5, :type => dt
64 get :show, :id => 5, :type => dt
65 assert_response :success
65 assert_response :success
66 assert_template 'diff'
66 assert_template 'diff'
67 assert_equal 'text/html', @response.content_type
67 assert_equal 'text/html', @response.content_type
68 assert_tag 'th',
68 assert_tag 'th',
69 :attributes => {:class => "filename"},
69 :attributes => {:class => "filename"},
70 :content => /issues_controller.rb\t\(r\?vision 1484\)/
70 :content => /issues_controller.rb\t\(r\?vision 1484\)/
71 assert_tag 'td',
71 assert_tag 'td',
72 :attributes => {:class => /line-code/},
72 :attributes => {:class => /line-code/},
73 :content => /Demande cr\?\?e avec succ\?s/
73 :content => /Demande cr\?\?e avec succ\?s/
74 end
74 end
75 end
75 end
76 set_tmp_attachments_directory
76 set_tmp_attachments_directory
77 end
77 end
78
78
79 def test_show_diff_latin_1
79 def test_show_diff_latin_1
80 with_settings :repositories_encodings => 'UTF-8,ISO-8859-1' do
80 with_settings :repositories_encodings => 'UTF-8,ISO-8859-1' do
81 ['inline', 'sbs'].each do |dt|
81 ['inline', 'sbs'].each do |dt|
82 # 060719210727_changeset_iso8859-1.diff
82 # 060719210727_changeset_iso8859-1.diff
83 get :show, :id => 5, :type => dt
83 get :show, :id => 5, :type => dt
84 assert_response :success
84 assert_response :success
85 assert_template 'diff'
85 assert_template 'diff'
86 assert_equal 'text/html', @response.content_type
86 assert_equal 'text/html', @response.content_type
87 assert_tag 'th',
87 assert_tag 'th',
88 :attributes => {:class => "filename"},
88 :attributes => {:class => "filename"},
89 :content => /issues_controller.rb\t\(rΓ©vision 1484\)/
89 :content => /issues_controller.rb\t\(rΓ©vision 1484\)/
90 assert_tag 'td',
90 assert_tag 'td',
91 :attributes => {:class => /line-code/},
91 :attributes => {:class => /line-code/},
92 :content => /Demande créée avec succès/
92 :content => /Demande créée avec succès/
93 end
93 end
94 end
94 end
95 set_tmp_attachments_directory
95 set_tmp_attachments_directory
96 end
96 end
97
97
98 def test_save_diff_type
98 def test_save_diff_type
99 @request.session[:user_id] = 1 # admin
99 @request.session[:user_id] = 1 # admin
100 user = User.find(1)
100 user = User.find(1)
101 get :show, :id => 5
101 get :show, :id => 5
102 assert_response :success
102 assert_response :success
103 assert_template 'diff'
103 assert_template 'diff'
104 user.reload
104 user.reload
105 assert_equal "inline", user.pref[:diff_type]
105 assert_equal "inline", user.pref[:diff_type]
106 get :show, :id => 5, :type => 'sbs'
106 get :show, :id => 5, :type => 'sbs'
107 assert_response :success
107 assert_response :success
108 assert_template 'diff'
108 assert_template 'diff'
109 user.reload
109 user.reload
110 assert_equal "sbs", user.pref[:diff_type]
110 assert_equal "sbs", user.pref[:diff_type]
111 end
111 end
112
112
113 def test_show_text_file
113 def test_show_text_file
114 get :show, :id => 4
114 get :show, :id => 4
115 assert_response :success
115 assert_response :success
116 assert_template 'file'
116 assert_template 'file'
117 assert_equal 'text/html', @response.content_type
117 assert_equal 'text/html', @response.content_type
118 set_tmp_attachments_directory
118 set_tmp_attachments_directory
119 end
119 end
120
120
121 def test_show_text_file_utf_8
121 def test_show_text_file_utf_8
122 set_tmp_attachments_directory
122 set_tmp_attachments_directory
123 a = Attachment.new(:container => Issue.find(1),
123 a = Attachment.new(:container => Issue.find(1),
124 :file => uploaded_test_file("japanese-utf-8.txt", "text/plain"),
124 :file => uploaded_test_file("japanese-utf-8.txt", "text/plain"),
125 :author => User.find(1))
125 :author => User.find(1))
126 assert a.save
126 assert a.save
127 assert_equal 'japanese-utf-8.txt', a.filename
127 assert_equal 'japanese-utf-8.txt', a.filename
128
128
129 str_japanese = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"
129 str_japanese = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"
130 str_japanese.force_encoding('UTF-8') if str_japanese.respond_to?(:force_encoding)
130 str_japanese.force_encoding('UTF-8') if str_japanese.respond_to?(:force_encoding)
131
131
132 get :show, :id => a.id
132 get :show, :id => a.id
133 assert_response :success
133 assert_response :success
134 assert_template 'file'
134 assert_template 'file'
135 assert_equal 'text/html', @response.content_type
135 assert_equal 'text/html', @response.content_type
136 assert_tag :tag => 'th',
136 assert_tag :tag => 'th',
137 :content => '1',
137 :content => '1',
138 :attributes => { :class => 'line-num' },
138 :attributes => { :class => 'line-num' },
139 :sibling => { :tag => 'td', :content => /#{str_japanese}/ }
139 :sibling => { :tag => 'td', :content => /#{str_japanese}/ }
140 end
140 end
141
141
142 def test_show_text_file_replcace_cannot_convert_content
142 def test_show_text_file_replcace_cannot_convert_content
143 set_tmp_attachments_directory
143 set_tmp_attachments_directory
144 with_settings :repositories_encodings => 'UTF-8' do
144 with_settings :repositories_encodings => 'UTF-8' do
145 a = Attachment.new(:container => Issue.find(1),
145 a = Attachment.new(:container => Issue.find(1),
146 :file => uploaded_test_file("iso8859-1.txt", "text/plain"),
146 :file => uploaded_test_file("iso8859-1.txt", "text/plain"),
147 :author => User.find(1))
147 :author => User.find(1))
148 assert a.save
148 assert a.save
149 assert_equal 'iso8859-1.txt', a.filename
149 assert_equal 'iso8859-1.txt', a.filename
150
150
151 get :show, :id => a.id
151 get :show, :id => a.id
152 assert_response :success
152 assert_response :success
153 assert_template 'file'
153 assert_template 'file'
154 assert_equal 'text/html', @response.content_type
154 assert_equal 'text/html', @response.content_type
155 assert_tag :tag => 'th',
155 assert_tag :tag => 'th',
156 :content => '7',
156 :content => '7',
157 :attributes => { :class => 'line-num' },
157 :attributes => { :class => 'line-num' },
158 :sibling => { :tag => 'td', :content => /Demande cr\?\?e avec succ\?s/ }
158 :sibling => { :tag => 'td', :content => /Demande cr\?\?e avec succ\?s/ }
159 end
159 end
160 end
160 end
161
161
162 def test_show_text_file_latin_1
162 def test_show_text_file_latin_1
163 set_tmp_attachments_directory
163 set_tmp_attachments_directory
164 with_settings :repositories_encodings => 'UTF-8,ISO-8859-1' do
164 with_settings :repositories_encodings => 'UTF-8,ISO-8859-1' do
165 a = Attachment.new(:container => Issue.find(1),
165 a = Attachment.new(:container => Issue.find(1),
166 :file => uploaded_test_file("iso8859-1.txt", "text/plain"),
166 :file => uploaded_test_file("iso8859-1.txt", "text/plain"),
167 :author => User.find(1))
167 :author => User.find(1))
168 assert a.save
168 assert a.save
169 assert_equal 'iso8859-1.txt', a.filename
169 assert_equal 'iso8859-1.txt', a.filename
170
170
171 get :show, :id => a.id
171 get :show, :id => a.id
172 assert_response :success
172 assert_response :success
173 assert_template 'file'
173 assert_template 'file'
174 assert_equal 'text/html', @response.content_type
174 assert_equal 'text/html', @response.content_type
175 assert_tag :tag => 'th',
175 assert_tag :tag => 'th',
176 :content => '7',
176 :content => '7',
177 :attributes => { :class => 'line-num' },
177 :attributes => { :class => 'line-num' },
178 :sibling => { :tag => 'td', :content => /Demande créée avec succès/ }
178 :sibling => { :tag => 'td', :content => /Demande créée avec succès/ }
179 end
179 end
180 end
180 end
181
181
182 def test_show_text_file_should_send_if_too_big
182 def test_show_text_file_should_send_if_too_big
183 Setting.file_max_size_displayed = 512
183 Setting.file_max_size_displayed = 512
184 Attachment.find(4).update_attribute :filesize, 754.kilobyte
184 Attachment.find(4).update_attribute :filesize, 754.kilobyte
185
185
186 get :show, :id => 4
186 get :show, :id => 4
187 assert_response :success
187 assert_response :success
188 assert_equal 'application/x-ruby', @response.content_type
188 assert_equal 'application/x-ruby', @response.content_type
189 set_tmp_attachments_directory
189 set_tmp_attachments_directory
190 end
190 end
191
191
192 def test_show_other
192 def test_show_other
193 get :show, :id => 6
193 get :show, :id => 6
194 assert_response :success
194 assert_response :success
195 assert_equal 'application/octet-stream', @response.content_type
195 assert_equal 'application/octet-stream', @response.content_type
196 set_tmp_attachments_directory
196 set_tmp_attachments_directory
197 end
197 end
198
198
199 def test_show_file_from_private_issue_without_permission
199 def test_show_file_from_private_issue_without_permission
200 get :show, :id => 15
200 get :show, :id => 15
201 assert_redirected_to '/login?back_url=http%3A%2F%2Ftest.host%2Fattachments%2F15'
201 assert_redirected_to '/login?back_url=http%3A%2F%2Ftest.host%2Fattachments%2F15'
202 set_tmp_attachments_directory
202 set_tmp_attachments_directory
203 end
203 end
204
204
205 def test_show_file_from_private_issue_with_permission
205 def test_show_file_from_private_issue_with_permission
206 @request.session[:user_id] = 2
206 @request.session[:user_id] = 2
207 get :show, :id => 15
207 get :show, :id => 15
208 assert_response :success
208 assert_response :success
209 assert_tag 'h2', :content => /private.diff/
209 assert_tag 'h2', :content => /private.diff/
210 set_tmp_attachments_directory
210 set_tmp_attachments_directory
211 end
211 end
212
212
213 def test_show_file_without_container_should_be_denied
213 def test_show_file_without_container_should_be_denied
214 set_tmp_attachments_directory
214 set_tmp_attachments_directory
215 attachment = Attachment.create!(:file => uploaded_test_file("testfile.txt", "text/plain"), :author_id => 2)
215 attachment = Attachment.create!(:file => uploaded_test_file("testfile.txt", "text/plain"), :author_id => 2)
216
216
217 @request.session[:user_id] = 2
217 @request.session[:user_id] = 2
218 get :show, :id => attachment.id
218 get :show, :id => attachment.id
219 assert_response 403
219 assert_response 403
220 end
220 end
221
221
222 def test_show_invalid_should_respond_with_404
222 def test_show_invalid_should_respond_with_404
223 get :show, :id => 999
223 get :show, :id => 999
224 assert_response 404
224 assert_response 404
225 end
225 end
226
226
227 def test_download_text_file
227 def test_download_text_file
228 get :download, :id => 4
228 get :download, :id => 4
229 assert_response :success
229 assert_response :success
230 assert_equal 'application/x-ruby', @response.content_type
230 assert_equal 'application/x-ruby', @response.content_type
231 set_tmp_attachments_directory
231 set_tmp_attachments_directory
232 end
232 end
233
233
234 def test_download_version_file_with_issue_tracking_disabled
234 def test_download_version_file_with_issue_tracking_disabled
235 Project.find(1).disable_module! :issue_tracking
235 Project.find(1).disable_module! :issue_tracking
236 get :download, :id => 9
236 get :download, :id => 9
237 assert_response :success
237 assert_response :success
238 end
238 end
239
239
240 def test_download_should_assign_content_type_if_blank
240 def test_download_should_assign_content_type_if_blank
241 Attachment.find(4).update_attribute(:content_type, '')
241 Attachment.find(4).update_attribute(:content_type, '')
242
242
243 get :download, :id => 4
243 get :download, :id => 4
244 assert_response :success
244 assert_response :success
245 assert_equal 'text/x-ruby', @response.content_type
245 assert_equal 'text/x-ruby', @response.content_type
246 set_tmp_attachments_directory
246 set_tmp_attachments_directory
247 end
247 end
248
248
249 def test_download_missing_file
249 def test_download_missing_file
250 get :download, :id => 2
250 get :download, :id => 2
251 assert_response 404
251 assert_response 404
252 set_tmp_attachments_directory
252 set_tmp_attachments_directory
253 end
253 end
254
254
255 def test_anonymous_on_private_private
255 def test_anonymous_on_private_private
256 get :download, :id => 7
256 get :download, :id => 7
257 assert_redirected_to '/login?back_url=http%3A%2F%2Ftest.host%2Fattachments%2Fdownload%2F7'
257 assert_redirected_to '/login?back_url=http%3A%2F%2Ftest.host%2Fattachments%2Fdownload%2F7'
258 set_tmp_attachments_directory
258 set_tmp_attachments_directory
259 end
259 end
260
260
261 def test_destroy_issue_attachment
261 def test_destroy_issue_attachment
262 set_tmp_attachments_directory
262 set_tmp_attachments_directory
263 issue = Issue.find(3)
263 issue = Issue.find(3)
264 @request.session[:user_id] = 2
264 @request.session[:user_id] = 2
265
265
266 assert_difference 'issue.attachments.count', -1 do
266 assert_difference 'issue.attachments.count', -1 do
267 delete :destroy, :id => 1
267 assert_difference 'Journal.count' do
268 delete :destroy, :id => 1
269 assert_redirected_to '/projects/ecookbook'
270 end
268 end
271 end
269 # no referrer
270 assert_redirected_to '/projects/ecookbook'
271 assert_nil Attachment.find_by_id(1)
272 assert_nil Attachment.find_by_id(1)
272 j = issue.journals.find(:first, :order => 'created_on DESC')
273 j = Journal.first(:order => 'id DESC')
274 assert_equal issue, j.journalized
273 assert_equal 'attachment', j.details.first.property
275 assert_equal 'attachment', j.details.first.property
274 assert_equal '1', j.details.first.prop_key
276 assert_equal '1', j.details.first.prop_key
275 assert_equal 'error281.txt', j.details.first.old_value
277 assert_equal 'error281.txt', j.details.first.old_value
278 assert_equal User.find(2), j.user
276 end
279 end
277
280
278 def test_destroy_wiki_page_attachment
281 def test_destroy_wiki_page_attachment
279 set_tmp_attachments_directory
282 set_tmp_attachments_directory
280 @request.session[:user_id] = 2
283 @request.session[:user_id] = 2
281 assert_difference 'Attachment.count', -1 do
284 assert_difference 'Attachment.count', -1 do
282 delete :destroy, :id => 3
285 delete :destroy, :id => 3
283 assert_response 302
286 assert_response 302
284 end
287 end
285 end
288 end
286
289
287 def test_destroy_project_attachment
290 def test_destroy_project_attachment
288 set_tmp_attachments_directory
291 set_tmp_attachments_directory
289 @request.session[:user_id] = 2
292 @request.session[:user_id] = 2
290 assert_difference 'Attachment.count', -1 do
293 assert_difference 'Attachment.count', -1 do
291 delete :destroy, :id => 8
294 delete :destroy, :id => 8
292 assert_response 302
295 assert_response 302
293 end
296 end
294 end
297 end
295
298
296 def test_destroy_version_attachment
299 def test_destroy_version_attachment
297 set_tmp_attachments_directory
300 set_tmp_attachments_directory
298 @request.session[:user_id] = 2
301 @request.session[:user_id] = 2
299 assert_difference 'Attachment.count', -1 do
302 assert_difference 'Attachment.count', -1 do
300 delete :destroy, :id => 9
303 delete :destroy, :id => 9
301 assert_response 302
304 assert_response 302
302 end
305 end
303 end
306 end
304
307
305 def test_destroy_without_permission
308 def test_destroy_without_permission
306 set_tmp_attachments_directory
309 set_tmp_attachments_directory
307 assert_no_difference 'Attachment.count' do
310 assert_no_difference 'Attachment.count' do
308 delete :destroy, :id => 3
311 delete :destroy, :id => 3
309 end
312 end
310 assert_response 302
313 assert_response 302
311 assert Attachment.find_by_id(3)
314 assert Attachment.find_by_id(3)
312 end
315 end
313 end
316 end
General Comments 0
You need to be logged in to leave comments. Login now