##// END OF EJS Templates
Code cleanup....
Jean-Philippe Lang -
r10677:6e1ff5bba62e
parent child
Show More
@@ -1,580 +1,590
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2012 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require 'uri'
19 19 require 'cgi'
20 20
21 21 class Unauthorized < Exception; end
22 22
23 23 class ApplicationController < ActionController::Base
24 24 include Redmine::I18n
25 25
26 26 class_attribute :accept_api_auth_actions
27 27 class_attribute :accept_rss_auth_actions
28 28 class_attribute :model_object
29 29
30 30 layout 'base'
31 31
32 32 protect_from_forgery
33 33 def handle_unverified_request
34 34 super
35 35 cookies.delete(:autologin)
36 36 end
37 37
38 38 before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
39 39
40 40 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
41 41 rescue_from ::Unauthorized, :with => :deny_access
42 42 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
43 43
44 44 include Redmine::Search::Controller
45 45 include Redmine::MenuManager::MenuController
46 46 helper Redmine::MenuManager::MenuHelper
47 47
48 48 def session_expiration
49 49 if session[:user_id]
50 50 if session_expired? && !try_to_autologin
51 51 reset_session
52 52 flash[:error] = l(:error_session_expired)
53 53 redirect_to signin_url
54 54 else
55 55 session[:atime] = Time.now.utc.to_i
56 56 end
57 57 end
58 58 end
59 59
60 60 def session_expired?
61 61 if Setting.session_lifetime?
62 62 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
63 63 return true
64 64 end
65 65 end
66 66 if Setting.session_timeout?
67 67 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
68 68 return true
69 69 end
70 70 end
71 71 false
72 72 end
73 73
74 74 def start_user_session(user)
75 75 session[:user_id] = user.id
76 76 session[:ctime] = Time.now.utc.to_i
77 77 session[:atime] = Time.now.utc.to_i
78 78 end
79 79
80 80 def user_setup
81 81 # Check the settings cache for each request
82 82 Setting.check_cache
83 83 # Find the current user
84 84 User.current = find_current_user
85 85 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
86 86 end
87 87
88 88 # Returns the current user or nil if no user is logged in
89 89 # and starts a session if needed
90 90 def find_current_user
91 91 user = nil
92 92 unless api_request?
93 93 if session[:user_id]
94 94 # existing session
95 95 user = (User.active.find(session[:user_id]) rescue nil)
96 96 elsif autologin_user = try_to_autologin
97 97 user = autologin_user
98 98 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
99 99 # RSS key authentication does not start a session
100 100 user = User.find_by_rss_key(params[:key])
101 101 end
102 102 end
103 103 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
104 104 if (key = api_key_from_request)
105 105 # Use API key
106 106 user = User.find_by_api_key(key)
107 107 else
108 108 # HTTP Basic, either username/password or API key/random
109 109 authenticate_with_http_basic do |username, password|
110 110 user = User.try_to_login(username, password) || User.find_by_api_key(username)
111 111 end
112 112 end
113 113 # Switch user if requested by an admin user
114 114 if user && user.admin? && (username = api_switch_user_from_request)
115 115 su = User.find_by_login(username)
116 116 if su && su.active?
117 117 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
118 118 user = su
119 119 else
120 120 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
121 121 end
122 122 end
123 123 end
124 124 user
125 125 end
126 126
127 127 def try_to_autologin
128 128 if cookies[:autologin] && Setting.autologin?
129 129 # auto-login feature starts a new session
130 130 user = User.try_to_autologin(cookies[:autologin])
131 131 if user
132 132 reset_session
133 133 start_user_session(user)
134 134 end
135 135 user
136 136 end
137 137 end
138 138
139 139 # Sets the logged in user
140 140 def logged_user=(user)
141 141 reset_session
142 142 if user && user.is_a?(User)
143 143 User.current = user
144 144 start_user_session(user)
145 145 else
146 146 User.current = User.anonymous
147 147 end
148 148 end
149 149
150 150 # Logs out current user
151 151 def logout_user
152 152 if User.current.logged?
153 153 cookies.delete :autologin
154 154 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
155 155 self.logged_user = nil
156 156 end
157 157 end
158 158
159 159 # check if login is globally required to access the application
160 160 def check_if_login_required
161 161 # no check needed if user is already logged in
162 162 return true if User.current.logged?
163 163 require_login if Setting.login_required?
164 164 end
165 165
166 166 def set_localization
167 167 lang = nil
168 168 if User.current.logged?
169 169 lang = find_language(User.current.language)
170 170 end
171 171 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
172 172 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
173 173 if !accept_lang.blank?
174 174 accept_lang = accept_lang.downcase
175 175 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
176 176 end
177 177 end
178 178 lang ||= Setting.default_language
179 179 set_language_if_valid(lang)
180 180 end
181 181
182 182 def require_login
183 183 if !User.current.logged?
184 184 # Extract only the basic url parameters on non-GET requests
185 185 if request.get?
186 186 url = url_for(params)
187 187 else
188 188 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
189 189 end
190 190 respond_to do |format|
191 191 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
192 192 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
193 193 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
194 194 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
195 195 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
196 196 end
197 197 return false
198 198 end
199 199 true
200 200 end
201 201
202 202 def require_admin
203 203 return unless require_login
204 204 if !User.current.admin?
205 205 render_403
206 206 return false
207 207 end
208 208 true
209 209 end
210 210
211 211 def deny_access
212 212 User.current.logged? ? render_403 : require_login
213 213 end
214 214
215 215 # Authorize the user for the requested action
216 216 def authorize(ctrl = params[:controller], action = params[:action], global = false)
217 217 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
218 218 if allowed
219 219 true
220 220 else
221 221 if @project && @project.archived?
222 222 render_403 :message => :notice_not_authorized_archived_project
223 223 else
224 224 deny_access
225 225 end
226 226 end
227 227 end
228 228
229 229 # Authorize the user for the requested action outside a project
230 230 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
231 231 authorize(ctrl, action, global)
232 232 end
233 233
234 234 # Find project of id params[:id]
235 235 def find_project
236 236 @project = Project.find(params[:id])
237 237 rescue ActiveRecord::RecordNotFound
238 238 render_404
239 239 end
240 240
241 241 # Find project of id params[:project_id]
242 242 def find_project_by_project_id
243 243 @project = Project.find(params[:project_id])
244 244 rescue ActiveRecord::RecordNotFound
245 245 render_404
246 246 end
247 247
248 248 # Find a project based on params[:project_id]
249 249 # TODO: some subclasses override this, see about merging their logic
250 250 def find_optional_project
251 251 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
252 252 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
253 253 allowed ? true : deny_access
254 254 rescue ActiveRecord::RecordNotFound
255 255 render_404
256 256 end
257 257
258 258 # Finds and sets @project based on @object.project
259 259 def find_project_from_association
260 260 render_404 unless @object.present?
261 261
262 262 @project = @object.project
263 263 end
264 264
265 265 def find_model_object
266 266 model = self.class.model_object
267 267 if model
268 268 @object = model.find(params[:id])
269 269 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
270 270 end
271 271 rescue ActiveRecord::RecordNotFound
272 272 render_404
273 273 end
274 274
275 275 def self.model_object(model)
276 276 self.model_object = model
277 277 end
278 278
279 # Filter for bulk issue operations
279 # Find the issue whose id is the :id parameter
280 # Raises a Unauthorized exception if the issue is not visible
281 def find_issue
282 # Issue.visible.find(...) can not be used to redirect user to the login form
283 # if the issue actually exists but requires authentication
284 @issue = Issue.find(params[:id])
285 raise Unauthorized unless @issue.visible?
286 @project = @issue.project
287 rescue ActiveRecord::RecordNotFound
288 render_404
289 end
290
291 # Find issues with a single :id param or :ids array param
292 # Raises a Unauthorized exception if one of the issues is not visible
280 293 def find_issues
281 294 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
282 295 raise ActiveRecord::RecordNotFound if @issues.empty?
283 if @issues.detect {|issue| !issue.visible?}
284 deny_access
285 return
286 end
296 raise Unauthorized if @issues.all?(&:visible?)
287 297 @projects = @issues.collect(&:project).compact.uniq
288 298 @project = @projects.first if @projects.size == 1
289 299 rescue ActiveRecord::RecordNotFound
290 300 render_404
291 301 end
292 302
293 303 # make sure that the user is a member of the project (or admin) if project is private
294 304 # used as a before_filter for actions that do not require any particular permission on the project
295 305 def check_project_privacy
296 306 if @project && !@project.archived?
297 307 if @project.visible?
298 308 true
299 309 else
300 310 deny_access
301 311 end
302 312 else
303 313 @project = nil
304 314 render_404
305 315 false
306 316 end
307 317 end
308 318
309 319 def back_url
310 320 url = params[:back_url]
311 321 if url.nil? && referer = request.env['HTTP_REFERER']
312 322 url = CGI.unescape(referer.to_s)
313 323 end
314 324 url
315 325 end
316 326
317 327 def redirect_back_or_default(default)
318 328 back_url = params[:back_url].to_s
319 329 if back_url.present?
320 330 begin
321 331 uri = URI.parse(back_url)
322 332 # do not redirect user to another host or to the login or register page
323 333 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
324 334 redirect_to(back_url)
325 335 return
326 336 end
327 337 rescue URI::InvalidURIError
328 338 logger.warn("Could not redirect to invalid URL #{back_url}")
329 339 # redirect to default
330 340 end
331 341 end
332 342 redirect_to default
333 343 false
334 344 end
335 345
336 346 # Redirects to the request referer if present, redirects to args or call block otherwise.
337 347 def redirect_to_referer_or(*args, &block)
338 348 redirect_to :back
339 349 rescue ::ActionController::RedirectBackError
340 350 if args.any?
341 351 redirect_to *args
342 352 elsif block_given?
343 353 block.call
344 354 else
345 355 raise "#redirect_to_referer_or takes arguments or a block"
346 356 end
347 357 end
348 358
349 359 def render_403(options={})
350 360 @project = nil
351 361 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
352 362 return false
353 363 end
354 364
355 365 def render_404(options={})
356 366 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
357 367 return false
358 368 end
359 369
360 370 # Renders an error response
361 371 def render_error(arg)
362 372 arg = {:message => arg} unless arg.is_a?(Hash)
363 373
364 374 @message = arg[:message]
365 375 @message = l(@message) if @message.is_a?(Symbol)
366 376 @status = arg[:status] || 500
367 377
368 378 respond_to do |format|
369 379 format.html {
370 380 render :template => 'common/error', :layout => use_layout, :status => @status
371 381 }
372 382 format.any { head @status }
373 383 end
374 384 end
375 385
376 386 # Handler for ActionView::MissingTemplate exception
377 387 def missing_template
378 388 logger.warn "Missing template, responding with 404"
379 389 @project = nil
380 390 render_404
381 391 end
382 392
383 393 # Filter for actions that provide an API response
384 394 # but have no HTML representation for non admin users
385 395 def require_admin_or_api_request
386 396 return true if api_request?
387 397 if User.current.admin?
388 398 true
389 399 elsif User.current.logged?
390 400 render_error(:status => 406)
391 401 else
392 402 deny_access
393 403 end
394 404 end
395 405
396 406 # Picks which layout to use based on the request
397 407 #
398 408 # @return [boolean, string] name of the layout to use or false for no layout
399 409 def use_layout
400 410 request.xhr? ? false : 'base'
401 411 end
402 412
403 413 def invalid_authenticity_token
404 414 if api_request?
405 415 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
406 416 end
407 417 render_error "Invalid form authenticity token."
408 418 end
409 419
410 420 def render_feed(items, options={})
411 421 @items = items || []
412 422 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
413 423 @items = @items.slice(0, Setting.feeds_limit.to_i)
414 424 @title = options[:title] || Setting.app_title
415 425 render :template => "common/feed", :formats => [:atom], :layout => false,
416 426 :content_type => 'application/atom+xml'
417 427 end
418 428
419 429 def self.accept_rss_auth(*actions)
420 430 if actions.any?
421 431 self.accept_rss_auth_actions = actions
422 432 else
423 433 self.accept_rss_auth_actions || []
424 434 end
425 435 end
426 436
427 437 def accept_rss_auth?(action=action_name)
428 438 self.class.accept_rss_auth.include?(action.to_sym)
429 439 end
430 440
431 441 def self.accept_api_auth(*actions)
432 442 if actions.any?
433 443 self.accept_api_auth_actions = actions
434 444 else
435 445 self.accept_api_auth_actions || []
436 446 end
437 447 end
438 448
439 449 def accept_api_auth?(action=action_name)
440 450 self.class.accept_api_auth.include?(action.to_sym)
441 451 end
442 452
443 453 # Returns the number of objects that should be displayed
444 454 # on the paginated list
445 455 def per_page_option
446 456 per_page = nil
447 457 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
448 458 per_page = params[:per_page].to_s.to_i
449 459 session[:per_page] = per_page
450 460 elsif session[:per_page]
451 461 per_page = session[:per_page]
452 462 else
453 463 per_page = Setting.per_page_options_array.first || 25
454 464 end
455 465 per_page
456 466 end
457 467
458 468 # Returns offset and limit used to retrieve objects
459 469 # for an API response based on offset, limit and page parameters
460 470 def api_offset_and_limit(options=params)
461 471 if options[:offset].present?
462 472 offset = options[:offset].to_i
463 473 if offset < 0
464 474 offset = 0
465 475 end
466 476 end
467 477 limit = options[:limit].to_i
468 478 if limit < 1
469 479 limit = 25
470 480 elsif limit > 100
471 481 limit = 100
472 482 end
473 483 if offset.nil? && options[:page].present?
474 484 offset = (options[:page].to_i - 1) * limit
475 485 offset = 0 if offset < 0
476 486 end
477 487 offset ||= 0
478 488
479 489 [offset, limit]
480 490 end
481 491
482 492 # qvalues http header parser
483 493 # code taken from webrick
484 494 def parse_qvalues(value)
485 495 tmp = []
486 496 if value
487 497 parts = value.split(/,\s*/)
488 498 parts.each {|part|
489 499 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
490 500 val = m[1]
491 501 q = (m[2] or 1).to_f
492 502 tmp.push([val, q])
493 503 end
494 504 }
495 505 tmp = tmp.sort_by{|val, q| -q}
496 506 tmp.collect!{|val, q| val}
497 507 end
498 508 return tmp
499 509 rescue
500 510 nil
501 511 end
502 512
503 513 # Returns a string that can be used as filename value in Content-Disposition header
504 514 def filename_for_content_disposition(name)
505 515 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
506 516 end
507 517
508 518 def api_request?
509 519 %w(xml json).include? params[:format]
510 520 end
511 521
512 522 # Returns the API key present in the request
513 523 def api_key_from_request
514 524 if params[:key].present?
515 525 params[:key].to_s
516 526 elsif request.headers["X-Redmine-API-Key"].present?
517 527 request.headers["X-Redmine-API-Key"].to_s
518 528 end
519 529 end
520 530
521 531 # Returns the API 'switch user' value if present
522 532 def api_switch_user_from_request
523 533 request.headers["X-Redmine-Switch-User"].to_s.presence
524 534 end
525 535
526 536 # Renders a warning flash if obj has unsaved attachments
527 537 def render_attachment_warning_if_needed(obj)
528 538 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
529 539 end
530 540
531 541 # Sets the `flash` notice or error based the number of issues that did not save
532 542 #
533 543 # @param [Array, Issue] issues all of the saved and unsaved Issues
534 544 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
535 545 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
536 546 if unsaved_issue_ids.empty?
537 547 flash[:notice] = l(:notice_successful_update) unless issues.empty?
538 548 else
539 549 flash[:error] = l(:notice_failed_to_save_issues,
540 550 :count => unsaved_issue_ids.size,
541 551 :total => issues.size,
542 552 :ids => '#' + unsaved_issue_ids.join(', #'))
543 553 end
544 554 end
545 555
546 556 # Rescues an invalid query statement. Just in case...
547 557 def query_statement_invalid(exception)
548 558 logger.error "Query::StatementInvalid: #{exception.message}" if logger
549 559 session.delete(:query)
550 560 sort_clear if respond_to?(:sort_clear)
551 561 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
552 562 end
553 563
554 564 # Renders a 200 response for successfull updates or deletions via the API
555 565 def render_api_ok
556 566 render_api_head :ok
557 567 end
558 568
559 569 # Renders a head API response
560 570 def render_api_head(status)
561 571 # #head would return a response body with one space
562 572 render :text => '', :status => status, :layout => nil
563 573 end
564 574
565 575 # Renders API response on validation failure
566 576 def render_validation_errors(objects)
567 577 if objects.is_a?(Array)
568 578 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
569 579 else
570 580 @error_messages = objects.errors.full_messages
571 581 end
572 582 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
573 583 end
574 584
575 585 # Overrides #_include_layout? so that #render with no arguments
576 586 # doesn't use the layout for api requests
577 587 def _include_layout?(*args)
578 588 api_request? ? false : super
579 589 end
580 590 end
@@ -1,443 +1,431
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2012 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class IssuesController < ApplicationController
19 19 menu_item :new_issue, :only => [:new, :create]
20 20 default_search_scope :issues
21 21
22 22 before_filter :find_issue, :only => [:show, :edit, :update]
23 23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy]
24 24 before_filter :find_project, :only => [:new, :create]
25 25 before_filter :authorize, :except => [:index]
26 26 before_filter :find_optional_project, :only => [:index]
27 27 before_filter :check_for_default_issue_status, :only => [:new, :create]
28 28 before_filter :build_new_issue_from_params, :only => [:new, :create]
29 29 accept_rss_auth :index, :show
30 30 accept_api_auth :index, :show, :create, :update, :destroy
31 31
32 32 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
33 33
34 34 helper :journals
35 35 helper :projects
36 36 include ProjectsHelper
37 37 helper :custom_fields
38 38 include CustomFieldsHelper
39 39 helper :issue_relations
40 40 include IssueRelationsHelper
41 41 helper :watchers
42 42 include WatchersHelper
43 43 helper :attachments
44 44 include AttachmentsHelper
45 45 helper :queries
46 46 include QueriesHelper
47 47 helper :repositories
48 48 include RepositoriesHelper
49 49 helper :sort
50 50 include SortHelper
51 51 include IssuesHelper
52 52 helper :timelog
53 53 include Redmine::Export::PDF
54 54
55 55 def index
56 56 retrieve_query
57 57 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
58 58 sort_update(@query.sortable_columns)
59 59 @query.sort_criteria = sort_criteria.to_a
60 60
61 61 if @query.valid?
62 62 case params[:format]
63 63 when 'csv', 'pdf'
64 64 @limit = Setting.issues_export_limit.to_i
65 65 when 'atom'
66 66 @limit = Setting.feeds_limit.to_i
67 67 when 'xml', 'json'
68 68 @offset, @limit = api_offset_and_limit
69 69 else
70 70 @limit = per_page_option
71 71 end
72 72
73 73 @issue_count = @query.issue_count
74 74 @issue_pages = Paginator.new self, @issue_count, @limit, params['page']
75 75 @offset ||= @issue_pages.current.offset
76 76 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
77 77 :order => sort_clause,
78 78 :offset => @offset,
79 79 :limit => @limit)
80 80 @issue_count_by_group = @query.issue_count_by_group
81 81
82 82 respond_to do |format|
83 83 format.html { render :template => 'issues/index', :layout => !request.xhr? }
84 84 format.api {
85 85 Issue.load_visible_relations(@issues) if include_in_api_response?('relations')
86 86 }
87 87 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
88 88 format.csv { send_data(issues_to_csv(@issues, @project, @query, params), :type => 'text/csv; header=present', :filename => 'export.csv') }
89 89 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
90 90 end
91 91 else
92 92 respond_to do |format|
93 93 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
94 94 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
95 95 format.api { render_validation_errors(@query) }
96 96 end
97 97 end
98 98 rescue ActiveRecord::RecordNotFound
99 99 render_404
100 100 end
101 101
102 102 def show
103 103 @journals = @issue.journals.includes(:user, :details).reorder("#{Journal.table_name}.id ASC").all
104 104 @journals.each_with_index {|j,i| j.indice = i+1}
105 105 @journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
106 106 @journals.reverse! if User.current.wants_comments_in_reverse_order?
107 107
108 108 @changesets = @issue.changesets.visible.all
109 109 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
110 110
111 111 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
112 112 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
113 113 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
114 114 @priorities = IssuePriority.active
115 115 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
116 116 respond_to do |format|
117 117 format.html {
118 118 retrieve_previous_and_next_issue_ids
119 119 render :template => 'issues/show'
120 120 }
121 121 format.api
122 122 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
123 123 format.pdf {
124 124 pdf = issue_to_pdf(@issue, :journals => @journals)
125 125 send_data(pdf, :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf")
126 126 }
127 127 end
128 128 end
129 129
130 130 # Add a new issue
131 131 # The new issue will be created from an existing one if copy_from parameter is given
132 132 def new
133 133 respond_to do |format|
134 134 format.html { render :action => 'new', :layout => !request.xhr? }
135 135 format.js { render :partial => 'update_form' }
136 136 end
137 137 end
138 138
139 139 def create
140 140 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
141 141 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
142 142 if @issue.save
143 143 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
144 144 respond_to do |format|
145 145 format.html {
146 146 render_attachment_warning_if_needed(@issue)
147 147 flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("##{@issue.id}", issue_path(@issue), :title => @issue.subject))
148 148 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?} } :
149 149 { :action => 'show', :id => @issue })
150 150 }
151 151 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
152 152 end
153 153 return
154 154 else
155 155 respond_to do |format|
156 156 format.html { render :action => 'new' }
157 157 format.api { render_validation_errors(@issue) }
158 158 end
159 159 end
160 160 end
161 161
162 162 def edit
163 163 return unless update_issue_from_params
164 164
165 165 respond_to do |format|
166 166 format.html { }
167 167 format.xml { }
168 168 end
169 169 end
170 170
171 171 def update
172 172 return unless update_issue_from_params
173 173 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
174 174 saved = false
175 175 begin
176 176 saved = @issue.save_issue_with_child_records(params, @time_entry)
177 177 rescue ActiveRecord::StaleObjectError
178 178 @conflict = true
179 179 if params[:last_journal_id]
180 180 @conflict_journals = @issue.journals_after(params[:last_journal_id]).all
181 181 @conflict_journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
182 182 end
183 183 end
184 184
185 185 if saved
186 186 render_attachment_warning_if_needed(@issue)
187 187 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
188 188
189 189 respond_to do |format|
190 190 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
191 191 format.api { render_api_ok }
192 192 end
193 193 else
194 194 respond_to do |format|
195 195 format.html { render :action => 'edit' }
196 196 format.api { render_validation_errors(@issue) }
197 197 end
198 198 end
199 199 end
200 200
201 201 # Bulk edit/copy a set of issues
202 202 def bulk_edit
203 203 @issues.sort!
204 204 @copy = params[:copy].present?
205 205 @notes = params[:notes]
206 206
207 207 if User.current.allowed_to?(:move_issues, @projects)
208 208 @allowed_projects = Issue.allowed_target_projects_on_move
209 209 if params[:issue]
210 210 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id].to_s}
211 211 if @target_project
212 212 target_projects = [@target_project]
213 213 end
214 214 end
215 215 end
216 216 target_projects ||= @projects
217 217
218 218 if @copy
219 219 @available_statuses = [IssueStatus.default]
220 220 else
221 221 @available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
222 222 end
223 223 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields}.reduce(:&)
224 224 @assignables = target_projects.map(&:assignable_users).reduce(:&)
225 225 @trackers = target_projects.map(&:trackers).reduce(:&)
226 226 @versions = target_projects.map {|p| p.shared_versions.open}.reduce(:&)
227 227 @categories = target_projects.map {|p| p.issue_categories}.reduce(:&)
228 228 if @copy
229 229 @attachments_present = @issues.detect {|i| i.attachments.any?}.present?
230 230 @subtasks_present = @issues.detect {|i| !i.leaf?}.present?
231 231 end
232 232
233 233 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
234 234 render :layout => false if request.xhr?
235 235 end
236 236
237 237 def bulk_update
238 238 @issues.sort!
239 239 @copy = params[:copy].present?
240 240 attributes = parse_params_for_bulk_issue_attributes(params)
241 241
242 242 unsaved_issue_ids = []
243 243 moved_issues = []
244 244
245 245 if @copy && params[:copy_subtasks].present?
246 246 # Descendant issues will be copied with the parent task
247 247 # Don't copy them twice
248 248 @issues.reject! {|issue| @issues.detect {|other| issue.is_descendant_of?(other)}}
249 249 end
250 250
251 251 @issues.each do |issue|
252 252 issue.reload
253 253 if @copy
254 254 issue = issue.copy({},
255 255 :attachments => params[:copy_attachments].present?,
256 256 :subtasks => params[:copy_subtasks].present?
257 257 )
258 258 end
259 259 journal = issue.init_journal(User.current, params[:notes])
260 260 issue.safe_attributes = attributes
261 261 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
262 262 if issue.save
263 263 moved_issues << issue
264 264 else
265 265 # Keep unsaved issue ids to display them in flash error
266 266 unsaved_issue_ids << issue.id
267 267 end
268 268 end
269 269 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
270 270
271 271 if params[:follow]
272 272 if @issues.size == 1 && moved_issues.size == 1
273 273 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
274 274 elsif moved_issues.map(&:project).uniq.size == 1
275 275 redirect_to :controller => 'issues', :action => 'index', :project_id => moved_issues.map(&:project).first
276 276 end
277 277 else
278 278 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
279 279 end
280 280 end
281 281
282 282 def destroy
283 283 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
284 284 if @hours > 0
285 285 case params[:todo]
286 286 when 'destroy'
287 287 # nothing to do
288 288 when 'nullify'
289 289 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
290 290 when 'reassign'
291 291 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
292 292 if reassign_to.nil?
293 293 flash.now[:error] = l(:error_issue_not_found_in_project)
294 294 return
295 295 else
296 296 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
297 297 end
298 298 else
299 299 # display the destroy form if it's a user request
300 300 return unless api_request?
301 301 end
302 302 end
303 303 @issues.each do |issue|
304 304 begin
305 305 issue.reload.destroy
306 306 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
307 307 # nothing to do, issue was already deleted (eg. by a parent)
308 308 end
309 309 end
310 310 respond_to do |format|
311 311 format.html { redirect_back_or_default(:action => 'index', :project_id => @project) }
312 312 format.api { render_api_ok }
313 313 end
314 314 end
315 315
316 316 private
317 def find_issue
318 # Issue.visible.find(...) can not be used to redirect user to the login form
319 # if the issue actually exists but requires authentication
320 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
321 unless @issue.visible?
322 deny_access
323 return
324 end
325 @project = @issue.project
326 rescue ActiveRecord::RecordNotFound
327 render_404
328 end
329 317
330 318 def find_project
331 319 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
332 320 @project = Project.find(project_id)
333 321 rescue ActiveRecord::RecordNotFound
334 322 render_404
335 323 end
336 324
337 325 def retrieve_previous_and_next_issue_ids
338 326 retrieve_query_from_session
339 327 if @query
340 328 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
341 329 sort_update(@query.sortable_columns, 'issues_index_sort')
342 330 limit = 500
343 331 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
344 332 if (idx = issue_ids.index(@issue.id)) && idx < limit
345 333 if issue_ids.size < 500
346 334 @issue_position = idx + 1
347 335 @issue_count = issue_ids.size
348 336 end
349 337 @prev_issue_id = issue_ids[idx - 1] if idx > 0
350 338 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
351 339 end
352 340 end
353 341 end
354 342
355 343 # Used by #edit and #update to set some common instance variables
356 344 # from the params
357 345 # TODO: Refactor, not everything in here is needed by #edit
358 346 def update_issue_from_params
359 347 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
360 348 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
361 349 @time_entry.attributes = params[:time_entry]
362 350
363 351 @issue.init_journal(User.current)
364 352
365 353 issue_attributes = params[:issue]
366 354 if issue_attributes && params[:conflict_resolution]
367 355 case params[:conflict_resolution]
368 356 when 'overwrite'
369 357 issue_attributes = issue_attributes.dup
370 358 issue_attributes.delete(:lock_version)
371 359 when 'add_notes'
372 360 issue_attributes = issue_attributes.slice(:notes)
373 361 when 'cancel'
374 362 redirect_to issue_path(@issue)
375 363 return false
376 364 end
377 365 end
378 366 @issue.safe_attributes = issue_attributes
379 367 @priorities = IssuePriority.active
380 368 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
381 369 true
382 370 end
383 371
384 372 # TODO: Refactor, lots of extra code in here
385 373 # TODO: Changing tracker on an existing issue should not trigger this
386 374 def build_new_issue_from_params
387 375 if params[:id].blank?
388 376 @issue = Issue.new
389 377 if params[:copy_from]
390 378 begin
391 379 @copy_from = Issue.visible.find(params[:copy_from])
392 380 @copy_attachments = params[:copy_attachments].present? || request.get?
393 381 @copy_subtasks = params[:copy_subtasks].present? || request.get?
394 382 @issue.copy_from(@copy_from, :attachments => @copy_attachments, :subtasks => @copy_subtasks)
395 383 rescue ActiveRecord::RecordNotFound
396 384 render_404
397 385 return
398 386 end
399 387 end
400 388 @issue.project = @project
401 389 else
402 390 @issue = @project.issues.visible.find(params[:id])
403 391 end
404 392
405 393 @issue.project = @project
406 394 @issue.author ||= User.current
407 395 # Tracker must be set before custom field values
408 396 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
409 397 if @issue.tracker.nil?
410 398 render_error l(:error_no_tracker_in_project)
411 399 return false
412 400 end
413 401 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
414 402 @issue.safe_attributes = params[:issue]
415 403
416 404 @priorities = IssuePriority.active
417 405 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
418 406 @available_watchers = (@issue.project.users.sort + @issue.watcher_users).uniq
419 407 end
420 408
421 409 def check_for_default_issue_status
422 410 if IssueStatus.default.nil?
423 411 render_error l(:error_no_default_issue_status)
424 412 return false
425 413 end
426 414 end
427 415
428 416 def parse_params_for_bulk_issue_attributes(params)
429 417 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
430 418 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
431 419 if custom = attributes[:custom_field_values]
432 420 custom.reject! {|k,v| v.blank?}
433 421 custom.keys.each do |k|
434 422 if custom[k].is_a?(Array)
435 423 custom[k] << '' if custom[k].delete('__none__')
436 424 else
437 425 custom[k] = '' if custom[k] == '__none__'
438 426 end
439 427 end
440 428 end
441 429 attributes
442 430 end
443 431 end
@@ -1,113 +1,105
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2012 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class JournalsController < ApplicationController
19 19 before_filter :find_journal, :only => [:edit, :diff]
20 20 before_filter :find_issue, :only => [:new]
21 21 before_filter :find_optional_project, :only => [:index]
22 22 before_filter :authorize, :only => [:new, :edit, :diff]
23 23 accept_rss_auth :index
24 24 menu_item :issues
25 25
26 26 helper :issues
27 27 helper :custom_fields
28 28 helper :queries
29 29 include QueriesHelper
30 30 helper :sort
31 31 include SortHelper
32 32
33 33 def index
34 34 retrieve_query
35 35 sort_init 'id', 'desc'
36 36 sort_update(@query.sortable_columns)
37 37
38 38 if @query.valid?
39 39 @journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC",
40 40 :limit => 25)
41 41 end
42 42 @title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
43 43 render :layout => false, :content_type => 'application/atom+xml'
44 44 rescue ActiveRecord::RecordNotFound
45 45 render_404
46 46 end
47 47
48 48 def diff
49 49 @issue = @journal.issue
50 50 if params[:detail_id].present?
51 51 @detail = @journal.details.find_by_id(params[:detail_id])
52 52 else
53 53 @detail = @journal.details.detect {|d| d.prop_key == 'description'}
54 54 end
55 55 (render_404; return false) unless @issue && @detail
56 56 @diff = Redmine::Helpers::Diff.new(@detail.value, @detail.old_value)
57 57 end
58 58
59 59 def new
60 60 @journal = Journal.visible.find(params[:journal_id]) if params[:journal_id]
61 61 if @journal
62 62 user = @journal.user
63 63 text = @journal.notes
64 64 else
65 65 user = @issue.author
66 66 text = @issue.description
67 67 end
68 68 # Replaces pre blocks with [...]
69 69 text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
70 70 @content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n> "
71 71 @content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
72 72 rescue ActiveRecord::RecordNotFound
73 73 render_404
74 74 end
75 75
76 76 def edit
77 77 (render_403; return false) unless @journal.editable_by?(User.current)
78 78 if request.post?
79 79 @journal.update_attributes(:notes => params[:notes]) if params[:notes]
80 80 @journal.destroy if @journal.details.empty? && @journal.notes.blank?
81 81 call_hook(:controller_journals_edit_post, { :journal => @journal, :params => params})
82 82 respond_to do |format|
83 83 format.html { redirect_to :controller => 'issues', :action => 'show', :id => @journal.journalized_id }
84 84 format.js { render :action => 'update' }
85 85 end
86 86 else
87 87 respond_to do |format|
88 88 format.html {
89 89 # TODO: implement non-JS journal update
90 90 render :nothing => true
91 91 }
92 92 format.js
93 93 end
94 94 end
95 95 end
96 96
97 97 private
98 98
99 99 def find_journal
100 100 @journal = Journal.visible.find(params[:id])
101 101 @project = @journal.journalized.project
102 102 rescue ActiveRecord::RecordNotFound
103 103 render_404
104 104 end
105
106 # TODO: duplicated in IssuesController
107 def find_issue
108 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
109 @project = @issue.project
110 rescue ActiveRecord::RecordNotFound
111 render_404
112 end
113 105 end
General Comments 0
You need to be logged in to leave comments. Login now