annotate app/controllers/application_controller.rb @ 1519:afce8026aaeb redmine-2.4-integration

Merge from branch "live"
author Chris Cannam
date Tue, 09 Sep 2014 09:34:53 +0100
parents 2e8063097240
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@0 123 else
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@0 205 if lang.nil? && 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@743 278 User.current.logged? ? render_404 : require_login
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@743 285 User.current.logged? ? render_404 : require_login
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@0 377 def redirect_back_or_default(default)
Chris@1115 378 back_url = params[:back_url].to_s
Chris@1516 379 if back_url.present? && valid_back_url?(back_url)
chris@365 380 # soundsoftware: if back_url is the home page,
chris@365 381 # change it to My Page (#125)
chris@365 382 if (uri.path == home_path)
chris@474 383 if (uri.path =~ /\/$/)
chris@474 384 uri.path = uri.path + "my"
chris@474 385 else
chris@474 386 uri.path = uri.path + "/my"
chris@474 387 end
chris@365 388 end
chris@237 389 # soundsoftware: if login page is https but back_url http,
chris@237 390 # switch back_url to https to ensure cookie validity (#83)
chris@237 391 if (uri.scheme == "http") && (URI.parse(request.url).scheme == "https")
chris@237 392 uri.scheme = "https"
chris@237 393 end
chris@365 394 back_url = uri.to_s
Chris@1516 395 redirect_to(back_url)
Chris@1516 396 return
Chris@0 397 end
Chris@0 398 redirect_to default
Chris@441 399 false
Chris@0 400 end
Chris@441 401
Chris@1516 402 # Returns true if back_url is a valid url for redirection, otherwise false
Chris@1516 403 def valid_back_url?(back_url)
Chris@1516 404 if CGI.unescape(back_url).include?('..')
Chris@1516 405 return false
Chris@1516 406 end
Chris@1516 407
Chris@1516 408 begin
Chris@1516 409 uri = URI.parse(back_url)
Chris@1516 410 rescue URI::InvalidURIError
Chris@1516 411 return false
Chris@1516 412 end
Chris@1516 413
Chris@1516 414 if uri.host.present? && uri.host != request.host
Chris@1516 415 return false
Chris@1516 416 end
Chris@1516 417
Chris@1516 418 if uri.path.match(%r{/(login|account/register)})
Chris@1516 419 return false
Chris@1516 420 end
Chris@1516 421
Chris@1516 422 if relative_url_root.present? && !uri.path.starts_with?(relative_url_root)
Chris@1516 423 return false
Chris@1516 424 end
Chris@1516 425
Chris@1516 426 return true
Chris@1516 427 end
Chris@1516 428 private :valid_back_url?
Chris@1516 429
Chris@1115 430 # Redirects to the request referer if present, redirects to args or call block otherwise.
Chris@1115 431 def redirect_to_referer_or(*args, &block)
Chris@1115 432 redirect_to :back
Chris@1115 433 rescue ::ActionController::RedirectBackError
Chris@1115 434 if args.any?
Chris@1115 435 redirect_to *args
Chris@1115 436 elsif block_given?
Chris@1115 437 block.call
Chris@1115 438 else
Chris@1115 439 raise "#redirect_to_referer_or takes arguments or a block"
Chris@1115 440 end
Chris@1115 441 end
Chris@1115 442
chris@37 443 def render_403(options={})
Chris@0 444 @project = nil
chris@37 445 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
Chris@0 446 return false
Chris@0 447 end
Chris@441 448
chris@37 449 def render_404(options={})
chris@37 450 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
Chris@0 451 return false
Chris@0 452 end
Chris@441 453
chris@37 454 # Renders an error response
chris@37 455 def render_error(arg)
chris@37 456 arg = {:message => arg} unless arg.is_a?(Hash)
Chris@441 457
chris@37 458 @message = arg[:message]
chris@37 459 @message = l(@message) if @message.is_a?(Symbol)
chris@37 460 @status = arg[:status] || 500
Chris@441 461
Chris@0 462 respond_to do |format|
chris@37 463 format.html {
chris@37 464 render :template => 'common/error', :layout => use_layout, :status => @status
Chris@0 465 }
Chris@1115 466 format.any { head @status }
Chris@0 467 end
Chris@0 468 end
Chris@1115 469
Chris@1115 470 # Handler for ActionView::MissingTemplate exception
Chris@1115 471 def missing_template
Chris@1115 472 logger.warn "Missing template, responding with 404"
Chris@1115 473 @project = nil
Chris@1115 474 render_404
Chris@1115 475 end
Chris@1115 476
Chris@909 477 # Filter for actions that provide an API response
Chris@909 478 # but have no HTML representation for non admin users
Chris@909 479 def require_admin_or_api_request
Chris@909 480 return true if api_request?
Chris@909 481 if User.current.admin?
Chris@909 482 true
Chris@909 483 elsif User.current.logged?
Chris@909 484 render_error(:status => 406)
Chris@909 485 else
Chris@909 486 deny_access
Chris@909 487 end
Chris@909 488 end
Chris@14 489
Chris@14 490 # Picks which layout to use based on the request
Chris@14 491 #
Chris@14 492 # @return [boolean, string] name of the layout to use or false for no layout
Chris@14 493 def use_layout
Chris@14 494 request.xhr? ? false : 'base'
Chris@14 495 end
Chris@441 496
Chris@441 497 def render_feed(items, options={})
Chris@0 498 @items = items || []
Chris@0 499 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
Chris@0 500 @items = @items.slice(0, Setting.feeds_limit.to_i)
Chris@0 501 @title = options[:title] || Setting.app_title
Chris@1115 502 render :template => "common/feed", :formats => [:atom], :layout => false,
Chris@909 503 :content_type => 'application/atom+xml'
Chris@0 504 end
Chris@909 505
Chris@507 506 def self.accept_rss_auth(*actions)
Chris@507 507 if actions.any?
Chris@1115 508 self.accept_rss_auth_actions = actions
Chris@507 509 else
Chris@1115 510 self.accept_rss_auth_actions || []
Chris@507 511 end
Chris@507 512 end
Chris@909 513
Chris@507 514 def accept_rss_auth?(action=action_name)
Chris@507 515 self.class.accept_rss_auth.include?(action.to_sym)
Chris@507 516 end
Chris@909 517
Chris@507 518 def self.accept_api_auth(*actions)
Chris@507 519 if actions.any?
Chris@1115 520 self.accept_api_auth_actions = actions
Chris@507 521 else
Chris@1115 522 self.accept_api_auth_actions || []
Chris@507 523 end
Chris@507 524 end
Chris@909 525
Chris@507 526 def accept_api_auth?(action=action_name)
Chris@507 527 self.class.accept_api_auth.include?(action.to_sym)
Chris@0 528 end
Chris@441 529
Chris@0 530 # Returns the number of objects that should be displayed
Chris@0 531 # on the paginated list
Chris@0 532 def per_page_option
Chris@0 533 per_page = nil
Chris@0 534 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
Chris@0 535 per_page = params[:per_page].to_s.to_i
Chris@0 536 session[:per_page] = per_page
Chris@0 537 elsif session[:per_page]
Chris@0 538 per_page = session[:per_page]
Chris@0 539 else
Chris@0 540 per_page = Setting.per_page_options_array.first || 25
Chris@0 541 end
Chris@0 542 per_page
Chris@0 543 end
Chris@0 544
Chris@117 545 # Returns offset and limit used to retrieve objects
Chris@117 546 # for an API response based on offset, limit and page parameters
Chris@117 547 def api_offset_and_limit(options=params)
Chris@117 548 if options[:offset].present?
Chris@117 549 offset = options[:offset].to_i
Chris@117 550 if offset < 0
Chris@117 551 offset = 0
Chris@117 552 end
Chris@117 553 end
Chris@117 554 limit = options[:limit].to_i
Chris@117 555 if limit < 1
Chris@117 556 limit = 25
Chris@117 557 elsif limit > 100
Chris@117 558 limit = 100
Chris@117 559 end
Chris@117 560 if offset.nil? && options[:page].present?
Chris@117 561 offset = (options[:page].to_i - 1) * limit
Chris@117 562 offset = 0 if offset < 0
Chris@117 563 end
Chris@117 564 offset ||= 0
Chris@441 565
Chris@117 566 [offset, limit]
Chris@117 567 end
Chris@441 568
Chris@0 569 # qvalues http header parser
Chris@0 570 # code taken from webrick
Chris@0 571 def parse_qvalues(value)
Chris@0 572 tmp = []
Chris@0 573 if value
Chris@0 574 parts = value.split(/,\s*/)
Chris@0 575 parts.each {|part|
Chris@0 576 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
Chris@0 577 val = m[1]
Chris@0 578 q = (m[2] or 1).to_f
Chris@0 579 tmp.push([val, q])
Chris@0 580 end
Chris@0 581 }
Chris@0 582 tmp = tmp.sort_by{|val, q| -q}
Chris@0 583 tmp.collect!{|val, q| val}
Chris@0 584 end
Chris@0 585 return tmp
Chris@0 586 rescue
Chris@0 587 nil
Chris@0 588 end
Chris@441 589
Chris@0 590 # Returns a string that can be used as filename value in Content-Disposition header
Chris@0 591 def filename_for_content_disposition(name)
Chris@1516 592 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
Chris@0 593 end
Chris@441 594
Chris@0 595 def api_request?
Chris@0 596 %w(xml json).include? params[:format]
Chris@0 597 end
Chris@441 598
Chris@117 599 # Returns the API key present in the request
Chris@117 600 def api_key_from_request
Chris@117 601 if params[:key].present?
Chris@1115 602 params[:key].to_s
Chris@117 603 elsif request.headers["X-Redmine-API-Key"].present?
Chris@1115 604 request.headers["X-Redmine-API-Key"].to_s
Chris@117 605 end
Chris@117 606 end
Chris@0 607
Chris@1115 608 # Returns the API 'switch user' value if present
Chris@1115 609 def api_switch_user_from_request
Chris@1115 610 request.headers["X-Redmine-Switch-User"].to_s.presence
Chris@1115 611 end
Chris@1115 612
Chris@0 613 # Renders a warning flash if obj has unsaved attachments
Chris@0 614 def render_attachment_warning_if_needed(obj)
Chris@0 615 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
Chris@0 616 end
Chris@0 617
Chris@0 618 # Rescues an invalid query statement. Just in case...
Chris@0 619 def query_statement_invalid(exception)
Chris@0 620 logger.error "Query::StatementInvalid: #{exception.message}" if logger
Chris@0 621 session.delete(:query)
Chris@0 622 sort_clear if respond_to?(:sort_clear)
Chris@0 623 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
Chris@0 624 end
Chris@0 625
Chris@1115 626 # Renders a 200 response for successfull updates or deletions via the API
Chris@1115 627 def render_api_ok
Chris@1115 628 render_api_head :ok
Chris@117 629 end
Chris@441 630
Chris@1115 631 # Renders a head API response
Chris@1115 632 def render_api_head(status)
Chris@1115 633 # #head would return a response body with one space
Chris@1115 634 render :text => '', :status => status, :layout => nil
Chris@117 635 end
Chris@441 636
Chris@1115 637 # Renders API response on validation failure
Chris@1115 638 def render_validation_errors(objects)
Chris@1115 639 if objects.is_a?(Array)
Chris@1115 640 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
Chris@1115 641 else
Chris@1115 642 @error_messages = objects.errors.full_messages
Chris@1115 643 end
Chris@1115 644 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
Chris@1115 645 end
Chris@1115 646
Chris@1115 647 # Overrides #_include_layout? so that #render with no arguments
Chris@117 648 # doesn't use the layout for api requests
Chris@1115 649 def _include_layout?(*args)
Chris@1115 650 api_request? ? false : super
Chris@117 651 end
Chris@0 652 end