annotate .svn/pristine/9f/9f81d7ae18ecd7486949ec6aa773ac587ff1d491.svn-base @ 1464:261b3d9a4903 redmine-2.4

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