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 @ 1270:b2f7f52a164d

History | View | Annotate | Download (17.3 KB)

1
# Redmine - project management software
2
# Copyright (C) 2006-2012  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_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false)
42

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

    
47
  def logger
48
    Rails.logger
49
  end
50

    
51
  cattr_accessor :ignored_emails_headers
52
  @@ignored_emails_headers = {
53
    'X-Auto-Response-Suppress' => 'oof',
54
    'Auto-Submitted' => /^auto-/
55
  }
56

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

    
119
  private
120

    
121
  MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
122
  ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
123
  MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
124

    
125
  def dispatch
126
    headers = [email.in_reply_to, email.references].flatten.compact
127
    subject = email.subject.to_s
128
    if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
129
      klass, object_id = $1, $2.to_i
130
      method_name = "receive_#{klass}_reply"
131
      if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
132
        send method_name, object_id
133
      else
134
        # ignoring it
135
      end
136
    elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
137
      receive_issue_reply(m[1].to_i)
138
    elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
139
      receive_message_reply(m[1].to_i)
140
    else
141
      dispatch_to_default
142
    end
143
  rescue ActiveRecord::RecordInvalid => e
144
    # TODO: send a email to the user
145
    logger.error e.message if logger
146
    false
147
  rescue MissingInformation => e
148
    logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
149
    false
150
  rescue UnauthorizedAction => e
151
    logger.error "MailHandler: unauthorized attempt from #{user}" if logger
152
    false
153
  end
154

    
155
  def dispatch_to_default
156
    receive_issue
157
  end
158

    
159
  # Creates a new issue
160
  def receive_issue
161
    project = target_project
162
    # check permission
163
    unless @@handler_options[:no_permission_check]
164
      raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
165
    end
166

    
167
    issue = Issue.new(:author => user, :project => project)
168
    issue.safe_attributes = issue_attributes_from_keywords(issue)
169
    issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
170
    issue.subject = cleaned_up_subject
171
    if issue.subject.blank?
172
      issue.subject = '(no subject)'
173
    end
174
    issue.description = cleaned_up_text_body
175

    
176
    # add To and Cc as watchers before saving so the watchers can reply to Redmine
177
    add_watchers(issue)
178
    issue.save!
179
    add_attachments(issue)
180
    logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
181
    issue
182
  end
183

    
184
  # Adds a note to an existing issue
185
  def receive_issue_reply(issue_id, from_journal=nil)
186
    issue = Issue.find_by_id(issue_id)
187
    return unless issue
188
    # check permission
189
    unless @@handler_options[:no_permission_check]
190
      unless user.allowed_to?(:add_issue_notes, issue.project) ||
191
               user.allowed_to?(:edit_issues, issue.project)
192
        raise UnauthorizedAction
193
      end
194
    end
195

    
196
    # ignore CLI-supplied defaults for new issues
197
    @@handler_options[:issue].clear
198

    
199
    journal = issue.init_journal(user)
200
    if from_journal && from_journal.private_notes?
201
      # If the received email was a reply to a private note, make the added note private
202
      issue.private_notes = true
203
    end
204
    issue.safe_attributes = issue_attributes_from_keywords(issue)
205
    issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
206
    journal.notes = cleaned_up_text_body
207
    add_attachments(issue)
208
    issue.save!
209
    if logger && logger.info
210
      logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
211
    end
212
    journal
213
  end
214

    
215
  # Reply will be added to the issue
216
  def receive_journal_reply(journal_id)
217
    journal = Journal.find_by_id(journal_id)
218
    if journal && journal.journalized_type == 'Issue'
219
      receive_issue_reply(journal.journalized_id, journal)
220
    end
221
  end
222

    
223
  # Receives a reply to a forum message
224
  def receive_message_reply(message_id)
225
    message = Message.find_by_id(message_id)
226
    if message
227
      message = message.root
228

    
229
      unless @@handler_options[:no_permission_check]
230
        raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
231
      end
232

    
233
      if !message.locked?
234
        reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
235
                            :content => cleaned_up_text_body)
236
        reply.author = user
237
        reply.board = message.board
238
        message.children << reply
239
        add_attachments(reply)
240
        reply
241
      else
242
        if logger && logger.info
243
          logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
244
        end
245
      end
246
    end
247
  end
248

    
249
  def add_attachments(obj)
250
    if email.attachments && email.attachments.any?
251
      email.attachments.each do |attachment|
252
        filename = attachment.filename
253
        unless filename.respond_to?(:encoding)
254
          # try to reencode to utf8 manually with ruby1.8
255
          h = attachment.header['Content-Disposition']
256
          unless h.nil?
257
            begin
258
              if m = h.value.match(/filename\*[0-9\*]*=([^=']+)'/)
259
                filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
260
              elsif m = h.value.match(/filename=.*=\?([^\?]+)\?[BbQq]\?/)
261
                # http://tools.ietf.org/html/rfc2047#section-4
262
                filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
263
              end
264
            rescue
265
              # nop
266
            end
267
          end
268
        end
269
        obj.attachments << Attachment.create(:container => obj,
270
                          :file => attachment.decoded,
271
                          :filename => filename,
272
                          :author => user,
273
                          :content_type => attachment.mime_type)
274
      end
275
    end
276
  end
277

    
278
  # Adds To and Cc as watchers of the given object if the sender has the
279
  # appropriate permission
280
  def add_watchers(obj)
281
    if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
282
      addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
283
      unless addresses.empty?
284
        watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
285
        watchers.each {|w| obj.add_watcher(w)}
286
      end
287
    end
288
  end
289

    
290
  def get_keyword(attr, options={})
291
    @keywords ||= {}
292
    if @keywords.has_key?(attr)
293
      @keywords[attr]
294
    else
295
      @keywords[attr] = begin
296
        if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
297
              (v = extract_keyword!(plain_text_body, attr, options[:format]))
298
          v
299
        elsif !@@handler_options[:issue][attr].blank?
300
          @@handler_options[:issue][attr]
301
        end
302
      end
303
    end
304
  end
305

    
306
  # Destructively extracts the value for +attr+ in +text+
307
  # Returns nil if no matching keyword found
308
  def extract_keyword!(text, attr, format=nil)
309
    keys = [attr.to_s.humanize]
310
    if attr.is_a?(Symbol)
311
      if user && user.language.present?
312
        keys << l("field_#{attr}", :default => '', :locale =>  user.language)
313
      end
314
      if Setting.default_language.present?
315
        keys << l("field_#{attr}", :default => '', :locale =>  Setting.default_language)
316
      end
317
    end
318
    keys.reject! {|k| k.blank?}
319
    keys.collect! {|k| Regexp.escape(k)}
320
    format ||= '.+'
321
    keyword = nil
322
    regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
323
    if m = text.match(regexp)
324
      keyword = m[2].strip
325
      text.gsub!(regexp, '')
326
    end
327
    keyword
328
  end
329

    
330
  def target_project
331
    # TODO: other ways to specify project:
332
    # * parse the email To field
333
    # * specific project (eg. Setting.mail_handler_target_project)
334
    target = Project.find_by_identifier(get_keyword(:project))
335
    raise MissingInformation.new('Unable to determine target project') if target.nil?
336
    target
337
  end
338

    
339
  # Returns a Hash of issue attributes extracted from keywords in the email body
340
  def issue_attributes_from_keywords(issue)
341
    assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
342

    
343
    attrs = {
344
      'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
345
      'status_id' =>  (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
346
      'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
347
      'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
348
      'assigned_to_id' => assigned_to.try(:id),
349
      'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
350
                                issue.project.shared_versions.named(k).first.try(:id),
351
      'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
352
      'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
353
      'estimated_hours' => get_keyword(:estimated_hours, :override => true),
354
      'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
355
    }.delete_if {|k, v| v.blank? }
356

    
357
    if issue.new_record? && attrs['tracker_id'].nil?
358
      attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
359
    end
360

    
361
    attrs
362
  end
363

    
364
  # Returns a Hash of issue custom field values extracted from keywords in the email body
365
  def custom_field_values_from_keywords(customized)
366
    customized.custom_field_values.inject({}) do |h, v|
367
      if keyword = get_keyword(v.custom_field.name, :override => true)
368
        h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
369
      end
370
      h
371
    end
372
  end
373

    
374
  # Returns the text/plain part of the email
375
  # If not found (eg. HTML-only email), returns the body with tags removed
376
  def plain_text_body
377
    return @plain_text_body unless @plain_text_body.nil?
378

    
379
    part = email.text_part || email.html_part || email
380
    @plain_text_body = Redmine::CodesetUtil.to_utf8(part.body.decoded, part.charset)
381

    
382
    # strip html tags and remove doctype directive
383
    @plain_text_body = strip_tags(@plain_text_body.strip)
384
    @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
385
    @plain_text_body
386
  end
387

    
388
  def cleaned_up_text_body
389
    cleanup_body(plain_text_body)
390
  end
391

    
392
  def cleaned_up_subject
393
    subject = email.subject.to_s
394
    unless subject.respond_to?(:encoding)
395
      # try to reencode to utf8 manually with ruby1.8
396
      begin
397
        if h = email.header[:subject]
398
          # http://tools.ietf.org/html/rfc2047#section-4
399
          if m = h.value.match(/=\?([^\?]+)\?[BbQq]\?/)
400
            subject = Redmine::CodesetUtil.to_utf8(subject, m[1])
401
          end
402
        end
403
      rescue
404
        # nop
405
      end
406
    end
407
    subject.strip[0,255]
408
  end
409

    
410
  def self.full_sanitizer
411
    @full_sanitizer ||= HTML::FullSanitizer.new
412
  end
413

    
414
  def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
415
    limit ||= object.class.columns_hash[attribute.to_s].limit || 255
416
    value = value.to_s.slice(0, limit)
417
    object.send("#{attribute}=", value)
418
  end
419

    
420
  # Returns a User from an email address and a full name
421
  def self.new_user_from_attributes(email_address, fullname=nil)
422
    user = User.new
423

    
424
    # Truncating the email address would result in an invalid format
425
    user.mail = email_address
426
    assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
427

    
428
    names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
429
    assign_string_attribute_with_limit(user, 'firstname', names.shift)
430
    assign_string_attribute_with_limit(user, 'lastname', names.join(' '))
431
    user.lastname = '-' if user.lastname.blank?
432

    
433
    password_length = [Setting.password_min_length.to_i, 10].max
434
    user.password = Redmine::Utils.random_hex(password_length / 2 + 1)
435
    user.language = Setting.default_language
436

    
437
    unless user.valid?
438
      user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
439
      user.firstname = "-" unless user.errors[:firstname].blank?
440
      user.lastname  = "-" unless user.errors[:lastname].blank?
441
    end
442

    
443
    user
444
  end
445

    
446
  # Creates a User for the +email+ sender
447
  # Returns the user or nil if it could not be created
448
  def create_user_from_email
449
    from = email.header['from'].to_s
450
    addr, name = from, nil
451
    if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
452
      addr, name = m[2], m[1]
453
    end
454
    if addr.present?
455
      user = self.class.new_user_from_attributes(addr, name)
456
      if user.save
457
        user
458
      else
459
        logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
460
        nil
461
      end
462
    else
463
      logger.error "MailHandler: failed to create User: no FROM address found" if logger
464
      nil
465
    end
466
  end
467

    
468
  # Removes the email body of text after the truncation configurations.
469
  def cleanup_body(body)
470
    delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
471
    unless delimiters.empty?
472
      regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
473
      body = body.gsub(regex, '')
474
    end
475
    body.strip
476
  end
477

    
478
  def find_assignee_from_keyword(keyword, issue)
479
    keyword = keyword.to_s.downcase
480
    assignable = issue.assignable_users
481
    assignee = nil
482
    assignee ||= assignable.detect {|a|
483
                   a.mail.to_s.downcase == keyword ||
484
                     a.login.to_s.downcase == keyword
485
                 }
486
    if assignee.nil? && keyword.match(/ /)
487
      firstname, lastname = *(keyword.split) # "First Last Throwaway"
488
      assignee ||= assignable.detect {|a| 
489
                     a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
490
                       a.lastname.to_s.downcase == lastname
491
                   }
492
    end
493
    if assignee.nil?
494
      assignee ||= assignable.detect {|a| a.name.downcase == keyword}
495
    end
496
    assignee
497
  end
498
end