Project

General

Profile

Feature #38353 » mailer.rb

Jouri Mamaev, 2023-03-14 16:54

 
1
# frozen_string_literal: true
2

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

    
20
require 'roadie'
21

    
22
class Mailer < ActionMailer::Base
23
  layout 'mailer'
24
  helper :application
25
  helper :issues
26
  helper :custom_fields
27

    
28
  include Redmine::I18n
29
  include Roadie::Rails::Automatic
30

    
31
  # Overrides ActionMailer::Base#process in order to set the recipient as the current user
32
  # and his language as the default locale.
33
  # The first argument of all actions of this Mailer must be a User (the recipient),
34
  # otherwise an ArgumentError is raised.
35
  def process(action, *args)
36
    user = args.first
37
    raise ArgumentError, "First argument has to be a user, was #{user.inspect}" unless user.is_a?(User)
38

    
39
    initial_user = User.current
40
    initial_language = ::I18n.locale
41
    begin
42
      User.current = user
43

    
44
      lang = find_language(user.language) if user.logged?
45
      lang ||= Setting.default_language
46
      set_language_if_valid(lang)
47

    
48
      super(action, *args)
49
    ensure
50
      User.current = initial_user
51
      ::I18n.locale = initial_language
52
    end
53
  end
54

    
55
  # Default URL options for generating URLs in emails based on host_name and protocol
56
  # defined in application settings.
57
  def self.default_url_options
58
    options = {:protocol => Setting.protocol}
59
    if Setting.host_name.to_s =~ /\A(https?\:\/\/)?(.+?)(\:(\d+))?(\/.+)?\z/i
60
      host, port, prefix = $2, $4, $5
61
      options.merge!(
62
        {
63
          :host => host, :port => port, :script_name => prefix
64
        }
65
      )
66
    else
67
      options[:host] = Setting.host_name
68
    end
69
    options
70
  end
71

    
72
  # Builds a mail for notifying user about a new issue
73
  def issue_add(user, issue)
74
    redmine_headers 'Project' => issue.project.identifier,
75
                    'Issue-Tracker' => issue.tracker.name,
76
                    'Issue-Id' => issue.id,
77
                    'Issue-Author' => issue.author.login,
78
                    'Issue-Assignee' => assignee_for_header(issue)
79
    message_id issue
80
    references issue
81
    @author = issue.author
82
    @issue = issue
83
    @user = user
84
    @issue_url = url_for(:controller => 'issues', :action => 'show', :id => issue)
85

    
86
    #s = "IssueNew:: Proj: [#{issue.project.name}] Pracker: [#{issue.tracker.name}] Id: [##{issue.id}]"
87
    #s += " Status: [#{issue.status.name}]" if Setting.show_status_changes_in_mail_subject?
88
    #s += " Subj: [#{issue.subject}]"
89

    
90
    s = l( "mail_subject_issue_new", 
91
           project:    issue.project.name, 
92
           tracker:    issue.tracker.name, 
93
           id:         issue.id, 
94
           status:     issue.status.name, 
95
           subj:       issue.subject,
96
           from:       issue.author.name,
97
           to:         issue.assigned_to.name )
98

    
99
    mail :to => user,
100
      :subject => s
101
  end
102

    
103
  # Notifies users about a new issue.
104
  #
105
  # Example:
106
  #   Mailer.deliver_issue_add(issue)
107
  def self.deliver_issue_add(issue)
108
    users = issue.notified_users | issue.notified_watchers | issue.notified_mentions
109
    users.each do |user|
110
      issue_add(user, issue).deliver_later
111
    end
112
  end
113

    
114
  # Builds a mail for notifying user about an issue update
115
  def issue_edit(user, journal)
116
    issue = journal.journalized
117
    redmine_headers 'Project' => issue.project.identifier,
118
                    'Issue-Tracker' => issue.tracker.name,
119
                    'Issue-Id' => issue.id,
120
                    'Issue-Author' => issue.author.login,
121
                    'Issue-Assignee' => assignee_for_header(issue)
122
    message_id journal
123
    references issue
124
    @author = journal.user
125

    
126
    @issue = issue
127
    @user = user
128
    @journal = journal
129
    @journal_details = journal.visible_details
130
    @issue_url = url_for(:controller => 'issues', :action => 'show', :id => issue, :anchor => "change-#{journal.id}")
131

    
132
    s = l( "mail_subject_issue_update", 
133
           project:    issue.project.name, 
134
           tracker:    issue.tracker.name, 
135
           id:         issue.id, 
136
           status:     issue.status.name, 
137
           subj:       issue.subject,
138
           from:       issue.author.name,
139
           to:         issue.assigned_to.name )
140

    
141
    mail :to => user,
142
      :subject => s
143
  end
144

    
145
  # Notifies users about an issue update.
146
  #
147
  # Example:
148
  #   Mailer.deliver_issue_edit(journal)
149
  def self.deliver_issue_edit(journal)
150
    users  = journal.notified_users | journal.notified_watchers | journal.notified_mentions | journal.journalized.notified_mentions
151
    users.select! do |user|
152
      journal.notes? || journal.visible_details(user).any?
153
    end
154
    users.each do |user|
155
      issue_edit(user, journal).deliver_later
156
    end
157
  end
158

    
159
  # Builds a mail to user about a new document.
160
  def document_added(user, document, author)
161
    redmine_headers 'Project' => document.project.identifier
162
    @author = author
163
    @document = document
164
    @user = user
165
    @document_url = url_for(:controller => 'documents', :action => 'show', :id => document)
166

    
167
    s = l( "mail_subject_document_added", 
168
           project: document.project.name,
169
           title:   document.title )
170

    
171
    mail :to => user,
172
      :subject => s
173
  end
174

    
175
  # Notifies users that document was created by author
176
  #
177
  # Example:
178
  #   Mailer.deliver_document_added(document, author)
179
  def self.deliver_document_added(document, author)
180
    users = document.notified_users
181
    users.each do |user|
182
      document_added(user, document, author).deliver_later
183
    end
184
  end
185

    
186
  # Builds a mail to user about new attachements.
187
  def attachments_added(user, attachments)
188
    container = attachments.first.container
189
    added_to = ''
190
    added_to_url = ''
191
    @author = attachments.first.author
192
    case container.class.name
193
    when 'Project'
194
      added_to_url = url_for(:controller => 'files', :action => 'index', :project_id => container)
195
      added_to = "#{l(:label_project)}: #{container}"
196
    when 'Version'
197
      added_to_url = url_for(:controller => 'files', :action => 'index', :project_id => container.project)
198
      added_to = "#{l(:label_version)}: #{container.name}"
199
    when 'Document'
200
      added_to_url = url_for(:controller => 'documents', :action => 'show', :id => container.id)
201
      added_to = "#{l(:label_document)}: #{container.title}"
202
    end
203
    redmine_headers 'Project' => container.project.identifier
204
    @attachments = attachments
205
    @user = user
206
    @added_to = added_to
207
    @added_to_url = added_to_url
208

    
209
    s = l( "mail_subject_doc_attach_new",
210
           project: container.project.name,
211
           to: added_to,
212
           count: attachments.size
213
         )
214

    
215
    mail :to => user,
216
      :subject => s
217
  end
218

    
219
  # Notifies users about new attachments
220
  #
221
  # Example:
222
  #   Mailer.deliver_attachments_added(attachments)
223
  def self.deliver_attachments_added(attachments)
224
    container = attachments.first.container
225
    case container.class.name
226
    when 'Project', 'Version'
227
      users = container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}
228
    when 'Document'
229
      users = container.notified_users
230
    end
231

    
232
    users.each do |user|
233
      attachments_added(user, attachments).deliver_later
234
    end
235
  end
236

    
237
  # Builds a mail to user about a new news.
238
  def news_added(user, news)
239
    redmine_headers 'Project' => news.project.identifier
240
    @author = news.author
241
    message_id news
242
    references news
243
    @news = news
244
    @user = user
245
    @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
246

    
247
    s = l( "mail_subject_news_added",
248
           project: news.project.name,
249
           title: news.title )
250

    
251
    mail :to => user,
252
      :subject => s
253
  end
254

    
255
  # Notifies users about new news
256
  #
257
  # Example:
258
  #   Mailer.deliver_news_added(news)
259
  def self.deliver_news_added(news)
260
    users = news.notified_users | news.notified_watchers_for_added_news
261
    users.each do |user|
262
      news_added(user, news).deliver_later
263
    end
264
  end
265

    
266
  # Builds a mail to user about a new news comment.
267
  def news_comment_added(user, comment)
268
    news = comment.commented
269
    redmine_headers 'Project' => news.project.identifier
270
    @author = comment.author
271
    message_id comment
272
    references news
273
    @news = news
274
    @comment = comment
275
    @user = user
276
    @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
277

    
278
    s = l( "mail_subject_news_comment",    
279
           project: news.project.name,
280
           title: news.title )
281

    
282
    mail :to => user,
283
     :subject => s
284
  end
285

    
286
  # Notifies users about a new comment on a news
287
  #
288
  # Example:
289
  #   Mailer.deliver_news_comment_added(comment)
290
  def self.deliver_news_comment_added(comment)
291
    news = comment.commented
292
    users = news.notified_users | news.notified_watchers
293
    users.each do |user|
294
      news_comment_added(user, comment).deliver_later
295
    end
296
  end
297

    
298
  # Builds a mail to user about a new message.
299
  def message_posted(user, message)
300
    redmine_headers 'Project' => message.project.identifier,
301
                    'Topic-Id' => (message.parent_id || message.id)
302
    @author = message.author
303
    message_id message
304
    references message.root
305
    @message = message
306
    @user = user
307
    @message_url = url_for(message.event_url)
308

    
309
    s = l( "mail_subject_message_new",
310
           project: message.board.project.name,
311
           forum:   message.board.name,
312
           id:      message.root.id,
313
           title:   message.subject,
314
           subj:    message.subject,
315
           from:    message.author.name )
316

    
317
    mail :to => user,
318
      :subject => s
319
  end
320

    
321
  # Notifies users about a new forum message.
322
  #
323
  # Example:
324
  #   Mailer.deliver_message_posted(message)
325
  def self.deliver_message_posted(message)
326
    users  = message.notified_users
327
    users |= message.root.notified_watchers
328
    users |= message.board.notified_watchers
329

    
330
    users.each do |user|
331
      message_posted(user, message).deliver_later
332
    end
333
  end
334

    
335
  # Builds a mail to user about a new wiki content.
336
  def wiki_content_added(user, wiki_content)
337
    redmine_headers 'Project' => wiki_content.project.identifier,
338
                    'Wiki-Page-Id' => wiki_content.page.id
339
    @author = wiki_content.author
340
    message_id wiki_content
341
    @wiki_content = wiki_content
342
    @user = user
343
    @wiki_content_url = url_for(:controller => 'wiki', :action => 'show',
344
                                      :project_id => wiki_content.project,
345
                                      :id => wiki_content.page.title)
346

    
347
    s = l( "mail_subject_wiki_new",
348
           project: wiki_content.project.name,
349
           id:      wiki_content.page.title,
350
           title:   wiki_content.page.pretty_title,
351
           from:    wiki_content.author.name )
352

    
353
    mail(
354
      :to => user,
355
      :subject => s
356
    )
357
  end
358

    
359
  # Notifies users about a new wiki content (wiki page added).
360
  #
361
  # Example:
362
  #   Mailer.deliver_wiki_content_added(wiki_content)
363
  def self.deliver_wiki_content_added(wiki_content)
364
    users = wiki_content.notified_users | wiki_content.page.wiki.notified_watchers | wiki_content.notified_mentions
365
    users.each do |user|
366
      wiki_content_added(user, wiki_content).deliver_later
367
    end
368
  end
369

    
370
  # Builds a mail to user about an update of the specified wiki content.
371
  def wiki_content_updated(user, wiki_content)
372
    redmine_headers 'Project' => wiki_content.project.identifier,
373
                    'Wiki-Page-Id' => wiki_content.page.id
374
    @author = wiki_content.author
375
    message_id wiki_content
376
    @wiki_content = wiki_content
377
    @user = user
378
    @wiki_content_url =
379
      url_for(:controller => 'wiki', :action => 'show',
380
              :project_id => wiki_content.project,
381
              :id => wiki_content.page.title)
382
    @wiki_diff_url =
383
      url_for(:controller => 'wiki', :action => 'diff',
384
              :project_id => wiki_content.project, :id => wiki_content.page.title,
385
              :version => wiki_content.version)
386
    mail(
387
      :to => user,
388
      :subject =>
389
        "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_updated, :id => wiki_content.page.pretty_title)}"
390
    )
391
  end
392

    
393
  # Notifies users about the update of the specified wiki content
394
  #
395
  # Example:
396
  #   Mailer.deliver_wiki_content_updated(wiki_content)
397
  def self.deliver_wiki_content_updated(wiki_content)
398
    users  = wiki_content.notified_users
399
    users |= wiki_content.page.notified_watchers
400
    users |= wiki_content.page.wiki.notified_watchers
401
    users |= wiki_content.notified_mentions
402

    
403
    users.each do |user|
404
      wiki_content_updated(user, wiki_content).deliver_later
405
    end
406
  end
407

    
408
  # Builds a mail to user about his account information.
409
  def account_information(user, password)
410
    @user = user
411
    @password = password
412
    @login_url = url_for(:controller => 'account', :action => 'login')
413
    mail :to => user.mail,
414
      :subject => l(:mail_subject_register, Setting.app_title)
415
  end
416

    
417
  # Notifies user about his account information.
418
  def self.deliver_account_information(user, password)
419
    account_information(user, password).deliver_later
420
  end
421

    
422
  # Builds a mail to user about an account activation request.
423
  def account_activation_request(user, new_user)
424
    @new_user = new_user
425
    @url = url_for(:controller => 'users', :action => 'index',
426
                         :status => User::STATUS_REGISTERED,
427
                         :sort_key => 'created_on', :sort_order => 'desc')
428
    mail :to => user,
429
      :subject => l(:mail_subject_account_activation_request, Setting.app_title)
430
  end
431

    
432
  # Notifies admin users that an account activation request needs
433
  # their approval.
434
  #
435
  # Exemple:
436
  #   Mailer.deliver_account_activation_request(new_user)
437
  def self.deliver_account_activation_request(new_user)
438
    # Send the email to all active administrators
439
    users = User.active.where(:admin => true)
440
    users.each do |user|
441
      account_activation_request(user, new_user).deliver_later
442
    end
443
  end
444

    
445
  # Builds a mail to notify user that his account was activated.
446
  def account_activated(user)
447
    @user = user
448
    @login_url = url_for(:controller => 'account', :action => 'login')
449
    mail :to => user.mail,
450
      :subject => l(:mail_subject_register, Setting.app_title)
451
  end
452

    
453
  # Notifies user that his account was activated.
454
  #
455
  # Exemple:
456
  #   Mailer.deliver_account_activated(user)
457
  def self.deliver_account_activated(user)
458
    account_activated(user).deliver_later
459
  end
460

    
461
  # Builds a mail with the password recovery link.
462
  def lost_password(user, token, recipient=nil)
463
    recipient ||= user.mail
464
    @token = token
465
    @url = url_for(:controller => 'account', :action => 'lost_password', :token => token.value)
466
    mail :to => recipient,
467
      :subject => l(:mail_subject_lost_password, Setting.app_title)
468
  end
469

    
470
  # Sends an email to user with a password recovery link.
471
  # The email will be sent to the email address specifiedby recipient if provided.
472
  #
473
  # Exemple:
474
  #   Mailer.deliver_lost_password(user, token)
475
  #   Mailer.deliver_lost_password(user, token, 'foo@example.net')
476
  def self.deliver_lost_password(user, token, recipient=nil)
477
    lost_password(user, token, recipient).deliver_later
478
  end
479

    
480
  # Notifies user that his password was updated by sender.
481
  #
482
  # Exemple:
483
  #   Mailer.deliver_password_updated(user, sender)
484
  def self.deliver_password_updated(user, sender)
485
    # Don't send a notification to the dummy email address when changing the password
486
    # of the default admin account which is required after the first login
487
    # TODO: maybe not the best way to handle this
488
    return if user.admin? && user.login == 'admin' && user.mail == 'admin@example.net'
489

    
490
    deliver_security_notification(
491
      user,
492
      sender,
493
      message: :mail_body_password_updated,
494
      title: :button_change_password,
495
      url: {controller: 'my', action: 'password'}
496
    )
497
  end
498

    
499
  # Builds a mail to user with his account activation link.
500
  def register(user, token)
501
    @token = token
502
    @url = url_for(:controller => 'account', :action => 'activate', :token => token.value)
503
    mail :to => user.mail,
504
      :subject => l(:mail_subject_register, Setting.app_title)
505
  end
506

    
507
  # Sends an mail to user with his account activation link.
508
  #
509
  # Exemple:
510
  #   Mailer.deliver_register(user, token)
511
  def self.deliver_register(user, token)
512
    register(user, token).deliver_later
513
  end
514

    
515
  # Build a mail to user and the additional recipients given in
516
  # options[:recipients] about a security related event made by sender.
517
  #
518
  # Example:
519
  #   security_notification(user,
520
  #     sender,
521
  #     message: :mail_body_security_notification_add,
522
  #     field: :field_mail,
523
  #     value: address
524
  #   ) => Mail::Message object
525
  def security_notification(user, sender, options={})
526
    @sender = sender
527
    redmine_headers 'Sender' => sender.login
528
    @message =
529
      l(options[:message],
530
        field: (options[:field] && l(options[:field])),
531
        value: options[:value])
532
    @title = options[:title] && l(options[:title])
533
    @remote_ip = options[:remote_ip] || @sender.remote_ip
534
    @url = options[:url] && (options[:url].is_a?(Hash) ? url_for(options[:url]) : options[:url])
535
    redmine_headers 'Url' => @url
536
    mail :to => [user, *options[:recipients]].uniq,
537
      :subject => "[#{Setting.app_title}] #{l(:mail_subject_security_notification)}"
538
  end
539

    
540
  # Notifies the given users about a security related event made by sender.
541
  #
542
  # You can specify additional recipients in options[:recipients]. These will be
543
  # added to all generated mails for all given users. Usually, you'll want to
544
  # give only a single user when setting the additional recipients.
545
  #
546
  # Example:
547
  #   Mailer.deliver_security_notification(users,
548
  #     sender,
549
  #     message: :mail_body_security_notification_add,
550
  #     field: :field_mail,
551
  #     value: address
552
  #   )
553
  def self.deliver_security_notification(users, sender, options={})
554
    # Symbols cannot be serialized:
555
    # ActiveJob::SerializationError: Unsupported argument type: Symbol
556
    options = options.transform_values {|v| v.is_a?(Symbol) ? v.to_s : v}
557
    # sender's remote_ip would be lost on serialization/deserialization
558
    # we have to pass it with options
559
    options[:remote_ip] ||= sender.remote_ip
560

    
561
    Array.wrap(users).each do |user|
562
      security_notification(user, sender, options).deliver_later
563
    end
564
  end
565

    
566
  # Build a mail to user about application settings changes made by sender.
567
  def settings_updated(user, sender, changes, options={})
568
    @sender = sender
569
    redmine_headers 'Sender' => sender.login
570
    @changes = changes
571
    @remote_ip = options[:remote_ip] || @sender.remote_ip
572
    @url = url_for(controller: 'settings', action: 'index')
573
    mail :to => user,
574
      :subject => "[#{Setting.app_title}] #{l(:mail_subject_security_notification)}"
575
  end
576

    
577
  # Notifies admins about application settings changes made by sender, where
578
  # changes is an array of settings names.
579
  #
580
  # Exemple:
581
  #   Mailer.deliver_settings_updated(sender, [:login_required, :self_registration])
582
  def self.deliver_settings_updated(sender, changes, options={})
583
    return unless changes.present?
584

    
585
    # Symbols cannot be serialized:
586
    # ActiveJob::SerializationError: Unsupported argument type: Symbol
587
    changes = changes.map(&:to_s)
588
    # sender's remote_ip would be lost on serialization/deserialization
589
    # we have to pass it with options
590
    options[:remote_ip] ||= sender.remote_ip
591

    
592
    users = User.active.where(admin: true).to_a
593
    users.each do |user|
594
      settings_updated(user, sender, changes, options).deliver_later
595
    end
596
  end
597

    
598
  # Build a test email to user.
599
  def test_email(user)
600
    @url = url_for(:controller => 'welcome')
601
    mail :to => user,
602
      :subject => l("email_subject_test")
603
  end
604

    
605
  # Send a test email to user. Will raise error that may occur during delivery.
606
  #
607
  # Exemple:
608
  #   Mailer.deliver_test_email(user)
609
  def self.deliver_test_email(user)
610
    raise_delivery_errors_was = self.raise_delivery_errors
611
    self.raise_delivery_errors = true
612
    # Email must be delivered synchronously so we can catch errors
613
    test_email(user).deliver_now
614
  ensure
615
    self.raise_delivery_errors = raise_delivery_errors_was
616
  end
617

    
618
  # Builds a reminder mail to user about issues that are due in the next days.
619
  def reminder(user, issues, days)
620
    @issues = issues
621
    @days = days
622
    @open_issues_url = url_for(:controller => 'issues', :action => 'index',
623
                                :set_filter => 1, :assigned_to_id => 'me',
624
                                :sort => 'due_date:asc')
625
    @reminder_issues_url = url_for(:controller => 'issues', :action => 'index',
626
      :set_filter => 1, :sort => 'due_date:asc',
627
      :f => ['status_id', 'assigned_to_id', "due_date"],
628
      :op => {'status_id' => 'o', 'assigned_to_id' => '=', 'due_date' => '<t+'},
629
      :v =>{'assigned_to_id' => ['me'], 'due_date' => [days]})
630

    
631
    query = IssueQuery.new(:name => '_')
632
    query.add_filter('assigned_to_id', '=', ['me'])
633
    @open_issues_count = query.issue_count
634

    
635
    mail :to => user,
636
      :subject => l(:mail_subject_reminder, :count => issues.size, :days => days)
637
  end
638

    
639
  # Sends reminders to issue assignees
640
  # Available options:
641
  # * :days     => how many days in the future to remind about (defaults to 7)
642
  # * :tracker  => id of tracker for filtering issues (defaults to all trackers)
643
  # * :project  => id or identifier of project to process (defaults to all projects)
644
  # * :users    => array of user/group ids who should be reminded
645
  # * :version  => name of target version for filtering issues (defaults to none)
646
  def self.reminders(options={})
647
    days = options[:days] || 7
648
    project = options[:project] ? Project.find(options[:project]) : nil
649
    tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil
650
    target_version_id = options[:version] ? Version.named(options[:version]).pluck(:id) : nil
651
    if options[:version] && target_version_id.blank?
652
      raise ActiveRecord::RecordNotFound.new("Couldn't find Version named #{options[:version]}")
653
    end
654

    
655
    user_ids = options[:users]
656

    
657
    scope =
658
      Issue.open.where(
659
        "#{Issue.table_name}.assigned_to_id IS NOT NULL" \
660
          " AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" \
661
          " AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date
662
      )
663
    scope = scope.where(:assigned_to_id => user_ids) if user_ids.present?
664
    scope = scope.where(:project_id => project.id) if project
665
    scope = scope.where(:fixed_version_id => target_version_id) if target_version_id.present?
666
    scope = scope.where(:tracker_id => tracker.id) if tracker
667
    issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker).
668
                              group_by(&:assigned_to)
669
    issues_by_assignee.keys.each do |assignee|
670
      if assignee.is_a?(Group)
671
        assignee.users.each do |user|
672
          issues_by_assignee[user] ||= []
673
          issues_by_assignee[user] += issues_by_assignee[assignee]
674
        end
675
      end
676
    end
677

    
678
    issues_by_assignee.each do |assignee, issues|
679
      if assignee.is_a?(User) && assignee.active? && issues.present?
680
        visible_issues = issues.select {|i| i.visible?(assignee)}
681
        visible_issues.sort!{|a, b| (a.due_date <=> b.due_date).nonzero? || (a.id <=> b.id)}
682
        reminder(assignee, visible_issues, days).deliver_later if visible_issues.present?
683
      end
684
    end
685
  end
686

    
687
  # Activates/desactivates email deliveries during +block+
688
  def self.with_deliveries(enabled = true, &block)
689
    was_enabled = ActionMailer::Base.perform_deliveries
690
    ActionMailer::Base.perform_deliveries = !!enabled
691
    yield
692
  ensure
693
    ActionMailer::Base.perform_deliveries = was_enabled
694
  end
695

    
696
  # Execute the given block with inline sending of emails if the default Async
697
  # queue is used for the mailer. See the Rails guide:
698
  # Using the asynchronous queue from a Rake task will generally not work because
699
  # Rake will likely end, causing the in-process thread pool to be deleted, before
700
  # any/all of the .deliver_later emails are processed
701
  def self.with_synched_deliveries(&block)
702
    adapter = ActionMailer::MailDeliveryJob.queue_adapter
703
    ActionMailer::MailDeliveryJob.queue_adapter = ActiveJob::QueueAdapters::InlineAdapter.new
704
    yield
705
  ensure
706
    ActionMailer::MailDeliveryJob.queue_adapter = adapter
707
  end
708

    
709
  def mail(headers={}, &block)
710
    # Add a display name to the From field if Setting.mail_from does not
711
    # include it
712
    begin
713
      mail_from = Mail::Address.new(Setting.mail_from)
714
      if mail_from.display_name.blank? && mail_from.comments.blank?
715
        mail_from.display_name =
716
          @author&.logged? ? @author.name : Setting.app_title
717
      end
718
      from = mail_from.format
719
      list_id = "<#{mail_from.address.to_s.tr('@', '.')}>"
720
    rescue Mail::Field::IncompleteParseError
721
      # Use Setting.mail_from as it is if Mail::Address cannot parse it
722
      # (probably the emission address is not RFC compliant)
723
      from = Setting.mail_from.to_s
724
      list_id = "<#{from.tr('@', '.')}>"
725
    end
726

    
727
    headers.reverse_merge! 'X-Mailer' => 'Redmine',
728
            'X-Redmine-Host' => Setting.host_name,
729
            'X-Redmine-Site' => Setting.app_title,
730
            'X-Auto-Response-Suppress' => 'All',
731
            'Auto-Submitted' => 'auto-generated',
732
            'From' => from,
733
            'List-Id' => list_id
734

    
735
    # Replaces users with their email addresses
736
    [:to, :cc, :bcc].each do |key|
737
      if headers[key].present?
738
        headers[key] = self.class.email_addresses(headers[key])
739
      end
740
    end
741

    
742
    # Removes the author from the recipients and cc
743
    # if the author does not want to receive notifications
744
    # about what the author do
745
    if @author&.logged? && @author.pref.no_self_notified
746
      addresses = @author.mails
747
      headers[:to] -= addresses if headers[:to].is_a?(Array)
748
      headers[:cc] -= addresses if headers[:cc].is_a?(Array)
749
    end
750

    
751
    if @author&.logged?
752
      redmine_headers 'Sender' => @author.login
753
    end
754

    
755
    if @message_id_object
756
      headers[:message_id] = "<#{self.class.message_id_for(@message_id_object, @user)}>"
757
    end
758
    if @references_objects
759
      headers[:references] = @references_objects.collect {|o| "<#{self.class.references_for(o, @user)}>"}.join(' ')
760
    end
761

    
762
    if block_given?
763
      super headers, &block
764
    else
765
      super headers do |format|
766
        format.text
767
        format.html unless Setting.plain_text_mail?
768
      end
769
    end
770
  end
771

    
772
  def self.deliver_mail(mail)
773
    return false if mail.to.blank? && mail.cc.blank? && mail.bcc.blank?
774

    
775
    begin
776
      # Log errors when raise_delivery_errors is set to false, Rails does not
777
      mail.raise_delivery_errors = true
778
      super
779
    rescue => e
780
      if ActionMailer::Base.raise_delivery_errors
781
        raise e
782
      else
783
        Rails.logger.error "Email delivery error: #{e.message}"
784
      end
785
    end
786
  end
787

    
788
  # Returns an array of email addresses to notify by
789
  # replacing users in arg with their notified email addresses
790
  #
791
  # Example:
792
  #   Mailer.email_addresses(users)
793
  #   => ["foo@example.net", "bar@example.net"]
794
  def self.email_addresses(arg)
795
    arr = Array.wrap(arg)
796
    mails = arr.reject {|a| a.is_a? Principal}
797
    users = arr - mails
798
    if users.any?
799
      mails += EmailAddress.
800
        where(:user_id => users.map(&:id)).
801
        where("is_default = ? OR notify = ?", true, true).
802
        pluck(:address)
803
    end
804
    mails
805
  end
806

    
807
  private
808

    
809
  # Appends a Redmine header field (name is prepended with 'X-Redmine-')
810
  def redmine_headers(h)
811
    h.compact.each {|k, v| headers["X-Redmine-#{k}"] = v.to_s}
812
  end
813

    
814
  def assignee_for_header(issue)
815
    case issue.assigned_to
816
    when User
817
      issue.assigned_to.login
818
    when Group
819
      "Group (#{issue.assigned_to.name})"
820
    end
821
  end
822

    
823
  # Singleton class method is public
824
  class << self
825
    def token_for(object, user)
826
      timestamp = object.send(object.respond_to?(:created_on) ? :created_on : :updated_on)
827
      hash = [
828
        "redmine",
829
        "#{object.class.name.demodulize.underscore}-#{object.id}",
830
        timestamp.utc.strftime("%Y%m%d%H%M%S")
831
      ]
832
      hash << user.id if user
833
      host = Setting.mail_from.to_s.strip.gsub(%r{^.*@|>}, '')
834
      host = "#{::Socket.gethostname}.redmine" if host.empty?
835
      "#{hash.join('.')}@#{host}"
836
    end
837

    
838
    # Returns a Message-Id for the given object
839
    def message_id_for(object, user)
840
      token_for(object, user)
841
    end
842

    
843
    # Returns a uniq token for a given object referenced by all notifications
844
    # related to this object
845
    def references_for(object, user)
846
      token_for(object, user)
847
    end
848
  end
849

    
850
  def message_id(object)
851
    @message_id_object = object
852
  end
853

    
854
  def references(object)
855
    @references_objects ||= []
856
    @references_objects << object
857
  end
858
end
(1-1/2)