##// END OF EJS Templates
Removed dead code....
Jean-Philippe Lang -
r8831:3be511cdab00
parent child
Show More
@@ -1,550 +1,541
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 require 'uri'
18 require 'uri'
19 require 'cgi'
19 require 'cgi'
20
20
21 class Unauthorized < Exception; end
21 class Unauthorized < Exception; end
22
22
23 class ApplicationController < ActionController::Base
23 class ApplicationController < ActionController::Base
24 include Redmine::I18n
24 include Redmine::I18n
25
25
26 layout 'base'
26 layout 'base'
27 exempt_from_layout 'builder', 'rsb'
27 exempt_from_layout 'builder', 'rsb'
28
28
29 protect_from_forgery
29 protect_from_forgery
30 def handle_unverified_request
30 def handle_unverified_request
31 super
31 super
32 cookies.delete(:autologin)
32 cookies.delete(:autologin)
33 end
33 end
34 # Remove broken cookie after upgrade from 0.8.x (#4292)
34 # Remove broken cookie after upgrade from 0.8.x (#4292)
35 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
35 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
36 # TODO: remove it when Rails is fixed
36 # TODO: remove it when Rails is fixed
37 before_filter :delete_broken_cookies
37 before_filter :delete_broken_cookies
38 def delete_broken_cookies
38 def delete_broken_cookies
39 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
39 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
40 cookies.delete '_redmine_session'
40 cookies.delete '_redmine_session'
41 redirect_to home_path
41 redirect_to home_path
42 return false
42 return false
43 end
43 end
44 end
44 end
45
45
46 # FIXME: Remove this when all of Rack and Rails have learned how to
46 # FIXME: Remove this when all of Rack and Rails have learned how to
47 # properly use encodings
47 # properly use encodings
48 before_filter :params_filter
48 before_filter :params_filter
49
49
50 def params_filter
50 def params_filter
51 if RUBY_VERSION >= '1.9' && defined?(Rails) && Rails::VERSION::MAJOR < 3
51 if RUBY_VERSION >= '1.9' && defined?(Rails) && Rails::VERSION::MAJOR < 3
52 self.utf8nize!(params)
52 self.utf8nize!(params)
53 end
53 end
54 end
54 end
55
55
56 def utf8nize!(obj)
56 def utf8nize!(obj)
57 if obj.frozen?
57 if obj.frozen?
58 obj
58 obj
59 elsif obj.is_a? String
59 elsif obj.is_a? String
60 obj.respond_to?(:force_encoding) ? obj.force_encoding("UTF-8") : obj
60 obj.respond_to?(:force_encoding) ? obj.force_encoding("UTF-8") : obj
61 elsif obj.is_a? Hash
61 elsif obj.is_a? Hash
62 obj.each {|k, v| obj[k] = self.utf8nize!(v)}
62 obj.each {|k, v| obj[k] = self.utf8nize!(v)}
63 elsif obj.is_a? Array
63 elsif obj.is_a? Array
64 obj.each {|v| self.utf8nize!(v)}
64 obj.each {|v| self.utf8nize!(v)}
65 else
65 else
66 obj
66 obj
67 end
67 end
68 end
68 end
69
69
70 before_filter :user_setup, :check_if_login_required, :set_localization
70 before_filter :user_setup, :check_if_login_required, :set_localization
71 filter_parameter_logging :password
71 filter_parameter_logging :password
72
72
73 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
73 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
74 rescue_from ::Unauthorized, :with => :deny_access
74 rescue_from ::Unauthorized, :with => :deny_access
75
75
76 include Redmine::Search::Controller
76 include Redmine::Search::Controller
77 include Redmine::MenuManager::MenuController
77 include Redmine::MenuManager::MenuController
78 helper Redmine::MenuManager::MenuHelper
78 helper Redmine::MenuManager::MenuHelper
79
79
80 Redmine::Scm::Base.all.each do |scm|
80 Redmine::Scm::Base.all.each do |scm|
81 require_dependency "repository/#{scm.underscore}"
81 require_dependency "repository/#{scm.underscore}"
82 end
82 end
83
83
84 def user_setup
84 def user_setup
85 # Check the settings cache for each request
85 # Check the settings cache for each request
86 Setting.check_cache
86 Setting.check_cache
87 # Find the current user
87 # Find the current user
88 User.current = find_current_user
88 User.current = find_current_user
89 end
89 end
90
90
91 # Returns the current user or nil if no user is logged in
91 # Returns the current user or nil if no user is logged in
92 # and starts a session if needed
92 # and starts a session if needed
93 def find_current_user
93 def find_current_user
94 if session[:user_id]
94 if session[:user_id]
95 # existing session
95 # existing session
96 (User.active.find(session[:user_id]) rescue nil)
96 (User.active.find(session[:user_id]) rescue nil)
97 elsif cookies[:autologin] && Setting.autologin?
97 elsif cookies[:autologin] && Setting.autologin?
98 # auto-login feature starts a new session
98 # auto-login feature starts a new session
99 user = User.try_to_autologin(cookies[:autologin])
99 user = User.try_to_autologin(cookies[:autologin])
100 session[:user_id] = user.id if user
100 session[:user_id] = user.id if user
101 user
101 user
102 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
102 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
103 # RSS key authentication does not start a session
103 # RSS key authentication does not start a session
104 User.find_by_rss_key(params[:key])
104 User.find_by_rss_key(params[:key])
105 elsif Setting.rest_api_enabled? && accept_api_auth?
105 elsif Setting.rest_api_enabled? && accept_api_auth?
106 if (key = api_key_from_request)
106 if (key = api_key_from_request)
107 # Use API key
107 # Use API key
108 User.find_by_api_key(key)
108 User.find_by_api_key(key)
109 else
109 else
110 # HTTP Basic, either username/password or API key/random
110 # HTTP Basic, either username/password or API key/random
111 authenticate_with_http_basic do |username, password|
111 authenticate_with_http_basic do |username, password|
112 User.try_to_login(username, password) || User.find_by_api_key(username)
112 User.try_to_login(username, password) || User.find_by_api_key(username)
113 end
113 end
114 end
114 end
115 end
115 end
116 end
116 end
117
117
118 # Sets the logged in user
118 # Sets the logged in user
119 def logged_user=(user)
119 def logged_user=(user)
120 reset_session
120 reset_session
121 if user && user.is_a?(User)
121 if user && user.is_a?(User)
122 User.current = user
122 User.current = user
123 session[:user_id] = user.id
123 session[:user_id] = user.id
124 else
124 else
125 User.current = User.anonymous
125 User.current = User.anonymous
126 end
126 end
127 end
127 end
128
128
129 # check if login is globally required to access the application
129 # check if login is globally required to access the application
130 def check_if_login_required
130 def check_if_login_required
131 # no check needed if user is already logged in
131 # no check needed if user is already logged in
132 return true if User.current.logged?
132 return true if User.current.logged?
133 require_login if Setting.login_required?
133 require_login if Setting.login_required?
134 end
134 end
135
135
136 def set_localization
136 def set_localization
137 lang = nil
137 lang = nil
138 if User.current.logged?
138 if User.current.logged?
139 lang = find_language(User.current.language)
139 lang = find_language(User.current.language)
140 end
140 end
141 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
141 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
142 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
142 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
143 if !accept_lang.blank?
143 if !accept_lang.blank?
144 accept_lang = accept_lang.downcase
144 accept_lang = accept_lang.downcase
145 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
145 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
146 end
146 end
147 end
147 end
148 lang ||= Setting.default_language
148 lang ||= Setting.default_language
149 set_language_if_valid(lang)
149 set_language_if_valid(lang)
150 end
150 end
151
151
152 def require_login
152 def require_login
153 if !User.current.logged?
153 if !User.current.logged?
154 # Extract only the basic url parameters on non-GET requests
154 # Extract only the basic url parameters on non-GET requests
155 if request.get?
155 if request.get?
156 url = url_for(params)
156 url = url_for(params)
157 else
157 else
158 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
158 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
159 end
159 end
160 respond_to do |format|
160 respond_to do |format|
161 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
161 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
162 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
162 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
163 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
163 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
164 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
164 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
165 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
165 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
166 end
166 end
167 return false
167 return false
168 end
168 end
169 true
169 true
170 end
170 end
171
171
172 def require_admin
172 def require_admin
173 return unless require_login
173 return unless require_login
174 if !User.current.admin?
174 if !User.current.admin?
175 render_403
175 render_403
176 return false
176 return false
177 end
177 end
178 true
178 true
179 end
179 end
180
180
181 def deny_access
181 def deny_access
182 User.current.logged? ? render_403 : require_login
182 User.current.logged? ? render_403 : require_login
183 end
183 end
184
184
185 # Authorize the user for the requested action
185 # Authorize the user for the requested action
186 def authorize(ctrl = params[:controller], action = params[:action], global = false)
186 def authorize(ctrl = params[:controller], action = params[:action], global = false)
187 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
187 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
188 if allowed
188 if allowed
189 true
189 true
190 else
190 else
191 if @project && @project.archived?
191 if @project && @project.archived?
192 render_403 :message => :notice_not_authorized_archived_project
192 render_403 :message => :notice_not_authorized_archived_project
193 else
193 else
194 deny_access
194 deny_access
195 end
195 end
196 end
196 end
197 end
197 end
198
198
199 # Authorize the user for the requested action outside a project
199 # Authorize the user for the requested action outside a project
200 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
200 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
201 authorize(ctrl, action, global)
201 authorize(ctrl, action, global)
202 end
202 end
203
203
204 # Find project of id params[:id]
204 # Find project of id params[:id]
205 def find_project
205 def find_project
206 @project = Project.find(params[:id])
206 @project = Project.find(params[:id])
207 rescue ActiveRecord::RecordNotFound
207 rescue ActiveRecord::RecordNotFound
208 render_404
208 render_404
209 end
209 end
210
210
211 # Find project of id params[:project_id]
211 # Find project of id params[:project_id]
212 def find_project_by_project_id
212 def find_project_by_project_id
213 @project = Project.find(params[:project_id])
213 @project = Project.find(params[:project_id])
214 rescue ActiveRecord::RecordNotFound
214 rescue ActiveRecord::RecordNotFound
215 render_404
215 render_404
216 end
216 end
217
217
218 # Find a project based on params[:project_id]
218 # Find a project based on params[:project_id]
219 # TODO: some subclasses override this, see about merging their logic
219 # TODO: some subclasses override this, see about merging their logic
220 def find_optional_project
220 def find_optional_project
221 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
221 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
222 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
222 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
223 allowed ? true : deny_access
223 allowed ? true : deny_access
224 rescue ActiveRecord::RecordNotFound
224 rescue ActiveRecord::RecordNotFound
225 render_404
225 render_404
226 end
226 end
227
227
228 # Finds and sets @project based on @object.project
228 # Finds and sets @project based on @object.project
229 def find_project_from_association
229 def find_project_from_association
230 render_404 unless @object.present?
230 render_404 unless @object.present?
231
231
232 @project = @object.project
232 @project = @object.project
233 end
233 end
234
234
235 def find_model_object
235 def find_model_object
236 model = self.class.read_inheritable_attribute('model_object')
236 model = self.class.read_inheritable_attribute('model_object')
237 if model
237 if model
238 @object = model.find(params[:id])
238 @object = model.find(params[:id])
239 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
239 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
240 end
240 end
241 rescue ActiveRecord::RecordNotFound
241 rescue ActiveRecord::RecordNotFound
242 render_404
242 render_404
243 end
243 end
244
244
245 def self.model_object(model)
245 def self.model_object(model)
246 write_inheritable_attribute('model_object', model)
246 write_inheritable_attribute('model_object', model)
247 end
247 end
248
248
249 # Filter for bulk issue operations
249 # Filter for bulk issue operations
250 def find_issues
250 def find_issues
251 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
251 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
252 raise ActiveRecord::RecordNotFound if @issues.empty?
252 raise ActiveRecord::RecordNotFound if @issues.empty?
253 if @issues.detect {|issue| !issue.visible?}
253 if @issues.detect {|issue| !issue.visible?}
254 deny_access
254 deny_access
255 return
255 return
256 end
256 end
257 @projects = @issues.collect(&:project).compact.uniq
257 @projects = @issues.collect(&:project).compact.uniq
258 @project = @projects.first if @projects.size == 1
258 @project = @projects.first if @projects.size == 1
259 rescue ActiveRecord::RecordNotFound
259 rescue ActiveRecord::RecordNotFound
260 render_404
260 render_404
261 end
261 end
262
262
263 # Check if project is unique before bulk operations
264 def check_project_uniqueness
265 unless @project
266 # TODO: let users bulk edit/move/destroy issues from different projects
267 render_error 'Can not bulk edit/move/destroy issues from different projects'
268 return false
269 end
270 end
271
272 # make sure that the user is a member of the project (or admin) if project is private
263 # make sure that the user is a member of the project (or admin) if project is private
273 # used as a before_filter for actions that do not require any particular permission on the project
264 # used as a before_filter for actions that do not require any particular permission on the project
274 def check_project_privacy
265 def check_project_privacy
275 if @project && @project.active?
266 if @project && @project.active?
276 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
267 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
277 true
268 true
278 else
269 else
279 deny_access
270 deny_access
280 end
271 end
281 else
272 else
282 @project = nil
273 @project = nil
283 render_404
274 render_404
284 false
275 false
285 end
276 end
286 end
277 end
287
278
288 def back_url
279 def back_url
289 params[:back_url] || request.env['HTTP_REFERER']
280 params[:back_url] || request.env['HTTP_REFERER']
290 end
281 end
291
282
292 def redirect_back_or_default(default)
283 def redirect_back_or_default(default)
293 back_url = CGI.unescape(params[:back_url].to_s)
284 back_url = CGI.unescape(params[:back_url].to_s)
294 if !back_url.blank?
285 if !back_url.blank?
295 begin
286 begin
296 uri = URI.parse(back_url)
287 uri = URI.parse(back_url)
297 # do not redirect user to another host or to the login or register page
288 # do not redirect user to another host or to the login or register page
298 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
289 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
299 redirect_to(back_url)
290 redirect_to(back_url)
300 return
291 return
301 end
292 end
302 rescue URI::InvalidURIError
293 rescue URI::InvalidURIError
303 # redirect to default
294 # redirect to default
304 end
295 end
305 end
296 end
306 redirect_to default
297 redirect_to default
307 false
298 false
308 end
299 end
309
300
310 def render_403(options={})
301 def render_403(options={})
311 @project = nil
302 @project = nil
312 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
303 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
313 return false
304 return false
314 end
305 end
315
306
316 def render_404(options={})
307 def render_404(options={})
317 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
308 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
318 return false
309 return false
319 end
310 end
320
311
321 # Renders an error response
312 # Renders an error response
322 def render_error(arg)
313 def render_error(arg)
323 arg = {:message => arg} unless arg.is_a?(Hash)
314 arg = {:message => arg} unless arg.is_a?(Hash)
324
315
325 @message = arg[:message]
316 @message = arg[:message]
326 @message = l(@message) if @message.is_a?(Symbol)
317 @message = l(@message) if @message.is_a?(Symbol)
327 @status = arg[:status] || 500
318 @status = arg[:status] || 500
328
319
329 respond_to do |format|
320 respond_to do |format|
330 format.html {
321 format.html {
331 render :template => 'common/error', :layout => use_layout, :status => @status
322 render :template => 'common/error', :layout => use_layout, :status => @status
332 }
323 }
333 format.atom { head @status }
324 format.atom { head @status }
334 format.xml { head @status }
325 format.xml { head @status }
335 format.js { head @status }
326 format.js { head @status }
336 format.json { head @status }
327 format.json { head @status }
337 end
328 end
338 end
329 end
339
330
340 # Filter for actions that provide an API response
331 # Filter for actions that provide an API response
341 # but have no HTML representation for non admin users
332 # but have no HTML representation for non admin users
342 def require_admin_or_api_request
333 def require_admin_or_api_request
343 return true if api_request?
334 return true if api_request?
344 if User.current.admin?
335 if User.current.admin?
345 true
336 true
346 elsif User.current.logged?
337 elsif User.current.logged?
347 render_error(:status => 406)
338 render_error(:status => 406)
348 else
339 else
349 deny_access
340 deny_access
350 end
341 end
351 end
342 end
352
343
353 # Picks which layout to use based on the request
344 # Picks which layout to use based on the request
354 #
345 #
355 # @return [boolean, string] name of the layout to use or false for no layout
346 # @return [boolean, string] name of the layout to use or false for no layout
356 def use_layout
347 def use_layout
357 request.xhr? ? false : 'base'
348 request.xhr? ? false : 'base'
358 end
349 end
359
350
360 def invalid_authenticity_token
351 def invalid_authenticity_token
361 if api_request?
352 if api_request?
362 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
353 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
363 end
354 end
364 render_error "Invalid form authenticity token."
355 render_error "Invalid form authenticity token."
365 end
356 end
366
357
367 def render_feed(items, options={})
358 def render_feed(items, options={})
368 @items = items || []
359 @items = items || []
369 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
360 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
370 @items = @items.slice(0, Setting.feeds_limit.to_i)
361 @items = @items.slice(0, Setting.feeds_limit.to_i)
371 @title = options[:title] || Setting.app_title
362 @title = options[:title] || Setting.app_title
372 render :template => "common/feed.atom", :layout => false,
363 render :template => "common/feed.atom", :layout => false,
373 :content_type => 'application/atom+xml'
364 :content_type => 'application/atom+xml'
374 end
365 end
375
366
376 # TODO: remove in Redmine 1.4
367 # TODO: remove in Redmine 1.4
377 def self.accept_key_auth(*actions)
368 def self.accept_key_auth(*actions)
378 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
369 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
379 accept_rss_auth(*actions)
370 accept_rss_auth(*actions)
380 end
371 end
381
372
382 # TODO: remove in Redmine 1.4
373 # TODO: remove in Redmine 1.4
383 def accept_key_auth_actions
374 def accept_key_auth_actions
384 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth_actions is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
375 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth_actions is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
385 self.class.accept_rss_auth
376 self.class.accept_rss_auth
386 end
377 end
387
378
388 def self.accept_rss_auth(*actions)
379 def self.accept_rss_auth(*actions)
389 if actions.any?
380 if actions.any?
390 write_inheritable_attribute('accept_rss_auth_actions', actions)
381 write_inheritable_attribute('accept_rss_auth_actions', actions)
391 else
382 else
392 read_inheritable_attribute('accept_rss_auth_actions') || []
383 read_inheritable_attribute('accept_rss_auth_actions') || []
393 end
384 end
394 end
385 end
395
386
396 def accept_rss_auth?(action=action_name)
387 def accept_rss_auth?(action=action_name)
397 self.class.accept_rss_auth.include?(action.to_sym)
388 self.class.accept_rss_auth.include?(action.to_sym)
398 end
389 end
399
390
400 def self.accept_api_auth(*actions)
391 def self.accept_api_auth(*actions)
401 if actions.any?
392 if actions.any?
402 write_inheritable_attribute('accept_api_auth_actions', actions)
393 write_inheritable_attribute('accept_api_auth_actions', actions)
403 else
394 else
404 read_inheritable_attribute('accept_api_auth_actions') || []
395 read_inheritable_attribute('accept_api_auth_actions') || []
405 end
396 end
406 end
397 end
407
398
408 def accept_api_auth?(action=action_name)
399 def accept_api_auth?(action=action_name)
409 self.class.accept_api_auth.include?(action.to_sym)
400 self.class.accept_api_auth.include?(action.to_sym)
410 end
401 end
411
402
412 # Returns the number of objects that should be displayed
403 # Returns the number of objects that should be displayed
413 # on the paginated list
404 # on the paginated list
414 def per_page_option
405 def per_page_option
415 per_page = nil
406 per_page = nil
416 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
407 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
417 per_page = params[:per_page].to_s.to_i
408 per_page = params[:per_page].to_s.to_i
418 session[:per_page] = per_page
409 session[:per_page] = per_page
419 elsif session[:per_page]
410 elsif session[:per_page]
420 per_page = session[:per_page]
411 per_page = session[:per_page]
421 else
412 else
422 per_page = Setting.per_page_options_array.first || 25
413 per_page = Setting.per_page_options_array.first || 25
423 end
414 end
424 per_page
415 per_page
425 end
416 end
426
417
427 # Returns offset and limit used to retrieve objects
418 # Returns offset and limit used to retrieve objects
428 # for an API response based on offset, limit and page parameters
419 # for an API response based on offset, limit and page parameters
429 def api_offset_and_limit(options=params)
420 def api_offset_and_limit(options=params)
430 if options[:offset].present?
421 if options[:offset].present?
431 offset = options[:offset].to_i
422 offset = options[:offset].to_i
432 if offset < 0
423 if offset < 0
433 offset = 0
424 offset = 0
434 end
425 end
435 end
426 end
436 limit = options[:limit].to_i
427 limit = options[:limit].to_i
437 if limit < 1
428 if limit < 1
438 limit = 25
429 limit = 25
439 elsif limit > 100
430 elsif limit > 100
440 limit = 100
431 limit = 100
441 end
432 end
442 if offset.nil? && options[:page].present?
433 if offset.nil? && options[:page].present?
443 offset = (options[:page].to_i - 1) * limit
434 offset = (options[:page].to_i - 1) * limit
444 offset = 0 if offset < 0
435 offset = 0 if offset < 0
445 end
436 end
446 offset ||= 0
437 offset ||= 0
447
438
448 [offset, limit]
439 [offset, limit]
449 end
440 end
450
441
451 # qvalues http header parser
442 # qvalues http header parser
452 # code taken from webrick
443 # code taken from webrick
453 def parse_qvalues(value)
444 def parse_qvalues(value)
454 tmp = []
445 tmp = []
455 if value
446 if value
456 parts = value.split(/,\s*/)
447 parts = value.split(/,\s*/)
457 parts.each {|part|
448 parts.each {|part|
458 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
449 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
459 val = m[1]
450 val = m[1]
460 q = (m[2] or 1).to_f
451 q = (m[2] or 1).to_f
461 tmp.push([val, q])
452 tmp.push([val, q])
462 end
453 end
463 }
454 }
464 tmp = tmp.sort_by{|val, q| -q}
455 tmp = tmp.sort_by{|val, q| -q}
465 tmp.collect!{|val, q| val}
456 tmp.collect!{|val, q| val}
466 end
457 end
467 return tmp
458 return tmp
468 rescue
459 rescue
469 nil
460 nil
470 end
461 end
471
462
472 # Returns a string that can be used as filename value in Content-Disposition header
463 # Returns a string that can be used as filename value in Content-Disposition header
473 def filename_for_content_disposition(name)
464 def filename_for_content_disposition(name)
474 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
465 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
475 end
466 end
476
467
477 def api_request?
468 def api_request?
478 %w(xml json).include? params[:format]
469 %w(xml json).include? params[:format]
479 end
470 end
480
471
481 # Returns the API key present in the request
472 # Returns the API key present in the request
482 def api_key_from_request
473 def api_key_from_request
483 if params[:key].present?
474 if params[:key].present?
484 params[:key]
475 params[:key]
485 elsif request.headers["X-Redmine-API-Key"].present?
476 elsif request.headers["X-Redmine-API-Key"].present?
486 request.headers["X-Redmine-API-Key"]
477 request.headers["X-Redmine-API-Key"]
487 end
478 end
488 end
479 end
489
480
490 # Renders a warning flash if obj has unsaved attachments
481 # Renders a warning flash if obj has unsaved attachments
491 def render_attachment_warning_if_needed(obj)
482 def render_attachment_warning_if_needed(obj)
492 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
483 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
493 end
484 end
494
485
495 # Sets the `flash` notice or error based the number of issues that did not save
486 # Sets the `flash` notice or error based the number of issues that did not save
496 #
487 #
497 # @param [Array, Issue] issues all of the saved and unsaved Issues
488 # @param [Array, Issue] issues all of the saved and unsaved Issues
498 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
489 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
499 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
490 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
500 if unsaved_issue_ids.empty?
491 if unsaved_issue_ids.empty?
501 flash[:notice] = l(:notice_successful_update) unless issues.empty?
492 flash[:notice] = l(:notice_successful_update) unless issues.empty?
502 else
493 else
503 flash[:error] = l(:notice_failed_to_save_issues,
494 flash[:error] = l(:notice_failed_to_save_issues,
504 :count => unsaved_issue_ids.size,
495 :count => unsaved_issue_ids.size,
505 :total => issues.size,
496 :total => issues.size,
506 :ids => '#' + unsaved_issue_ids.join(', #'))
497 :ids => '#' + unsaved_issue_ids.join(', #'))
507 end
498 end
508 end
499 end
509
500
510 # Rescues an invalid query statement. Just in case...
501 # Rescues an invalid query statement. Just in case...
511 def query_statement_invalid(exception)
502 def query_statement_invalid(exception)
512 logger.error "Query::StatementInvalid: #{exception.message}" if logger
503 logger.error "Query::StatementInvalid: #{exception.message}" if logger
513 session.delete(:query)
504 session.delete(:query)
514 sort_clear if respond_to?(:sort_clear)
505 sort_clear if respond_to?(:sort_clear)
515 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
506 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
516 end
507 end
517
508
518 # Renders API response on validation failure
509 # Renders API response on validation failure
519 def render_validation_errors(object)
510 def render_validation_errors(object)
520 options = { :status => :unprocessable_entity, :layout => false }
511 options = { :status => :unprocessable_entity, :layout => false }
521 options.merge!(case params[:format]
512 options.merge!(case params[:format]
522 when 'xml'; { :xml => object.errors }
513 when 'xml'; { :xml => object.errors }
523 when 'json'; { :json => {'errors' => object.errors} } # ActiveResource client compliance
514 when 'json'; { :json => {'errors' => object.errors} } # ActiveResource client compliance
524 else
515 else
525 raise "Unknown format #{params[:format]} in #render_validation_errors"
516 raise "Unknown format #{params[:format]} in #render_validation_errors"
526 end
517 end
527 )
518 )
528 render options
519 render options
529 end
520 end
530
521
531 # Overrides #default_template so that the api template
522 # Overrides #default_template so that the api template
532 # is used automatically if it exists
523 # is used automatically if it exists
533 def default_template(action_name = self.action_name)
524 def default_template(action_name = self.action_name)
534 if api_request?
525 if api_request?
535 begin
526 begin
536 return self.view_paths.find_template(default_template_name(action_name), 'api')
527 return self.view_paths.find_template(default_template_name(action_name), 'api')
537 rescue ::ActionView::MissingTemplate
528 rescue ::ActionView::MissingTemplate
538 # the api template was not found
529 # the api template was not found
539 # fallback to the default behaviour
530 # fallback to the default behaviour
540 end
531 end
541 end
532 end
542 super
533 super
543 end
534 end
544
535
545 # Overrides #pick_layout so that #render with no arguments
536 # Overrides #pick_layout so that #render with no arguments
546 # doesn't use the layout for api requests
537 # doesn't use the layout for api requests
547 def pick_layout(*args)
538 def pick_layout(*args)
548 api_request? ? nil : super
539 api_request? ? nil : super
549 end
540 end
550 end
541 end
@@ -1,429 +1,428
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 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]
22 before_filter :find_issue, :only => [:show, :edit, :update]
23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :move, :perform_move, :destroy]
23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy]
24 before_filter :check_project_uniqueness, :only => [:move, :perform_move]
25 before_filter :find_project, :only => [:new, :create]
24 before_filter :find_project, :only => [:new, :create]
26 before_filter :authorize, :except => [:index]
25 before_filter :authorize, :except => [:index]
27 before_filter :find_optional_project, :only => [:index]
26 before_filter :find_optional_project, :only => [:index]
28 before_filter :check_for_default_issue_status, :only => [:new, :create]
27 before_filter :check_for_default_issue_status, :only => [:new, :create]
29 before_filter :build_new_issue_from_params, :only => [:new, :create]
28 before_filter :build_new_issue_from_params, :only => [:new, :create]
30 accept_rss_auth :index, :show
29 accept_rss_auth :index, :show
31 accept_api_auth :index, :show, :create, :update, :destroy
30 accept_api_auth :index, :show, :create, :update, :destroy
32
31
33 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
32 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
34
33
35 helper :journals
34 helper :journals
36 helper :projects
35 helper :projects
37 include ProjectsHelper
36 include ProjectsHelper
38 helper :custom_fields
37 helper :custom_fields
39 include CustomFieldsHelper
38 include CustomFieldsHelper
40 helper :issue_relations
39 helper :issue_relations
41 include IssueRelationsHelper
40 include IssueRelationsHelper
42 helper :watchers
41 helper :watchers
43 include WatchersHelper
42 include WatchersHelper
44 helper :attachments
43 helper :attachments
45 include AttachmentsHelper
44 include AttachmentsHelper
46 helper :queries
45 helper :queries
47 include QueriesHelper
46 include QueriesHelper
48 helper :repositories
47 helper :repositories
49 include RepositoriesHelper
48 include RepositoriesHelper
50 helper :sort
49 helper :sort
51 include SortHelper
50 include SortHelper
52 include IssuesHelper
51 include IssuesHelper
53 helper :timelog
52 helper :timelog
54 helper :gantt
53 helper :gantt
55 include Redmine::Export::PDF
54 include Redmine::Export::PDF
56
55
57 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 }
58 verify :method => :post, :only => :bulk_update, :render => {:nothing => true, :status => :method_not_allowed }
57 verify :method => :post, :only => :bulk_update, :render => {:nothing => true, :status => :method_not_allowed }
59 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
58 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
60
59
61 def index
60 def index
62 retrieve_query
61 retrieve_query
63 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
62 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
64 sort_update(@query.sortable_columns)
63 sort_update(@query.sortable_columns)
65
64
66 if @query.valid?
65 if @query.valid?
67 case params[:format]
66 case params[:format]
68 when 'csv', 'pdf'
67 when 'csv', 'pdf'
69 @limit = Setting.issues_export_limit.to_i
68 @limit = Setting.issues_export_limit.to_i
70 when 'atom'
69 when 'atom'
71 @limit = Setting.feeds_limit.to_i
70 @limit = Setting.feeds_limit.to_i
72 when 'xml', 'json'
71 when 'xml', 'json'
73 @offset, @limit = api_offset_and_limit
72 @offset, @limit = api_offset_and_limit
74 else
73 else
75 @limit = per_page_option
74 @limit = per_page_option
76 end
75 end
77
76
78 @issue_count = @query.issue_count
77 @issue_count = @query.issue_count
79 @issue_pages = Paginator.new self, @issue_count, @limit, params['page']
78 @issue_pages = Paginator.new self, @issue_count, @limit, params['page']
80 @offset ||= @issue_pages.current.offset
79 @offset ||= @issue_pages.current.offset
81 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
80 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
82 :order => sort_clause,
81 :order => sort_clause,
83 :offset => @offset,
82 :offset => @offset,
84 :limit => @limit)
83 :limit => @limit)
85 @issue_count_by_group = @query.issue_count_by_group
84 @issue_count_by_group = @query.issue_count_by_group
86
85
87 respond_to do |format|
86 respond_to do |format|
88 format.html { render :template => 'issues/index', :layout => !request.xhr? }
87 format.html { render :template => 'issues/index', :layout => !request.xhr? }
89 format.api {
88 format.api {
90 Issue.load_relations(@issues) if include_in_api_response?('relations')
89 Issue.load_relations(@issues) if include_in_api_response?('relations')
91 }
90 }
92 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
91 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
93 format.csv { send_data(issues_to_csv(@issues, @project, @query, params), :type => 'text/csv; header=present', :filename => 'export.csv') }
92 format.csv { send_data(issues_to_csv(@issues, @project, @query, params), :type => 'text/csv; header=present', :filename => 'export.csv') }
94 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
93 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
95 end
94 end
96 else
95 else
97 respond_to do |format|
96 respond_to do |format|
98 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
97 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
99 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
98 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
100 format.api { render_validation_errors(@query) }
99 format.api { render_validation_errors(@query) }
101 end
100 end
102 end
101 end
103 rescue ActiveRecord::RecordNotFound
102 rescue ActiveRecord::RecordNotFound
104 render_404
103 render_404
105 end
104 end
106
105
107 def show
106 def show
108 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
107 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
109 @journals.each_with_index {|j,i| j.indice = i+1}
108 @journals.each_with_index {|j,i| j.indice = i+1}
110 @journals.reverse! if User.current.wants_comments_in_reverse_order?
109 @journals.reverse! if User.current.wants_comments_in_reverse_order?
111
110
112 @changesets = @issue.changesets.visible.all
111 @changesets = @issue.changesets.visible.all
113 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
112 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
114
113
115 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
114 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
116 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
115 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
117 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
116 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
118 @priorities = IssuePriority.active
117 @priorities = IssuePriority.active
119 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
118 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
120 respond_to do |format|
119 respond_to do |format|
121 format.html {
120 format.html {
122 retrieve_previous_and_next_issue_ids
121 retrieve_previous_and_next_issue_ids
123 render :template => 'issues/show'
122 render :template => 'issues/show'
124 }
123 }
125 format.api
124 format.api
126 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
125 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
127 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
126 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
128 end
127 end
129 end
128 end
130
129
131 # Add a new issue
130 # Add a new issue
132 # The new issue will be created from an existing one if copy_from parameter is given
131 # The new issue will be created from an existing one if copy_from parameter is given
133 def new
132 def new
134 respond_to do |format|
133 respond_to do |format|
135 format.html { render :action => 'new', :layout => !request.xhr? }
134 format.html { render :action => 'new', :layout => !request.xhr? }
136 format.js {
135 format.js {
137 render(:update) { |page|
136 render(:update) { |page|
138 if params[:project_change]
137 if params[:project_change]
139 page.replace_html 'all_attributes', :partial => 'form'
138 page.replace_html 'all_attributes', :partial => 'form'
140 else
139 else
141 page.replace_html 'attributes', :partial => 'attributes'
140 page.replace_html 'attributes', :partial => 'attributes'
142 end
141 end
143 m = User.current.allowed_to?(:log_time, @issue.project) ? 'show' : 'hide'
142 m = User.current.allowed_to?(:log_time, @issue.project) ? 'show' : 'hide'
144 page << "if ($('log_time')) {Element.#{m}('log_time');}"
143 page << "if ($('log_time')) {Element.#{m}('log_time');}"
145 }
144 }
146 }
145 }
147 end
146 end
148 end
147 end
149
148
150 def create
149 def create
151 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
150 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
152 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
151 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
153 if @issue.save
152 if @issue.save
154 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
153 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
155 respond_to do |format|
154 respond_to do |format|
156 format.html {
155 format.html {
157 render_attachment_warning_if_needed(@issue)
156 render_attachment_warning_if_needed(@issue)
158 flash[:notice] = l(:notice_issue_successful_create, :id => "<a href='#{issue_path(@issue)}'>##{@issue.id}</a>")
157 flash[:notice] = l(:notice_issue_successful_create, :id => "<a href='#{issue_path(@issue)}'>##{@issue.id}</a>")
159 redirect_to(params[:continue] ? { :action => 'new', :project_id => @issue.project, :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
158 redirect_to(params[:continue] ? { :action => 'new', :project_id => @issue.project, :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
160 { :action => 'show', :id => @issue })
159 { :action => 'show', :id => @issue })
161 }
160 }
162 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
161 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
163 end
162 end
164 return
163 return
165 else
164 else
166 respond_to do |format|
165 respond_to do |format|
167 format.html { render :action => 'new' }
166 format.html { render :action => 'new' }
168 format.api { render_validation_errors(@issue) }
167 format.api { render_validation_errors(@issue) }
169 end
168 end
170 end
169 end
171 end
170 end
172
171
173 def edit
172 def edit
174 return unless update_issue_from_params
173 return unless update_issue_from_params
175
174
176 respond_to do |format|
175 respond_to do |format|
177 format.html { }
176 format.html { }
178 format.xml { }
177 format.xml { }
179 end
178 end
180 end
179 end
181
180
182 def update
181 def update
183 return unless update_issue_from_params
182 return unless update_issue_from_params
184 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
183 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
185 saved = false
184 saved = false
186 begin
185 begin
187 saved = @issue.save_issue_with_child_records(params, @time_entry)
186 saved = @issue.save_issue_with_child_records(params, @time_entry)
188 rescue ActiveRecord::StaleObjectError
187 rescue ActiveRecord::StaleObjectError
189 @conflict = true
188 @conflict = true
190 if params[:last_journal_id]
189 if params[:last_journal_id]
191 if params[:last_journal_id].present?
190 if params[:last_journal_id].present?
192 last_journal_id = params[:last_journal_id].to_i
191 last_journal_id = params[:last_journal_id].to_i
193 @conflict_journals = @issue.journals.all(:conditions => ["#{Journal.table_name}.id > ?", last_journal_id])
192 @conflict_journals = @issue.journals.all(:conditions => ["#{Journal.table_name}.id > ?", last_journal_id])
194 else
193 else
195 @conflict_journals = @issue.journals.all
194 @conflict_journals = @issue.journals.all
196 end
195 end
197 end
196 end
198 end
197 end
199
198
200 if saved
199 if saved
201 render_attachment_warning_if_needed(@issue)
200 render_attachment_warning_if_needed(@issue)
202 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
201 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
203
202
204 respond_to do |format|
203 respond_to do |format|
205 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
204 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
206 format.api { head :ok }
205 format.api { head :ok }
207 end
206 end
208 else
207 else
209 respond_to do |format|
208 respond_to do |format|
210 format.html { render :action => 'edit' }
209 format.html { render :action => 'edit' }
211 format.api { render_validation_errors(@issue) }
210 format.api { render_validation_errors(@issue) }
212 end
211 end
213 end
212 end
214 end
213 end
215
214
216 # Bulk edit/copy a set of issues
215 # Bulk edit/copy a set of issues
217 def bulk_edit
216 def bulk_edit
218 @issues.sort!
217 @issues.sort!
219 @copy = params[:copy].present?
218 @copy = params[:copy].present?
220 @notes = params[:notes]
219 @notes = params[:notes]
221
220
222 if User.current.allowed_to?(:move_issues, @projects)
221 if User.current.allowed_to?(:move_issues, @projects)
223 @allowed_projects = Issue.allowed_target_projects_on_move
222 @allowed_projects = Issue.allowed_target_projects_on_move
224 if params[:issue]
223 if params[:issue]
225 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id]}
224 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id]}
226 if @target_project
225 if @target_project
227 target_projects = [@target_project]
226 target_projects = [@target_project]
228 end
227 end
229 end
228 end
230 end
229 end
231 target_projects ||= @projects
230 target_projects ||= @projects
232
231
233 @available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
232 @available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
234 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields}.reduce(:&)
233 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields}.reduce(:&)
235 @assignables = target_projects.map(&:assignable_users).reduce(:&)
234 @assignables = target_projects.map(&:assignable_users).reduce(:&)
236 @trackers = target_projects.map(&:trackers).reduce(:&)
235 @trackers = target_projects.map(&:trackers).reduce(:&)
237
236
238 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
237 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
239 render :layout => false if request.xhr?
238 render :layout => false if request.xhr?
240 end
239 end
241
240
242 def bulk_update
241 def bulk_update
243 @issues.sort!
242 @issues.sort!
244 @copy = params[:copy].present?
243 @copy = params[:copy].present?
245 attributes = parse_params_for_bulk_issue_attributes(params)
244 attributes = parse_params_for_bulk_issue_attributes(params)
246
245
247 unsaved_issue_ids = []
246 unsaved_issue_ids = []
248 moved_issues = []
247 moved_issues = []
249 @issues.each do |issue|
248 @issues.each do |issue|
250 issue.reload
249 issue.reload
251 if @copy
250 if @copy
252 issue = issue.copy
251 issue = issue.copy
253 end
252 end
254 journal = issue.init_journal(User.current, params[:notes])
253 journal = issue.init_journal(User.current, params[:notes])
255 issue.safe_attributes = attributes
254 issue.safe_attributes = attributes
256 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
255 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
257 if issue.save
256 if issue.save
258 moved_issues << issue
257 moved_issues << issue
259 else
258 else
260 # Keep unsaved issue ids to display them in flash error
259 # Keep unsaved issue ids to display them in flash error
261 unsaved_issue_ids << issue.id
260 unsaved_issue_ids << issue.id
262 end
261 end
263 end
262 end
264 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
263 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
265
264
266 if params[:follow]
265 if params[:follow]
267 if @issues.size == 1 && moved_issues.size == 1
266 if @issues.size == 1 && moved_issues.size == 1
268 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
267 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
269 elsif moved_issues.map(&:project).uniq.size == 1
268 elsif moved_issues.map(&:project).uniq.size == 1
270 redirect_to :controller => 'issues', :action => 'index', :project_id => moved_issues.map(&:project).first
269 redirect_to :controller => 'issues', :action => 'index', :project_id => moved_issues.map(&:project).first
271 end
270 end
272 else
271 else
273 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
272 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
274 end
273 end
275 end
274 end
276
275
277 verify :method => :delete, :only => :destroy, :render => { :nothing => true, :status => :method_not_allowed }
276 verify :method => :delete, :only => :destroy, :render => { :nothing => true, :status => :method_not_allowed }
278 def destroy
277 def destroy
279 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
278 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
280 if @hours > 0
279 if @hours > 0
281 case params[:todo]
280 case params[:todo]
282 when 'destroy'
281 when 'destroy'
283 # nothing to do
282 # nothing to do
284 when 'nullify'
283 when 'nullify'
285 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
284 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
286 when 'reassign'
285 when 'reassign'
287 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
286 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
288 if reassign_to.nil?
287 if reassign_to.nil?
289 flash.now[:error] = l(:error_issue_not_found_in_project)
288 flash.now[:error] = l(:error_issue_not_found_in_project)
290 return
289 return
291 else
290 else
292 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
291 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
293 end
292 end
294 else
293 else
295 # display the destroy form if it's a user request
294 # display the destroy form if it's a user request
296 return unless api_request?
295 return unless api_request?
297 end
296 end
298 end
297 end
299 @issues.each do |issue|
298 @issues.each do |issue|
300 begin
299 begin
301 issue.reload.destroy
300 issue.reload.destroy
302 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
301 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
303 # nothing to do, issue was already deleted (eg. by a parent)
302 # nothing to do, issue was already deleted (eg. by a parent)
304 end
303 end
305 end
304 end
306 respond_to do |format|
305 respond_to do |format|
307 format.html { redirect_back_or_default(:action => 'index', :project_id => @project) }
306 format.html { redirect_back_or_default(:action => 'index', :project_id => @project) }
308 format.api { head :ok }
307 format.api { head :ok }
309 end
308 end
310 end
309 end
311
310
312 private
311 private
313 def find_issue
312 def find_issue
314 # Issue.visible.find(...) can not be used to redirect user to the login form
313 # Issue.visible.find(...) can not be used to redirect user to the login form
315 # if the issue actually exists but requires authentication
314 # if the issue actually exists but requires authentication
316 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
315 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
317 unless @issue.visible?
316 unless @issue.visible?
318 deny_access
317 deny_access
319 return
318 return
320 end
319 end
321 @project = @issue.project
320 @project = @issue.project
322 rescue ActiveRecord::RecordNotFound
321 rescue ActiveRecord::RecordNotFound
323 render_404
322 render_404
324 end
323 end
325
324
326 def find_project
325 def find_project
327 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
326 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
328 @project = Project.find(project_id)
327 @project = Project.find(project_id)
329 rescue ActiveRecord::RecordNotFound
328 rescue ActiveRecord::RecordNotFound
330 render_404
329 render_404
331 end
330 end
332
331
333 def retrieve_previous_and_next_issue_ids
332 def retrieve_previous_and_next_issue_ids
334 retrieve_query_from_session
333 retrieve_query_from_session
335 if @query
334 if @query
336 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
335 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
337 sort_update(@query.sortable_columns, 'issues_index_sort')
336 sort_update(@query.sortable_columns, 'issues_index_sort')
338 limit = 500
337 limit = 500
339 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
338 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
340 if (idx = issue_ids.index(@issue.id)) && idx < limit
339 if (idx = issue_ids.index(@issue.id)) && idx < limit
341 if issue_ids.size < 500
340 if issue_ids.size < 500
342 @issue_position = idx + 1
341 @issue_position = idx + 1
343 @issue_count = issue_ids.size
342 @issue_count = issue_ids.size
344 end
343 end
345 @prev_issue_id = issue_ids[idx - 1] if idx > 0
344 @prev_issue_id = issue_ids[idx - 1] if idx > 0
346 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
345 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
347 end
346 end
348 end
347 end
349 end
348 end
350
349
351 # Used by #edit and #update to set some common instance variables
350 # Used by #edit and #update to set some common instance variables
352 # from the params
351 # from the params
353 # TODO: Refactor, not everything in here is needed by #edit
352 # TODO: Refactor, not everything in here is needed by #edit
354 def update_issue_from_params
353 def update_issue_from_params
355 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
354 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
356 @priorities = IssuePriority.active
355 @priorities = IssuePriority.active
357 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
356 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
358 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
357 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
359 @time_entry.attributes = params[:time_entry]
358 @time_entry.attributes = params[:time_entry]
360
359
361 @notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
360 @notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
362 @issue.init_journal(User.current, @notes)
361 @issue.init_journal(User.current, @notes)
363
362
364 issue_attributes = params[:issue]
363 issue_attributes = params[:issue]
365 if issue_attributes && params[:conflict_resolution]
364 if issue_attributes && params[:conflict_resolution]
366 case params[:conflict_resolution]
365 case params[:conflict_resolution]
367 when 'overwrite'
366 when 'overwrite'
368 issue_attributes = issue_attributes.dup
367 issue_attributes = issue_attributes.dup
369 issue_attributes.delete(:lock_version)
368 issue_attributes.delete(:lock_version)
370 when 'add_notes'
369 when 'add_notes'
371 issue_attributes = {}
370 issue_attributes = {}
372 when 'cancel'
371 when 'cancel'
373 redirect_to issue_path(@issue)
372 redirect_to issue_path(@issue)
374 return false
373 return false
375 end
374 end
376 end
375 end
377 @issue.safe_attributes = issue_attributes
376 @issue.safe_attributes = issue_attributes
378 true
377 true
379 end
378 end
380
379
381 # TODO: Refactor, lots of extra code in here
380 # TODO: Refactor, lots of extra code in here
382 # TODO: Changing tracker on an existing issue should not trigger this
381 # TODO: Changing tracker on an existing issue should not trigger this
383 def build_new_issue_from_params
382 def build_new_issue_from_params
384 if params[:id].blank?
383 if params[:id].blank?
385 @issue = Issue.new
384 @issue = Issue.new
386 if params[:copy_from]
385 if params[:copy_from]
387 begin
386 begin
388 @copy_from = Issue.visible.find(params[:copy_from])
387 @copy_from = Issue.visible.find(params[:copy_from])
389 @copy_attachments = params[:copy_attachments].present? || request.get?
388 @copy_attachments = params[:copy_attachments].present? || request.get?
390 @issue.copy_from(@copy_from, :attachments => @copy_attachments)
389 @issue.copy_from(@copy_from, :attachments => @copy_attachments)
391 rescue ActiveRecord::RecordNotFound
390 rescue ActiveRecord::RecordNotFound
392 render_404
391 render_404
393 return
392 return
394 end
393 end
395 end
394 end
396 @issue.project = @project
395 @issue.project = @project
397 else
396 else
398 @issue = @project.issues.visible.find(params[:id])
397 @issue = @project.issues.visible.find(params[:id])
399 end
398 end
400
399
401 @issue.project = @project
400 @issue.project = @project
402 @issue.author = User.current
401 @issue.author = User.current
403 # Tracker must be set before custom field values
402 # Tracker must be set before custom field values
404 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
403 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
405 if @issue.tracker.nil?
404 if @issue.tracker.nil?
406 render_error l(:error_no_tracker_in_project)
405 render_error l(:error_no_tracker_in_project)
407 return false
406 return false
408 end
407 end
409 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
408 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
410 @issue.safe_attributes = params[:issue]
409 @issue.safe_attributes = params[:issue]
411
410
412 @priorities = IssuePriority.active
411 @priorities = IssuePriority.active
413 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
412 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
414 end
413 end
415
414
416 def check_for_default_issue_status
415 def check_for_default_issue_status
417 if IssueStatus.default.nil?
416 if IssueStatus.default.nil?
418 render_error l(:error_no_default_issue_status)
417 render_error l(:error_no_default_issue_status)
419 return false
418 return false
420 end
419 end
421 end
420 end
422
421
423 def parse_params_for_bulk_issue_attributes(params)
422 def parse_params_for_bulk_issue_attributes(params)
424 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
423 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
425 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
424 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
426 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
425 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
427 attributes
426 attributes
428 end
427 end
429 end
428 end
General Comments 0
You need to be logged in to leave comments. Login now