annotate app/controllers/application_controller.rb @ 1517:dffacf8a6908 redmine-2.5

Update to Redmine SVN revision 13367 on 2.5-stable branch
author Chris Cannam
date Tue, 09 Sep 2014 09:29:00 +0100
parents b450a9d58aed
children a1bdbf8a87d5
rev   line source
Chris@441 1 # Redmine - project management software
Chris@1494 2 # Copyright (C) 2006-2014 Jean-Philippe Lang
Chris@0 3 #
Chris@0 4 # This program is free software; you can redistribute it and/or
Chris@0 5 # modify it under the terms of the GNU General Public License
Chris@0 6 # as published by the Free Software Foundation; either version 2
Chris@0 7 # of the License, or (at your option) any later version.
Chris@441 8 #
Chris@0 9 # This program is distributed in the hope that it will be useful,
Chris@0 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@0 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@0 12 # GNU General Public License for more details.
Chris@441 13 #
Chris@0 14 # You should have received a copy of the GNU General Public License
Chris@0 15 # along with this program; if not, write to the Free Software
Chris@0 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@0 17
Chris@0 18 require 'uri'
Chris@0 19 require 'cgi'
Chris@0 20
Chris@507 21 class Unauthorized < Exception; end
Chris@507 22
Chris@0 23 class ApplicationController < ActionController::Base
Chris@0 24 include Redmine::I18n
Chris@1464 25 include Redmine::Pagination
Chris@1464 26 include RoutesHelper
Chris@1464 27 helper :routes
Chris@0 28
Chris@1115 29 class_attribute :accept_api_auth_actions
Chris@1115 30 class_attribute :accept_rss_auth_actions
Chris@1115 31 class_attribute :model_object
Chris@1115 32
Chris@0 33 layout 'base'
Chris@441 34
Chris@909 35 protect_from_forgery
Chris@1464 36
Chris@1464 37 def verify_authenticity_token
Chris@1464 38 unless api_request?
Chris@1464 39 super
Chris@1464 40 end
Chris@909 41 end
Chris@441 42
Chris@1464 43 def handle_unverified_request
Chris@1464 44 unless api_request?
Chris@1464 45 super
Chris@1464 46 cookies.delete(autologin_cookie_name)
Chris@1516 47 self.logged_user = nil
Chris@1464 48 render_error :status => 422, :message => "Invalid form authenticity token."
Chris@1464 49 end
Chris@1464 50 end
Chris@441 51
Chris@1464 52 before_filter :session_expiration, :user_setup, :check_if_login_required, :check_password_change, :set_localization
Chris@1464 53
Chris@507 54 rescue_from ::Unauthorized, :with => :deny_access
Chris@1115 55 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
Chris@441 56
Chris@0 57 include Redmine::Search::Controller
Chris@0 58 include Redmine::MenuManager::MenuController
Chris@0 59 helper Redmine::MenuManager::MenuHelper
Chris@441 60
Chris@1115 61 def session_expiration
Chris@1115 62 if session[:user_id]
Chris@1115 63 if session_expired? && !try_to_autologin
Chris@1115 64 reset_session
Chris@1115 65 flash[:error] = l(:error_session_expired)
Chris@1115 66 redirect_to signin_url
Chris@1115 67 else
Chris@1115 68 session[:atime] = Time.now.utc.to_i
Chris@1115 69 end
Chris@1115 70 end
Chris@1115 71 end
Chris@1115 72
Chris@1115 73 def session_expired?
Chris@1115 74 if Setting.session_lifetime?
Chris@1115 75 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
Chris@1115 76 return true
Chris@1115 77 end
Chris@1115 78 end
Chris@1115 79 if Setting.session_timeout?
Chris@1115 80 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
Chris@1115 81 return true
Chris@1115 82 end
Chris@1115 83 end
Chris@1115 84 false
Chris@1115 85 end
Chris@1115 86
Chris@1115 87 def start_user_session(user)
Chris@1115 88 session[:user_id] = user.id
Chris@1115 89 session[:ctime] = Time.now.utc.to_i
Chris@1115 90 session[:atime] = Time.now.utc.to_i
Chris@1464 91 if user.must_change_password?
Chris@1464 92 session[:pwd] = '1'
Chris@1464 93 end
Chris@0 94 end
Chris@0 95
Chris@0 96 def user_setup
Chris@0 97 # Check the settings cache for each request
Chris@0 98 Setting.check_cache
Chris@0 99 # Find the current user
Chris@0 100 User.current = find_current_user
Chris@1115 101 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
Chris@0 102 end
Chris@441 103
Chris@0 104 # Returns the current user or nil if no user is logged in
Chris@0 105 # and starts a session if needed
Chris@0 106 def find_current_user
Chris@1115 107 user = nil
Chris@1115 108 unless api_request?
Chris@1115 109 if session[:user_id]
Chris@1115 110 # existing session
Chris@1115 111 user = (User.active.find(session[:user_id]) rescue nil)
Chris@1115 112 elsif autologin_user = try_to_autologin
Chris@1115 113 user = autologin_user
Chris@1115 114 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
Chris@1115 115 # RSS key authentication does not start a session
Chris@1115 116 user = User.find_by_rss_key(params[:key])
Chris@1115 117 end
Chris@1115 118 end
Chris@1115 119 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
Chris@507 120 if (key = api_key_from_request)
Chris@0 121 # Use API key
Chris@1115 122 user = User.find_by_api_key(key)
Chris@1517 123 elsif request.authorization.to_s =~ /\ABasic /i
Chris@0 124 # HTTP Basic, either username/password or API key/random
Chris@0 125 authenticate_with_http_basic do |username, password|
Chris@1115 126 user = User.try_to_login(username, password) || User.find_by_api_key(username)
Chris@0 127 end
Chris@1464 128 if user && user.must_change_password?
Chris@1464 129 render_error :message => 'You must change your password', :status => 403
Chris@1464 130 return
Chris@1464 131 end
Chris@0 132 end
Chris@1115 133 # Switch user if requested by an admin user
Chris@1115 134 if user && user.admin? && (username = api_switch_user_from_request)
Chris@1115 135 su = User.find_by_login(username)
Chris@1115 136 if su && su.active?
Chris@1115 137 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
Chris@1115 138 user = su
Chris@1115 139 else
Chris@1115 140 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
Chris@1115 141 end
Chris@1115 142 end
Chris@1115 143 end
Chris@1115 144 user
Chris@1115 145 end
Chris@1115 146
Chris@1464 147 def autologin_cookie_name
Chris@1464 148 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
Chris@1464 149 end
Chris@1464 150
Chris@1115 151 def try_to_autologin
Chris@1464 152 if cookies[autologin_cookie_name] && Setting.autologin?
Chris@1115 153 # auto-login feature starts a new session
Chris@1464 154 user = User.try_to_autologin(cookies[autologin_cookie_name])
Chris@1115 155 if user
Chris@1115 156 reset_session
Chris@1115 157 start_user_session(user)
Chris@1115 158 end
Chris@1115 159 user
Chris@0 160 end
Chris@0 161 end
Chris@0 162
Chris@0 163 # Sets the logged in user
Chris@0 164 def logged_user=(user)
Chris@0 165 reset_session
Chris@0 166 if user && user.is_a?(User)
Chris@0 167 User.current = user
Chris@1115 168 start_user_session(user)
Chris@0 169 else
Chris@0 170 User.current = User.anonymous
Chris@0 171 end
Chris@0 172 end
Chris@441 173
Chris@1115 174 # Logs out current user
Chris@1115 175 def logout_user
Chris@1115 176 if User.current.logged?
Chris@1464 177 cookies.delete(autologin_cookie_name)
Chris@1115 178 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
Chris@1115 179 self.logged_user = nil
Chris@1115 180 end
Chris@1115 181 end
Chris@1115 182
Chris@0 183 # check if login is globally required to access the application
Chris@0 184 def check_if_login_required
Chris@0 185 # no check needed if user is already logged in
Chris@0 186 return true if User.current.logged?
Chris@0 187 require_login if Setting.login_required?
Chris@441 188 end
Chris@441 189
Chris@1464 190 def check_password_change
Chris@1464 191 if session[:pwd]
Chris@1464 192 if User.current.must_change_password?
Chris@1464 193 redirect_to my_password_path
Chris@1464 194 else
Chris@1464 195 session.delete(:pwd)
Chris@1464 196 end
Chris@1464 197 end
Chris@1464 198 end
Chris@1464 199
Chris@0 200 def set_localization
Chris@0 201 lang = nil
Chris@0 202 if User.current.logged?
Chris@0 203 lang = find_language(User.current.language)
Chris@0 204 end
Chris@1517 205 if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
Chris@0 206 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
Chris@0 207 if !accept_lang.blank?
Chris@0 208 accept_lang = accept_lang.downcase
Chris@0 209 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
Chris@0 210 end
Chris@0 211 end
Chris@0 212 lang ||= Setting.default_language
Chris@0 213 set_language_if_valid(lang)
Chris@0 214 end
Chris@441 215
Chris@0 216 def require_login
Chris@0 217 if !User.current.logged?
Chris@0 218 # Extract only the basic url parameters on non-GET requests
Chris@0 219 if request.get?
Chris@0 220 url = url_for(params)
Chris@0 221 else
Chris@0 222 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
Chris@0 223 end
Chris@0 224 respond_to do |format|
Chris@1464 225 format.html {
Chris@1464 226 if request.xhr?
Chris@1464 227 head :unauthorized
Chris@1464 228 else
Chris@1464 229 redirect_to :controller => "account", :action => "login", :back_url => url
Chris@1464 230 end
Chris@1464 231 }
Chris@0 232 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
Chris@0 233 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
Chris@0 234 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
Chris@0 235 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
Chris@0 236 end
Chris@0 237 return false
Chris@0 238 end
Chris@0 239 true
Chris@0 240 end
Chris@0 241
Chris@0 242 def require_admin
Chris@0 243 return unless require_login
Chris@0 244 if !User.current.admin?
Chris@0 245 render_403
Chris@0 246 return false
Chris@0 247 end
Chris@0 248 true
Chris@0 249 end
Chris@441 250
Chris@0 251 def deny_access
Chris@0 252 User.current.logged? ? render_403 : require_login
Chris@0 253 end
Chris@0 254
Chris@0 255 # Authorize the user for the requested action
Chris@0 256 def authorize(ctrl = params[:controller], action = params[:action], global = false)
chris@37 257 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
chris@37 258 if allowed
chris@37 259 true
chris@37 260 else
chris@37 261 if @project && @project.archived?
chris@37 262 render_403 :message => :notice_not_authorized_archived_project
chris@37 263 else
chris@37 264 deny_access
chris@37 265 end
chris@37 266 end
Chris@0 267 end
Chris@0 268
Chris@0 269 # Authorize the user for the requested action outside a project
Chris@0 270 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
Chris@0 271 authorize(ctrl, action, global)
Chris@0 272 end
Chris@0 273
Chris@0 274 # Find project of id params[:id]
Chris@0 275 def find_project
Chris@0 276 @project = Project.find(params[:id])
Chris@0 277 rescue ActiveRecord::RecordNotFound
Chris@0 278 render_404
Chris@0 279 end
Chris@0 280
chris@22 281 # Find project of id params[:project_id]
chris@22 282 def find_project_by_project_id
chris@22 283 @project = Project.find(params[:project_id])
chris@22 284 rescue ActiveRecord::RecordNotFound
chris@22 285 render_404
chris@22 286 end
chris@22 287
Chris@0 288 # Find a project based on params[:project_id]
Chris@0 289 # TODO: some subclasses override this, see about merging their logic
Chris@0 290 def find_optional_project
Chris@0 291 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
Chris@0 292 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
Chris@0 293 allowed ? true : deny_access
Chris@0 294 rescue ActiveRecord::RecordNotFound
Chris@0 295 render_404
Chris@0 296 end
Chris@0 297
Chris@0 298 # Finds and sets @project based on @object.project
Chris@0 299 def find_project_from_association
Chris@0 300 render_404 unless @object.present?
Chris@441 301
Chris@0 302 @project = @object.project
Chris@0 303 end
Chris@0 304
Chris@0 305 def find_model_object
Chris@1115 306 model = self.class.model_object
Chris@0 307 if model
Chris@0 308 @object = model.find(params[:id])
Chris@0 309 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
Chris@0 310 end
Chris@0 311 rescue ActiveRecord::RecordNotFound
Chris@0 312 render_404
Chris@0 313 end
Chris@0 314
Chris@0 315 def self.model_object(model)
Chris@1115 316 self.model_object = model
Chris@0 317 end
Chris@14 318
Chris@1115 319 # Find the issue whose id is the :id parameter
Chris@1115 320 # Raises a Unauthorized exception if the issue is not visible
Chris@1115 321 def find_issue
Chris@1115 322 # Issue.visible.find(...) can not be used to redirect user to the login form
Chris@1115 323 # if the issue actually exists but requires authentication
Chris@1115 324 @issue = Issue.find(params[:id])
Chris@1115 325 raise Unauthorized unless @issue.visible?
Chris@1115 326 @project = @issue.project
Chris@1115 327 rescue ActiveRecord::RecordNotFound
Chris@1115 328 render_404
Chris@1115 329 end
Chris@1115 330
Chris@1115 331 # Find issues with a single :id param or :ids array param
Chris@1115 332 # Raises a Unauthorized exception if one of the issues is not visible
Chris@14 333 def find_issues
Chris@1464 334 @issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
Chris@14 335 raise ActiveRecord::RecordNotFound if @issues.empty?
Chris@1115 336 raise Unauthorized unless @issues.all?(&:visible?)
chris@37 337 @projects = @issues.collect(&:project).compact.uniq
chris@37 338 @project = @projects.first if @projects.size == 1
chris@37 339 rescue ActiveRecord::RecordNotFound
chris@37 340 render_404
chris@37 341 end
Chris@441 342
Chris@1464 343 def find_attachments
Chris@1464 344 if (attachments = params[:attachments]).present?
Chris@1464 345 att = attachments.values.collect do |attachment|
Chris@1464 346 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
Chris@1464 347 end
Chris@1464 348 att.compact!
Chris@1464 349 end
Chris@1464 350 @attachments = att || []
Chris@1464 351 end
Chris@1464 352
Chris@0 353 # make sure that the user is a member of the project (or admin) if project is private
Chris@0 354 # used as a before_filter for actions that do not require any particular permission on the project
Chris@0 355 def check_project_privacy
Chris@1115 356 if @project && !@project.archived?
Chris@1115 357 if @project.visible?
Chris@0 358 true
Chris@0 359 else
Chris@909 360 deny_access
Chris@0 361 end
Chris@0 362 else
Chris@0 363 @project = nil
Chris@0 364 render_404
Chris@0 365 false
Chris@0 366 end
Chris@0 367 end
Chris@0 368
Chris@14 369 def back_url
Chris@1115 370 url = params[:back_url]
Chris@1115 371 if url.nil? && referer = request.env['HTTP_REFERER']
Chris@1115 372 url = CGI.unescape(referer.to_s)
Chris@1115 373 end
Chris@1115 374 url
Chris@14 375 end
Chris@14 376
Chris@1517 377 def redirect_back_or_default(default, options={})
Chris@1115 378 back_url = params[:back_url].to_s
Chris@1516 379 if back_url.present? && valid_back_url?(back_url)
Chris@1516 380 redirect_to(back_url)
Chris@1516 381 return
Chris@1517 382 elsif options[:referer]
Chris@1517 383 redirect_to_referer_or default
Chris@1517 384 return
Chris@0 385 end
Chris@0 386 redirect_to default
Chris@441 387 false
Chris@0 388 end
Chris@441 389
Chris@1516 390 # Returns true if back_url is a valid url for redirection, otherwise false
Chris@1516 391 def valid_back_url?(back_url)
Chris@1516 392 if CGI.unescape(back_url).include?('..')
Chris@1516 393 return false
Chris@1516 394 end
Chris@1516 395
Chris@1516 396 begin
Chris@1516 397 uri = URI.parse(back_url)
Chris@1516 398 rescue URI::InvalidURIError
Chris@1516 399 return false
Chris@1516 400 end
Chris@1516 401
Chris@1516 402 if uri.host.present? && uri.host != request.host
Chris@1516 403 return false
Chris@1516 404 end
Chris@1516 405
Chris@1516 406 if uri.path.match(%r{/(login|account/register)})
Chris@1516 407 return false
Chris@1516 408 end
Chris@1516 409
Chris@1516 410 if relative_url_root.present? && !uri.path.starts_with?(relative_url_root)
Chris@1516 411 return false
Chris@1516 412 end
Chris@1516 413
Chris@1516 414 return true
Chris@1516 415 end
Chris@1516 416 private :valid_back_url?
Chris@1516 417
Chris@1115 418 # Redirects to the request referer if present, redirects to args or call block otherwise.
Chris@1115 419 def redirect_to_referer_or(*args, &block)
Chris@1115 420 redirect_to :back
Chris@1115 421 rescue ::ActionController::RedirectBackError
Chris@1115 422 if args.any?
Chris@1115 423 redirect_to *args
Chris@1115 424 elsif block_given?
Chris@1115 425 block.call
Chris@1115 426 else
Chris@1115 427 raise "#redirect_to_referer_or takes arguments or a block"
Chris@1115 428 end
Chris@1115 429 end
Chris@1115 430
chris@37 431 def render_403(options={})
Chris@0 432 @project = nil
chris@37 433 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
Chris@0 434 return false
Chris@0 435 end
Chris@441 436
chris@37 437 def render_404(options={})
chris@37 438 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
Chris@0 439 return false
Chris@0 440 end
Chris@441 441
chris@37 442 # Renders an error response
chris@37 443 def render_error(arg)
chris@37 444 arg = {:message => arg} unless arg.is_a?(Hash)
Chris@441 445
chris@37 446 @message = arg[:message]
chris@37 447 @message = l(@message) if @message.is_a?(Symbol)
chris@37 448 @status = arg[:status] || 500
Chris@441 449
Chris@0 450 respond_to do |format|
chris@37 451 format.html {
chris@37 452 render :template => 'common/error', :layout => use_layout, :status => @status
Chris@0 453 }
Chris@1115 454 format.any { head @status }
Chris@0 455 end
Chris@0 456 end
Chris@1115 457
Chris@1115 458 # Handler for ActionView::MissingTemplate exception
Chris@1115 459 def missing_template
Chris@1115 460 logger.warn "Missing template, responding with 404"
Chris@1115 461 @project = nil
Chris@1115 462 render_404
Chris@1115 463 end
Chris@1115 464
Chris@909 465 # Filter for actions that provide an API response
Chris@909 466 # but have no HTML representation for non admin users
Chris@909 467 def require_admin_or_api_request
Chris@909 468 return true if api_request?
Chris@909 469 if User.current.admin?
Chris@909 470 true
Chris@909 471 elsif User.current.logged?
Chris@909 472 render_error(:status => 406)
Chris@909 473 else
Chris@909 474 deny_access
Chris@909 475 end
Chris@909 476 end
Chris@14 477
Chris@14 478 # Picks which layout to use based on the request
Chris@14 479 #
Chris@14 480 # @return [boolean, string] name of the layout to use or false for no layout
Chris@14 481 def use_layout
Chris@14 482 request.xhr? ? false : 'base'
Chris@14 483 end
Chris@441 484
Chris@441 485 def render_feed(items, options={})
Chris@0 486 @items = items || []
Chris@0 487 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
Chris@0 488 @items = @items.slice(0, Setting.feeds_limit.to_i)
Chris@0 489 @title = options[:title] || Setting.app_title
Chris@1115 490 render :template => "common/feed", :formats => [:atom], :layout => false,
Chris@909 491 :content_type => 'application/atom+xml'
Chris@0 492 end
Chris@909 493
Chris@507 494 def self.accept_rss_auth(*actions)
Chris@507 495 if actions.any?
Chris@1115 496 self.accept_rss_auth_actions = actions
Chris@507 497 else
Chris@1115 498 self.accept_rss_auth_actions || []
Chris@507 499 end
Chris@507 500 end
Chris@909 501
Chris@507 502 def accept_rss_auth?(action=action_name)
Chris@507 503 self.class.accept_rss_auth.include?(action.to_sym)
Chris@507 504 end
Chris@909 505
Chris@507 506 def self.accept_api_auth(*actions)
Chris@507 507 if actions.any?
Chris@1115 508 self.accept_api_auth_actions = actions
Chris@507 509 else
Chris@1115 510 self.accept_api_auth_actions || []
Chris@507 511 end
Chris@507 512 end
Chris@909 513
Chris@507 514 def accept_api_auth?(action=action_name)
Chris@507 515 self.class.accept_api_auth.include?(action.to_sym)
Chris@0 516 end
Chris@441 517
Chris@0 518 # Returns the number of objects that should be displayed
Chris@0 519 # on the paginated list
Chris@0 520 def per_page_option
Chris@0 521 per_page = nil
Chris@0 522 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
Chris@0 523 per_page = params[:per_page].to_s.to_i
Chris@0 524 session[:per_page] = per_page
Chris@0 525 elsif session[:per_page]
Chris@0 526 per_page = session[:per_page]
Chris@0 527 else
Chris@0 528 per_page = Setting.per_page_options_array.first || 25
Chris@0 529 end
Chris@0 530 per_page
Chris@0 531 end
Chris@0 532
Chris@119 533 # Returns offset and limit used to retrieve objects
Chris@119 534 # for an API response based on offset, limit and page parameters
Chris@119 535 def api_offset_and_limit(options=params)
Chris@119 536 if options[:offset].present?
Chris@119 537 offset = options[:offset].to_i
Chris@119 538 if offset < 0
Chris@119 539 offset = 0
Chris@119 540 end
Chris@119 541 end
Chris@119 542 limit = options[:limit].to_i
Chris@119 543 if limit < 1
Chris@119 544 limit = 25
Chris@119 545 elsif limit > 100
Chris@119 546 limit = 100
Chris@119 547 end
Chris@119 548 if offset.nil? && options[:page].present?
Chris@119 549 offset = (options[:page].to_i - 1) * limit
Chris@119 550 offset = 0 if offset < 0
Chris@119 551 end
Chris@119 552 offset ||= 0
Chris@441 553
Chris@119 554 [offset, limit]
Chris@119 555 end
Chris@441 556
Chris@0 557 # qvalues http header parser
Chris@0 558 # code taken from webrick
Chris@0 559 def parse_qvalues(value)
Chris@0 560 tmp = []
Chris@0 561 if value
Chris@0 562 parts = value.split(/,\s*/)
Chris@0 563 parts.each {|part|
Chris@0 564 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
Chris@0 565 val = m[1]
Chris@0 566 q = (m[2] or 1).to_f
Chris@0 567 tmp.push([val, q])
Chris@0 568 end
Chris@0 569 }
Chris@0 570 tmp = tmp.sort_by{|val, q| -q}
Chris@0 571 tmp.collect!{|val, q| val}
Chris@0 572 end
Chris@0 573 return tmp
Chris@0 574 rescue
Chris@0 575 nil
Chris@0 576 end
Chris@441 577
Chris@0 578 # Returns a string that can be used as filename value in Content-Disposition header
Chris@0 579 def filename_for_content_disposition(name)
Chris@1516 580 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
Chris@0 581 end
Chris@441 582
Chris@0 583 def api_request?
Chris@0 584 %w(xml json).include? params[:format]
Chris@0 585 end
Chris@441 586
Chris@119 587 # Returns the API key present in the request
Chris@119 588 def api_key_from_request
Chris@119 589 if params[:key].present?
Chris@1115 590 params[:key].to_s
Chris@119 591 elsif request.headers["X-Redmine-API-Key"].present?
Chris@1115 592 request.headers["X-Redmine-API-Key"].to_s
Chris@119 593 end
Chris@119 594 end
Chris@0 595
Chris@1115 596 # Returns the API 'switch user' value if present
Chris@1115 597 def api_switch_user_from_request
Chris@1115 598 request.headers["X-Redmine-Switch-User"].to_s.presence
Chris@1115 599 end
Chris@1115 600
Chris@0 601 # Renders a warning flash if obj has unsaved attachments
Chris@0 602 def render_attachment_warning_if_needed(obj)
Chris@0 603 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
Chris@0 604 end
Chris@0 605
Chris@0 606 # Rescues an invalid query statement. Just in case...
Chris@0 607 def query_statement_invalid(exception)
Chris@0 608 logger.error "Query::StatementInvalid: #{exception.message}" if logger
Chris@0 609 session.delete(:query)
Chris@0 610 sort_clear if respond_to?(:sort_clear)
Chris@0 611 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
Chris@0 612 end
Chris@0 613
Chris@1115 614 # Renders a 200 response for successfull updates or deletions via the API
Chris@1115 615 def render_api_ok
Chris@1115 616 render_api_head :ok
Chris@119 617 end
Chris@441 618
Chris@1115 619 # Renders a head API response
Chris@1115 620 def render_api_head(status)
Chris@1115 621 # #head would return a response body with one space
Chris@1115 622 render :text => '', :status => status, :layout => nil
Chris@119 623 end
Chris@441 624
Chris@1115 625 # Renders API response on validation failure
Chris@1115 626 def render_validation_errors(objects)
Chris@1115 627 if objects.is_a?(Array)
Chris@1115 628 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
Chris@1115 629 else
Chris@1115 630 @error_messages = objects.errors.full_messages
Chris@1115 631 end
Chris@1115 632 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
Chris@1115 633 end
Chris@1115 634
Chris@1115 635 # Overrides #_include_layout? so that #render with no arguments
Chris@119 636 # doesn't use the layout for api requests
Chris@1115 637 def _include_layout?(*args)
Chris@1115 638 api_request? ? false : super
Chris@119 639 end
Chris@0 640 end