To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / mail_handler.rb @ 1591:63650ae64bf2

History | View | Annotate | Download (18.9 KB)

1
# Redmine - project management software
2
# Copyright (C) 2006-2014  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
26

    
27
  def self.receive(email, options={})
28
    @@handler_options = options.dup
29

    
30
    @@handler_options[:issue] ||= {}
31

    
32
    if @@handler_options[:allow_override].is_a?(String)
33
      @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip)
34
    end
35
    @@handler_options[:allow_override] ||= []
36
    # Project needs to be overridable if not specified
37
    @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
38
    # Status overridable by default
39
    @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
40

    
41
    @@handler_options[:no_account_notice] = (@@handler_options[:no_account_notice].to_s == '1')
42
    @@handler_options[:no_notification] = (@@handler_options[:no_notification].to_s == '1')
43
    @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1')
44

    
45
    email.force_encoding('ASCII-8BIT') if email.respond_to?(:force_encoding)
46
    super(email)
47
  end
48

    
49
  # Extracts MailHandler options from environment variables
50
  # Use when receiving emails with rake tasks
51
  def self.extract_options_from_env(env)
52
    options = {:issue => {}}
53
    %w(project status tracker category priority).each do |option|
54
      options[:issue][option.to_sym] = env[option] if env[option]
55
    end
56
    %w(allow_override unknown_user no_permission_check no_account_notice default_group).each do |option|
57
      options[option.to_sym] = env[option] if env[option]
58
    end
59
    options
60
  end
61

    
62
  def logger
63
    Rails.logger
64
  end
65

    
66
  cattr_accessor :ignored_emails_headers
67
  @@ignored_emails_headers = {
68
    'X-Auto-Response-Suppress' => 'oof',
69
    'Auto-Submitted' => /^auto-/
70
  }
71

    
72
  # Processes incoming emails
73
  # Returns the created object (eg. an issue, a message) or false
74
  def receive(email)
75
    @email = email
76
    sender_email = email.from.to_a.first.to_s.strip
77
    # Ignore emails received from the application emission address to avoid hell cycles
78
    if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
79
      if logger
80
        logger.info  "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
81
      end
82
      return false
83
    end
84
    # Ignore auto generated emails
85
    self.class.ignored_emails_headers.each do |key, ignored_value|
86
      value = email.header[key]
87
      if value
88
        value = value.to_s.downcase
89
        if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
90
          if logger
91
            logger.info "MailHandler: ignoring email with #{key}:#{value} header"
92
          end
93
          return false
94
        end
95
      end
96
    end
97
    @user = User.find_by_mail(sender_email) if sender_email.present?
98
    if @user && !@user.active?
99
      if logger
100
        logger.info  "MailHandler: ignoring email from non-active user [#{@user.login}]"
101
      end
102
      return false
103
    end
104
    if @user.nil?
105
      # Email was submitted by an unknown user
106
      case @@handler_options[:unknown_user]
107
      when 'accept'
108
        @user = User.anonymous
109
      when 'create'
110
        @user = create_user_from_email
111
        if @user
112
          if logger
113
            logger.info "MailHandler: [#{@user.login}] account created"
114
          end
115
          add_user_to_group(@@handler_options[:default_group])
116
          unless @@handler_options[:no_account_notice]
117
            Mailer.account_information(@user, @user.password).deliver
118
          end
119
        else
120
          if logger
121
            logger.error "MailHandler: could not create account for [#{sender_email}]"
122
          end
123
          return false
124
        end
125
      else
126
        # Default behaviour, emails from unknown users are ignored
127
        if logger
128
          logger.info  "MailHandler: ignoring email from unknown user [#{sender_email}]"
129
        end
130
        return false
131
      end
132
    end
133
    User.current = @user
134
    dispatch
135
  end
136

    
137
  private
138

    
139
  MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+(\.[a-f0-9]+)?@}
140
  ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
141
  MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
142

    
143
  def dispatch
144
    headers = [email.in_reply_to, email.references].flatten.compact
145
    subject = email.subject.to_s
146
    if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
147
      klass, object_id = $1, $2.to_i
148
      method_name = "receive_#{klass}_reply"
149
      if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
150
        send method_name, object_id
151
      else
152
        # ignoring it
153
      end
154
    elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
155
      receive_issue_reply(m[1].to_i)
156
    elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
157
      receive_message_reply(m[1].to_i)
158
    else
159
      dispatch_to_default
160
    end
161
  rescue ActiveRecord::RecordInvalid => e
162
    # TODO: send a email to the user
163
    logger.error e.message if logger
164
    false
165
  rescue MissingInformation => e
166
    logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
167
    false
168
  rescue UnauthorizedAction => e
169
    logger.error "MailHandler: unauthorized attempt from #{user}" if logger
170
    false
171
  end
172

    
173
  def dispatch_to_default
174
    receive_issue
175
  end
176

    
177
  # Creates a new issue
178
  def receive_issue
179
    project = target_project
180
    # check permission
181
    unless @@handler_options[:no_permission_check]
182
      raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
183
    end
184

    
185
    issue = Issue.new(:author => user, :project => project)
186
    issue.safe_attributes = issue_attributes_from_keywords(issue)
187
    issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
188
    issue.subject = cleaned_up_subject
189
    if issue.subject.blank?
190
      issue.subject = '(no subject)'
191
    end
192
    issue.description = cleaned_up_text_body
193
    issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
194

    
195
    # add To and Cc as watchers before saving so the watchers can reply to Redmine
196
    add_watchers(issue)
197
    issue.save!
198
    add_attachments(issue)
199
    logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger
200
    issue
201
  end
202

    
203
  # Adds a note to an existing issue
204
  def receive_issue_reply(issue_id, from_journal=nil)
205
    issue = Issue.find_by_id(issue_id)
206
    return unless issue
207
    # check permission
208
    unless @@handler_options[:no_permission_check]
209
      unless user.allowed_to?(:add_issue_notes, issue.project) ||
210
               user.allowed_to?(:edit_issues, issue.project)
211
        raise UnauthorizedAction
212
      end
213
    end
214

    
215
    # ignore CLI-supplied defaults for new issues
216
    @@handler_options[:issue].clear
217

    
218
    journal = issue.init_journal(user)
219
    if from_journal && from_journal.private_notes?
220
      # If the received email was a reply to a private note, make the added note private
221
      issue.private_notes = true
222
    end
223
    issue.safe_attributes = issue_attributes_from_keywords(issue)
224
    issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
225
    journal.notes = cleaned_up_text_body
226
    add_attachments(issue)
227
    issue.save!
228
    if logger
229
      logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
230
    end
231
    journal
232
  end
233

    
234
  # Reply will be added to the issue
235
  def receive_journal_reply(journal_id)
236
    journal = Journal.find_by_id(journal_id)
237
    if journal && journal.journalized_type == 'Issue'
238
      receive_issue_reply(journal.journalized_id, journal)
239
    end
240
  end
241

    
242
  # Receives a reply to a forum message
243
  def receive_message_reply(message_id)
244
    message = Message.find_by_id(message_id)
245
    if message
246
      message = message.root
247

    
248
      unless @@handler_options[:no_permission_check]
249
        raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
250
      end
251

    
252
      if !message.locked?
253
        reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
254
                            :content => cleaned_up_text_body)
255
        reply.author = user
256
        reply.board = message.board
257
        message.children << reply
258
        add_attachments(reply)
259
        reply
260
      else
261
        if logger
262
          logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
263
        end
264
      end
265
    end
266
  end
267

    
268
  def add_attachments(obj)
269
    if email.attachments && email.attachments.any?
270
      email.attachments.each do |attachment|
271
        next unless accept_attachment?(attachment)
272
        obj.attachments << Attachment.create(:container => obj,
273
                          :file => attachment.decoded,
274
                          :filename => attachment.filename,
275
                          :author => user,
276
                          :content_type => attachment.mime_type)
277
      end
278
    end
279
  end
280

    
281
  # Returns false if the +attachment+ of the incoming email should be ignored
282
  def accept_attachment?(attachment)
283
    @excluded ||= Setting.mail_handler_excluded_filenames.to_s.split(',').map(&:strip).reject(&:blank?)
284
    @excluded.each do |pattern|
285
      regexp = %r{\A#{Regexp.escape(pattern).gsub("\\*", ".*")}\z}i
286
      if attachment.filename.to_s =~ regexp
287
        logger.info "MailHandler: ignoring attachment #{attachment.filename} matching #{pattern}"
288
        return false
289
      end
290
    end
291
    true
292
  end
293

    
294
  # Adds To and Cc as watchers of the given object if the sender has the
295
  # appropriate permission
296
  def add_watchers(obj)
297
    if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
298
      addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
299
      unless addresses.empty?
300
        User.active.where('LOWER(mail) IN (?)', addresses).each do |w|
301
          obj.add_watcher(w)
302
        end
303
      end
304
    end
305
  end
306

    
307
  def get_keyword(attr, options={})
308
    @keywords ||= {}
309
    if @keywords.has_key?(attr)
310
      @keywords[attr]
311
    else
312
      @keywords[attr] = begin
313
        if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
314
              (v = extract_keyword!(plain_text_body, attr, options[:format]))
315
          v
316
        elsif !@@handler_options[:issue][attr].blank?
317
          @@handler_options[:issue][attr]
318
        end
319
      end
320
    end
321
  end
322

    
323
  # Destructively extracts the value for +attr+ in +text+
324
  # Returns nil if no matching keyword found
325
  def extract_keyword!(text, attr, format=nil)
326
    keys = [attr.to_s.humanize]
327
    if attr.is_a?(Symbol)
328
      if user && user.language.present?
329
        keys << l("field_#{attr}", :default => '', :locale =>  user.language)
330
      end
331
      if Setting.default_language.present?
332
        keys << l("field_#{attr}", :default => '', :locale =>  Setting.default_language)
333
      end
334
    end
335
    keys.reject! {|k| k.blank?}
336
    keys.collect! {|k| Regexp.escape(k)}
337
    format ||= '.+'
338
    keyword = nil
339
    regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
340
    if m = text.match(regexp)
341
      keyword = m[2].strip
342
      text.gsub!(regexp, '')
343
    end
344
    keyword
345
  end
346

    
347
  def target_project
348
    # TODO: other ways to specify project:
349
    # * parse the email To field
350
    # * specific project (eg. Setting.mail_handler_target_project)
351
    target = Project.find_by_identifier(get_keyword(:project))
352
    if target.nil?
353
      # Invalid project keyword, use the project specified as the default one
354
      default_project = @@handler_options[:issue][:project]
355
      if default_project.present?
356
        target = Project.find_by_identifier(default_project)
357
      end
358
    end
359
    raise MissingInformation.new('Unable to determine target project') if target.nil?
360
    target
361
  end
362

    
363
  # Returns a Hash of issue attributes extracted from keywords in the email body
364
  def issue_attributes_from_keywords(issue)
365
    assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
366

    
367
    attrs = {
368
      'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
369
      'status_id' =>  (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
370
      'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
371
      'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
372
      'assigned_to_id' => assigned_to.try(:id),
373
      'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
374
                                issue.project.shared_versions.named(k).first.try(:id),
375
      'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
376
      'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
377
      'estimated_hours' => get_keyword(:estimated_hours, :override => true),
378
      'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
379
    }.delete_if {|k, v| v.blank? }
380

    
381
    if issue.new_record? && attrs['tracker_id'].nil?
382
      attrs['tracker_id'] = issue.project.trackers.first.try(:id)
383
    end
384

    
385
    attrs
386
  end
387

    
388
  # Returns a Hash of issue custom field values extracted from keywords in the email body
389
  def custom_field_values_from_keywords(customized)
390
    customized.custom_field_values.inject({}) do |h, v|
391
      if keyword = get_keyword(v.custom_field.name, :override => true)
392
        h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
393
      end
394
      h
395
    end
396
  end
397

    
398
  # Returns the text/plain part of the email
399
  # If not found (eg. HTML-only email), returns the body with tags removed
400
  def plain_text_body
401
    return @plain_text_body unless @plain_text_body.nil?
402

    
403
    parts = if (text_parts = email.all_parts.select {|p| p.mime_type == 'text/plain'}).present?
404
              text_parts
405
            elsif (html_parts = email.all_parts.select {|p| p.mime_type == 'text/html'}).present?
406
              html_parts
407
            else
408
              [email]
409
            end
410

    
411
    parts.reject! do |part|
412
      part.header[:content_disposition].try(:disposition_type) == 'attachment'
413
    end
414

    
415
    @plain_text_body = parts.map do |p|
416
      body_charset = p.charset.respond_to?(:force_encoding) ?
417
                       Mail::RubyVer.pick_encoding(p.charset).to_s : p.charset
418
      Redmine::CodesetUtil.to_utf8(p.body.decoded, body_charset)
419
    end.join("\r\n")
420

    
421
    # strip html tags and remove doctype directive
422
    if parts.any? {|p| p.mime_type == 'text/html'}
423
      @plain_text_body = strip_tags(@plain_text_body.strip)
424
      @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
425
    end
426

    
427
    @plain_text_body
428
  end
429

    
430
  def cleaned_up_text_body
431
    cleanup_body(plain_text_body)
432
  end
433

    
434
  def cleaned_up_subject
435
    subject = email.subject.to_s
436
    subject.strip[0,255]
437
  end
438

    
439
  def self.full_sanitizer
440
    @full_sanitizer ||= HTML::FullSanitizer.new
441
  end
442

    
443
  def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
444
    limit ||= object.class.columns_hash[attribute.to_s].limit || 255
445
    value = value.to_s.slice(0, limit)
446
    object.send("#{attribute}=", value)
447
  end
448

    
449
  # Returns a User from an email address and a full name
450
  def self.new_user_from_attributes(email_address, fullname=nil)
451
    user = User.new
452

    
453
    # Truncating the email address would result in an invalid format
454
    user.mail = email_address
455
    assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
456

    
457
    names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
458
    assign_string_attribute_with_limit(user, 'firstname', names.shift, 30)
459
    assign_string_attribute_with_limit(user, 'lastname', names.join(' '), 30)
460
    user.lastname = '-' if user.lastname.blank?
461
    user.language = Setting.default_language
462
    user.generate_password = true
463
    user.mail_notification = 'only_my_events'
464

    
465
    unless user.valid?
466
      user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
467
      user.firstname = "-" unless user.errors[:firstname].blank?
468
      (puts user.errors[:lastname];user.lastname  = "-") unless user.errors[:lastname].blank?
469
    end
470

    
471
    user
472
  end
473

    
474
  # Creates a User for the +email+ sender
475
  # Returns the user or nil if it could not be created
476
  def create_user_from_email
477
    from = email.header['from'].to_s
478
    addr, name = from, nil
479
    if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
480
      addr, name = m[2], m[1]
481
    end
482
    if addr.present?
483
      user = self.class.new_user_from_attributes(addr, name)
484
      if @@handler_options[:no_notification]
485
        user.mail_notification = 'none'
486
      end
487
      if user.save
488
        user
489
      else
490
        logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
491
        nil
492
      end
493
    else
494
      logger.error "MailHandler: failed to create User: no FROM address found" if logger
495
      nil
496
    end
497
  end
498

    
499
  # Adds the newly created user to default group
500
  def add_user_to_group(default_group)
501
    if default_group.present?
502
      default_group.split(',').each do |group_name|
503
        if group = Group.named(group_name).first
504
          group.users << @user
505
        elsif logger
506
          logger.warn "MailHandler: could not add user to [#{group_name}], group not found"
507
        end
508
      end
509
    end
510
  end
511

    
512
  # Removes the email body of text after the truncation configurations.
513
  def cleanup_body(body)
514
    delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
515
    unless delimiters.empty?
516
      regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
517
      body = body.gsub(regex, '')
518
    end
519
    body.strip
520
  end
521

    
522
  def find_assignee_from_keyword(keyword, issue)
523
    keyword = keyword.to_s.downcase
524
    assignable = issue.assignable_users
525
    assignee = nil
526
    assignee ||= assignable.detect {|a|
527
                   a.mail.to_s.downcase == keyword ||
528
                     a.login.to_s.downcase == keyword
529
                 }
530
    if assignee.nil? && keyword.match(/ /)
531
      firstname, lastname = *(keyword.split) # "First Last Throwaway"
532
      assignee ||= assignable.detect {|a|
533
                     a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
534
                       a.lastname.to_s.downcase == lastname
535
                   }
536
    end
537
    if assignee.nil?
538
      assignee ||= assignable.detect {|a| a.name.downcase == keyword}
539
    end
540
    assignee
541
  end
542
end