annotate .svn/pristine/e2/e2663416e08530744c35899c831ba16745bb5a80.svn-base @ 1519:afce8026aaeb redmine-2.4-integration

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