Project

General

Profile

RE: creating tickets from emails ยป mail_handler.rb

mail_handler.rb patched - iniyavan karan, 2013-02-26 12:31

 
1
# Redmine - project management software
2
# Copyright (C) 2006-2013  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
    #patched to write the sender's email id in the body of the new issue created
175
    issue.description = cleaned_up_text_body + "| This issue is reported by: #{email.header['from'].to_s} |"
176

    
177

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
363
    attrs
364
  end
365

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

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

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

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

    
390
  def cleaned_up_text_body
391
    cleanup_body(plain_text_body)
392
  end
393

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

    
412
  def self.full_sanitizer
413
    @full_sanitizer ||= HTML::FullSanitizer.new
414
  end
415

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

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

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

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

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

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

    
445
    user
446
  end
447

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

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

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