##// END OF EJS Templates
Let the mailer set the email content (#21421)....
Jean-Philippe Lang -
r14885:a47eab886835
parent child
Show More
@@ -1,366 +1,361
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
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
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.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class AccountController < ApplicationController
18 class AccountController < ApplicationController
19 helper :custom_fields
19 helper :custom_fields
20 include CustomFieldsHelper
20 include CustomFieldsHelper
21
21
22 # prevents login action to be filtered by check_if_login_required application scope filter
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
23 skip_before_filter :check_if_login_required, :check_password_change
24
24
25 # Overrides ApplicationController#verify_authenticity_token to disable
25 # Overrides ApplicationController#verify_authenticity_token to disable
26 # token verification on openid callbacks
26 # token verification on openid callbacks
27 def verify_authenticity_token
27 def verify_authenticity_token
28 unless using_open_id?
28 unless using_open_id?
29 super
29 super
30 end
30 end
31 end
31 end
32
32
33 # Login request and validation
33 # Login request and validation
34 def login
34 def login
35 if request.get?
35 if request.get?
36 if User.current.logged?
36 if User.current.logged?
37 redirect_back_or_default home_url, :referer => true
37 redirect_back_or_default home_url, :referer => true
38 end
38 end
39 else
39 else
40 authenticate_user
40 authenticate_user
41 end
41 end
42 rescue AuthSourceException => e
42 rescue AuthSourceException => e
43 logger.error "An error occured when authenticating #{params[:username]}: #{e.message}"
43 logger.error "An error occured when authenticating #{params[:username]}: #{e.message}"
44 render_error :message => e.message
44 render_error :message => e.message
45 end
45 end
46
46
47 # Log out current user and redirect to welcome page
47 # Log out current user and redirect to welcome page
48 def logout
48 def logout
49 if User.current.anonymous?
49 if User.current.anonymous?
50 redirect_to home_url
50 redirect_to home_url
51 elsif request.post?
51 elsif request.post?
52 logout_user
52 logout_user
53 redirect_to home_url
53 redirect_to home_url
54 end
54 end
55 # display the logout form
55 # display the logout form
56 end
56 end
57
57
58 # Lets user choose a new password
58 # Lets user choose a new password
59 def lost_password
59 def lost_password
60 (redirect_to(home_url); return) unless Setting.lost_password?
60 (redirect_to(home_url); return) unless Setting.lost_password?
61 if params[:token]
61 if params[:token]
62 @token = Token.find_token("recovery", params[:token].to_s)
62 @token = Token.find_token("recovery", params[:token].to_s)
63 if @token.nil? || @token.expired?
63 if @token.nil? || @token.expired?
64 redirect_to home_url
64 redirect_to home_url
65 return
65 return
66 end
66 end
67 @user = @token.user
67 @user = @token.user
68 unless @user && @user.active?
68 unless @user && @user.active?
69 redirect_to home_url
69 redirect_to home_url
70 return
70 return
71 end
71 end
72 if request.post?
72 if request.post?
73 @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
73 @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
74 if @user.save
74 if @user.save
75 @token.destroy
75 @token.destroy
76 Mailer.security_notification(@user,
76 Mailer.password_updated(@user)
77 message: :mail_body_security_notification_change,
78 field: :field_password,
79 title: :button_change_password,
80 url: {controller: 'my', action: 'password'}
81 ).deliver
82 flash[:notice] = l(:notice_account_password_updated)
77 flash[:notice] = l(:notice_account_password_updated)
83 redirect_to signin_path
78 redirect_to signin_path
84 return
79 return
85 end
80 end
86 end
81 end
87 render :template => "account/password_recovery"
82 render :template => "account/password_recovery"
88 return
83 return
89 else
84 else
90 if request.post?
85 if request.post?
91 email = params[:mail].to_s
86 email = params[:mail].to_s
92 user = User.find_by_mail(email)
87 user = User.find_by_mail(email)
93 # user not found
88 # user not found
94 unless user
89 unless user
95 flash.now[:error] = l(:notice_account_unknown_email)
90 flash.now[:error] = l(:notice_account_unknown_email)
96 return
91 return
97 end
92 end
98 unless user.active?
93 unless user.active?
99 handle_inactive_user(user, lost_password_path)
94 handle_inactive_user(user, lost_password_path)
100 return
95 return
101 end
96 end
102 # user cannot change its password
97 # user cannot change its password
103 unless user.change_password_allowed?
98 unless user.change_password_allowed?
104 flash.now[:error] = l(:notice_can_t_change_password)
99 flash.now[:error] = l(:notice_can_t_change_password)
105 return
100 return
106 end
101 end
107 # create a new token for password recovery
102 # create a new token for password recovery
108 token = Token.new(:user => user, :action => "recovery")
103 token = Token.new(:user => user, :action => "recovery")
109 if token.save
104 if token.save
110 # Don't use the param to send the email
105 # Don't use the param to send the email
111 recipent = user.mails.detect {|e| email.casecmp(e) == 0} || user.mail
106 recipent = user.mails.detect {|e| email.casecmp(e) == 0} || user.mail
112 Mailer.lost_password(token, recipent).deliver
107 Mailer.lost_password(token, recipent).deliver
113 flash[:notice] = l(:notice_account_lost_email_sent)
108 flash[:notice] = l(:notice_account_lost_email_sent)
114 redirect_to signin_path
109 redirect_to signin_path
115 return
110 return
116 end
111 end
117 end
112 end
118 end
113 end
119 end
114 end
120
115
121 # User self-registration
116 # User self-registration
122 def register
117 def register
123 (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration]
118 (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration]
124 if request.get?
119 if request.get?
125 session[:auth_source_registration] = nil
120 session[:auth_source_registration] = nil
126 @user = User.new(:language => current_language.to_s)
121 @user = User.new(:language => current_language.to_s)
127 else
122 else
128 user_params = params[:user] || {}
123 user_params = params[:user] || {}
129 @user = User.new
124 @user = User.new
130 @user.safe_attributes = user_params
125 @user.safe_attributes = user_params
131 @user.pref.attributes = params[:pref] if params[:pref]
126 @user.pref.attributes = params[:pref] if params[:pref]
132 @user.admin = false
127 @user.admin = false
133 @user.register
128 @user.register
134 if session[:auth_source_registration]
129 if session[:auth_source_registration]
135 @user.activate
130 @user.activate
136 @user.login = session[:auth_source_registration][:login]
131 @user.login = session[:auth_source_registration][:login]
137 @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
132 @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
138 if @user.save
133 if @user.save
139 session[:auth_source_registration] = nil
134 session[:auth_source_registration] = nil
140 self.logged_user = @user
135 self.logged_user = @user
141 flash[:notice] = l(:notice_account_activated)
136 flash[:notice] = l(:notice_account_activated)
142 redirect_to my_account_path
137 redirect_to my_account_path
143 end
138 end
144 else
139 else
145 @user.login = params[:user][:login]
140 @user.login = params[:user][:login]
146 unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank?
141 unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank?
147 @user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
142 @user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
148 end
143 end
149
144
150 case Setting.self_registration
145 case Setting.self_registration
151 when '1'
146 when '1'
152 register_by_email_activation(@user)
147 register_by_email_activation(@user)
153 when '3'
148 when '3'
154 register_automatically(@user)
149 register_automatically(@user)
155 else
150 else
156 register_manually_by_administrator(@user)
151 register_manually_by_administrator(@user)
157 end
152 end
158 end
153 end
159 end
154 end
160 end
155 end
161
156
162 # Token based account activation
157 # Token based account activation
163 def activate
158 def activate
164 (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present?
159 (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present?
165 token = Token.find_token('register', params[:token].to_s)
160 token = Token.find_token('register', params[:token].to_s)
166 (redirect_to(home_url); return) unless token and !token.expired?
161 (redirect_to(home_url); return) unless token and !token.expired?
167 user = token.user
162 user = token.user
168 (redirect_to(home_url); return) unless user.registered?
163 (redirect_to(home_url); return) unless user.registered?
169 user.activate
164 user.activate
170 if user.save
165 if user.save
171 token.destroy
166 token.destroy
172 flash[:notice] = l(:notice_account_activated)
167 flash[:notice] = l(:notice_account_activated)
173 end
168 end
174 redirect_to signin_path
169 redirect_to signin_path
175 end
170 end
176
171
177 # Sends a new account activation email
172 # Sends a new account activation email
178 def activation_email
173 def activation_email
179 if session[:registered_user_id] && Setting.self_registration == '1'
174 if session[:registered_user_id] && Setting.self_registration == '1'
180 user_id = session.delete(:registered_user_id).to_i
175 user_id = session.delete(:registered_user_id).to_i
181 user = User.find_by_id(user_id)
176 user = User.find_by_id(user_id)
182 if user && user.registered?
177 if user && user.registered?
183 register_by_email_activation(user)
178 register_by_email_activation(user)
184 return
179 return
185 end
180 end
186 end
181 end
187 redirect_to(home_url)
182 redirect_to(home_url)
188 end
183 end
189
184
190 private
185 private
191
186
192 def authenticate_user
187 def authenticate_user
193 if Setting.openid? && using_open_id?
188 if Setting.openid? && using_open_id?
194 open_id_authenticate(params[:openid_url])
189 open_id_authenticate(params[:openid_url])
195 else
190 else
196 password_authentication
191 password_authentication
197 end
192 end
198 end
193 end
199
194
200 def password_authentication
195 def password_authentication
201 user = User.try_to_login(params[:username], params[:password], false)
196 user = User.try_to_login(params[:username], params[:password], false)
202
197
203 if user.nil?
198 if user.nil?
204 invalid_credentials
199 invalid_credentials
205 elsif user.new_record?
200 elsif user.new_record?
206 onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
201 onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
207 else
202 else
208 # Valid user
203 # Valid user
209 if user.active?
204 if user.active?
210 successful_authentication(user)
205 successful_authentication(user)
211 update_sudo_timestamp! # activate Sudo Mode
206 update_sudo_timestamp! # activate Sudo Mode
212 else
207 else
213 handle_inactive_user(user)
208 handle_inactive_user(user)
214 end
209 end
215 end
210 end
216 end
211 end
217
212
218 def open_id_authenticate(openid_url)
213 def open_id_authenticate(openid_url)
219 back_url = signin_url(:autologin => params[:autologin])
214 back_url = signin_url(:autologin => params[:autologin])
220 authenticate_with_open_id(
215 authenticate_with_open_id(
221 openid_url, :required => [:nickname, :fullname, :email],
216 openid_url, :required => [:nickname, :fullname, :email],
222 :return_to => back_url, :method => :post
217 :return_to => back_url, :method => :post
223 ) do |result, identity_url, registration|
218 ) do |result, identity_url, registration|
224 if result.successful?
219 if result.successful?
225 user = User.find_or_initialize_by_identity_url(identity_url)
220 user = User.find_or_initialize_by_identity_url(identity_url)
226 if user.new_record?
221 if user.new_record?
227 # Self-registration off
222 # Self-registration off
228 (redirect_to(home_url); return) unless Setting.self_registration?
223 (redirect_to(home_url); return) unless Setting.self_registration?
229 # Create on the fly
224 # Create on the fly
230 user.login = registration['nickname'] unless registration['nickname'].nil?
225 user.login = registration['nickname'] unless registration['nickname'].nil?
231 user.mail = registration['email'] unless registration['email'].nil?
226 user.mail = registration['email'] unless registration['email'].nil?
232 user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil?
227 user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil?
233 user.random_password
228 user.random_password
234 user.register
229 user.register
235 case Setting.self_registration
230 case Setting.self_registration
236 when '1'
231 when '1'
237 register_by_email_activation(user) do
232 register_by_email_activation(user) do
238 onthefly_creation_failed(user)
233 onthefly_creation_failed(user)
239 end
234 end
240 when '3'
235 when '3'
241 register_automatically(user) do
236 register_automatically(user) do
242 onthefly_creation_failed(user)
237 onthefly_creation_failed(user)
243 end
238 end
244 else
239 else
245 register_manually_by_administrator(user) do
240 register_manually_by_administrator(user) do
246 onthefly_creation_failed(user)
241 onthefly_creation_failed(user)
247 end
242 end
248 end
243 end
249 else
244 else
250 # Existing record
245 # Existing record
251 if user.active?
246 if user.active?
252 successful_authentication(user)
247 successful_authentication(user)
253 else
248 else
254 handle_inactive_user(user)
249 handle_inactive_user(user)
255 end
250 end
256 end
251 end
257 end
252 end
258 end
253 end
259 end
254 end
260
255
261 def successful_authentication(user)
256 def successful_authentication(user)
262 logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
257 logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
263 # Valid user
258 # Valid user
264 self.logged_user = user
259 self.logged_user = user
265 # generate a key and set cookie if autologin
260 # generate a key and set cookie if autologin
266 if params[:autologin] && Setting.autologin?
261 if params[:autologin] && Setting.autologin?
267 set_autologin_cookie(user)
262 set_autologin_cookie(user)
268 end
263 end
269 call_hook(:controller_account_success_authentication_after, {:user => user })
264 call_hook(:controller_account_success_authentication_after, {:user => user })
270 redirect_back_or_default my_page_path
265 redirect_back_or_default my_page_path
271 end
266 end
272
267
273 def set_autologin_cookie(user)
268 def set_autologin_cookie(user)
274 token = Token.create(:user => user, :action => 'autologin')
269 token = Token.create(:user => user, :action => 'autologin')
275 secure = Redmine::Configuration['autologin_cookie_secure']
270 secure = Redmine::Configuration['autologin_cookie_secure']
276 if secure.nil?
271 if secure.nil?
277 secure = request.ssl?
272 secure = request.ssl?
278 end
273 end
279 cookie_options = {
274 cookie_options = {
280 :value => token.value,
275 :value => token.value,
281 :expires => 1.year.from_now,
276 :expires => 1.year.from_now,
282 :path => (Redmine::Configuration['autologin_cookie_path'] || RedmineApp::Application.config.relative_url_root || '/'),
277 :path => (Redmine::Configuration['autologin_cookie_path'] || RedmineApp::Application.config.relative_url_root || '/'),
283 :secure => secure,
278 :secure => secure,
284 :httponly => true
279 :httponly => true
285 }
280 }
286 cookies[autologin_cookie_name] = cookie_options
281 cookies[autologin_cookie_name] = cookie_options
287 end
282 end
288
283
289 # Onthefly creation failed, display the registration form to fill/fix attributes
284 # Onthefly creation failed, display the registration form to fill/fix attributes
290 def onthefly_creation_failed(user, auth_source_options = { })
285 def onthefly_creation_failed(user, auth_source_options = { })
291 @user = user
286 @user = user
292 session[:auth_source_registration] = auth_source_options unless auth_source_options.empty?
287 session[:auth_source_registration] = auth_source_options unless auth_source_options.empty?
293 render :action => 'register'
288 render :action => 'register'
294 end
289 end
295
290
296 def invalid_credentials
291 def invalid_credentials
297 logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
292 logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
298 flash.now[:error] = l(:notice_account_invalid_credentials)
293 flash.now[:error] = l(:notice_account_invalid_credentials)
299 end
294 end
300
295
301 # Register a user for email activation.
296 # Register a user for email activation.
302 #
297 #
303 # Pass a block for behavior when a user fails to save
298 # Pass a block for behavior when a user fails to save
304 def register_by_email_activation(user, &block)
299 def register_by_email_activation(user, &block)
305 token = Token.new(:user => user, :action => "register")
300 token = Token.new(:user => user, :action => "register")
306 if user.save and token.save
301 if user.save and token.save
307 Mailer.register(token).deliver
302 Mailer.register(token).deliver
308 flash[:notice] = l(:notice_account_register_done, :email => ERB::Util.h(user.mail))
303 flash[:notice] = l(:notice_account_register_done, :email => ERB::Util.h(user.mail))
309 redirect_to signin_path
304 redirect_to signin_path
310 else
305 else
311 yield if block_given?
306 yield if block_given?
312 end
307 end
313 end
308 end
314
309
315 # Automatically register a user
310 # Automatically register a user
316 #
311 #
317 # Pass a block for behavior when a user fails to save
312 # Pass a block for behavior when a user fails to save
318 def register_automatically(user, &block)
313 def register_automatically(user, &block)
319 # Automatic activation
314 # Automatic activation
320 user.activate
315 user.activate
321 user.last_login_on = Time.now
316 user.last_login_on = Time.now
322 if user.save
317 if user.save
323 self.logged_user = user
318 self.logged_user = user
324 flash[:notice] = l(:notice_account_activated)
319 flash[:notice] = l(:notice_account_activated)
325 redirect_to my_account_path
320 redirect_to my_account_path
326 else
321 else
327 yield if block_given?
322 yield if block_given?
328 end
323 end
329 end
324 end
330
325
331 # Manual activation by the administrator
326 # Manual activation by the administrator
332 #
327 #
333 # Pass a block for behavior when a user fails to save
328 # Pass a block for behavior when a user fails to save
334 def register_manually_by_administrator(user, &block)
329 def register_manually_by_administrator(user, &block)
335 if user.save
330 if user.save
336 # Sends an email to the administrators
331 # Sends an email to the administrators
337 Mailer.account_activation_request(user).deliver
332 Mailer.account_activation_request(user).deliver
338 account_pending(user)
333 account_pending(user)
339 else
334 else
340 yield if block_given?
335 yield if block_given?
341 end
336 end
342 end
337 end
343
338
344 def handle_inactive_user(user, redirect_path=signin_path)
339 def handle_inactive_user(user, redirect_path=signin_path)
345 if user.registered?
340 if user.registered?
346 account_pending(user, redirect_path)
341 account_pending(user, redirect_path)
347 else
342 else
348 account_locked(user, redirect_path)
343 account_locked(user, redirect_path)
349 end
344 end
350 end
345 end
351
346
352 def account_pending(user, redirect_path=signin_path)
347 def account_pending(user, redirect_path=signin_path)
353 if Setting.self_registration == '1'
348 if Setting.self_registration == '1'
354 flash[:error] = l(:notice_account_not_activated_yet, :url => activation_email_path)
349 flash[:error] = l(:notice_account_not_activated_yet, :url => activation_email_path)
355 session[:registered_user_id] = user.id
350 session[:registered_user_id] = user.id
356 else
351 else
357 flash[:error] = l(:notice_account_pending)
352 flash[:error] = l(:notice_account_pending)
358 end
353 end
359 redirect_to redirect_path
354 redirect_to redirect_path
360 end
355 end
361
356
362 def account_locked(user, redirect_path=signin_path)
357 def account_locked(user, redirect_path=signin_path)
363 flash[:error] = l(:notice_account_locked)
358 flash[:error] = l(:notice_account_locked)
364 redirect_to redirect_path
359 redirect_to redirect_path
365 end
360 end
366 end
361 end
@@ -1,216 +1,211
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
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
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.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class MyController < ApplicationController
18 class MyController < ApplicationController
19 before_filter :require_login
19 before_filter :require_login
20 # let user change user's password when user has to
20 # let user change user's password when user has to
21 skip_before_filter :check_password_change, :only => :password
21 skip_before_filter :check_password_change, :only => :password
22
22
23 require_sudo_mode :account, only: :post
23 require_sudo_mode :account, only: :post
24 require_sudo_mode :reset_rss_key, :reset_api_key, :show_api_key, :destroy
24 require_sudo_mode :reset_rss_key, :reset_api_key, :show_api_key, :destroy
25
25
26 helper :issues
26 helper :issues
27 helper :users
27 helper :users
28 helper :custom_fields
28 helper :custom_fields
29
29
30 BLOCKS = { 'issuesassignedtome' => :label_assigned_to_me_issues,
30 BLOCKS = { 'issuesassignedtome' => :label_assigned_to_me_issues,
31 'issuesreportedbyme' => :label_reported_issues,
31 'issuesreportedbyme' => :label_reported_issues,
32 'issueswatched' => :label_watched_issues,
32 'issueswatched' => :label_watched_issues,
33 'news' => :label_news_latest,
33 'news' => :label_news_latest,
34 'calendar' => :label_calendar,
34 'calendar' => :label_calendar,
35 'documents' => :label_document_plural,
35 'documents' => :label_document_plural,
36 'timelog' => :label_spent_time
36 'timelog' => :label_spent_time
37 }.merge(Redmine::Views::MyPage::Block.additional_blocks).freeze
37 }.merge(Redmine::Views::MyPage::Block.additional_blocks).freeze
38
38
39 DEFAULT_LAYOUT = { 'left' => ['issuesassignedtome'],
39 DEFAULT_LAYOUT = { 'left' => ['issuesassignedtome'],
40 'right' => ['issuesreportedbyme']
40 'right' => ['issuesreportedbyme']
41 }.freeze
41 }.freeze
42
42
43 def index
43 def index
44 page
44 page
45 render :action => 'page'
45 render :action => 'page'
46 end
46 end
47
47
48 # Show user's page
48 # Show user's page
49 def page
49 def page
50 @user = User.current
50 @user = User.current
51 @blocks = @user.pref[:my_page_layout] || DEFAULT_LAYOUT
51 @blocks = @user.pref[:my_page_layout] || DEFAULT_LAYOUT
52 end
52 end
53
53
54 # Edit user's account
54 # Edit user's account
55 def account
55 def account
56 @user = User.current
56 @user = User.current
57 @pref = @user.pref
57 @pref = @user.pref
58 if request.post?
58 if request.post?
59 @user.safe_attributes = params[:user] if params[:user]
59 @user.safe_attributes = params[:user] if params[:user]
60 @user.pref.attributes = params[:pref] if params[:pref]
60 @user.pref.attributes = params[:pref] if params[:pref]
61 if @user.save
61 if @user.save
62 @user.pref.save
62 @user.pref.save
63 set_language_if_valid @user.language
63 set_language_if_valid @user.language
64 flash[:notice] = l(:notice_account_updated)
64 flash[:notice] = l(:notice_account_updated)
65 redirect_to my_account_path
65 redirect_to my_account_path
66 return
66 return
67 end
67 end
68 end
68 end
69 end
69 end
70
70
71 # Destroys user's account
71 # Destroys user's account
72 def destroy
72 def destroy
73 @user = User.current
73 @user = User.current
74 unless @user.own_account_deletable?
74 unless @user.own_account_deletable?
75 redirect_to my_account_path
75 redirect_to my_account_path
76 return
76 return
77 end
77 end
78
78
79 if request.post? && params[:confirm]
79 if request.post? && params[:confirm]
80 @user.destroy
80 @user.destroy
81 if @user.destroyed?
81 if @user.destroyed?
82 logout_user
82 logout_user
83 flash[:notice] = l(:notice_account_deleted)
83 flash[:notice] = l(:notice_account_deleted)
84 end
84 end
85 redirect_to home_path
85 redirect_to home_path
86 end
86 end
87 end
87 end
88
88
89 # Manage user's password
89 # Manage user's password
90 def password
90 def password
91 @user = User.current
91 @user = User.current
92 unless @user.change_password_allowed?
92 unless @user.change_password_allowed?
93 flash[:error] = l(:notice_can_t_change_password)
93 flash[:error] = l(:notice_can_t_change_password)
94 redirect_to my_account_path
94 redirect_to my_account_path
95 return
95 return
96 end
96 end
97 if request.post?
97 if request.post?
98 if !@user.check_password?(params[:password])
98 if !@user.check_password?(params[:password])
99 flash.now[:error] = l(:notice_account_wrong_password)
99 flash.now[:error] = l(:notice_account_wrong_password)
100 elsif params[:password] == params[:new_password]
100 elsif params[:password] == params[:new_password]
101 flash.now[:error] = l(:notice_new_password_must_be_different)
101 flash.now[:error] = l(:notice_new_password_must_be_different)
102 else
102 else
103 @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
103 @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
104 @user.must_change_passwd = false
104 @user.must_change_passwd = false
105 if @user.save
105 if @user.save
106 # The session token was destroyed by the password change, generate a new one
106 # The session token was destroyed by the password change, generate a new one
107 session[:tk] = @user.generate_session_token
107 session[:tk] = @user.generate_session_token
108 Mailer.security_notification(@user,
108 Mailer.password_updated(@user)
109 message: :mail_body_security_notification_change,
110 field: :field_password,
111 title: :button_change_password,
112 url: {controller: 'my', action: 'password'}
113 ).deliver
114 flash[:notice] = l(:notice_account_password_updated)
109 flash[:notice] = l(:notice_account_password_updated)
115 redirect_to my_account_path
110 redirect_to my_account_path
116 end
111 end
117 end
112 end
118 end
113 end
119 end
114 end
120
115
121 # Create a new feeds key
116 # Create a new feeds key
122 def reset_rss_key
117 def reset_rss_key
123 if request.post?
118 if request.post?
124 if User.current.rss_token
119 if User.current.rss_token
125 User.current.rss_token.destroy
120 User.current.rss_token.destroy
126 User.current.reload
121 User.current.reload
127 end
122 end
128 User.current.rss_key
123 User.current.rss_key
129 flash[:notice] = l(:notice_feeds_access_key_reseted)
124 flash[:notice] = l(:notice_feeds_access_key_reseted)
130 end
125 end
131 redirect_to my_account_path
126 redirect_to my_account_path
132 end
127 end
133
128
134 def show_api_key
129 def show_api_key
135 @user = User.current
130 @user = User.current
136 end
131 end
137
132
138 # Create a new API key
133 # Create a new API key
139 def reset_api_key
134 def reset_api_key
140 if request.post?
135 if request.post?
141 if User.current.api_token
136 if User.current.api_token
142 User.current.api_token.destroy
137 User.current.api_token.destroy
143 User.current.reload
138 User.current.reload
144 end
139 end
145 User.current.api_key
140 User.current.api_key
146 flash[:notice] = l(:notice_api_access_key_reseted)
141 flash[:notice] = l(:notice_api_access_key_reseted)
147 end
142 end
148 redirect_to my_account_path
143 redirect_to my_account_path
149 end
144 end
150
145
151 # User's page layout configuration
146 # User's page layout configuration
152 def page_layout
147 def page_layout
153 @user = User.current
148 @user = User.current
154 @blocks = @user.pref[:my_page_layout] || DEFAULT_LAYOUT.dup
149 @blocks = @user.pref[:my_page_layout] || DEFAULT_LAYOUT.dup
155 @block_options = []
150 @block_options = []
156 BLOCKS.each do |k, v|
151 BLOCKS.each do |k, v|
157 unless @blocks.values.flatten.include?(k)
152 unless @blocks.values.flatten.include?(k)
158 @block_options << [l("my.blocks.#{v}", :default => [v, v.to_s.humanize]), k.dasherize]
153 @block_options << [l("my.blocks.#{v}", :default => [v, v.to_s.humanize]), k.dasherize]
159 end
154 end
160 end
155 end
161 end
156 end
162
157
163 # Add a block to user's page
158 # Add a block to user's page
164 # The block is added on top of the page
159 # The block is added on top of the page
165 # params[:block] : id of the block to add
160 # params[:block] : id of the block to add
166 def add_block
161 def add_block
167 block = params[:block].to_s.underscore
162 block = params[:block].to_s.underscore
168 if block.present? && BLOCKS.key?(block)
163 if block.present? && BLOCKS.key?(block)
169 @user = User.current
164 @user = User.current
170 layout = @user.pref[:my_page_layout] || {}
165 layout = @user.pref[:my_page_layout] || {}
171 # remove if already present in a group
166 # remove if already present in a group
172 %w(top left right).each {|f| (layout[f] ||= []).delete block }
167 %w(top left right).each {|f| (layout[f] ||= []).delete block }
173 # add it on top
168 # add it on top
174 layout['top'].unshift block
169 layout['top'].unshift block
175 @user.pref[:my_page_layout] = layout
170 @user.pref[:my_page_layout] = layout
176 @user.pref.save
171 @user.pref.save
177 end
172 end
178 redirect_to my_page_layout_path
173 redirect_to my_page_layout_path
179 end
174 end
180
175
181 # Remove a block to user's page
176 # Remove a block to user's page
182 # params[:block] : id of the block to remove
177 # params[:block] : id of the block to remove
183 def remove_block
178 def remove_block
184 block = params[:block].to_s.underscore
179 block = params[:block].to_s.underscore
185 @user = User.current
180 @user = User.current
186 # remove block in all groups
181 # remove block in all groups
187 layout = @user.pref[:my_page_layout] || {}
182 layout = @user.pref[:my_page_layout] || {}
188 %w(top left right).each {|f| (layout[f] ||= []).delete block }
183 %w(top left right).each {|f| (layout[f] ||= []).delete block }
189 @user.pref[:my_page_layout] = layout
184 @user.pref[:my_page_layout] = layout
190 @user.pref.save
185 @user.pref.save
191 redirect_to my_page_layout_path
186 redirect_to my_page_layout_path
192 end
187 end
193
188
194 # Change blocks order on user's page
189 # Change blocks order on user's page
195 # params[:group] : group to order (top, left or right)
190 # params[:group] : group to order (top, left or right)
196 # params[:list-(top|left|right)] : array of block ids of the group
191 # params[:list-(top|left|right)] : array of block ids of the group
197 def order_blocks
192 def order_blocks
198 group = params[:group]
193 group = params[:group]
199 @user = User.current
194 @user = User.current
200 if group.is_a?(String)
195 if group.is_a?(String)
201 group_items = (params["blocks"] || []).collect(&:underscore)
196 group_items = (params["blocks"] || []).collect(&:underscore)
202 group_items.each {|s| s.sub!(/^block_/, '')}
197 group_items.each {|s| s.sub!(/^block_/, '')}
203 if group_items and group_items.is_a? Array
198 if group_items and group_items.is_a? Array
204 layout = @user.pref[:my_page_layout] || {}
199 layout = @user.pref[:my_page_layout] || {}
205 # remove group blocks if they are presents in other groups
200 # remove group blocks if they are presents in other groups
206 %w(top left right).each {|f|
201 %w(top left right).each {|f|
207 layout[f] = (layout[f] || []) - group_items
202 layout[f] = (layout[f] || []) - group_items
208 }
203 }
209 layout[group] = group_items
204 layout[group] = group_items
210 @user.pref[:my_page_layout] = layout
205 @user.pref[:my_page_layout] = layout
211 @user.pref.save
206 @user.pref.save
212 end
207 end
213 end
208 end
214 render :nothing => true
209 render :nothing => true
215 end
210 end
216 end
211 end
@@ -1,571 +1,581
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
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
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.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require 'roadie'
18 require 'roadie'
19
19
20 class Mailer < ActionMailer::Base
20 class Mailer < ActionMailer::Base
21 layout 'mailer'
21 layout 'mailer'
22 helper :application
22 helper :application
23 helper :issues
23 helper :issues
24 helper :custom_fields
24 helper :custom_fields
25
25
26 include Redmine::I18n
26 include Redmine::I18n
27 include Roadie::Rails::Automatic
27 include Roadie::Rails::Automatic
28
28
29 def self.default_url_options
29 def self.default_url_options
30 options = {:protocol => Setting.protocol}
30 options = {:protocol => Setting.protocol}
31 if Setting.host_name.to_s =~ /\A(https?\:\/\/)?(.+?)(\:(\d+))?(\/.+)?\z/i
31 if Setting.host_name.to_s =~ /\A(https?\:\/\/)?(.+?)(\:(\d+))?(\/.+)?\z/i
32 host, port, prefix = $2, $4, $5
32 host, port, prefix = $2, $4, $5
33 options.merge!({
33 options.merge!({
34 :host => host, :port => port, :script_name => prefix
34 :host => host, :port => port, :script_name => prefix
35 })
35 })
36 else
36 else
37 options[:host] = Setting.host_name
37 options[:host] = Setting.host_name
38 end
38 end
39 options
39 options
40 end
40 end
41
41
42 # Builds a mail for notifying to_users and cc_users about a new issue
42 # Builds a mail for notifying to_users and cc_users about a new issue
43 def issue_add(issue, to_users, cc_users)
43 def issue_add(issue, to_users, cc_users)
44 redmine_headers 'Project' => issue.project.identifier,
44 redmine_headers 'Project' => issue.project.identifier,
45 'Issue-Id' => issue.id,
45 'Issue-Id' => issue.id,
46 'Issue-Author' => issue.author.login
46 'Issue-Author' => issue.author.login
47 redmine_headers 'Issue-Assignee' => issue.assigned_to.login if issue.assigned_to
47 redmine_headers 'Issue-Assignee' => issue.assigned_to.login if issue.assigned_to
48 message_id issue
48 message_id issue
49 references issue
49 references issue
50 @author = issue.author
50 @author = issue.author
51 @issue = issue
51 @issue = issue
52 @users = to_users + cc_users
52 @users = to_users + cc_users
53 @issue_url = url_for(:controller => 'issues', :action => 'show', :id => issue)
53 @issue_url = url_for(:controller => 'issues', :action => 'show', :id => issue)
54 mail :to => to_users,
54 mail :to => to_users,
55 :cc => cc_users,
55 :cc => cc_users,
56 :subject => "[#{issue.project.name} - #{issue.tracker.name} ##{issue.id}] (#{issue.status.name}) #{issue.subject}"
56 :subject => "[#{issue.project.name} - #{issue.tracker.name} ##{issue.id}] (#{issue.status.name}) #{issue.subject}"
57 end
57 end
58
58
59 # Notifies users about a new issue
59 # Notifies users about a new issue
60 def self.deliver_issue_add(issue)
60 def self.deliver_issue_add(issue)
61 to = issue.notified_users
61 to = issue.notified_users
62 cc = issue.notified_watchers - to
62 cc = issue.notified_watchers - to
63 issue.each_notification(to + cc) do |users|
63 issue.each_notification(to + cc) do |users|
64 Mailer.issue_add(issue, to & users, cc & users).deliver
64 Mailer.issue_add(issue, to & users, cc & users).deliver
65 end
65 end
66 end
66 end
67
67
68 # Builds a mail for notifying to_users and cc_users about an issue update
68 # Builds a mail for notifying to_users and cc_users about an issue update
69 def issue_edit(journal, to_users, cc_users)
69 def issue_edit(journal, to_users, cc_users)
70 issue = journal.journalized
70 issue = journal.journalized
71 redmine_headers 'Project' => issue.project.identifier,
71 redmine_headers 'Project' => issue.project.identifier,
72 'Issue-Id' => issue.id,
72 'Issue-Id' => issue.id,
73 'Issue-Author' => issue.author.login
73 'Issue-Author' => issue.author.login
74 redmine_headers 'Issue-Assignee' => issue.assigned_to.login if issue.assigned_to
74 redmine_headers 'Issue-Assignee' => issue.assigned_to.login if issue.assigned_to
75 message_id journal
75 message_id journal
76 references issue
76 references issue
77 @author = journal.user
77 @author = journal.user
78 s = "[#{issue.project.name} - #{issue.tracker.name} ##{issue.id}] "
78 s = "[#{issue.project.name} - #{issue.tracker.name} ##{issue.id}] "
79 s << "(#{issue.status.name}) " if journal.new_value_for('status_id')
79 s << "(#{issue.status.name}) " if journal.new_value_for('status_id')
80 s << issue.subject
80 s << issue.subject
81 @issue = issue
81 @issue = issue
82 @users = to_users + cc_users
82 @users = to_users + cc_users
83 @journal = journal
83 @journal = journal
84 @journal_details = journal.visible_details(@users.first)
84 @journal_details = journal.visible_details(@users.first)
85 @issue_url = url_for(:controller => 'issues', :action => 'show', :id => issue, :anchor => "change-#{journal.id}")
85 @issue_url = url_for(:controller => 'issues', :action => 'show', :id => issue, :anchor => "change-#{journal.id}")
86 mail :to => to_users,
86 mail :to => to_users,
87 :cc => cc_users,
87 :cc => cc_users,
88 :subject => s
88 :subject => s
89 end
89 end
90
90
91 # Notifies users about an issue update
91 # Notifies users about an issue update
92 def self.deliver_issue_edit(journal)
92 def self.deliver_issue_edit(journal)
93 issue = journal.journalized.reload
93 issue = journal.journalized.reload
94 to = journal.notified_users
94 to = journal.notified_users
95 cc = journal.notified_watchers - to
95 cc = journal.notified_watchers - to
96 journal.each_notification(to + cc) do |users|
96 journal.each_notification(to + cc) do |users|
97 issue.each_notification(users) do |users2|
97 issue.each_notification(users) do |users2|
98 Mailer.issue_edit(journal, to & users2, cc & users2).deliver
98 Mailer.issue_edit(journal, to & users2, cc & users2).deliver
99 end
99 end
100 end
100 end
101 end
101 end
102
102
103 def reminder(user, issues, days)
103 def reminder(user, issues, days)
104 set_language_if_valid user.language
104 set_language_if_valid user.language
105 @issues = issues
105 @issues = issues
106 @days = days
106 @days = days
107 @issues_url = url_for(:controller => 'issues', :action => 'index',
107 @issues_url = url_for(:controller => 'issues', :action => 'index',
108 :set_filter => 1, :assigned_to_id => user.id,
108 :set_filter => 1, :assigned_to_id => user.id,
109 :sort => 'due_date:asc')
109 :sort => 'due_date:asc')
110 mail :to => user,
110 mail :to => user,
111 :subject => l(:mail_subject_reminder, :count => issues.size, :days => days)
111 :subject => l(:mail_subject_reminder, :count => issues.size, :days => days)
112 end
112 end
113
113
114 # Builds a Mail::Message object used to email users belonging to the added document's project.
114 # Builds a Mail::Message object used to email users belonging to the added document's project.
115 #
115 #
116 # Example:
116 # Example:
117 # document_added(document) => Mail::Message object
117 # document_added(document) => Mail::Message object
118 # Mailer.document_added(document).deliver => sends an email to the document's project recipients
118 # Mailer.document_added(document).deliver => sends an email to the document's project recipients
119 def document_added(document)
119 def document_added(document)
120 redmine_headers 'Project' => document.project.identifier
120 redmine_headers 'Project' => document.project.identifier
121 @author = User.current
121 @author = User.current
122 @document = document
122 @document = document
123 @document_url = url_for(:controller => 'documents', :action => 'show', :id => document)
123 @document_url = url_for(:controller => 'documents', :action => 'show', :id => document)
124 mail :to => document.notified_users,
124 mail :to => document.notified_users,
125 :subject => "[#{document.project.name}] #{l(:label_document_new)}: #{document.title}"
125 :subject => "[#{document.project.name}] #{l(:label_document_new)}: #{document.title}"
126 end
126 end
127
127
128 # Builds a Mail::Message object used to email recipients of a project when an attachements are added.
128 # Builds a Mail::Message object used to email recipients of a project when an attachements are added.
129 #
129 #
130 # Example:
130 # Example:
131 # attachments_added(attachments) => Mail::Message object
131 # attachments_added(attachments) => Mail::Message object
132 # Mailer.attachments_added(attachments).deliver => sends an email to the project's recipients
132 # Mailer.attachments_added(attachments).deliver => sends an email to the project's recipients
133 def attachments_added(attachments)
133 def attachments_added(attachments)
134 container = attachments.first.container
134 container = attachments.first.container
135 added_to = ''
135 added_to = ''
136 added_to_url = ''
136 added_to_url = ''
137 @author = attachments.first.author
137 @author = attachments.first.author
138 case container.class.name
138 case container.class.name
139 when 'Project'
139 when 'Project'
140 added_to_url = url_for(:controller => 'files', :action => 'index', :project_id => container)
140 added_to_url = url_for(:controller => 'files', :action => 'index', :project_id => container)
141 added_to = "#{l(:label_project)}: #{container}"
141 added_to = "#{l(:label_project)}: #{container}"
142 recipients = container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}
142 recipients = container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}
143 when 'Version'
143 when 'Version'
144 added_to_url = url_for(:controller => 'files', :action => 'index', :project_id => container.project)
144 added_to_url = url_for(:controller => 'files', :action => 'index', :project_id => container.project)
145 added_to = "#{l(:label_version)}: #{container.name}"
145 added_to = "#{l(:label_version)}: #{container.name}"
146 recipients = container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}
146 recipients = container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}
147 when 'Document'
147 when 'Document'
148 added_to_url = url_for(:controller => 'documents', :action => 'show', :id => container.id)
148 added_to_url = url_for(:controller => 'documents', :action => 'show', :id => container.id)
149 added_to = "#{l(:label_document)}: #{container.title}"
149 added_to = "#{l(:label_document)}: #{container.title}"
150 recipients = container.notified_users
150 recipients = container.notified_users
151 end
151 end
152 redmine_headers 'Project' => container.project.identifier
152 redmine_headers 'Project' => container.project.identifier
153 @attachments = attachments
153 @attachments = attachments
154 @added_to = added_to
154 @added_to = added_to
155 @added_to_url = added_to_url
155 @added_to_url = added_to_url
156 mail :to => recipients,
156 mail :to => recipients,
157 :subject => "[#{container.project.name}] #{l(:label_attachment_new)}"
157 :subject => "[#{container.project.name}] #{l(:label_attachment_new)}"
158 end
158 end
159
159
160 # Builds a Mail::Message object used to email recipients of a news' project when a news item is added.
160 # Builds a Mail::Message object used to email recipients of a news' project when a news item is added.
161 #
161 #
162 # Example:
162 # Example:
163 # news_added(news) => Mail::Message object
163 # news_added(news) => Mail::Message object
164 # Mailer.news_added(news).deliver => sends an email to the news' project recipients
164 # Mailer.news_added(news).deliver => sends an email to the news' project recipients
165 def news_added(news)
165 def news_added(news)
166 redmine_headers 'Project' => news.project.identifier
166 redmine_headers 'Project' => news.project.identifier
167 @author = news.author
167 @author = news.author
168 message_id news
168 message_id news
169 references news
169 references news
170 @news = news
170 @news = news
171 @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
171 @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
172 mail :to => news.notified_users,
172 mail :to => news.notified_users,
173 :cc => news.notified_watchers_for_added_news,
173 :cc => news.notified_watchers_for_added_news,
174 :subject => "[#{news.project.name}] #{l(:label_news)}: #{news.title}"
174 :subject => "[#{news.project.name}] #{l(:label_news)}: #{news.title}"
175 end
175 end
176
176
177 # Builds a Mail::Message object used to email recipients of a news' project when a news comment is added.
177 # Builds a Mail::Message object used to email recipients of a news' project when a news comment is added.
178 #
178 #
179 # Example:
179 # Example:
180 # news_comment_added(comment) => Mail::Message object
180 # news_comment_added(comment) => Mail::Message object
181 # Mailer.news_comment_added(comment) => sends an email to the news' project recipients
181 # Mailer.news_comment_added(comment) => sends an email to the news' project recipients
182 def news_comment_added(comment)
182 def news_comment_added(comment)
183 news = comment.commented
183 news = comment.commented
184 redmine_headers 'Project' => news.project.identifier
184 redmine_headers 'Project' => news.project.identifier
185 @author = comment.author
185 @author = comment.author
186 message_id comment
186 message_id comment
187 references news
187 references news
188 @news = news
188 @news = news
189 @comment = comment
189 @comment = comment
190 @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
190 @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
191 mail :to => news.notified_users,
191 mail :to => news.notified_users,
192 :cc => news.notified_watchers,
192 :cc => news.notified_watchers,
193 :subject => "Re: [#{news.project.name}] #{l(:label_news)}: #{news.title}"
193 :subject => "Re: [#{news.project.name}] #{l(:label_news)}: #{news.title}"
194 end
194 end
195
195
196 # Builds a Mail::Message object used to email the recipients of the specified message that was posted.
196 # Builds a Mail::Message object used to email the recipients of the specified message that was posted.
197 #
197 #
198 # Example:
198 # Example:
199 # message_posted(message) => Mail::Message object
199 # message_posted(message) => Mail::Message object
200 # Mailer.message_posted(message).deliver => sends an email to the recipients
200 # Mailer.message_posted(message).deliver => sends an email to the recipients
201 def message_posted(message)
201 def message_posted(message)
202 redmine_headers 'Project' => message.project.identifier,
202 redmine_headers 'Project' => message.project.identifier,
203 'Topic-Id' => (message.parent_id || message.id)
203 'Topic-Id' => (message.parent_id || message.id)
204 @author = message.author
204 @author = message.author
205 message_id message
205 message_id message
206 references message.root
206 references message.root
207 recipients = message.notified_users
207 recipients = message.notified_users
208 cc = ((message.root.notified_watchers + message.board.notified_watchers).uniq - recipients)
208 cc = ((message.root.notified_watchers + message.board.notified_watchers).uniq - recipients)
209 @message = message
209 @message = message
210 @message_url = url_for(message.event_url)
210 @message_url = url_for(message.event_url)
211 mail :to => recipients,
211 mail :to => recipients,
212 :cc => cc,
212 :cc => cc,
213 :subject => "[#{message.board.project.name} - #{message.board.name} - msg#{message.root.id}] #{message.subject}"
213 :subject => "[#{message.board.project.name} - #{message.board.name} - msg#{message.root.id}] #{message.subject}"
214 end
214 end
215
215
216 # Builds a Mail::Message object used to email the recipients of a project of the specified wiki content was added.
216 # Builds a Mail::Message object used to email the recipients of a project of the specified wiki content was added.
217 #
217 #
218 # Example:
218 # Example:
219 # wiki_content_added(wiki_content) => Mail::Message object
219 # wiki_content_added(wiki_content) => Mail::Message object
220 # Mailer.wiki_content_added(wiki_content).deliver => sends an email to the project's recipients
220 # Mailer.wiki_content_added(wiki_content).deliver => sends an email to the project's recipients
221 def wiki_content_added(wiki_content)
221 def wiki_content_added(wiki_content)
222 redmine_headers 'Project' => wiki_content.project.identifier,
222 redmine_headers 'Project' => wiki_content.project.identifier,
223 'Wiki-Page-Id' => wiki_content.page.id
223 'Wiki-Page-Id' => wiki_content.page.id
224 @author = wiki_content.author
224 @author = wiki_content.author
225 message_id wiki_content
225 message_id wiki_content
226 recipients = wiki_content.notified_users
226 recipients = wiki_content.notified_users
227 cc = wiki_content.page.wiki.notified_watchers - recipients
227 cc = wiki_content.page.wiki.notified_watchers - recipients
228 @wiki_content = wiki_content
228 @wiki_content = wiki_content
229 @wiki_content_url = url_for(:controller => 'wiki', :action => 'show',
229 @wiki_content_url = url_for(:controller => 'wiki', :action => 'show',
230 :project_id => wiki_content.project,
230 :project_id => wiki_content.project,
231 :id => wiki_content.page.title)
231 :id => wiki_content.page.title)
232 mail :to => recipients,
232 mail :to => recipients,
233 :cc => cc,
233 :cc => cc,
234 :subject => "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_added, :id => wiki_content.page.pretty_title)}"
234 :subject => "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_added, :id => wiki_content.page.pretty_title)}"
235 end
235 end
236
236
237 # Builds a Mail::Message object used to email the recipients of a project of the specified wiki content was updated.
237 # Builds a Mail::Message object used to email the recipients of a project of the specified wiki content was updated.
238 #
238 #
239 # Example:
239 # Example:
240 # wiki_content_updated(wiki_content) => Mail::Message object
240 # wiki_content_updated(wiki_content) => Mail::Message object
241 # Mailer.wiki_content_updated(wiki_content).deliver => sends an email to the project's recipients
241 # Mailer.wiki_content_updated(wiki_content).deliver => sends an email to the project's recipients
242 def wiki_content_updated(wiki_content)
242 def wiki_content_updated(wiki_content)
243 redmine_headers 'Project' => wiki_content.project.identifier,
243 redmine_headers 'Project' => wiki_content.project.identifier,
244 'Wiki-Page-Id' => wiki_content.page.id
244 'Wiki-Page-Id' => wiki_content.page.id
245 @author = wiki_content.author
245 @author = wiki_content.author
246 message_id wiki_content
246 message_id wiki_content
247 recipients = wiki_content.notified_users
247 recipients = wiki_content.notified_users
248 cc = wiki_content.page.wiki.notified_watchers + wiki_content.page.notified_watchers - recipients
248 cc = wiki_content.page.wiki.notified_watchers + wiki_content.page.notified_watchers - recipients
249 @wiki_content = wiki_content
249 @wiki_content = wiki_content
250 @wiki_content_url = url_for(:controller => 'wiki', :action => 'show',
250 @wiki_content_url = url_for(:controller => 'wiki', :action => 'show',
251 :project_id => wiki_content.project,
251 :project_id => wiki_content.project,
252 :id => wiki_content.page.title)
252 :id => wiki_content.page.title)
253 @wiki_diff_url = url_for(:controller => 'wiki', :action => 'diff',
253 @wiki_diff_url = url_for(:controller => 'wiki', :action => 'diff',
254 :project_id => wiki_content.project, :id => wiki_content.page.title,
254 :project_id => wiki_content.project, :id => wiki_content.page.title,
255 :version => wiki_content.version)
255 :version => wiki_content.version)
256 mail :to => recipients,
256 mail :to => recipients,
257 :cc => cc,
257 :cc => cc,
258 :subject => "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_updated, :id => wiki_content.page.pretty_title)}"
258 :subject => "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_updated, :id => wiki_content.page.pretty_title)}"
259 end
259 end
260
260
261 # Builds a Mail::Message object used to email the specified user their account information.
261 # Builds a Mail::Message object used to email the specified user their account information.
262 #
262 #
263 # Example:
263 # Example:
264 # account_information(user, password) => Mail::Message object
264 # account_information(user, password) => Mail::Message object
265 # Mailer.account_information(user, password).deliver => sends account information to the user
265 # Mailer.account_information(user, password).deliver => sends account information to the user
266 def account_information(user, password)
266 def account_information(user, password)
267 set_language_if_valid user.language
267 set_language_if_valid user.language
268 @user = user
268 @user = user
269 @password = password
269 @password = password
270 @login_url = url_for(:controller => 'account', :action => 'login')
270 @login_url = url_for(:controller => 'account', :action => 'login')
271 mail :to => user.mail,
271 mail :to => user.mail,
272 :subject => l(:mail_subject_register, Setting.app_title)
272 :subject => l(:mail_subject_register, Setting.app_title)
273 end
273 end
274
274
275 # Builds a Mail::Message object used to email all active administrators of an account activation request.
275 # Builds a Mail::Message object used to email all active administrators of an account activation request.
276 #
276 #
277 # Example:
277 # Example:
278 # account_activation_request(user) => Mail::Message object
278 # account_activation_request(user) => Mail::Message object
279 # Mailer.account_activation_request(user).deliver => sends an email to all active administrators
279 # Mailer.account_activation_request(user).deliver => sends an email to all active administrators
280 def account_activation_request(user)
280 def account_activation_request(user)
281 # Send the email to all active administrators
281 # Send the email to all active administrators
282 recipients = User.active.where(:admin => true)
282 recipients = User.active.where(:admin => true)
283 @user = user
283 @user = user
284 @url = url_for(:controller => 'users', :action => 'index',
284 @url = url_for(:controller => 'users', :action => 'index',
285 :status => User::STATUS_REGISTERED,
285 :status => User::STATUS_REGISTERED,
286 :sort_key => 'created_on', :sort_order => 'desc')
286 :sort_key => 'created_on', :sort_order => 'desc')
287 mail :to => recipients,
287 mail :to => recipients,
288 :subject => l(:mail_subject_account_activation_request, Setting.app_title)
288 :subject => l(:mail_subject_account_activation_request, Setting.app_title)
289 end
289 end
290
290
291 # Builds a Mail::Message object used to email the specified user that their account was activated by an administrator.
291 # Builds a Mail::Message object used to email the specified user that their account was activated by an administrator.
292 #
292 #
293 # Example:
293 # Example:
294 # account_activated(user) => Mail::Message object
294 # account_activated(user) => Mail::Message object
295 # Mailer.account_activated(user).deliver => sends an email to the registered user
295 # Mailer.account_activated(user).deliver => sends an email to the registered user
296 def account_activated(user)
296 def account_activated(user)
297 set_language_if_valid user.language
297 set_language_if_valid user.language
298 @user = user
298 @user = user
299 @login_url = url_for(:controller => 'account', :action => 'login')
299 @login_url = url_for(:controller => 'account', :action => 'login')
300 mail :to => user.mail,
300 mail :to => user.mail,
301 :subject => l(:mail_subject_register, Setting.app_title)
301 :subject => l(:mail_subject_register, Setting.app_title)
302 end
302 end
303
303
304 def lost_password(token, recipient=nil)
304 def lost_password(token, recipient=nil)
305 set_language_if_valid(token.user.language)
305 set_language_if_valid(token.user.language)
306 recipient ||= token.user.mail
306 recipient ||= token.user.mail
307 @token = token
307 @token = token
308 @url = url_for(:controller => 'account', :action => 'lost_password', :token => token.value)
308 @url = url_for(:controller => 'account', :action => 'lost_password', :token => token.value)
309 mail :to => recipient,
309 mail :to => recipient,
310 :subject => l(:mail_subject_lost_password, Setting.app_title)
310 :subject => l(:mail_subject_lost_password, Setting.app_title)
311 end
311 end
312
312
313 # Notifies user that his password was updated
314 def self.password_updated(user)
315 Mailer.security_notification(user,
316 message: :mail_body_security_notification_change,
317 field: :field_password,
318 title: :button_change_password,
319 url: {controller: 'my', action: 'password'}
320 ).deliver
321 end
322
313 def register(token)
323 def register(token)
314 set_language_if_valid(token.user.language)
324 set_language_if_valid(token.user.language)
315 @token = token
325 @token = token
316 @url = url_for(:controller => 'account', :action => 'activate', :token => token.value)
326 @url = url_for(:controller => 'account', :action => 'activate', :token => token.value)
317 mail :to => token.user.mail,
327 mail :to => token.user.mail,
318 :subject => l(:mail_subject_register, Setting.app_title)
328 :subject => l(:mail_subject_register, Setting.app_title)
319 end
329 end
320
330
321 def security_notification(recipients, options={})
331 def security_notification(recipients, options={})
322 redmine_headers 'Sender' => User.current.login
332 redmine_headers 'Sender' => User.current.login
323 @user = Array(recipients).detect{|r| r.is_a? User }
333 @user = Array(recipients).detect{|r| r.is_a? User }
324 set_language_if_valid(@user.try :language)
334 set_language_if_valid(@user.try :language)
325 @message = l(options[:message],
335 @message = l(options[:message],
326 field: (options[:field] && l(options[:field])),
336 field: (options[:field] && l(options[:field])),
327 value: options[:value]
337 value: options[:value]
328 )
338 )
329 @title = options[:title] && l(options[:title])
339 @title = options[:title] && l(options[:title])
330 @url = options[:url] && (options[:url].is_a?(Hash) ? url_for(options[:url]) : options[:url])
340 @url = options[:url] && (options[:url].is_a?(Hash) ? url_for(options[:url]) : options[:url])
331 mail :to => recipients,
341 mail :to => recipients,
332 :subject => l(:mail_subject_security_notification)
342 :subject => l(:mail_subject_security_notification)
333 end
343 end
334
344
335 def settings_updated(recipients, changes)
345 def settings_updated(recipients, changes)
336 redmine_headers 'Sender' => User.current.login
346 redmine_headers 'Sender' => User.current.login
337 @changes = changes
347 @changes = changes
338 @url = url_for(controller: 'settings', action: 'index')
348 @url = url_for(controller: 'settings', action: 'index')
339 mail :to => recipients,
349 mail :to => recipients,
340 :subject => l(:mail_subject_security_notification)
350 :subject => l(:mail_subject_security_notification)
341 end
351 end
342
352
343 # Notifies admins about settings changes
353 # Notifies admins about settings changes
344 def self.security_settings_updated(changes)
354 def self.security_settings_updated(changes)
345 return unless changes.present?
355 return unless changes.present?
346
356
347 users = User.active.where(admin: true).to_a
357 users = User.active.where(admin: true).to_a
348 Mailer.settings_updated(users, changes).deliver
358 Mailer.settings_updated(users, changes).deliver
349 end
359 end
350
360
351 def test_email(user)
361 def test_email(user)
352 set_language_if_valid(user.language)
362 set_language_if_valid(user.language)
353 @url = url_for(:controller => 'welcome')
363 @url = url_for(:controller => 'welcome')
354 mail :to => user.mail,
364 mail :to => user.mail,
355 :subject => 'Redmine test'
365 :subject => 'Redmine test'
356 end
366 end
357
367
358 # Sends reminders to issue assignees
368 # Sends reminders to issue assignees
359 # Available options:
369 # Available options:
360 # * :days => how many days in the future to remind about (defaults to 7)
370 # * :days => how many days in the future to remind about (defaults to 7)
361 # * :tracker => id of tracker for filtering issues (defaults to all trackers)
371 # * :tracker => id of tracker for filtering issues (defaults to all trackers)
362 # * :project => id or identifier of project to process (defaults to all projects)
372 # * :project => id or identifier of project to process (defaults to all projects)
363 # * :users => array of user/group ids who should be reminded
373 # * :users => array of user/group ids who should be reminded
364 # * :version => name of target version for filtering issues (defaults to none)
374 # * :version => name of target version for filtering issues (defaults to none)
365 def self.reminders(options={})
375 def self.reminders(options={})
366 days = options[:days] || 7
376 days = options[:days] || 7
367 project = options[:project] ? Project.find(options[:project]) : nil
377 project = options[:project] ? Project.find(options[:project]) : nil
368 tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil
378 tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil
369 target_version_id = options[:version] ? Version.named(options[:version]).pluck(:id) : nil
379 target_version_id = options[:version] ? Version.named(options[:version]).pluck(:id) : nil
370 if options[:version] && target_version_id.blank?
380 if options[:version] && target_version_id.blank?
371 raise ActiveRecord::RecordNotFound.new("Couldn't find Version with named #{options[:version]}")
381 raise ActiveRecord::RecordNotFound.new("Couldn't find Version with named #{options[:version]}")
372 end
382 end
373 user_ids = options[:users]
383 user_ids = options[:users]
374
384
375 scope = Issue.open.where("#{Issue.table_name}.assigned_to_id IS NOT NULL" +
385 scope = Issue.open.where("#{Issue.table_name}.assigned_to_id IS NOT NULL" +
376 " AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" +
386 " AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" +
377 " AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date
387 " AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date
378 )
388 )
379 scope = scope.where(:assigned_to_id => user_ids) if user_ids.present?
389 scope = scope.where(:assigned_to_id => user_ids) if user_ids.present?
380 scope = scope.where(:project_id => project.id) if project
390 scope = scope.where(:project_id => project.id) if project
381 scope = scope.where(:fixed_version_id => target_version_id) if target_version_id.present?
391 scope = scope.where(:fixed_version_id => target_version_id) if target_version_id.present?
382 scope = scope.where(:tracker_id => tracker.id) if tracker
392 scope = scope.where(:tracker_id => tracker.id) if tracker
383 issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker).
393 issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker).
384 group_by(&:assigned_to)
394 group_by(&:assigned_to)
385 issues_by_assignee.keys.each do |assignee|
395 issues_by_assignee.keys.each do |assignee|
386 if assignee.is_a?(Group)
396 if assignee.is_a?(Group)
387 assignee.users.each do |user|
397 assignee.users.each do |user|
388 issues_by_assignee[user] ||= []
398 issues_by_assignee[user] ||= []
389 issues_by_assignee[user] += issues_by_assignee[assignee]
399 issues_by_assignee[user] += issues_by_assignee[assignee]
390 end
400 end
391 end
401 end
392 end
402 end
393
403
394 issues_by_assignee.each do |assignee, issues|
404 issues_by_assignee.each do |assignee, issues|
395 reminder(assignee, issues, days).deliver if assignee.is_a?(User) && assignee.active?
405 reminder(assignee, issues, days).deliver if assignee.is_a?(User) && assignee.active?
396 end
406 end
397 end
407 end
398
408
399 # Activates/desactivates email deliveries during +block+
409 # Activates/desactivates email deliveries during +block+
400 def self.with_deliveries(enabled = true, &block)
410 def self.with_deliveries(enabled = true, &block)
401 was_enabled = ActionMailer::Base.perform_deliveries
411 was_enabled = ActionMailer::Base.perform_deliveries
402 ActionMailer::Base.perform_deliveries = !!enabled
412 ActionMailer::Base.perform_deliveries = !!enabled
403 yield
413 yield
404 ensure
414 ensure
405 ActionMailer::Base.perform_deliveries = was_enabled
415 ActionMailer::Base.perform_deliveries = was_enabled
406 end
416 end
407
417
408 # Sends emails synchronously in the given block
418 # Sends emails synchronously in the given block
409 def self.with_synched_deliveries(&block)
419 def self.with_synched_deliveries(&block)
410 saved_method = ActionMailer::Base.delivery_method
420 saved_method = ActionMailer::Base.delivery_method
411 if m = saved_method.to_s.match(%r{^async_(.+)$})
421 if m = saved_method.to_s.match(%r{^async_(.+)$})
412 synched_method = m[1]
422 synched_method = m[1]
413 ActionMailer::Base.delivery_method = synched_method.to_sym
423 ActionMailer::Base.delivery_method = synched_method.to_sym
414 ActionMailer::Base.send "#{synched_method}_settings=", ActionMailer::Base.send("async_#{synched_method}_settings")
424 ActionMailer::Base.send "#{synched_method}_settings=", ActionMailer::Base.send("async_#{synched_method}_settings")
415 end
425 end
416 yield
426 yield
417 ensure
427 ensure
418 ActionMailer::Base.delivery_method = saved_method
428 ActionMailer::Base.delivery_method = saved_method
419 end
429 end
420
430
421 def mail(headers={}, &block)
431 def mail(headers={}, &block)
422 headers.reverse_merge! 'X-Mailer' => 'Redmine',
432 headers.reverse_merge! 'X-Mailer' => 'Redmine',
423 'X-Redmine-Host' => Setting.host_name,
433 'X-Redmine-Host' => Setting.host_name,
424 'X-Redmine-Site' => Setting.app_title,
434 'X-Redmine-Site' => Setting.app_title,
425 'X-Auto-Response-Suppress' => 'All',
435 'X-Auto-Response-Suppress' => 'All',
426 'Auto-Submitted' => 'auto-generated',
436 'Auto-Submitted' => 'auto-generated',
427 'From' => Setting.mail_from,
437 'From' => Setting.mail_from,
428 'List-Id' => "<#{Setting.mail_from.to_s.gsub('@', '.')}>"
438 'List-Id' => "<#{Setting.mail_from.to_s.gsub('@', '.')}>"
429
439
430 # Replaces users with their email addresses
440 # Replaces users with their email addresses
431 [:to, :cc, :bcc].each do |key|
441 [:to, :cc, :bcc].each do |key|
432 if headers[key].present?
442 if headers[key].present?
433 headers[key] = self.class.email_addresses(headers[key])
443 headers[key] = self.class.email_addresses(headers[key])
434 end
444 end
435 end
445 end
436
446
437 # Removes the author from the recipients and cc
447 # Removes the author from the recipients and cc
438 # if the author does not want to receive notifications
448 # if the author does not want to receive notifications
439 # about what the author do
449 # about what the author do
440 if @author && @author.logged? && @author.pref.no_self_notified
450 if @author && @author.logged? && @author.pref.no_self_notified
441 addresses = @author.mails
451 addresses = @author.mails
442 headers[:to] -= addresses if headers[:to].is_a?(Array)
452 headers[:to] -= addresses if headers[:to].is_a?(Array)
443 headers[:cc] -= addresses if headers[:cc].is_a?(Array)
453 headers[:cc] -= addresses if headers[:cc].is_a?(Array)
444 end
454 end
445
455
446 if @author && @author.logged?
456 if @author && @author.logged?
447 redmine_headers 'Sender' => @author.login
457 redmine_headers 'Sender' => @author.login
448 end
458 end
449
459
450 # Blind carbon copy recipients
460 # Blind carbon copy recipients
451 if Setting.bcc_recipients?
461 if Setting.bcc_recipients?
452 headers[:bcc] = [headers[:to], headers[:cc]].flatten.uniq.reject(&:blank?)
462 headers[:bcc] = [headers[:to], headers[:cc]].flatten.uniq.reject(&:blank?)
453 headers[:to] = nil
463 headers[:to] = nil
454 headers[:cc] = nil
464 headers[:cc] = nil
455 end
465 end
456
466
457 if @message_id_object
467 if @message_id_object
458 headers[:message_id] = "<#{self.class.message_id_for(@message_id_object)}>"
468 headers[:message_id] = "<#{self.class.message_id_for(@message_id_object)}>"
459 end
469 end
460 if @references_objects
470 if @references_objects
461 headers[:references] = @references_objects.collect {|o| "<#{self.class.references_for(o)}>"}.join(' ')
471 headers[:references] = @references_objects.collect {|o| "<#{self.class.references_for(o)}>"}.join(' ')
462 end
472 end
463
473
464 m = if block_given?
474 m = if block_given?
465 super headers, &block
475 super headers, &block
466 else
476 else
467 super headers do |format|
477 super headers do |format|
468 format.text
478 format.text
469 format.html unless Setting.plain_text_mail?
479 format.html unless Setting.plain_text_mail?
470 end
480 end
471 end
481 end
472 set_language_if_valid @initial_language
482 set_language_if_valid @initial_language
473
483
474 m
484 m
475 end
485 end
476
486
477 def initialize(*args)
487 def initialize(*args)
478 @initial_language = current_language
488 @initial_language = current_language
479 set_language_if_valid Setting.default_language
489 set_language_if_valid Setting.default_language
480 super
490 super
481 end
491 end
482
492
483 def self.deliver_mail(mail)
493 def self.deliver_mail(mail)
484 return false if mail.to.blank? && mail.cc.blank? && mail.bcc.blank?
494 return false if mail.to.blank? && mail.cc.blank? && mail.bcc.blank?
485 begin
495 begin
486 # Log errors when raise_delivery_errors is set to false, Rails does not
496 # Log errors when raise_delivery_errors is set to false, Rails does not
487 mail.raise_delivery_errors = true
497 mail.raise_delivery_errors = true
488 super
498 super
489 rescue Exception => e
499 rescue Exception => e
490 if ActionMailer::Base.raise_delivery_errors
500 if ActionMailer::Base.raise_delivery_errors
491 raise e
501 raise e
492 else
502 else
493 Rails.logger.error "Email delivery error: #{e.message}"
503 Rails.logger.error "Email delivery error: #{e.message}"
494 end
504 end
495 end
505 end
496 end
506 end
497
507
498 def self.method_missing(method, *args, &block)
508 def self.method_missing(method, *args, &block)
499 if m = method.to_s.match(%r{^deliver_(.+)$})
509 if m = method.to_s.match(%r{^deliver_(.+)$})
500 ActiveSupport::Deprecation.warn "Mailer.deliver_#{m[1]}(*args) is deprecated. Use Mailer.#{m[1]}(*args).deliver instead."
510 ActiveSupport::Deprecation.warn "Mailer.deliver_#{m[1]}(*args) is deprecated. Use Mailer.#{m[1]}(*args).deliver instead."
501 send(m[1], *args).deliver
511 send(m[1], *args).deliver
502 else
512 else
503 super
513 super
504 end
514 end
505 end
515 end
506
516
507 # Returns an array of email addresses to notify by
517 # Returns an array of email addresses to notify by
508 # replacing users in arg with their notified email addresses
518 # replacing users in arg with their notified email addresses
509 #
519 #
510 # Example:
520 # Example:
511 # Mailer.email_addresses(users)
521 # Mailer.email_addresses(users)
512 # => ["foo@example.net", "bar@example.net"]
522 # => ["foo@example.net", "bar@example.net"]
513 def self.email_addresses(arg)
523 def self.email_addresses(arg)
514 arr = Array.wrap(arg)
524 arr = Array.wrap(arg)
515 mails = arr.reject {|a| a.is_a? Principal}
525 mails = arr.reject {|a| a.is_a? Principal}
516 users = arr - mails
526 users = arr - mails
517 if users.any?
527 if users.any?
518 mails += EmailAddress.
528 mails += EmailAddress.
519 where(:user_id => users.map(&:id)).
529 where(:user_id => users.map(&:id)).
520 where("is_default = ? OR notify = ?", true, true).
530 where("is_default = ? OR notify = ?", true, true).
521 pluck(:address)
531 pluck(:address)
522 end
532 end
523 mails
533 mails
524 end
534 end
525
535
526 private
536 private
527
537
528 # Appends a Redmine header field (name is prepended with 'X-Redmine-')
538 # Appends a Redmine header field (name is prepended with 'X-Redmine-')
529 def redmine_headers(h)
539 def redmine_headers(h)
530 h.each { |k,v| headers["X-Redmine-#{k}"] = v.to_s }
540 h.each { |k,v| headers["X-Redmine-#{k}"] = v.to_s }
531 end
541 end
532
542
533 def self.token_for(object, rand=true)
543 def self.token_for(object, rand=true)
534 timestamp = object.send(object.respond_to?(:created_on) ? :created_on : :updated_on)
544 timestamp = object.send(object.respond_to?(:created_on) ? :created_on : :updated_on)
535 hash = [
545 hash = [
536 "redmine",
546 "redmine",
537 "#{object.class.name.demodulize.underscore}-#{object.id}",
547 "#{object.class.name.demodulize.underscore}-#{object.id}",
538 timestamp.strftime("%Y%m%d%H%M%S")
548 timestamp.strftime("%Y%m%d%H%M%S")
539 ]
549 ]
540 if rand
550 if rand
541 hash << Redmine::Utils.random_hex(8)
551 hash << Redmine::Utils.random_hex(8)
542 end
552 end
543 host = Setting.mail_from.to_s.strip.gsub(%r{^.*@|>}, '')
553 host = Setting.mail_from.to_s.strip.gsub(%r{^.*@|>}, '')
544 host = "#{::Socket.gethostname}.redmine" if host.empty?
554 host = "#{::Socket.gethostname}.redmine" if host.empty?
545 "#{hash.join('.')}@#{host}"
555 "#{hash.join('.')}@#{host}"
546 end
556 end
547
557
548 # Returns a Message-Id for the given object
558 # Returns a Message-Id for the given object
549 def self.message_id_for(object)
559 def self.message_id_for(object)
550 token_for(object, true)
560 token_for(object, true)
551 end
561 end
552
562
553 # Returns a uniq token for a given object referenced by all notifications
563 # Returns a uniq token for a given object referenced by all notifications
554 # related to this object
564 # related to this object
555 def self.references_for(object)
565 def self.references_for(object)
556 token_for(object, false)
566 token_for(object, false)
557 end
567 end
558
568
559 def message_id(object)
569 def message_id(object)
560 @message_id_object = object
570 @message_id_object = object
561 end
571 end
562
572
563 def references(object)
573 def references(object)
564 @references_objects ||= []
574 @references_objects ||= []
565 @references_objects << object
575 @references_objects << object
566 end
576 end
567
577
568 def mylogger
578 def mylogger
569 Rails.logger
579 Rails.logger
570 end
580 end
571 end
581 end
General Comments 0
You need to be logged in to leave comments. Login now