Project

General

Profile

Defect #31937 » mail_handler.rb

Dominik Kro, 2019-08-22 16:06

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

    
18
class MailHandler < ActionMailer::Base
19
  include ActionView::Helpers::SanitizeHelper
20
  include Redmine::I18n
21

    
22
  class UnauthorizedAction < StandardError; end
23
  class MissingInformation < StandardError; end
24

    
25
  attr_reader :email, :user, :handler_options
26

    
27
  def self.receive(raw_mail, options={})
28
    options = options.deep_dup
29

    
30
    options[:issue] ||= {}
31

    
32
    options[:allow_override] ||= []
33
    if options[:allow_override].is_a?(String)
34
      options[:allow_override] = options[:allow_override].split(',')
35
    end
36
    options[:allow_override].map! {|s| s.strip.downcase.gsub(/\s+/, '_')}
37
    # Project needs to be overridable if not specified
38
    options[:allow_override] << 'project' unless options[:issue].has_key?(:project)
39

    
40
    options[:no_account_notice] = (options[:no_account_notice].to_s == '1')
41
    options[:no_notification] = (options[:no_notification].to_s == '1')
42
    options[:no_permission_check] = (options[:no_permission_check].to_s == '1')
43

    
44
    raw_mail.force_encoding('ASCII-8BIT')
45

    
46
    ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
47
      mail = Mail.new(raw_mail)
48
      set_payload_for_mail(payload, mail)
49
      new.receive(mail, options)
50
    end
51
  end
52

    
53
  # Receives an email and rescues any exception
54
  def self.safe_receive(*args)
55
    receive(*args)
56
  rescue Exception => e
57
    Rails.logger.error "MailHandler: an unexpected error occurred when receiving email: #{e.message}"
58
    return false
59
  end
60

    
61
  # Extracts MailHandler options from environment variables
62
  # Use when receiving emails with rake tasks
63
  def self.extract_options_from_env(env)
64
    options = {:issue => {}}
65
    %w(project status tracker category priority assigned_to fixed_version).each do |option|
66
      options[:issue][option.to_sym] = env[option] if env[option]
67
    end
68
    %w(allow_override unknown_user no_permission_check no_account_notice no_notification default_group project_from_subaddress).each do |option|
69
      options[option.to_sym] = env[option] if env[option]
70
    end
71
    if env['private']
72
      options[:issue][:is_private] = '1'
73
    end
74
    options
75
  end
76

    
77
  def logger
78
    Rails.logger
79
  end
80

    
81
  cattr_accessor :ignored_emails_headers
82
  self.ignored_emails_headers = {
83
    'Auto-Submitted' => /\Aauto-(replied|generated)/,
84
    'X-Autoreply' => 'yes'
85
  }
86

    
87
  # Processes incoming emails
88
  # Returns the created object (eg. an issue, a message) or false
89
  def receive(email, options={})
90
    @email = email
91
    @handler_options = options
92
    sender_email = email.from.to_a.first.to_s.strip
93
    # Ignore emails received from the application emission address to avoid hell cycles
94
    emission_address = Setting.mail_from.to_s.gsub(/(?:.*<|>.*|\(.*\))/, '').strip
95
    if sender_email.casecmp(emission_address) == 0
96
      if logger
97
        logger.info  "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
98
      end
99
      return false
100
    end
101
    # Ignore auto generated emails
102
    self.class.ignored_emails_headers.each do |key, ignored_value|
103
      value = email.header[key]
104
      if value
105
        value = value.to_s.downcase
106
        if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
107
          if logger
108
            logger.info "MailHandler: ignoring email with #{key}:#{value} header"
109
          end
110
          return false
111
        end
112
      end
113
    end
114
    @user = User.find_by_mail(sender_email) if sender_email.present?
115
    if @user && !@user.active?
116
      if logger
117
        logger.info  "MailHandler: ignoring email from non-active user [#{@user.login}]"
118
      end
119
      return false
120
    end
121
    if @user.nil?
122
      # Email was submitted by an unknown user
123
      case handler_options[:unknown_user]
124
      when 'accept'
125
        @user = User.anonymous
126
      when 'create'
127
        @user = create_user_from_email
128
        if @user
129
          if logger
130
            logger.info "MailHandler: [#{@user.login}] account created"
131
          end
132
          add_user_to_group(handler_options[:default_group])
133
          unless handler_options[:no_account_notice]
134
            ::Mailer.deliver_account_information(@user, @user.password)
135
          end
136
        else
137
          if logger
138
            logger.error "MailHandler: could not create account for [#{sender_email}]"
139
          end
140
          return false
141
        end
142
      else
143
        # Default behaviour, emails from unknown users are ignored
144
        if logger
145
          logger.info  "MailHandler: ignoring email from unknown user [#{sender_email}]"
146
        end
147
        return false
148
      end
149
    end
150
    User.current = @user
151
    dispatch
152
  end
153

    
154
  private
155

    
156
  MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+(\.[a-f0-9]+)?@}
157
  ISSUE_REPLY_SUBJECT_RE = %r{\[(?:[^\]]*\s+)?#(\d+)\]}
158
  MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
159

    
160
  def dispatch
161
    headers = [email.in_reply_to, email.references].flatten.compact
162
    subject = email.subject.to_s
163
    if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
164
      klass, object_id = $1, $2.to_i
165
      method_name = "receive_#{klass}_reply"
166
      if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
167
        send method_name, object_id
168
      else
169
        # ignoring it
170
      end
171
    elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
172
      receive_issue_reply(m[1].to_i)
173
    elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
174
      receive_message_reply(m[1].to_i)
175
    else
176
      dispatch_to_default
177
    end
178
  rescue ActiveRecord::RecordInvalid => e
179
    # TODO: send a email to the user
180
    logger.error "MailHandler: #{e.message}" if logger
181
    false
182
  rescue MissingInformation => e
183
    logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
184
    false
185
  rescue UnauthorizedAction => e
186
    logger.error "MailHandler: unauthorized attempt from #{user}" if logger
187
    false
188
  end
189

    
190
  def dispatch_to_default
191
    receive_issue
192
  end
193

    
194
  # Creates a new issue
195
  def receive_issue
196
    project = target_project
197
    # check permission
198
    unless handler_options[:no_permission_check]
199
      raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
200
    end
201

    
202
    issue = Issue.new(:author => user, :project => project)
203
    attributes = issue_attributes_from_keywords(issue)
204
    if handler_options[:no_permission_check]
205
      issue.tracker_id = attributes['tracker_id']
206
      if project
207
        issue.tracker_id ||= project.trackers.first.try(:id)
208
      end
209
    end
210
    issue.safe_attributes = attributes
211
    issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
212
    issue.subject = cleaned_up_subject
213
    if issue.subject.blank?
214
      issue.subject = '(no subject)'
215
    end
216
    issue.description = cleaned_up_text_body
217
    issue.start_date ||= User.current.today if Setting.default_issue_start_date_to_creation_date?
218
    issue.is_private = (handler_options[:issue][:is_private] == '1')
219

    
220
    # add To and Cc as watchers before saving so the watchers can reply to Redmine
221
    add_watchers(issue)
222
    issue.save!
223
    add_attachments(issue)
224
    logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger
225
    issue
226
  end
227

    
228
  # Adds a note to an existing issue
229
  def receive_issue_reply(issue_id, from_journal=nil)
230
    issue = Issue.find_by_id(issue_id)
231
    return unless issue
232
    # check permission
233
    unless handler_options[:no_permission_check]
234
      unless user.allowed_to?(:add_issue_notes, issue.project) ||
235
               user.allowed_to?(:edit_issues, issue.project)
236
        raise UnauthorizedAction
237
      end
238
    end
239

    
240
    # ignore CLI-supplied defaults for new issues
241
    handler_options[:issue] = {}
242

    
243
    journal = issue.init_journal(user)
244
    if from_journal && from_journal.private_notes?
245
      # If the received email was a reply to a private note, make the added note private
246
      issue.private_notes = true
247
    end
248
    issue.safe_attributes = issue_attributes_from_keywords(issue)
249
    issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
250
    journal.notes = cleaned_up_text_body
251

    
252
    # add To and Cc as watchers before saving so the watchers can reply to Redmine
253
    add_watchers(issue)
254
    issue.save!
255
    add_attachments(issue)
256
    if logger
257
      logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
258
    end
259
    journal
260
  end
261

    
262
  # Reply will be added to the issue
263
  def receive_journal_reply(journal_id)
264
    journal = Journal.find_by_id(journal_id)
265
    if journal && journal.journalized_type == 'Issue'
266
      receive_issue_reply(journal.journalized_id, journal)
267
    end
268
  end
269

    
270
  # Receives a reply to a forum message
271
  def receive_message_reply(message_id)
272
    message = Message.find_by_id(message_id)
273
    if message
274
      message = message.root
275

    
276
      unless handler_options[:no_permission_check]
277
        raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
278
      end
279

    
280
      if !message.locked?
281
        reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
282
                            :content => cleaned_up_text_body)
283
        reply.author = user
284
        reply.board = message.board
285
        message.children << reply
286
        add_attachments(reply)
287
        reply
288
      else
289
        if logger
290
          logger.info "MailHandler: ignoring reply from [#{email.from.first}] to a locked topic"
291
        end
292
      end
293
    end
294
  end
295

    
296
  def add_attachments(obj)
297
    if email.attachments && email.attachments.any?
298
      email.attachments.each do |attachment|
299
        next unless accept_attachment?(attachment)
300
        next unless attachment.body.decoded.size > 0
301
        obj.attachments << Attachment.create(:container => obj,
302
                          :file => attachment.body.decoded,
303
                          :filename => attachment.filename,
304
                          :author => user,
305
                          :content_type => attachment.mime_type)
306
      end
307
    end
308
  end
309

    
310
  # Returns false if the +attachment+ of the incoming email should be ignored
311
  def accept_attachment?(attachment)
312
    @excluded ||= Setting.mail_handler_excluded_filenames.to_s.split(',').map(&:strip).reject(&:blank?)
313
    @excluded.each do |pattern|
314
      if Setting.mail_handler_enable_regex_excluded_filenames?
315
        regexp = %r{\A#{pattern}\z}i
316
      else
317
        regexp = %r{\A#{Regexp.escape(pattern).gsub("\\*", ".*")}\z}i
318
      end
319
      if attachment.filename.to_s =~ regexp
320
        logger.info "MailHandler: ignoring attachment #{attachment.filename} matching #{pattern}"
321
        return false
322
      end
323
    end
324
    true
325
  end
326

    
327
  # Adds To and Cc as watchers of the given object if the sender has the
328
  # appropriate permission
329
  def add_watchers(obj)
330
    if handler_options[:no_permission_check] || user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
331
      addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
332
      unless addresses.empty?
333
        users = User.active.having_mail(addresses).to_a
334
        users -= obj.watcher_users
335
        users.each do |u|
336
          obj.add_watcher(u)
337
        end
338
      end
339
    end
340
  end
341

    
342
  def get_keyword(attr, options={})
343
    @keywords ||= {}
344
    if @keywords.has_key?(attr)
345
      @keywords[attr]
346
    else
347
      @keywords[attr] = begin
348
        override = options.key?(:override) ?
349
          options[:override] :
350
          (handler_options[:allow_override] & [attr.to_s.downcase.gsub(/\s+/, '_'), 'all']).present?
351

    
352
        if override && (v = extract_keyword!(cleaned_up_text_body, attr, options[:format]))
353
          v
354
        elsif !handler_options[:issue][attr].blank?
355
          handler_options[:issue][attr]
356
        end
357
      end
358
    end
359
  end
360

    
361
  # Destructively extracts the value for +attr+ in +text+
362
  # Returns nil if no matching keyword found
363
  def extract_keyword!(text, attr, format=nil)
364
    keys = [attr.to_s.humanize]
365
    if attr.is_a?(Symbol)
366
      if user && user.language.present?
367
        keys << l("field_#{attr}", :default => '', :locale =>  user.language)
368
      end
369
      if Setting.default_language.present?
370
        keys << l("field_#{attr}", :default => '', :locale =>  Setting.default_language)
371
      end
372
    end
373
    keys.reject! {|k| k.blank?}
374
    keys.collect! {|k| Regexp.escape(k)}
375
    format ||= '.+'
376
    keyword = nil
377
    regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
378
    if m = text.match(regexp)
379
      keyword = m[2].strip
380
      text.sub!(regexp, '')
381
    end
382
    keyword
383
  end
384

    
385
  def get_project_from_receiver_addresses
386
    local, domain = handler_options[:project_from_subaddress].to_s.split("@")
387
    return nil unless local && domain
388
    local = Regexp.escape(local)
389

    
390
    [:to, :cc, :bcc].each do |field|
391
      header = @email[field]
392
      next if header.blank? || header.field.blank? || !header.field.respond_to?(:addrs)
393
      header.field.addrs.each do |addr|
394
        if addr.domain.to_s.casecmp(domain)==0 && addr.local.to_s =~ /\A#{local}\+([^+]+)\z/
395
          if project = Project.find_by_identifier($1)
396
            return project
397
          end
398
        end
399
      end
400
    end
401
    nil
402
  end
403

    
404
  def target_project
405
    # TODO: other ways to specify project:
406
    # * parse the email To field
407
    # * specific project (eg. Setting.mail_handler_target_project)
408
    target = get_project_from_receiver_addresses
409
    target ||= Project.find_by_identifier(get_keyword(:project))
410
    if target.nil?
411
      # Invalid project keyword, use the project specified as the default one
412
      default_project = handler_options[:issue][:project]
413
      if default_project.present?
414
        target = Project.find_by_identifier(default_project)
415
      end
416
    end
417
    raise MissingInformation.new('Unable to determine target project') if target.nil?
418
    target
419
  end
420

    
421
  # Returns a Hash of issue attributes extracted from keywords in the email body
422
  def issue_attributes_from_keywords(issue)
423
    attrs = {
424
      'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
425
      'status_id' =>  (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
426
      'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
427
      'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
428
      'assigned_to_id' => (k = get_keyword(:assigned_to)) && find_assignee_from_keyword(k, issue).try(:id),
429
      'fixed_version_id' => (k = get_keyword(:fixed_version)) && issue.project.shared_versions.named(k).first.try(:id),
430
      'start_date' => get_keyword(:start_date, :format => '\d{4}-\d{2}-\d{2}'),
431
      'due_date' => get_keyword(:due_date, :format => '\d{4}-\d{2}-\d{2}'),
432
      'estimated_hours' => get_keyword(:estimated_hours),
433
      'done_ratio' => get_keyword(:done_ratio, :format => '(\d|10)?0'),
434
      'parent_issue_id' => get_keyword(:parent_issue)
435
    }.delete_if {|k, v| v.blank? }
436

    
437
    attrs
438
  end
439

    
440
  # Returns a Hash of issue custom field values extracted from keywords in the email body
441
  def custom_field_values_from_keywords(customized)
442
    customized.custom_field_values.inject({}) do |h, v|
443
      if keyword = get_keyword(v.custom_field.name)
444
        h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
445
      end
446
      h
447
    end
448
  end
449

    
450
  # Returns the text/plain part of the email
451
  # If not found (eg. HTML-only email), returns the body with tags removed
452
  def plain_text_body
453
    return @plain_text_body unless @plain_text_body.nil?
454

    
455
    # check if we have any plain-text parts with content
456
    @plain_text_body = email_parts_to_text(email.all_parts.select {|p| p.mime_type == 'text/plain'}).presence
457

    
458
    # if not, we try to parse the body from the HTML-parts
459
    @plain_text_body ||= email_parts_to_text(email.all_parts.select {|p| p.mime_type == 'text/html'}).presence
460

    
461
    # If there is still no body found, and there are no mime-parts defined,
462
    # we use the whole raw mail body
463
    @plain_text_body ||= email_parts_to_text([email]).presence if email.all_parts.empty?
464

    
465
    # As a fallback we return an empty plain text body (e.g. if we have only
466
    # empty text parts but a non-text attachment)
467
    @plain_text_body ||= ""
468
  end
469

    
470
  def email_parts_to_text(parts)
471
    parts.reject! do |part|
472
      part.attachment?
473
    end
474

    
475
    parts.map do |p|
476
      body_charset = Mail::RubyVer.respond_to?(:pick_encoding) ?
477
                       Mail::RubyVer.pick_encoding(p.charset).to_s : p.charset
478

    
479
      body = Redmine::CodesetUtil.to_utf8(p.body.decoded, body_charset)
480
      # convert html parts to text
481
      p.mime_type == 'text/html' ? self.class.html_body_to_text(body) : self.class.plain_text_body_to_text(body)
482
    end.join("\r\n")
483
  end
484

    
485
  def cleaned_up_text_body
486
    @cleaned_up_text_body ||= cleanup_body(plain_text_body)
487
  end
488

    
489
  def cleaned_up_subject
490
    subject = email.subject.to_s
491
    subject.strip[0,255]
492
  end
493

    
494
  # Converts a HTML email body to text
495
  def self.html_body_to_text(html)
496
    Redmine::WikiFormatting.html_parser.to_text(html)
497
  end
498

    
499
  # Converts a plain/text email body to text
500
  def self.plain_text_body_to_text(text)
501
    # Removes leading spaces that would cause the line to be rendered as
502
    # preformatted text with textile
503
    text.gsub(/^ +(?![*#])/, '')
504
  end
505

    
506
  def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
507
    limit ||= object.class.columns_hash[attribute.to_s].limit || 255
508
    value = value.to_s.slice(0, limit)
509
    object.send("#{attribute}=", value)
510
  end
511

    
512
  # Returns a User from an email address and a full name
513
  def self.new_user_from_attributes(email_address, fullname=nil)
514
    user = User.new
515

    
516
    # Truncating the email address would result in an invalid format
517
    user.mail = email_address
518
    assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
519

    
520
    names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
521
    assign_string_attribute_with_limit(user, 'firstname', names.shift, 30)
522
    assign_string_attribute_with_limit(user, 'lastname', names.join(' '), 30)
523
    user.lastname = '-' if user.lastname.blank?
524
    user.language = Setting.default_language
525
    user.generate_password = true
526
    user.mail_notification = 'only_my_events'
527

    
528
    unless user.valid?
529
      user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
530
      user.firstname = "-" unless user.errors[:firstname].blank?
531
      (puts user.errors[:lastname];user.lastname  = "-") unless user.errors[:lastname].blank?
532
    end
533

    
534
    user
535
  end
536

    
537
  # Creates a User for the +email+ sender
538
  # Returns the user or nil if it could not be created
539
  def create_user_from_email
540
    from = email.header['from'].to_s
541
    addr, name = from, nil
542
    if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
543
      addr, name = m[2], m[1]
544
    end
545
    if addr.present?
546
      user = self.class.new_user_from_attributes(addr, name)
547
      if handler_options[:no_notification]
548
        user.mail_notification = 'none'
549
      end
550
      if user.save
551
        user
552
      else
553
        logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
554
        nil
555
      end
556
    else
557
      logger.error "MailHandler: failed to create User: no FROM address found" if logger
558
      nil
559
    end
560
  end
561

    
562
  # Adds the newly created user to default group
563
  def add_user_to_group(default_group)
564
    if default_group.present?
565
      default_group.split(',').each do |group_name|
566
        if group = Group.named(group_name).first
567
          group.users << @user
568
        elsif logger
569
          logger.warn "MailHandler: could not add user to [#{group_name}], group not found"
570
        end
571
      end
572
    end
573
  end
574

    
575
  # Removes the email body of text after the truncation configurations.
576
  def cleanup_body(body)
577
    delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?)
578

    
579
    if Setting.mail_handler_enable_regex_delimiters?
580
      begin
581
        delimiters = delimiters.map {|s| Regexp.new(s)}
582
      rescue RegexpError => e
583
        logger.error "MailHandler: invalid regexp delimiter found in mail_handler_body_delimiters setting (#{e.message})" if logger
584
      end
585
    end
586

    
587
    unless delimiters.empty?
588
      regex = Regexp.new("^[> ]*(#{ Regexp.union(delimiters) })[[:blank:]]*[\r\n].*", Regexp::MULTILINE)
589
      body = body.gsub(regex, '')
590
    end
591
    body.strip
592
  end
593

    
594
  def find_assignee_from_keyword(keyword, issue)
595
    Principal.detect_by_keyword(issue.assignable_users, keyword)
596
  end
597
end
(3-3/3)