##// END OF EJS Templates
Refactor: pull up method to ApplicationController....
Eric Davis -
r3826:13fe01a185c5
parent child
Show More
@@ -1,383 +1,398
1 # redMine - project management software
1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
2 # Copyright (C) 2006-2007 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 require 'uri'
18 require 'uri'
19 require 'cgi'
19 require 'cgi'
20
20
21 class ApplicationController < ActionController::Base
21 class ApplicationController < ActionController::Base
22 include Redmine::I18n
22 include Redmine::I18n
23
23
24 layout 'base'
24 layout 'base'
25 exempt_from_layout 'builder'
25 exempt_from_layout 'builder'
26
26
27 # Remove broken cookie after upgrade from 0.8.x (#4292)
27 # Remove broken cookie after upgrade from 0.8.x (#4292)
28 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
28 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
29 # TODO: remove it when Rails is fixed
29 # TODO: remove it when Rails is fixed
30 before_filter :delete_broken_cookies
30 before_filter :delete_broken_cookies
31 def delete_broken_cookies
31 def delete_broken_cookies
32 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
32 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
33 cookies.delete '_redmine_session'
33 cookies.delete '_redmine_session'
34 redirect_to home_path
34 redirect_to home_path
35 return false
35 return false
36 end
36 end
37 end
37 end
38
38
39 before_filter :user_setup, :check_if_login_required, :set_localization
39 before_filter :user_setup, :check_if_login_required, :set_localization
40 filter_parameter_logging :password
40 filter_parameter_logging :password
41 protect_from_forgery
41 protect_from_forgery
42
42
43 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
43 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
44
44
45 include Redmine::Search::Controller
45 include Redmine::Search::Controller
46 include Redmine::MenuManager::MenuController
46 include Redmine::MenuManager::MenuController
47 helper Redmine::MenuManager::MenuHelper
47 helper Redmine::MenuManager::MenuHelper
48
48
49 Redmine::Scm::Base.all.each do |scm|
49 Redmine::Scm::Base.all.each do |scm|
50 require_dependency "repository/#{scm.underscore}"
50 require_dependency "repository/#{scm.underscore}"
51 end
51 end
52
52
53 def user_setup
53 def user_setup
54 # Check the settings cache for each request
54 # Check the settings cache for each request
55 Setting.check_cache
55 Setting.check_cache
56 # Find the current user
56 # Find the current user
57 User.current = find_current_user
57 User.current = find_current_user
58 end
58 end
59
59
60 # Returns the current user or nil if no user is logged in
60 # Returns the current user or nil if no user is logged in
61 # and starts a session if needed
61 # and starts a session if needed
62 def find_current_user
62 def find_current_user
63 if session[:user_id]
63 if session[:user_id]
64 # existing session
64 # existing session
65 (User.active.find(session[:user_id]) rescue nil)
65 (User.active.find(session[:user_id]) rescue nil)
66 elsif cookies[:autologin] && Setting.autologin?
66 elsif cookies[:autologin] && Setting.autologin?
67 # auto-login feature starts a new session
67 # auto-login feature starts a new session
68 user = User.try_to_autologin(cookies[:autologin])
68 user = User.try_to_autologin(cookies[:autologin])
69 session[:user_id] = user.id if user
69 session[:user_id] = user.id if user
70 user
70 user
71 elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action])
71 elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action])
72 # RSS key authentication does not start a session
72 # RSS key authentication does not start a session
73 User.find_by_rss_key(params[:key])
73 User.find_by_rss_key(params[:key])
74 elsif Setting.rest_api_enabled? && ['xml', 'json'].include?(params[:format])
74 elsif Setting.rest_api_enabled? && ['xml', 'json'].include?(params[:format])
75 if params[:key].present? && accept_key_auth_actions.include?(params[:action])
75 if params[:key].present? && accept_key_auth_actions.include?(params[:action])
76 # Use API key
76 # Use API key
77 User.find_by_api_key(params[:key])
77 User.find_by_api_key(params[:key])
78 else
78 else
79 # HTTP Basic, either username/password or API key/random
79 # HTTP Basic, either username/password or API key/random
80 authenticate_with_http_basic do |username, password|
80 authenticate_with_http_basic do |username, password|
81 User.try_to_login(username, password) || User.find_by_api_key(username)
81 User.try_to_login(username, password) || User.find_by_api_key(username)
82 end
82 end
83 end
83 end
84 end
84 end
85 end
85 end
86
86
87 # Sets the logged in user
87 # Sets the logged in user
88 def logged_user=(user)
88 def logged_user=(user)
89 reset_session
89 reset_session
90 if user && user.is_a?(User)
90 if user && user.is_a?(User)
91 User.current = user
91 User.current = user
92 session[:user_id] = user.id
92 session[:user_id] = user.id
93 else
93 else
94 User.current = User.anonymous
94 User.current = User.anonymous
95 end
95 end
96 end
96 end
97
97
98 # check if login is globally required to access the application
98 # check if login is globally required to access the application
99 def check_if_login_required
99 def check_if_login_required
100 # no check needed if user is already logged in
100 # no check needed if user is already logged in
101 return true if User.current.logged?
101 return true if User.current.logged?
102 require_login if Setting.login_required?
102 require_login if Setting.login_required?
103 end
103 end
104
104
105 def set_localization
105 def set_localization
106 lang = nil
106 lang = nil
107 if User.current.logged?
107 if User.current.logged?
108 lang = find_language(User.current.language)
108 lang = find_language(User.current.language)
109 end
109 end
110 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
110 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
111 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
111 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
112 if !accept_lang.blank?
112 if !accept_lang.blank?
113 accept_lang = accept_lang.downcase
113 accept_lang = accept_lang.downcase
114 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
114 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
115 end
115 end
116 end
116 end
117 lang ||= Setting.default_language
117 lang ||= Setting.default_language
118 set_language_if_valid(lang)
118 set_language_if_valid(lang)
119 end
119 end
120
120
121 def require_login
121 def require_login
122 if !User.current.logged?
122 if !User.current.logged?
123 # Extract only the basic url parameters on non-GET requests
123 # Extract only the basic url parameters on non-GET requests
124 if request.get?
124 if request.get?
125 url = url_for(params)
125 url = url_for(params)
126 else
126 else
127 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
127 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
128 end
128 end
129 respond_to do |format|
129 respond_to do |format|
130 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
130 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
131 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
131 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
132 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
132 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
133 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
133 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
134 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
134 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
135 end
135 end
136 return false
136 return false
137 end
137 end
138 true
138 true
139 end
139 end
140
140
141 def require_admin
141 def require_admin
142 return unless require_login
142 return unless require_login
143 if !User.current.admin?
143 if !User.current.admin?
144 render_403
144 render_403
145 return false
145 return false
146 end
146 end
147 true
147 true
148 end
148 end
149
149
150 def deny_access
150 def deny_access
151 User.current.logged? ? render_403 : require_login
151 User.current.logged? ? render_403 : require_login
152 end
152 end
153
153
154 # Authorize the user for the requested action
154 # Authorize the user for the requested action
155 def authorize(ctrl = params[:controller], action = params[:action], global = false)
155 def authorize(ctrl = params[:controller], action = params[:action], global = false)
156 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project, :global => global)
156 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project, :global => global)
157 allowed ? true : deny_access
157 allowed ? true : deny_access
158 end
158 end
159
159
160 # Authorize the user for the requested action outside a project
160 # Authorize the user for the requested action outside a project
161 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
161 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
162 authorize(ctrl, action, global)
162 authorize(ctrl, action, global)
163 end
163 end
164
164
165 # Find project of id params[:id]
165 # Find project of id params[:id]
166 def find_project
166 def find_project
167 @project = Project.find(params[:id])
167 @project = Project.find(params[:id])
168 rescue ActiveRecord::RecordNotFound
168 rescue ActiveRecord::RecordNotFound
169 render_404
169 render_404
170 end
170 end
171
171
172 # Find a project based on params[:project_id]
172 # Find a project based on params[:project_id]
173 # TODO: some subclasses override this, see about merging their logic
173 # TODO: some subclasses override this, see about merging their logic
174 def find_optional_project
174 def find_optional_project
175 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
175 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
176 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
176 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
177 allowed ? true : deny_access
177 allowed ? true : deny_access
178 rescue ActiveRecord::RecordNotFound
178 rescue ActiveRecord::RecordNotFound
179 render_404
179 render_404
180 end
180 end
181
181
182 # Finds and sets @project based on @object.project
182 # Finds and sets @project based on @object.project
183 def find_project_from_association
183 def find_project_from_association
184 render_404 unless @object.present?
184 render_404 unless @object.present?
185
185
186 @project = @object.project
186 @project = @object.project
187 rescue ActiveRecord::RecordNotFound
187 rescue ActiveRecord::RecordNotFound
188 render_404
188 render_404
189 end
189 end
190
190
191 def find_model_object
191 def find_model_object
192 model = self.class.read_inheritable_attribute('model_object')
192 model = self.class.read_inheritable_attribute('model_object')
193 if model
193 if model
194 @object = model.find(params[:id])
194 @object = model.find(params[:id])
195 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
195 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
196 end
196 end
197 rescue ActiveRecord::RecordNotFound
197 rescue ActiveRecord::RecordNotFound
198 render_404
198 render_404
199 end
199 end
200
200
201 def self.model_object(model)
201 def self.model_object(model)
202 write_inheritable_attribute('model_object', model)
202 write_inheritable_attribute('model_object', model)
203 end
203 end
204
204
205 # Filter for bulk issue operations
205 # Filter for bulk issue operations
206 def find_issues
206 def find_issues
207 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
207 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
208 raise ActiveRecord::RecordNotFound if @issues.empty?
208 raise ActiveRecord::RecordNotFound if @issues.empty?
209 projects = @issues.collect(&:project).compact.uniq
209 projects = @issues.collect(&:project).compact.uniq
210 if projects.size == 1
210 if projects.size == 1
211 @project = projects.first
211 @project = projects.first
212 else
212 else
213 # TODO: let users bulk edit/move/destroy issues from different projects
213 # TODO: let users bulk edit/move/destroy issues from different projects
214 render_error 'Can not bulk edit/move/destroy issues from different projects'
214 render_error 'Can not bulk edit/move/destroy issues from different projects'
215 return false
215 return false
216 end
216 end
217 rescue ActiveRecord::RecordNotFound
217 rescue ActiveRecord::RecordNotFound
218 render_404
218 render_404
219 end
219 end
220
220
221 # make sure that the user is a member of the project (or admin) if project is private
221 # make sure that the user is a member of the project (or admin) if project is private
222 # used as a before_filter for actions that do not require any particular permission on the project
222 # used as a before_filter for actions that do not require any particular permission on the project
223 def check_project_privacy
223 def check_project_privacy
224 if @project && @project.active?
224 if @project && @project.active?
225 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
225 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
226 true
226 true
227 else
227 else
228 User.current.logged? ? render_403 : require_login
228 User.current.logged? ? render_403 : require_login
229 end
229 end
230 else
230 else
231 @project = nil
231 @project = nil
232 render_404
232 render_404
233 false
233 false
234 end
234 end
235 end
235 end
236
236
237 def back_url
237 def back_url
238 params[:back_url] || request.env['HTTP_REFERER']
238 params[:back_url] || request.env['HTTP_REFERER']
239 end
239 end
240
240
241 def redirect_back_or_default(default)
241 def redirect_back_or_default(default)
242 back_url = CGI.unescape(params[:back_url].to_s)
242 back_url = CGI.unescape(params[:back_url].to_s)
243 if !back_url.blank?
243 if !back_url.blank?
244 begin
244 begin
245 uri = URI.parse(back_url)
245 uri = URI.parse(back_url)
246 # do not redirect user to another host or to the login or register page
246 # do not redirect user to another host or to the login or register page
247 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
247 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
248 redirect_to(back_url)
248 redirect_to(back_url)
249 return
249 return
250 end
250 end
251 rescue URI::InvalidURIError
251 rescue URI::InvalidURIError
252 # redirect to default
252 # redirect to default
253 end
253 end
254 end
254 end
255 redirect_to default
255 redirect_to default
256 end
256 end
257
257
258 def render_403
258 def render_403
259 @project = nil
259 @project = nil
260 respond_to do |format|
260 respond_to do |format|
261 format.html { render :template => "common/403", :layout => (request.xhr? ? false : 'base'), :status => 403 }
261 format.html { render :template => "common/403", :layout => (request.xhr? ? false : 'base'), :status => 403 }
262 format.atom { head 403 }
262 format.atom { head 403 }
263 format.xml { head 403 }
263 format.xml { head 403 }
264 format.js { head 403 }
264 format.js { head 403 }
265 format.json { head 403 }
265 format.json { head 403 }
266 end
266 end
267 return false
267 return false
268 end
268 end
269
269
270 def render_404
270 def render_404
271 respond_to do |format|
271 respond_to do |format|
272 format.html { render :template => "common/404", :layout => !request.xhr?, :status => 404 }
272 format.html { render :template => "common/404", :layout => !request.xhr?, :status => 404 }
273 format.atom { head 404 }
273 format.atom { head 404 }
274 format.xml { head 404 }
274 format.xml { head 404 }
275 format.js { head 404 }
275 format.js { head 404 }
276 format.json { head 404 }
276 format.json { head 404 }
277 end
277 end
278 return false
278 return false
279 end
279 end
280
280
281 def render_error(msg)
281 def render_error(msg)
282 respond_to do |format|
282 respond_to do |format|
283 format.html {
283 format.html {
284 flash.now[:error] = msg
284 flash.now[:error] = msg
285 render :text => '', :layout => !request.xhr?, :status => 500
285 render :text => '', :layout => !request.xhr?, :status => 500
286 }
286 }
287 format.atom { head 500 }
287 format.atom { head 500 }
288 format.xml { head 500 }
288 format.xml { head 500 }
289 format.js { head 500 }
289 format.js { head 500 }
290 format.json { head 500 }
290 format.json { head 500 }
291 end
291 end
292 end
292 end
293
293
294 def invalid_authenticity_token
294 def invalid_authenticity_token
295 if api_request?
295 if api_request?
296 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
296 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
297 end
297 end
298 render_error "Invalid form authenticity token."
298 render_error "Invalid form authenticity token."
299 end
299 end
300
300
301 def render_feed(items, options={})
301 def render_feed(items, options={})
302 @items = items || []
302 @items = items || []
303 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
303 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
304 @items = @items.slice(0, Setting.feeds_limit.to_i)
304 @items = @items.slice(0, Setting.feeds_limit.to_i)
305 @title = options[:title] || Setting.app_title
305 @title = options[:title] || Setting.app_title
306 render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
306 render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
307 end
307 end
308
308
309 def self.accept_key_auth(*actions)
309 def self.accept_key_auth(*actions)
310 actions = actions.flatten.map(&:to_s)
310 actions = actions.flatten.map(&:to_s)
311 write_inheritable_attribute('accept_key_auth_actions', actions)
311 write_inheritable_attribute('accept_key_auth_actions', actions)
312 end
312 end
313
313
314 def accept_key_auth_actions
314 def accept_key_auth_actions
315 self.class.read_inheritable_attribute('accept_key_auth_actions') || []
315 self.class.read_inheritable_attribute('accept_key_auth_actions') || []
316 end
316 end
317
317
318 # Returns the number of objects that should be displayed
318 # Returns the number of objects that should be displayed
319 # on the paginated list
319 # on the paginated list
320 def per_page_option
320 def per_page_option
321 per_page = nil
321 per_page = nil
322 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
322 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
323 per_page = params[:per_page].to_s.to_i
323 per_page = params[:per_page].to_s.to_i
324 session[:per_page] = per_page
324 session[:per_page] = per_page
325 elsif session[:per_page]
325 elsif session[:per_page]
326 per_page = session[:per_page]
326 per_page = session[:per_page]
327 else
327 else
328 per_page = Setting.per_page_options_array.first || 25
328 per_page = Setting.per_page_options_array.first || 25
329 end
329 end
330 per_page
330 per_page
331 end
331 end
332
332
333 # qvalues http header parser
333 # qvalues http header parser
334 # code taken from webrick
334 # code taken from webrick
335 def parse_qvalues(value)
335 def parse_qvalues(value)
336 tmp = []
336 tmp = []
337 if value
337 if value
338 parts = value.split(/,\s*/)
338 parts = value.split(/,\s*/)
339 parts.each {|part|
339 parts.each {|part|
340 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
340 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
341 val = m[1]
341 val = m[1]
342 q = (m[2] or 1).to_f
342 q = (m[2] or 1).to_f
343 tmp.push([val, q])
343 tmp.push([val, q])
344 end
344 end
345 }
345 }
346 tmp = tmp.sort_by{|val, q| -q}
346 tmp = tmp.sort_by{|val, q| -q}
347 tmp.collect!{|val, q| val}
347 tmp.collect!{|val, q| val}
348 end
348 end
349 return tmp
349 return tmp
350 rescue
350 rescue
351 nil
351 nil
352 end
352 end
353
353
354 # Returns a string that can be used as filename value in Content-Disposition header
354 # Returns a string that can be used as filename value in Content-Disposition header
355 def filename_for_content_disposition(name)
355 def filename_for_content_disposition(name)
356 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
356 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
357 end
357 end
358
358
359 def api_request?
359 def api_request?
360 %w(xml json).include? params[:format]
360 %w(xml json).include? params[:format]
361 end
361 end
362
362
363 # Renders a warning flash if obj has unsaved attachments
363 # Renders a warning flash if obj has unsaved attachments
364 def render_attachment_warning_if_needed(obj)
364 def render_attachment_warning_if_needed(obj)
365 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
365 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
366 end
366 end
367
367
368 # Sets the `flash` notice or error based the number of issues that did not save
369 #
370 # @param [Array, Issue] issues all of the saved and unsaved Issues
371 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
372 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
373 if unsaved_issue_ids.empty?
374 flash[:notice] = l(:notice_successful_update) unless issues.empty?
375 else
376 flash[:error] = l(:notice_failed_to_save_issues,
377 :count => unsaved_issue_ids.size,
378 :total => issues.size,
379 :ids => '#' + unsaved_issue_ids.join(', #'))
380 end
381 end
382
368 # Rescues an invalid query statement. Just in case...
383 # Rescues an invalid query statement. Just in case...
369 def query_statement_invalid(exception)
384 def query_statement_invalid(exception)
370 logger.error "Query::StatementInvalid: #{exception.message}" if logger
385 logger.error "Query::StatementInvalid: #{exception.message}" if logger
371 session.delete(:query)
386 session.delete(:query)
372 sort_clear if respond_to?(:sort_clear)
387 sort_clear if respond_to?(:sort_clear)
373 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
388 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
374 end
389 end
375
390
376 # Converts the errors on an ActiveRecord object into a common JSON format
391 # Converts the errors on an ActiveRecord object into a common JSON format
377 def object_errors_to_json(object)
392 def object_errors_to_json(object)
378 object.errors.collect do |attribute, error|
393 object.errors.collect do |attribute, error|
379 { attribute => error }
394 { attribute => error }
380 end.to_json
395 end.to_json
381 end
396 end
382
397
383 end
398 end
@@ -1,77 +1,65
1 class IssueMovesController < ApplicationController
1 class IssueMovesController < ApplicationController
2 default_search_scope :issues
2 default_search_scope :issues
3 before_filter :find_issues
3 before_filter :find_issues
4 before_filter :authorize
4 before_filter :authorize
5
5
6 def new
6 def new
7 prepare_for_issue_move
7 prepare_for_issue_move
8 render :layout => false if request.xhr?
8 render :layout => false if request.xhr?
9 end
9 end
10
10
11 def create
11 def create
12 prepare_for_issue_move
12 prepare_for_issue_move
13
13
14 if request.post?
14 if request.post?
15 new_tracker = params[:new_tracker_id].blank? ? nil : @target_project.trackers.find_by_id(params[:new_tracker_id])
15 new_tracker = params[:new_tracker_id].blank? ? nil : @target_project.trackers.find_by_id(params[:new_tracker_id])
16 unsaved_issue_ids = []
16 unsaved_issue_ids = []
17 moved_issues = []
17 moved_issues = []
18 @issues.each do |issue|
18 @issues.each do |issue|
19 issue.reload
19 issue.reload
20 issue.init_journal(User.current)
20 issue.init_journal(User.current)
21 call_hook(:controller_issues_move_before_save, { :params => params, :issue => issue, :target_project => @target_project, :copy => !!@copy })
21 call_hook(:controller_issues_move_before_save, { :params => params, :issue => issue, :target_project => @target_project, :copy => !!@copy })
22 if r = issue.move_to_project(@target_project, new_tracker, {:copy => @copy, :attributes => extract_changed_attributes_for_move(params)})
22 if r = issue.move_to_project(@target_project, new_tracker, {:copy => @copy, :attributes => extract_changed_attributes_for_move(params)})
23 moved_issues << r
23 moved_issues << r
24 else
24 else
25 unsaved_issue_ids << issue.id
25 unsaved_issue_ids << issue.id
26 end
26 end
27 end
27 end
28 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
28 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
29
29
30 if params[:follow]
30 if params[:follow]
31 if @issues.size == 1 && moved_issues.size == 1
31 if @issues.size == 1 && moved_issues.size == 1
32 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
32 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
33 else
33 else
34 redirect_to :controller => 'issues', :action => 'index', :project_id => (@target_project || @project)
34 redirect_to :controller => 'issues', :action => 'index', :project_id => (@target_project || @project)
35 end
35 end
36 else
36 else
37 redirect_to :controller => 'issues', :action => 'index', :project_id => @project
37 redirect_to :controller => 'issues', :action => 'index', :project_id => @project
38 end
38 end
39 return
39 return
40 end
40 end
41 end
41 end
42
42
43 private
43 private
44
44
45 def prepare_for_issue_move
45 def prepare_for_issue_move
46 @issues.sort!
46 @issues.sort!
47 @copy = params[:copy_options] && params[:copy_options][:copy]
47 @copy = params[:copy_options] && params[:copy_options][:copy]
48 @allowed_projects = Issue.allowed_target_projects_on_move
48 @allowed_projects = Issue.allowed_target_projects_on_move
49 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:new_project_id]} if params[:new_project_id]
49 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:new_project_id]} if params[:new_project_id]
50 @target_project ||= @project
50 @target_project ||= @project
51 @trackers = @target_project.trackers
51 @trackers = @target_project.trackers
52 @available_statuses = Workflow.available_statuses(@project)
52 @available_statuses = Workflow.available_statuses(@project)
53 end
53 end
54
54
55 # TODO: duplicated in IssuesController
56 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
57 if unsaved_issue_ids.empty?
58 flash[:notice] = l(:notice_successful_update) unless issues.empty?
59 else
60 flash[:error] = l(:notice_failed_to_save_issues,
61 :count => unsaved_issue_ids.size,
62 :total => issues.size,
63 :ids => '#' + unsaved_issue_ids.join(', #'))
64 end
65 end
66
67 def extract_changed_attributes_for_move(params)
55 def extract_changed_attributes_for_move(params)
68 changed_attributes = {}
56 changed_attributes = {}
69 [:assigned_to_id, :status_id, :start_date, :due_date].each do |valid_attribute|
57 [:assigned_to_id, :status_id, :start_date, :due_date].each do |valid_attribute|
70 unless params[valid_attribute].blank?
58 unless params[valid_attribute].blank?
71 changed_attributes[valid_attribute] = (params[valid_attribute] == 'none' ? nil : params[valid_attribute])
59 changed_attributes[valid_attribute] = (params[valid_attribute] == 'none' ? nil : params[valid_attribute])
72 end
60 end
73 end
61 end
74 changed_attributes
62 changed_attributes
75 end
63 end
76
64
77 end
65 end
@@ -1,428 +1,417
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2008 Jean-Philippe Lang
2 # Copyright (C) 2006-2008 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 IssuesController < ApplicationController
18 class IssuesController < ApplicationController
19 menu_item :new_issue, :only => [:new, :create]
19 menu_item :new_issue, :only => [:new, :create]
20 default_search_scope :issues
20 default_search_scope :issues
21
21
22 before_filter :find_issue, :only => [:show, :edit, :update, :reply]
22 before_filter :find_issue, :only => [:show, :edit, :update, :reply]
23 before_filter :find_issues, :only => [:bulk_edit, :move, :perform_move, :destroy]
23 before_filter :find_issues, :only => [:bulk_edit, :move, :perform_move, :destroy]
24 before_filter :find_project, :only => [:new, :create, :update_form, :preview, :auto_complete]
24 before_filter :find_project, :only => [:new, :create, :update_form, :preview, :auto_complete]
25 before_filter :authorize, :except => [:index, :changes, :preview, :context_menu]
25 before_filter :authorize, :except => [:index, :changes, :preview, :context_menu]
26 before_filter :find_optional_project, :only => [:index, :changes]
26 before_filter :find_optional_project, :only => [:index, :changes]
27 before_filter :check_for_default_issue_status, :only => [:new, :create]
27 before_filter :check_for_default_issue_status, :only => [:new, :create]
28 before_filter :build_new_issue_from_params, :only => [:new, :create]
28 before_filter :build_new_issue_from_params, :only => [:new, :create]
29 accept_key_auth :index, :show, :changes
29 accept_key_auth :index, :show, :changes
30
30
31 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
31 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
32
32
33 helper :journals
33 helper :journals
34 helper :projects
34 helper :projects
35 include ProjectsHelper
35 include ProjectsHelper
36 helper :custom_fields
36 helper :custom_fields
37 include CustomFieldsHelper
37 include CustomFieldsHelper
38 helper :issue_relations
38 helper :issue_relations
39 include IssueRelationsHelper
39 include IssueRelationsHelper
40 helper :watchers
40 helper :watchers
41 include WatchersHelper
41 include WatchersHelper
42 helper :attachments
42 helper :attachments
43 include AttachmentsHelper
43 include AttachmentsHelper
44 helper :queries
44 helper :queries
45 include QueriesHelper
45 include QueriesHelper
46 helper :sort
46 helper :sort
47 include SortHelper
47 include SortHelper
48 include IssuesHelper
48 include IssuesHelper
49 helper :timelog
49 helper :timelog
50 include Redmine::Export::PDF
50 include Redmine::Export::PDF
51
51
52 verify :method => [:post, :delete],
52 verify :method => [:post, :delete],
53 :only => :destroy,
53 :only => :destroy,
54 :render => { :nothing => true, :status => :method_not_allowed }
54 :render => { :nothing => true, :status => :method_not_allowed }
55
55
56 verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed }
56 verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed }
57 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
57 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
58
58
59 def index
59 def index
60 retrieve_query
60 retrieve_query
61 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
61 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
62 sort_update(@query.sortable_columns)
62 sort_update(@query.sortable_columns)
63
63
64 if @query.valid?
64 if @query.valid?
65 limit = case params[:format]
65 limit = case params[:format]
66 when 'csv', 'pdf'
66 when 'csv', 'pdf'
67 Setting.issues_export_limit.to_i
67 Setting.issues_export_limit.to_i
68 when 'atom'
68 when 'atom'
69 Setting.feeds_limit.to_i
69 Setting.feeds_limit.to_i
70 else
70 else
71 per_page_option
71 per_page_option
72 end
72 end
73
73
74 @issue_count = @query.issue_count
74 @issue_count = @query.issue_count
75 @issue_pages = Paginator.new self, @issue_count, limit, params['page']
75 @issue_pages = Paginator.new self, @issue_count, limit, params['page']
76 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
76 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
77 :order => sort_clause,
77 :order => sort_clause,
78 :offset => @issue_pages.current.offset,
78 :offset => @issue_pages.current.offset,
79 :limit => limit)
79 :limit => limit)
80 @issue_count_by_group = @query.issue_count_by_group
80 @issue_count_by_group = @query.issue_count_by_group
81
81
82 respond_to do |format|
82 respond_to do |format|
83 format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? }
83 format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? }
84 format.xml { render :layout => false }
84 format.xml { render :layout => false }
85 format.json { render :text => @issues.to_json, :layout => false }
85 format.json { render :text => @issues.to_json, :layout => false }
86 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
86 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
87 format.csv { send_data(issues_to_csv(@issues, @project), :type => 'text/csv; header=present', :filename => 'export.csv') }
87 format.csv { send_data(issues_to_csv(@issues, @project), :type => 'text/csv; header=present', :filename => 'export.csv') }
88 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
88 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
89 end
89 end
90 else
90 else
91 # Send html if the query is not valid
91 # Send html if the query is not valid
92 render(:template => 'issues/index.rhtml', :layout => !request.xhr?)
92 render(:template => 'issues/index.rhtml', :layout => !request.xhr?)
93 end
93 end
94 rescue ActiveRecord::RecordNotFound
94 rescue ActiveRecord::RecordNotFound
95 render_404
95 render_404
96 end
96 end
97
97
98 def changes
98 def changes
99 retrieve_query
99 retrieve_query
100 sort_init 'id', 'desc'
100 sort_init 'id', 'desc'
101 sort_update(@query.sortable_columns)
101 sort_update(@query.sortable_columns)
102
102
103 if @query.valid?
103 if @query.valid?
104 @journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC",
104 @journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC",
105 :limit => 25)
105 :limit => 25)
106 end
106 end
107 @title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
107 @title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
108 render :layout => false, :content_type => 'application/atom+xml'
108 render :layout => false, :content_type => 'application/atom+xml'
109 rescue ActiveRecord::RecordNotFound
109 rescue ActiveRecord::RecordNotFound
110 render_404
110 render_404
111 end
111 end
112
112
113 def show
113 def show
114 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
114 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
115 @journals.each_with_index {|j,i| j.indice = i+1}
115 @journals.each_with_index {|j,i| j.indice = i+1}
116 @journals.reverse! if User.current.wants_comments_in_reverse_order?
116 @journals.reverse! if User.current.wants_comments_in_reverse_order?
117 @changesets = @issue.changesets.visible.all
117 @changesets = @issue.changesets.visible.all
118 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
118 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
119 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
119 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
120 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
120 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
121 @priorities = IssuePriority.all
121 @priorities = IssuePriority.all
122 @time_entry = TimeEntry.new
122 @time_entry = TimeEntry.new
123 respond_to do |format|
123 respond_to do |format|
124 format.html { render :template => 'issues/show.rhtml' }
124 format.html { render :template => 'issues/show.rhtml' }
125 format.xml { render :layout => false }
125 format.xml { render :layout => false }
126 format.json { render :text => @issue.to_json, :layout => false }
126 format.json { render :text => @issue.to_json, :layout => false }
127 format.atom { render :action => 'changes', :layout => false, :content_type => 'application/atom+xml' }
127 format.atom { render :action => 'changes', :layout => false, :content_type => 'application/atom+xml' }
128 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
128 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
129 end
129 end
130 end
130 end
131
131
132 # Add a new issue
132 # Add a new issue
133 # The new issue will be created from an existing one if copy_from parameter is given
133 # The new issue will be created from an existing one if copy_from parameter is given
134 def new
134 def new
135 render :action => 'new', :layout => !request.xhr?
135 render :action => 'new', :layout => !request.xhr?
136 end
136 end
137
137
138 def create
138 def create
139 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
139 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
140 if @issue.save
140 if @issue.save
141 attachments = Attachment.attach_files(@issue, params[:attachments])
141 attachments = Attachment.attach_files(@issue, params[:attachments])
142 render_attachment_warning_if_needed(@issue)
142 render_attachment_warning_if_needed(@issue)
143 flash[:notice] = l(:notice_successful_create)
143 flash[:notice] = l(:notice_successful_create)
144 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
144 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
145 respond_to do |format|
145 respond_to do |format|
146 format.html {
146 format.html {
147 redirect_to(params[:continue] ? { :action => 'new', :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
147 redirect_to(params[:continue] ? { :action => 'new', :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
148 { :action => 'show', :id => @issue })
148 { :action => 'show', :id => @issue })
149 }
149 }
150 format.xml { render :action => 'show', :status => :created, :location => url_for(:controller => 'issues', :action => 'show', :id => @issue) }
150 format.xml { render :action => 'show', :status => :created, :location => url_for(:controller => 'issues', :action => 'show', :id => @issue) }
151 format.json { render :text => @issue.to_json, :status => :created, :location => url_for(:controller => 'issues', :action => 'show'), :layout => false }
151 format.json { render :text => @issue.to_json, :status => :created, :location => url_for(:controller => 'issues', :action => 'show'), :layout => false }
152 end
152 end
153 return
153 return
154 else
154 else
155 respond_to do |format|
155 respond_to do |format|
156 format.html { render :action => 'new' }
156 format.html { render :action => 'new' }
157 format.xml { render(:xml => @issue.errors, :status => :unprocessable_entity); return }
157 format.xml { render(:xml => @issue.errors, :status => :unprocessable_entity); return }
158 format.json { render :text => object_errors_to_json(@issue), :status => :unprocessable_entity, :layout => false }
158 format.json { render :text => object_errors_to_json(@issue), :status => :unprocessable_entity, :layout => false }
159 end
159 end
160 end
160 end
161 end
161 end
162
162
163 # Attributes that can be updated on workflow transition (without :edit permission)
163 # Attributes that can be updated on workflow transition (without :edit permission)
164 # TODO: make it configurable (at least per role)
164 # TODO: make it configurable (at least per role)
165 UPDATABLE_ATTRS_ON_TRANSITION = %w(status_id assigned_to_id fixed_version_id done_ratio) unless const_defined?(:UPDATABLE_ATTRS_ON_TRANSITION)
165 UPDATABLE_ATTRS_ON_TRANSITION = %w(status_id assigned_to_id fixed_version_id done_ratio) unless const_defined?(:UPDATABLE_ATTRS_ON_TRANSITION)
166
166
167 def edit
167 def edit
168 update_issue_from_params
168 update_issue_from_params
169
169
170 @journal = @issue.current_journal
170 @journal = @issue.current_journal
171
171
172 respond_to do |format|
172 respond_to do |format|
173 format.html { }
173 format.html { }
174 format.xml { }
174 format.xml { }
175 end
175 end
176 end
176 end
177
177
178 def update
178 def update
179 update_issue_from_params
179 update_issue_from_params
180
180
181 if @issue.save_issue_with_child_records(params, @time_entry)
181 if @issue.save_issue_with_child_records(params, @time_entry)
182 render_attachment_warning_if_needed(@issue)
182 render_attachment_warning_if_needed(@issue)
183 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
183 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
184
184
185 respond_to do |format|
185 respond_to do |format|
186 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
186 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
187 format.xml { head :ok }
187 format.xml { head :ok }
188 format.json { head :ok }
188 format.json { head :ok }
189 end
189 end
190 else
190 else
191 render_attachment_warning_if_needed(@issue)
191 render_attachment_warning_if_needed(@issue)
192 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
192 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
193 @journal = @issue.current_journal
193 @journal = @issue.current_journal
194
194
195 respond_to do |format|
195 respond_to do |format|
196 format.html { render :action => 'edit' }
196 format.html { render :action => 'edit' }
197 format.xml { render :xml => @issue.errors, :status => :unprocessable_entity }
197 format.xml { render :xml => @issue.errors, :status => :unprocessable_entity }
198 format.json { render :text => object_errors_to_json(@issue), :status => :unprocessable_entity, :layout => false }
198 format.json { render :text => object_errors_to_json(@issue), :status => :unprocessable_entity, :layout => false }
199 end
199 end
200 end
200 end
201 end
201 end
202
202
203 def reply
203 def reply
204 journal = Journal.find(params[:journal_id]) if params[:journal_id]
204 journal = Journal.find(params[:journal_id]) if params[:journal_id]
205 if journal
205 if journal
206 user = journal.user
206 user = journal.user
207 text = journal.notes
207 text = journal.notes
208 else
208 else
209 user = @issue.author
209 user = @issue.author
210 text = @issue.description
210 text = @issue.description
211 end
211 end
212 # Replaces pre blocks with [...]
212 # Replaces pre blocks with [...]
213 text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
213 text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
214 content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n> "
214 content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n> "
215 content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
215 content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
216
216
217 render(:update) { |page|
217 render(:update) { |page|
218 page.<< "$('notes').value = \"#{escape_javascript content}\";"
218 page.<< "$('notes').value = \"#{escape_javascript content}\";"
219 page.show 'update'
219 page.show 'update'
220 page << "Form.Element.focus('notes');"
220 page << "Form.Element.focus('notes');"
221 page << "Element.scrollTo('update');"
221 page << "Element.scrollTo('update');"
222 page << "$('notes').scrollTop = $('notes').scrollHeight - $('notes').clientHeight;"
222 page << "$('notes').scrollTop = $('notes').scrollHeight - $('notes').clientHeight;"
223 }
223 }
224 end
224 end
225
225
226 # Bulk edit a set of issues
226 # Bulk edit a set of issues
227 def bulk_edit
227 def bulk_edit
228 @issues.sort!
228 @issues.sort!
229 if request.post?
229 if request.post?
230 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
230 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
231 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
231 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
232 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
232 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
233
233
234 unsaved_issue_ids = []
234 unsaved_issue_ids = []
235 @issues.each do |issue|
235 @issues.each do |issue|
236 issue.reload
236 issue.reload
237 journal = issue.init_journal(User.current, params[:notes])
237 journal = issue.init_journal(User.current, params[:notes])
238 issue.safe_attributes = attributes
238 issue.safe_attributes = attributes
239 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
239 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
240 unless issue.save
240 unless issue.save
241 # Keep unsaved issue ids to display them in flash error
241 # Keep unsaved issue ids to display them in flash error
242 unsaved_issue_ids << issue.id
242 unsaved_issue_ids << issue.id
243 end
243 end
244 end
244 end
245 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
245 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
246 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
246 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
247 return
247 return
248 end
248 end
249 @available_statuses = Workflow.available_statuses(@project)
249 @available_statuses = Workflow.available_statuses(@project)
250 @custom_fields = @project.all_issue_custom_fields
250 @custom_fields = @project.all_issue_custom_fields
251 end
251 end
252
252
253 def destroy
253 def destroy
254 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
254 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
255 if @hours > 0
255 if @hours > 0
256 case params[:todo]
256 case params[:todo]
257 when 'destroy'
257 when 'destroy'
258 # nothing to do
258 # nothing to do
259 when 'nullify'
259 when 'nullify'
260 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
260 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
261 when 'reassign'
261 when 'reassign'
262 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
262 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
263 if reassign_to.nil?
263 if reassign_to.nil?
264 flash.now[:error] = l(:error_issue_not_found_in_project)
264 flash.now[:error] = l(:error_issue_not_found_in_project)
265 return
265 return
266 else
266 else
267 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
267 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
268 end
268 end
269 else
269 else
270 unless params[:format] == 'xml' || params[:format] == 'json'
270 unless params[:format] == 'xml' || params[:format] == 'json'
271 # display the destroy form if it's a user request
271 # display the destroy form if it's a user request
272 return
272 return
273 end
273 end
274 end
274 end
275 end
275 end
276 @issues.each(&:destroy)
276 @issues.each(&:destroy)
277 respond_to do |format|
277 respond_to do |format|
278 format.html { redirect_to :action => 'index', :project_id => @project }
278 format.html { redirect_to :action => 'index', :project_id => @project }
279 format.xml { head :ok }
279 format.xml { head :ok }
280 format.json { head :ok }
280 format.json { head :ok }
281 end
281 end
282 end
282 end
283
283
284 def context_menu
284 def context_menu
285 @issues = Issue.find_all_by_id(params[:ids], :include => :project)
285 @issues = Issue.find_all_by_id(params[:ids], :include => :project)
286 if (@issues.size == 1)
286 if (@issues.size == 1)
287 @issue = @issues.first
287 @issue = @issues.first
288 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
288 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
289 end
289 end
290 projects = @issues.collect(&:project).compact.uniq
290 projects = @issues.collect(&:project).compact.uniq
291 @project = projects.first if projects.size == 1
291 @project = projects.first if projects.size == 1
292
292
293 @can = {:edit => (@project && User.current.allowed_to?(:edit_issues, @project)),
293 @can = {:edit => (@project && User.current.allowed_to?(:edit_issues, @project)),
294 :log_time => (@project && User.current.allowed_to?(:log_time, @project)),
294 :log_time => (@project && User.current.allowed_to?(:log_time, @project)),
295 :update => (@project && (User.current.allowed_to?(:edit_issues, @project) || (User.current.allowed_to?(:change_status, @project) && @allowed_statuses && !@allowed_statuses.empty?))),
295 :update => (@project && (User.current.allowed_to?(:edit_issues, @project) || (User.current.allowed_to?(:change_status, @project) && @allowed_statuses && !@allowed_statuses.empty?))),
296 :move => (@project && User.current.allowed_to?(:move_issues, @project)),
296 :move => (@project && User.current.allowed_to?(:move_issues, @project)),
297 :copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
297 :copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
298 :delete => (@project && User.current.allowed_to?(:delete_issues, @project))
298 :delete => (@project && User.current.allowed_to?(:delete_issues, @project))
299 }
299 }
300 if @project
300 if @project
301 @assignables = @project.assignable_users
301 @assignables = @project.assignable_users
302 @assignables << @issue.assigned_to if @issue && @issue.assigned_to && !@assignables.include?(@issue.assigned_to)
302 @assignables << @issue.assigned_to if @issue && @issue.assigned_to && !@assignables.include?(@issue.assigned_to)
303 @trackers = @project.trackers
303 @trackers = @project.trackers
304 end
304 end
305
305
306 @priorities = IssuePriority.all.reverse
306 @priorities = IssuePriority.all.reverse
307 @statuses = IssueStatus.find(:all, :order => 'position')
307 @statuses = IssueStatus.find(:all, :order => 'position')
308 @back = back_url
308 @back = back_url
309
309
310 render :layout => false
310 render :layout => false
311 end
311 end
312
312
313 def update_form
313 def update_form
314 if params[:id].blank?
314 if params[:id].blank?
315 @issue = Issue.new
315 @issue = Issue.new
316 @issue.project = @project
316 @issue.project = @project
317 else
317 else
318 @issue = @project.issues.visible.find(params[:id])
318 @issue = @project.issues.visible.find(params[:id])
319 end
319 end
320 @issue.attributes = params[:issue]
320 @issue.attributes = params[:issue]
321 @allowed_statuses = ([@issue.status] + @issue.status.find_new_statuses_allowed_to(User.current.roles_for_project(@project), @issue.tracker)).uniq
321 @allowed_statuses = ([@issue.status] + @issue.status.find_new_statuses_allowed_to(User.current.roles_for_project(@project), @issue.tracker)).uniq
322 @priorities = IssuePriority.all
322 @priorities = IssuePriority.all
323
323
324 render :partial => 'attributes'
324 render :partial => 'attributes'
325 end
325 end
326
326
327 def preview
327 def preview
328 @issue = @project.issues.find_by_id(params[:id]) unless params[:id].blank?
328 @issue = @project.issues.find_by_id(params[:id]) unless params[:id].blank?
329 if @issue
329 if @issue
330 @attachements = @issue.attachments
330 @attachements = @issue.attachments
331 @description = params[:issue] && params[:issue][:description]
331 @description = params[:issue] && params[:issue][:description]
332 if @description && @description.gsub(/(\r?\n|\n\r?)/, "\n") == @issue.description.to_s.gsub(/(\r?\n|\n\r?)/, "\n")
332 if @description && @description.gsub(/(\r?\n|\n\r?)/, "\n") == @issue.description.to_s.gsub(/(\r?\n|\n\r?)/, "\n")
333 @description = nil
333 @description = nil
334 end
334 end
335 @notes = params[:notes]
335 @notes = params[:notes]
336 else
336 else
337 @description = (params[:issue] ? params[:issue][:description] : nil)
337 @description = (params[:issue] ? params[:issue][:description] : nil)
338 end
338 end
339 render :layout => false
339 render :layout => false
340 end
340 end
341
341
342 def auto_complete
342 def auto_complete
343 @issues = []
343 @issues = []
344 q = params[:q].to_s
344 q = params[:q].to_s
345 if q.match(/^\d+$/)
345 if q.match(/^\d+$/)
346 @issues << @project.issues.visible.find_by_id(q.to_i)
346 @issues << @project.issues.visible.find_by_id(q.to_i)
347 end
347 end
348 unless q.blank?
348 unless q.blank?
349 @issues += @project.issues.visible.find(:all, :conditions => ["LOWER(#{Issue.table_name}.subject) LIKE ?", "%#{q.downcase}%"], :limit => 10)
349 @issues += @project.issues.visible.find(:all, :conditions => ["LOWER(#{Issue.table_name}.subject) LIKE ?", "%#{q.downcase}%"], :limit => 10)
350 end
350 end
351 render :layout => false
351 render :layout => false
352 end
352 end
353
353
354 private
354 private
355 def find_issue
355 def find_issue
356 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
356 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
357 @project = @issue.project
357 @project = @issue.project
358 rescue ActiveRecord::RecordNotFound
358 rescue ActiveRecord::RecordNotFound
359 render_404
359 render_404
360 end
360 end
361
361
362 def find_project
362 def find_project
363 project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id]
363 project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id]
364 @project = Project.find(project_id)
364 @project = Project.find(project_id)
365 rescue ActiveRecord::RecordNotFound
365 rescue ActiveRecord::RecordNotFound
366 render_404
366 render_404
367 end
367 end
368
368
369 # Used by #edit and #update to set some common instance variables
369 # Used by #edit and #update to set some common instance variables
370 # from the params
370 # from the params
371 # TODO: Refactor, not everything in here is needed by #edit
371 # TODO: Refactor, not everything in here is needed by #edit
372 def update_issue_from_params
372 def update_issue_from_params
373 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
373 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
374 @priorities = IssuePriority.all
374 @priorities = IssuePriority.all
375 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
375 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
376 @time_entry = TimeEntry.new
376 @time_entry = TimeEntry.new
377
377
378 @notes = params[:notes]
378 @notes = params[:notes]
379 @issue.init_journal(User.current, @notes)
379 @issue.init_journal(User.current, @notes)
380 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
380 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
381 if (@edit_allowed || !@allowed_statuses.empty?) && params[:issue]
381 if (@edit_allowed || !@allowed_statuses.empty?) && params[:issue]
382 attrs = params[:issue].dup
382 attrs = params[:issue].dup
383 attrs.delete_if {|k,v| !UPDATABLE_ATTRS_ON_TRANSITION.include?(k) } unless @edit_allowed
383 attrs.delete_if {|k,v| !UPDATABLE_ATTRS_ON_TRANSITION.include?(k) } unless @edit_allowed
384 attrs.delete(:status_id) unless @allowed_statuses.detect {|s| s.id.to_s == attrs[:status_id].to_s}
384 attrs.delete(:status_id) unless @allowed_statuses.detect {|s| s.id.to_s == attrs[:status_id].to_s}
385 @issue.safe_attributes = attrs
385 @issue.safe_attributes = attrs
386 end
386 end
387
387
388 end
388 end
389
389
390 # TODO: Refactor, lots of extra code in here
390 # TODO: Refactor, lots of extra code in here
391 def build_new_issue_from_params
391 def build_new_issue_from_params
392 @issue = Issue.new
392 @issue = Issue.new
393 @issue.copy_from(params[:copy_from]) if params[:copy_from]
393 @issue.copy_from(params[:copy_from]) if params[:copy_from]
394 @issue.project = @project
394 @issue.project = @project
395 # Tracker must be set before custom field values
395 # Tracker must be set before custom field values
396 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
396 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
397 if @issue.tracker.nil?
397 if @issue.tracker.nil?
398 render_error l(:error_no_tracker_in_project)
398 render_error l(:error_no_tracker_in_project)
399 return false
399 return false
400 end
400 end
401 if params[:issue].is_a?(Hash)
401 if params[:issue].is_a?(Hash)
402 @issue.safe_attributes = params[:issue]
402 @issue.safe_attributes = params[:issue]
403 @issue.watcher_user_ids = params[:issue]['watcher_user_ids'] if User.current.allowed_to?(:add_issue_watchers, @project)
403 @issue.watcher_user_ids = params[:issue]['watcher_user_ids'] if User.current.allowed_to?(:add_issue_watchers, @project)
404 end
404 end
405 @issue.author = User.current
405 @issue.author = User.current
406 @issue.start_date ||= Date.today
406 @issue.start_date ||= Date.today
407 @priorities = IssuePriority.all
407 @priorities = IssuePriority.all
408 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
408 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
409 end
409 end
410
410
411 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
412 if unsaved_issue_ids.empty?
413 flash[:notice] = l(:notice_successful_update) unless issues.empty?
414 else
415 flash[:error] = l(:notice_failed_to_save_issues,
416 :count => unsaved_issue_ids.size,
417 :total => issues.size,
418 :ids => '#' + unsaved_issue_ids.join(', #'))
419 end
420 end
421
422 def check_for_default_issue_status
411 def check_for_default_issue_status
423 if IssueStatus.default.nil?
412 if IssueStatus.default.nil?
424 render_error l(:error_no_default_issue_status)
413 render_error l(:error_no_default_issue_status)
425 return false
414 return false
426 end
415 end
427 end
416 end
428 end
417 end
General Comments 0
You need to be logged in to leave comments. Login now