annotate .svn/pristine/c5/c58c8e6ce884b34a42a4036c1723c49ce867318b.svn-base @ 1628:9c5f8e24dadc live tip

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