Project

General



Profile

« Previous | Next » 

Revision 15902

tagged version 3.1.7

View differences:

tags/3.1.7/.gitignore
1
/.project
2
/.loadpath
3
/.powrc
4
/.rvmrc
5
/config/additional_environment.rb
6
/config/configuration.yml
7
/config/database.yml
8
/config/email.yml
9
/config/secrets.yml
10
/config/initializers/session_store.rb
11
/config/initializers/secret_token.rb
12
/coverage
13
/db/*.db
14
/db/*.sqlite3
15
/db/schema.rb
16
/files/*
17
/lib/redmine/scm/adapters/mercurial/redminehelper.pyc
18
/lib/redmine/scm/adapters/mercurial/redminehelper.pyo
19
/log/*.log*
20
/log/mongrel_debug
21
/plugins/*
22
!/plugins/README
23
/public/dispatch.*
24
/public/plugin_assets/*
25
/public/themes/*
26
!/public/themes/alternate
27
!/public/themes/classic
28
!/public/themes/README
29
/tmp/*
30
/tmp/cache/*
31
/tmp/pdf/*
32
/tmp/sessions/*
33
/tmp/sockets/*
34
/tmp/test/*
35
/tmp/thumbnails/*
36
/vendor/cache
37
*.rbc
38

  
39
/.bundle
40
/Gemfile.lock
41
/Gemfile.local
42

  
tags/3.1.7/.hgignore
1
syntax: glob
2

  
3
.project
4
.loadpath
5
.powrc
6
.rvmrc
7
config/additional_environment.rb
8
config/configuration.yml
9
config/database.yml
10
config/email.yml
11
config/secrets.yml
12
config/initializers/session_store.rb
13
config/initializers/secret_token.rb
14
coverage
15
db/*.db
16
db/*.sqlite3
17
db/schema.rb
18
files/*
19
lib/redmine/scm/adapters/mercurial/redminehelper.pyc
20
lib/redmine/scm/adapters/mercurial/redminehelper.pyo
21
log/*.log*
22
log/mongrel_debug
23
public/dispatch.*
24
public/plugin_assets/*
25
tmp/*
26
tmp/cache/*
27
tmp/pdf/*
28
tmp/sessions/*
29
tmp/sockets/*
30
tmp/test/*
31
tmp/thumbnails/*
32
vendor/cache
33
*.rbc
34

  
35
.svn/
36
.git/
37

  
38
.bundle
39
Gemfile.lock
40
Gemfile.local
41

  
tags/3.1.7/CONTRIBUTING.md
1

  
2
**Do not send a pull request to this GitHub repository**.
3

  
4
For more detail, please see [official website] wiki [Contribute].
5

  
6
[official website]: http://www.redmine.org
7
[Contribute]: http://www.redmine.org/projects/redmine/wiki/Contribute
8

  
0 9

  
tags/3.1.7/Gemfile
1
source 'https://rubygems.org'
2

  
3
if Gem::Version.new(Bundler::VERSION) < Gem::Version.new('1.5.0')
4
  abort "Redmine requires Bundler 1.5.0 or higher (you're using #{Bundler::VERSION}).\nPlease update with 'gem update bundler'."
5
end
6

  
7
gem "rails", "4.2.7.1"
8
gem "jquery-rails", "~> 3.1.4"
9
gem "coderay", "~> 1.1.0"
10
gem "builder", ">= 3.0.4"
11
gem "request_store", "1.0.5"
12
gem "mime-types", (RUBY_VERSION >= "2.0" ? "~> 3.0" : "~> 2.99")
13
gem "protected_attributes"
14
gem "actionpack-action_caching"
15
gem "actionpack-xml_parser"
16
gem "loofah", "~> 2.0"
17
gem "mimemagic"
18

  
19
# Request at least nokogiri 1.6.7.2 because of security advisories
20
gem "nokogiri", ">= 1.6.7.2"
21

  
22
# Request at least rails-html-sanitizer 1.0.3 because of security advisories 
23
gem "rails-html-sanitizer", ">= 1.0.3"
24

  
25
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
26
gem 'tzinfo-data', platforms: [:mingw, :x64_mingw, :mswin, :jruby]
27
gem "rbpdf", "~> 1.18.7"
28

  
29
# Optional gem for LDAP authentication
30
group :ldap do
31
  gem "net-ldap", "~> 0.3.1"
32
end
33

  
34
# Optional gem for OpenID authentication
35
group :openid do
36
  gem "ruby-openid", "~> 2.3.0", :require => "openid"
37
  gem "rack-openid"
38
end
39

  
40
platforms :mri, :mingw, :x64_mingw do
41
  # Optional gem for exporting the gantt to a PNG file, not supported with jruby
42
  group :rmagick do
43
    gem "rmagick", ">= 2.14.0"
44
  end
45

  
46
  # Optional Markdown support, not for JRuby
47
  group :markdown do
48
    gem "redcarpet", "~> 3.3.2"
49
  end
50
end
51

  
52
platforms :jruby do
53
  # jruby-openssl is bundled with JRuby 1.7.0
54
  gem "jruby-openssl" if Object.const_defined?(:JRUBY_VERSION) && JRUBY_VERSION < '1.7.0'
55
  gem "activerecord-jdbc-adapter", "~> 1.3.2"
56
end
57

  
58
# Include database gems for the adapters found in the database
59
# configuration file
60
require 'erb'
61
require 'yaml'
62
database_file = File.join(File.dirname(__FILE__), "config/database.yml")
63
if File.exist?(database_file)
64
  database_config = YAML::load(ERB.new(IO.read(database_file)).result)
65
  adapters = database_config.values.map {|c| c['adapter']}.compact.uniq
66
  if adapters.any?
67
    adapters.each do |adapter|
68
      case adapter
69
      when 'mysql2'
70
        gem "mysql2", "~> 0.3.11", :platforms => [:mri, :mingw, :x64_mingw]
71
        gem "activerecord-jdbcmysql-adapter", :platforms => :jruby
72
      when 'mysql'
73
        gem "activerecord-jdbcmysql-adapter", :platforms => :jruby
74
      when /postgresql/
75
        gem "pg", "~> 0.18.1", :platforms => [:mri, :mingw, :x64_mingw]
76
        gem "activerecord-jdbcpostgresql-adapter", :platforms => :jruby
77
      when /sqlite3/
78
        gem "sqlite3", :platforms => [:mri, :mingw, :x64_mingw]
79
        gem "jdbc-sqlite3", ">= 3.8.10.1", :platforms => :jruby
80
        gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
81
      when /sqlserver/
82
        gem "tiny_tds", "~> 0.6.2", :platforms => [:mri, :mingw, :x64_mingw]
83
        gem "activerecord-sqlserver-adapter", :platforms => [:mri, :mingw, :x64_mingw]
84
      else
85
        warn("Unknown database adapter `#{adapter}` found in config/database.yml, use Gemfile.local to load your own database gems")
86
      end
87
    end
88
  else
89
    warn("No adapter found in config/database.yml, please configure it first")
90
  end
91
else
92
  warn("Please configure your config/database.yml first")
93
end
94

  
95
group :development do
96
  gem "rdoc", ">= 2.4.2"
97
  gem "yard"
98
end
99

  
100
group :test do
101
  gem "minitest"
102
  gem "rails-dom-testing"
103
  gem "mocha"
104
  gem "simplecov", "~> 0.9.1", :require => false
105
  # For running UI tests
106
  gem "capybara"
107
  gem "selenium-webdriver"
108
end
109

  
110
local_gemfile = File.join(File.dirname(__FILE__), "Gemfile.local")
111
if File.exists?(local_gemfile)
112
  eval_gemfile local_gemfile
113
end
114

  
115
# Load plugins' Gemfiles
116
Dir.glob File.expand_path("../plugins/*/{Gemfile,PluginGemfile}", __FILE__) do |file|
117
  eval_gemfile file
118
end
0 119

  
tags/3.1.7/README.rdoc
1
= Redmine
2

  
3
Redmine is a flexible project management web application written using Ruby on Rails framework.
4

  
5
More details can be found in the doc directory or on the official website http://www.redmine.org
tags/3.1.7/Rakefile
1
#!/usr/bin/env rake
2
# Add your own tasks in files placed in lib/tasks ending in .rake,
3
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
4

  
5
require File.expand_path('../config/application', __FILE__)
6

  
7
RedmineApp::Application.load_tasks
tags/3.1.7/app/controllers/account_controller.rb
1
# Redmine - project management software
2
# Copyright (C) 2006-2016  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

  
18
class AccountController < ApplicationController
19
  helper :custom_fields
20
  include CustomFieldsHelper
21

  
22
  # prevents login action to be filtered by check_if_login_required application scope filter
23
  skip_before_filter :check_if_login_required, :check_password_change
24

  
25
  # Overrides ApplicationController#verify_authenticity_token to disable
26
  # token verification on openid callbacks
27
  def verify_authenticity_token
28
    unless using_open_id?
29
      super
30
    end
31
  end
32

  
33
  # Login request and validation
34
  def login
35
    if request.get?
36
      if User.current.logged?
37
        redirect_back_or_default home_url, :referer => true
38
      end
39
    else
40
      authenticate_user
41
    end
42
  rescue AuthSourceException => e
43
    logger.error "An error occured when authenticating #{params[:username]}: #{e.message}"
44
    render_error :message => e.message
45
  end
46

  
47
  # Log out current user and redirect to welcome page
48
  def logout
49
    if User.current.anonymous?
50
      redirect_to home_url
51
    elsif request.post?
52
      logout_user
53
      redirect_to home_url
54
    end
55
    # display the logout form
56
  end
57

  
58
  # Lets user choose a new password
59
  def lost_password
60
    (redirect_to(home_url); return) unless Setting.lost_password?
61
    if params[:token]
62
      @token = Token.find_token("recovery", params[:token].to_s)
63
      if @token.nil? || @token.expired?
64
        redirect_to home_url
65
        return
66
      end
67
      @user = @token.user
68
      unless @user && @user.active?
69
        redirect_to home_url
70
        return
71
      end
72
      if request.post?
73
        @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
74
        if @user.save
75
          @token.destroy
76
          flash[:notice] = l(:notice_account_password_updated)
77
          redirect_to signin_path
78
          return
79
        end
80
      end
81
      render :template => "account/password_recovery"
82
      return
83
    else
84
      if request.post?
85
        email = params[:mail].to_s
86
        user = User.find_by_mail(email)
87
        # user not found
88
        unless user
89
          flash.now[:error] = l(:notice_account_unknown_email)
90
          return
91
        end
92
        unless user.active?
93
          handle_inactive_user(user, lost_password_path)
94
          return
95
        end
96
        # user cannot change its password
97
        unless user.change_password_allowed?
98
          flash.now[:error] = l(:notice_can_t_change_password)
99
          return
100
        end
101
        # create a new token for password recovery
102
        token = Token.new(:user => user, :action => "recovery")
103
        if token.save
104
          # Don't use the param to send the email
105
          recipent = user.mails.detect {|e| e.downcase == email.downcase} || user.mail
106
          Mailer.lost_password(token, recipent).deliver
107
          flash[:notice] = l(:notice_account_lost_email_sent)
108
          redirect_to signin_path
109
          return
110
        end
111
      end
112
    end
113
  end
114

  
115
  # User self-registration
116
  def register
117
    (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration]
118
    if request.get?
119
      session[:auth_source_registration] = nil
120
      @user = User.new(:language => current_language.to_s)
121
    else
122
      user_params = params[:user] || {}
123
      @user = User.new
124
      @user.safe_attributes = user_params
125
      @user.admin = false
126
      @user.register
127
      if session[:auth_source_registration]
128
        @user.activate
129
        @user.login = session[:auth_source_registration][:login]
130
        @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
131
        if @user.save
132
          session[:auth_source_registration] = nil
133
          self.logged_user = @user
134
          flash[:notice] = l(:notice_account_activated)
135
          redirect_to my_account_path
136
        end
137
      else
138
        @user.login = params[:user][:login]
139
        unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank?
140
          @user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
141
        end
142

  
143
        case Setting.self_registration
144
        when '1'
145
          register_by_email_activation(@user)
146
        when '3'
147
          register_automatically(@user)
148
        else
149
          register_manually_by_administrator(@user)
150
        end
151
      end
152
    end
153
  end
154

  
155
  # Token based account activation
156
  def activate
157
    (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present?
158
    token = Token.find_token('register', params[:token].to_s)
159
    (redirect_to(home_url); return) unless token and !token.expired?
160
    user = token.user
161
    (redirect_to(home_url); return) unless user.registered?
162
    user.activate
163
    if user.save
164
      token.destroy
165
      flash[:notice] = l(:notice_account_activated)
166
    end
167
    redirect_to signin_path
168
  end
169

  
170
  # Sends a new account activation email
171
  def activation_email
172
    if session[:registered_user_id] && Setting.self_registration == '1'
173
      user_id = session.delete(:registered_user_id).to_i
174
      user = User.find_by_id(user_id)
175
      if user && user.registered?
176
        register_by_email_activation(user)
177
        return
178
      end
179
    end
180
    redirect_to(home_url)
181
  end
182

  
183
  private
184

  
185
  def authenticate_user
186
    if Setting.openid? && using_open_id?
187
      open_id_authenticate(params[:openid_url])
188
    else
189
      password_authentication
190
    end
191
  end
192

  
193
  def password_authentication
194
    user = User.try_to_login(params[:username], params[:password], false)
195

  
196
    if user.nil?
197
      invalid_credentials
198
    elsif user.new_record?
199
      onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
200
    else
201
      # Valid user
202
      if user.active?
203
        successful_authentication(user)
204
      else
205
        handle_inactive_user(user)
206
      end
207
    end
208
  end
209

  
210
  def open_id_authenticate(openid_url)
211
    back_url = signin_url(:autologin => params[:autologin])
212
    authenticate_with_open_id(
213
          openid_url, :required => [:nickname, :fullname, :email],
214
          :return_to => back_url, :method => :post
215
    ) do |result, identity_url, registration|
216
      if result.successful?
217
        user = User.find_or_initialize_by_identity_url(identity_url)
218
        if user.new_record?
219
          # Self-registration off
220
          (redirect_to(home_url); return) unless Setting.self_registration?
221
          # Create on the fly
222
          user.login = registration['nickname'] unless registration['nickname'].nil?
223
          user.mail = registration['email'] unless registration['email'].nil?
224
          user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil?
225
          user.random_password
226
          user.register
227
          case Setting.self_registration
228
          when '1'
229
            register_by_email_activation(user) do
230
              onthefly_creation_failed(user)
231
            end
232
          when '3'
233
            register_automatically(user) do
234
              onthefly_creation_failed(user)
235
            end
236
          else
237
            register_manually_by_administrator(user) do
238
              onthefly_creation_failed(user)
239
            end
240
          end
241
        else
242
          # Existing record
243
          if user.active?
244
            successful_authentication(user)
245
          else
246
            handle_inactive_user(user)
247
          end
248
        end
249
      end
250
    end
251
  end
252

  
253
  def successful_authentication(user)
254
    logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
255
    # Valid user
256
    self.logged_user = user
257
    # generate a key and set cookie if autologin
258
    if params[:autologin] && Setting.autologin?
259
      set_autologin_cookie(user)
260
    end
261
    call_hook(:controller_account_success_authentication_after, {:user => user })
262
    redirect_back_or_default my_page_path
263
  end
264

  
265
  def set_autologin_cookie(user)
266
    token = Token.create(:user => user, :action => 'autologin')
267
    cookie_options = {
268
      :value => token.value,
269
      :expires => 1.year.from_now,
270
      :path => (Redmine::Configuration['autologin_cookie_path'] || '/'),
271
      :secure => (Redmine::Configuration['autologin_cookie_secure'] ? true : false),
272
      :httponly => true
273
    }
274
    cookies[autologin_cookie_name] = cookie_options
275
  end
276

  
277
  # Onthefly creation failed, display the registration form to fill/fix attributes
278
  def onthefly_creation_failed(user, auth_source_options = { })
279
    @user = user
280
    session[:auth_source_registration] = auth_source_options unless auth_source_options.empty?
281
    render :action => 'register'
282
  end
283

  
284
  def invalid_credentials
285
    logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
286
    flash.now[:error] = l(:notice_account_invalid_creditentials)
287
  end
288

  
289
  # Register a user for email activation.
290
  #
291
  # Pass a block for behavior when a user fails to save
292
  def register_by_email_activation(user, &block)
293
    token = Token.new(:user => user, :action => "register")
294
    if user.save and token.save
295
      Mailer.register(token).deliver
296
      flash[:notice] = l(:notice_account_register_done, :email => ERB::Util.h(user.mail))
297
      redirect_to signin_path
298
    else
299
      yield if block_given?
300
    end
301
  end
302

  
303
  # Automatically register a user
304
  #
305
  # Pass a block for behavior when a user fails to save
306
  def register_automatically(user, &block)
307
    # Automatic activation
308
    user.activate
309
    user.last_login_on = Time.now
310
    if user.save
311
      self.logged_user = user
312
      flash[:notice] = l(:notice_account_activated)
313
      redirect_to my_account_path
314
    else
315
      yield if block_given?
316
    end
317
  end
318

  
319
  # Manual activation by the administrator
320
  #
321
  # Pass a block for behavior when a user fails to save
322
  def register_manually_by_administrator(user, &block)
323
    if user.save
324
      # Sends an email to the administrators
325
      Mailer.account_activation_request(user).deliver
326
      account_pending(user)
327
    else
328
      yield if block_given?
329
    end
330
  end
331

  
332
  def handle_inactive_user(user, redirect_path=signin_path)
333
    if user.registered?
334
      account_pending(user, redirect_path)
335
    else
336
      account_locked(user, redirect_path)
337
    end
338
  end
339

  
340
  def account_pending(user, redirect_path=signin_path)
341
    if Setting.self_registration == '1'
342
      flash[:error] = l(:notice_account_not_activated_yet, :url => activation_email_path)
343
      session[:registered_user_id] = user.id
344
    else
345
      flash[:error] = l(:notice_account_pending)
346
    end
347
    redirect_to redirect_path
348
  end
349

  
350
  def account_locked(user, redirect_path=signin_path)
351
    flash[:error] = l(:notice_account_locked)
352
    redirect_to redirect_path
353
  end
354
end
0 355

  
tags/3.1.7/app/controllers/activities_controller.rb
1
# Redmine - project management software
2
# Copyright (C) 2006-2016  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

  
18
class ActivitiesController < ApplicationController
19
  menu_item :activity
20
  before_filter :find_optional_project
21
  accept_rss_auth :index
22

  
23
  def index
24
    @days = Setting.activity_days_default.to_i
25

  
26
    if params[:from]
27
      begin; @date_to = params[:from].to_date + 1; rescue; end
28
    end
29

  
30
    @date_to ||= Date.today + 1
31
    @date_from = @date_to - @days
32
    @with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1')
33
    if params[:user_id].present?
34
      @author = User.active.find(params[:user_id])
35
    end
36

  
37
    @activity = Redmine::Activity::Fetcher.new(User.current, :project => @project,
38
                                                             :with_subprojects => @with_subprojects,
39
                                                             :author => @author)
40
    @activity.scope_select {|t| !params["show_#{t}"].nil?}
41
    @activity.scope = (@author.nil? ? :default : :all) if @activity.scope.empty?
42

  
43
    events = @activity.events(@date_from, @date_to)
44

  
45
    if events.empty? || stale?(:etag => [@activity.scope, @date_to, @date_from, @with_subprojects, @author, events.first, events.size, User.current, current_language])
46
      respond_to do |format|
47
        format.html {
48
          @events_by_day = events.group_by {|event| User.current.time_to_date(event.event_datetime)}
49
          render :layout => false if request.xhr?
50
        }
51
        format.atom {
52
          title = l(:label_activity)
53
          if @author
54
            title = @author.name
55
          elsif @activity.scope.size == 1
56
            title = l("label_#{@activity.scope.first.singularize}_plural")
57
          end
58
          render_feed(events, :title => "#{@project || Setting.app_title}: #{title}")
59
        }
60
      end
61
    end
62

  
63
  rescue ActiveRecord::RecordNotFound
64
    render_404
65
  end
66

  
67
  private
68

  
69
  # TODO: refactor, duplicated in projects_controller
70
  def find_optional_project
71
    return true unless params[:id]
72
    @project = Project.find(params[:id])
73
    authorize
74
  rescue ActiveRecord::RecordNotFound
75
    render_404
76
  end
77
end
0 78

  
tags/3.1.7/app/controllers/admin_controller.rb
1
# Redmine - project management software
2
# Copyright (C) 2006-2016  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

  
18
class AdminController < ApplicationController
19
  layout 'admin'
20
  menu_item :projects, :only => :projects
21
  menu_item :plugins, :only => :plugins
22
  menu_item :info, :only => :info
23

  
24
  before_filter :require_admin
25
  helper :sort
26
  include SortHelper
27

  
28
  def index
29
    @no_configuration_data = Redmine::DefaultData::Loader::no_data?
30
  end
31

  
32
  def projects
33
    @status = params[:status] || 1
34

  
35
    scope = Project.status(@status).sorted
36
    scope = scope.like(params[:name]) if params[:name].present?
37
    @projects = scope.to_a
38

  
39
    render :action => "projects", :layout => false if request.xhr?
40
  end
41

  
42
  def plugins
43
    @plugins = Redmine::Plugin.all
44
  end
45

  
46
  # Loads the default configuration
47
  # (roles, trackers, statuses, workflow, enumerations)
48
  def default_configuration
49
    if request.post?
50
      begin
51
        Redmine::DefaultData::Loader::load(params[:lang])
52
        flash[:notice] = l(:notice_default_data_loaded)
53
      rescue Exception => e
54
        flash[:error] = l(:error_can_t_load_default_data, ERB::Util.h(e.message))
55
      end
56
    end
57
    redirect_to admin_path
58
  end
59

  
60
  def test_email
61
    raise_delivery_errors = ActionMailer::Base.raise_delivery_errors
62
    # Force ActionMailer to raise delivery errors so we can catch it
63
    ActionMailer::Base.raise_delivery_errors = true
64
    begin
65
      @test = Mailer.test_email(User.current).deliver
66
      flash[:notice] = l(:notice_email_sent, ERB::Util.h(User.current.mail))
67
    rescue Exception => e
68
      flash[:error] = l(:notice_email_error, ERB::Util.h(Redmine::CodesetUtil.replace_invalid_utf8(e.message.dup)))
69
    end
70
    ActionMailer::Base.raise_delivery_errors = raise_delivery_errors
71
    redirect_to settings_path(:tab => 'notifications')
72
  end
73

  
74
  def info
75
    @db_adapter_name = ActiveRecord::Base.connection.adapter_name
76
    @checklist = [
77
      [:text_default_administrator_account_changed, User.default_admin_account_changed?],
78
      [:text_file_repository_writable, File.writable?(Attachment.storage_path)],
79
      ["#{l :text_plugin_assets_writable} (./public/plugin_assets)",   File.writable?(Redmine::Plugin.public_directory)],
80
      [:text_rmagick_available,        Object.const_defined?(:Magick)],
81
      [:text_convert_available,        Redmine::Thumbnail.convert_available?]
82
    ]
83
  end
84
end
0 85

  
tags/3.1.7/app/controllers/application_controller.rb
1
# Redmine - project management software
2
# Copyright (C) 2006-2016  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

  
18
require 'uri'
19
require 'cgi'
20

  
21
class Unauthorized < Exception; end
22

  
23
class ApplicationController < ActionController::Base
24
  include Redmine::I18n
25
  include Redmine::Pagination
26
  include RoutesHelper
27
  helper :routes
28

  
29
  class_attribute :accept_api_auth_actions
30
  class_attribute :accept_rss_auth_actions
31
  class_attribute :model_object
32

  
33
  layout 'base'
34

  
35
  protect_from_forgery
36

  
37
  def verify_authenticity_token
38
    unless api_request?
39
      super
40
    end
41
  end
42

  
43
  def handle_unverified_request
44
    unless api_request?
45
      super
46
      cookies.delete(autologin_cookie_name)
47
      self.logged_user = nil
48
      set_localization
49
      render_error :status => 422, :message => "Invalid form authenticity token."
50
    end
51
  end
52

  
53
  before_filter :session_expiration, :user_setup, :force_logout_if_password_changed, :check_if_login_required, :check_password_change, :set_localization
54

  
55
  rescue_from ::Unauthorized, :with => :deny_access
56
  rescue_from ::ActionView::MissingTemplate, :with => :missing_template
57

  
58
  include Redmine::Search::Controller
59
  include Redmine::MenuManager::MenuController
60
  helper Redmine::MenuManager::MenuHelper
61

  
62
  include Redmine::SudoMode::Controller
63

  
64
  def session_expiration
65
    if session[:user_id]
66
      if session_expired? && !try_to_autologin
67
        set_localization(User.active.find_by_id(session[:user_id]))
68
        self.logged_user = nil
69
        flash[:error] = l(:error_session_expired)
70
        require_login
71
      else
72
        session[:atime] = Time.now.utc.to_i
73
      end
74
    end
75
  end
76

  
77
  def session_expired?
78
    if Setting.session_lifetime?
79
      unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
80
        return true
81
      end
82
    end
83
    if Setting.session_timeout?
84
      unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
85
        return true
86
      end
87
    end
88
    false
89
  end
90

  
91
  def start_user_session(user)
92
    session[:user_id] = user.id
93
    session[:ctime] = Time.now.utc.to_i
94
    session[:atime] = Time.now.utc.to_i
95
    if user.must_change_password?
96
      session[:pwd] = '1'
97
    end
98
  end
99

  
100
  def user_setup
101
    # Check the settings cache for each request
102
    Setting.check_cache
103
    # Find the current user
104
    User.current = find_current_user
105
    logger.info("  Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
106
  end
107

  
108
  # Returns the current user or nil if no user is logged in
109
  # and starts a session if needed
110
  def find_current_user
111
    user = nil
112
    unless api_request?
113
      if session[:user_id]
114
        # existing session
115
        user = (User.active.find(session[:user_id]) rescue nil)
116
      elsif autologin_user = try_to_autologin
117
        user = autologin_user
118
      elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
119
        # RSS key authentication does not start a session
120
        user = User.find_by_rss_key(params[:key])
121
      end
122
    end
123
    if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
124
      if (key = api_key_from_request)
125
        # Use API key
126
        user = User.find_by_api_key(key)
127
      elsif request.authorization.to_s =~ /\ABasic /i
128
        # HTTP Basic, either username/password or API key/random
129
        authenticate_with_http_basic do |username, password|
130
          user = User.try_to_login(username, password) || User.find_by_api_key(username)
131
        end
132
        if user && user.must_change_password?
133
          render_error :message => 'You must change your password', :status => 403
134
          return
135
        end
136
      end
137
      # Switch user if requested by an admin user
138
      if user && user.admin? && (username = api_switch_user_from_request)
139
        su = User.find_by_login(username)
140
        if su && su.active?
141
          logger.info("  User switched by: #{user.login} (id=#{user.id})") if logger
142
          user = su
143
        else
144
          render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
145
        end
146
      end
147
    end
148
    user
149
  end
150

  
151
  def force_logout_if_password_changed
152
    passwd_changed_on = User.current.passwd_changed_on || Time.at(0)
153
    # Make sure we force logout only for web browser sessions, not API calls
154
    # if the password was changed after the session creation.
155
    if session[:user_id] && passwd_changed_on.utc.to_i > session[:ctime].to_i
156
      reset_session
157
      set_localization
158
      flash[:error] = l(:error_session_expired)
159
      redirect_to signin_url
160
    end
161
  end
162

  
163
  def autologin_cookie_name
164
    Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
165
  end
166

  
167
  def try_to_autologin
168
    if cookies[autologin_cookie_name] && Setting.autologin?
169
      # auto-login feature starts a new session
170
      user = User.try_to_autologin(cookies[autologin_cookie_name])
171
      if user
172
        reset_session
173
        start_user_session(user)
174
      end
175
      user
176
    end
177
  end
178

  
179
  # Sets the logged in user
180
  def logged_user=(user)
181
    reset_session
182
    if user && user.is_a?(User)
183
      User.current = user
184
      start_user_session(user)
185
    else
186
      User.current = User.anonymous
187
    end
188
  end
189

  
190
  # Logs out current user
191
  def logout_user
192
    if User.current.logged?
193
      cookies.delete(autologin_cookie_name)
194
      Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
195
      self.logged_user = nil
196
    end
197
  end
198

  
199
  # check if login is globally required to access the application
200
  def check_if_login_required
201
    # no check needed if user is already logged in
202
    return true if User.current.logged?
203
    require_login if Setting.login_required?
204
  end
205

  
206
  def check_password_change
207
    if session[:pwd]
208
      if User.current.must_change_password?
209
        flash[:error] = l(:error_password_expired)
210
        redirect_to my_password_path
211
      else
212
        session.delete(:pwd)
213
      end
214
    end
215
  end
216

  
217
  def set_localization(user=User.current)
218
    lang = nil
219
    if user && user.logged?
220
      lang = find_language(user.language)
221
    end
222
    if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
223
      accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
224
      if !accept_lang.blank?
225
        accept_lang = accept_lang.downcase
226
        lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
227
      end
228
    end
229
    lang ||= Setting.default_language
230
    set_language_if_valid(lang)
231
  end
232

  
233
  def require_login
234
    if !User.current.logged?
235
      # Extract only the basic url parameters on non-GET requests
236
      if request.get?
237
        url = url_for(params)
238
      else
239
        url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
240
      end
241
      respond_to do |format|
242
        format.html {
243
          if request.xhr?
244
            head :unauthorized
245
          else
246
            redirect_to signin_path(:back_url => url)
247
          end
248
        }
249
        format.any(:atom, :pdf, :csv) {
250
          redirect_to signin_path(:back_url => url)
251
        }
252
        format.xml  { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
253
        format.js   { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
254
        format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
255
        format.any  { head :unauthorized }
256
      end
257
      return false
258
    end
259
    true
260
  end
261

  
262
  def require_admin
263
    return unless require_login
264
    if !User.current.admin?
265
      render_403
266
      return false
267
    end
268
    true
269
  end
270

  
271
  def deny_access
272
    User.current.logged? ? render_403 : require_login
273
  end
274

  
275
  # Authorize the user for the requested action
276
  def authorize(ctrl = params[:controller], action = params[:action], global = false)
277
    allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
278
    if allowed
279
      true
280
    else
281
      if @project && @project.archived?
282
        render_403 :message => :notice_not_authorized_archived_project
283
      else
284
        deny_access
285
      end
286
    end
287
  end
288

  
289
  # Authorize the user for the requested action outside a project
290
  def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
291
    authorize(ctrl, action, global)
292
  end
293

  
294
  # Find project of id params[:id]
295
  def find_project
296
    @project = Project.find(params[:id])
297
  rescue ActiveRecord::RecordNotFound
298
    render_404
299
  end
300

  
301
  # Find project of id params[:project_id]
302
  def find_project_by_project_id
303
    @project = Project.find(params[:project_id])
304
  rescue ActiveRecord::RecordNotFound
305
    render_404
306
  end
307

  
308
  # Find a project based on params[:project_id]
309
  # TODO: some subclasses override this, see about merging their logic
310
  def find_optional_project
311
    @project = Project.find(params[:project_id]) unless params[:project_id].blank?
312
    allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
313
    allowed ? true : deny_access
314
  rescue ActiveRecord::RecordNotFound
315
    render_404
316
  end
317

  
318
  # Finds and sets @project based on @object.project
319
  def find_project_from_association
320
    render_404 unless @object.present?
321

  
322
    @project = @object.project
323
  end
324

  
325
  def find_model_object
326
    model = self.class.model_object
327
    if model
328
      @object = model.find(params[:id])
329
      self.instance_variable_set('@' + controller_name.singularize, @object) if @object
330
    end
331
  rescue ActiveRecord::RecordNotFound
332
    render_404
333
  end
334

  
335
  def self.model_object(model)
336
    self.model_object = model
337
  end
338

  
339
  # Find the issue whose id is the :id parameter
340
  # Raises a Unauthorized exception if the issue is not visible
341
  def find_issue
342
    # Issue.visible.find(...) can not be used to redirect user to the login form
343
    # if the issue actually exists but requires authentication
344
    @issue = Issue.find(params[:id])
345
    raise Unauthorized unless @issue.visible?
346
    @project = @issue.project
347
  rescue ActiveRecord::RecordNotFound
348
    render_404
349
  end
350

  
351
  # Find issues with a single :id param or :ids array param
352
  # Raises a Unauthorized exception if one of the issues is not visible
353
  def find_issues
354
    @issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
355
    raise ActiveRecord::RecordNotFound if @issues.empty?
356
    raise Unauthorized unless @issues.all?(&:visible?)
357
    @projects = @issues.collect(&:project).compact.uniq
358
    @project = @projects.first if @projects.size == 1
359
  rescue ActiveRecord::RecordNotFound
360
    render_404
361
  end
362

  
363
  def find_attachments
364
    if (attachments = params[:attachments]).present?
365
      att = attachments.values.collect do |attachment|
366
        Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
367
      end
368
      att.compact!
369
    end
370
    @attachments = att || []
371
  end
372

  
373
  # make sure that the user is a member of the project (or admin) if project is private
374
  # used as a before_filter for actions that do not require any particular permission on the project
375
  def check_project_privacy
376
    if @project && !@project.archived?
377
      if @project.visible?
378
        true
379
      else
380
        deny_access
381
      end
382
    else
383
      @project = nil
384
      render_404
385
      false
386
    end
387
  end
388

  
389
  def back_url
390
    url = params[:back_url]
391
    if url.nil? && referer = request.env['HTTP_REFERER']
392
      url = CGI.unescape(referer.to_s)
393
    end
394
    url
395
  end
396

  
397
  def redirect_back_or_default(default, options={})
398
    back_url = params[:back_url].to_s
399
    if back_url.present? && valid_url = validate_back_url(back_url)
400
      redirect_to(valid_url)
401
      return
402
    elsif options[:referer]
403
      redirect_to_referer_or default
404
      return
405
    end
406
    redirect_to default
407
    false
408
  end
409

  
410
  # Returns a validated URL string if back_url is a valid url for redirection,
411
  # otherwise false
412
  def validate_back_url(back_url)
413
    if CGI.unescape(back_url).include?('..')
414
      return false
415
    end
416

  
417
    begin
418
      uri = URI.parse(back_url)
419
    rescue URI::InvalidURIError
420
      return false
421
    end
422

  
423
    [:scheme, :host, :port].each do |component|
424
      if uri.send(component).present? && uri.send(component) != request.send(component)
425
        return false
426
      end
427
      uri.send(:"#{component}=", nil)
428
    end
429
    # Always ignore basic user:password in the URL
430
    uri.userinfo = nil
431

  
432
    path = uri.to_s
433
    # Ensure that the remaining URL starts with a slash, followed by a
434
    # non-slash character or the end
435
    if path !~ %r{\A/([^/]|\z)}
436
      return false
437
    end
438

  
439
    if path.match(%r{/(login|account/register)})
440
      return false
441
    end
442

  
443
    if relative_url_root.present? && !path.starts_with?(relative_url_root)
444
      return false
445
    end
446

  
447
    return path
448
  end
449
  private :validate_back_url
450

  
451
  def valid_back_url?(back_url)
452
    !!validate_back_url(back_url)
453
  end
454
  private :valid_back_url?
455

  
456
  # Redirects to the request referer if present, redirects to args or call block otherwise.
457
  def redirect_to_referer_or(*args, &block)
458
    redirect_to :back
459
  rescue ::ActionController::RedirectBackError
460
    if args.any?
461
      redirect_to *args
462
    elsif block_given?
463
      block.call
464
    else
465
      raise "#redirect_to_referer_or takes arguments or a block"
466
    end
467
  end
468

  
469
  def render_403(options={})
470
    @project = nil
471
    render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
472
    return false
473
  end
474

  
475
  def render_404(options={})
476
    render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
477
    return false
478
  end
479

  
480
  # Renders an error response
481
  def render_error(arg)
482
    arg = {:message => arg} unless arg.is_a?(Hash)
483

  
484
    @message = arg[:message]
485
    @message = l(@message) if @message.is_a?(Symbol)
486
    @status = arg[:status] || 500
487

  
488
    respond_to do |format|
489
      format.html {
490
        render :template => 'common/error', :layout => use_layout, :status => @status
491
      }
492
      format.any { head @status }
493
    end
494
  end
495

  
496
  # Handler for ActionView::MissingTemplate exception
497
  def missing_template
498
    logger.warn "Missing template, responding with 404"
499
    @project = nil
500
    render_404
501
  end
502

  
503
  # Filter for actions that provide an API response
504
  # but have no HTML representation for non admin users
505
  def require_admin_or_api_request
506
    return true if api_request?
507
    if User.current.admin?
508
      true
509
    elsif User.current.logged?
510
      render_error(:status => 406)
511
    else
512
      deny_access
513
    end
514
  end
515

  
516
  # Picks which layout to use based on the request
517
  #
518
  # @return [boolean, string] name of the layout to use or false for no layout
519
  def use_layout
520
    request.xhr? ? false : 'base'
521
  end
522

  
523
  def render_feed(items, options={})
524
    @items = (items || []).to_a
525
    @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
526
    @items = @items.slice(0, Setting.feeds_limit.to_i)
527
    @title = options[:title] || Setting.app_title
528
    render :template => "common/feed", :formats => [:atom], :layout => false,
529
           :content_type => 'application/atom+xml'
530
  end
531

  
532
  def self.accept_rss_auth(*actions)
533
    if actions.any?
534
      self.accept_rss_auth_actions = actions
535
    else
536
      self.accept_rss_auth_actions || []
537
    end
538
  end
539

  
540
  def accept_rss_auth?(action=action_name)
541
    self.class.accept_rss_auth.include?(action.to_sym)
542
  end
543

  
544
  def self.accept_api_auth(*actions)
545
    if actions.any?
546
      self.accept_api_auth_actions = actions
547
    else
548
      self.accept_api_auth_actions || []
549
    end
550
  end
551

  
552
  def accept_api_auth?(action=action_name)
553
    self.class.accept_api_auth.include?(action.to_sym)
554
  end
555

  
556
  # Returns the number of objects that should be displayed
557
  # on the paginated list
558
  def per_page_option
559
    per_page = nil
560
    if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
561
      per_page = params[:per_page].to_s.to_i
562
      session[:per_page] = per_page
563
    elsif session[:per_page]
564
      per_page = session[:per_page]
565
    else
566
      per_page = Setting.per_page_options_array.first || 25
567
    end
568
    per_page
569
  end
570

  
571
  # Returns offset and limit used to retrieve objects
572
  # for an API response based on offset, limit and page parameters
573
  def api_offset_and_limit(options=params)
574
    if options[:offset].present?
575
      offset = options[:offset].to_i
576
      if offset < 0
577
        offset = 0
578
      end
579
    end
580
    limit = options[:limit].to_i
581
    if limit < 1
582
      limit = 25
583
    elsif limit > 100
584
      limit = 100
585
    end
586
    if offset.nil? && options[:page].present?
587
      offset = (options[:page].to_i - 1) * limit
588
      offset = 0 if offset < 0
589
    end
590
    offset ||= 0
591

  
592
    [offset, limit]
593
  end
594

  
595
  # qvalues http header parser
596
  # code taken from webrick
597
  def parse_qvalues(value)
598
    tmp = []
599
    if value
600
      parts = value.split(/,\s*/)
601
      parts.each {|part|
602
        if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
603
          val = m[1]
604
          q = (m[2] or 1).to_f
605
          tmp.push([val, q])
606
        end
607
      }
608
      tmp = tmp.sort_by{|val, q| -q}
609
      tmp.collect!{|val, q| val}
610
    end
611
    return tmp
612
  rescue
613
    nil
614
  end
615

  
616
  # Returns a string that can be used as filename value in Content-Disposition header
617
  def filename_for_content_disposition(name)
618
    request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident|Edge)} ? ERB::Util.url_encode(name) : name
619
  end
620

  
621
  def api_request?
622
    %w(xml json).include? params[:format]
623
  end
624

  
625
  # Returns the API key present in the request
626
  def api_key_from_request
627
    if params[:key].present?
628
      params[:key].to_s
629
    elsif request.headers["X-Redmine-API-Key"].present?
630
      request.headers["X-Redmine-API-Key"].to_s
631
    end
632
  end
633

  
634
  # Returns the API 'switch user' value if present
635
  def api_switch_user_from_request
636
    request.headers["X-Redmine-Switch-User"].to_s.presence
637
  end
638

  
639
  # Renders a warning flash if obj has unsaved attachments
640
  def render_attachment_warning_if_needed(obj)
641
    flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
642
  end
643

  
644
  # Rescues an invalid query statement. Just in case...
645
  def query_statement_invalid(exception)
646
    logger.error "Query::StatementInvalid: #{exception.message}" if logger
647
    session.delete(:query)
648
    sort_clear if respond_to?(:sort_clear)
649
    render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
650
  end
651

  
652
  # Renders a 200 response for successfull updates or deletions via the API
653
  def render_api_ok
654
    render_api_head :ok
655
  end
656

  
657
  # Renders a head API response
658
  def render_api_head(status)
659
    # #head would return a response body with one space
660
    render :text => '', :status => status, :layout => nil
661
  end
662

  
663
  # Renders API response on validation failure
664
  # for an object or an array of objects
665
  def render_validation_errors(objects)
666
    messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
667
    render_api_errors(messages)
668
  end
669

  
670
  def render_api_errors(*messages)
671
    @error_messages = messages.flatten
672
    render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
673
  end
674

  
675
  # Overrides #_include_layout? so that #render with no arguments
676
  # doesn't use the layout for api requests
677
  def _include_layout?(*args)
678
    api_request? ? false : super
679
  end
680
end
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff