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