diff app/models/mail_handler.rb @ 1338:25603efa57b5

Merge from live branch
author Chris Cannam
date Thu, 20 Jun 2013 13:14:14 +0100
parents 0a574315af3e
children 4f746d8966dd fb9a13467253
line wrap: on
line diff
--- a/app/models/mail_handler.rb	Wed Jan 23 13:11:25 2013 +0000
+++ b/app/models/mail_handler.rb	Thu Jun 20 13:14:14 2013 +0100
@@ -1,5 +1,5 @@
 # Redmine - project management software
-# Copyright (C) 2006-2011  Jean-Philippe Lang
+# Copyright (C) 2006-2012  Jean-Philippe Lang
 #
 # This program is free software; you can redistribute it and/or
 # modify it under the terms of the GNU General Public License
@@ -29,7 +29,9 @@
 
     @@handler_options[:issue] ||= {}
 
-    @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String)
+    if @@handler_options[:allow_override].is_a?(String)
+      @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip)
+    end
     @@handler_options[:allow_override] ||= []
     # Project needs to be overridable if not specified
     @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
@@ -37,9 +39,21 @@
     @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
 
     @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false)
-    super email
+
+    email.force_encoding('ASCII-8BIT') if email.respond_to?(:force_encoding)
+    super(email)
   end
 
+  def logger
+    Rails.logger
+  end
+
+  cattr_accessor :ignored_emails_headers
+  @@ignored_emails_headers = {
+    'X-Auto-Response-Suppress' => 'oof',
+    'Auto-Submitted' => /^auto-/
+  }
+
   # Processes incoming emails
   # Returns the created object (eg. an issue, a message) or false
   def receive(email)
@@ -47,12 +61,29 @@
     sender_email = email.from.to_a.first.to_s.strip
     # Ignore emails received from the application emission address to avoid hell cycles
     if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
-      logger.info  "MailHandler: ignoring email from Redmine emission address [#{sender_email}]" if logger && logger.info
+      if logger && logger.info
+        logger.info  "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
+      end
       return false
     end
+    # Ignore auto generated emails
+    self.class.ignored_emails_headers.each do |key, ignored_value|
+      value = email.header[key]
+      if value
+        value = value.to_s.downcase
+        if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
+          if logger && logger.info
+            logger.info "MailHandler: ignoring email with #{key}:#{value} header"
+          end
+          return false
+        end
+      end
+    end
     @user = User.find_by_mail(sender_email) if sender_email.present?
     if @user && !@user.active?
-      logger.info  "MailHandler: ignoring email from non-active user [#{@user.login}]" if logger && logger.info
+      if logger && logger.info
+        logger.info  "MailHandler: ignoring email from non-active user [#{@user.login}]"
+      end
       return false
     end
     if @user.nil?
@@ -61,17 +92,23 @@
       when 'accept'
         @user = User.anonymous
       when 'create'
-        @user = create_user_from_email(email)
+        @user = create_user_from_email
         if @user
-          logger.info "MailHandler: [#{@user.login}] account created" if logger && logger.info
-          Mailer.deliver_account_information(@user, @user.password)
+          if logger && logger.info
+            logger.info "MailHandler: [#{@user.login}] account created"
+          end
+          Mailer.account_information(@user, @user.password).deliver
         else
-          logger.error "MailHandler: could not create account for [#{sender_email}]" if logger && logger.error
+          if logger && logger.error
+            logger.error "MailHandler: could not create account for [#{sender_email}]"
+          end
           return false
         end
       else
         # Default behaviour, emails from unknown users are ignored
-        logger.info  "MailHandler: ignoring email from unknown user [#{sender_email}]" if logger && logger.info
+        if logger && logger.info
+          logger.info  "MailHandler: ignoring email from unknown user [#{sender_email}]" 
+        end
         return false
       end
     end
@@ -81,12 +118,13 @@
 
   private
 
-  MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
+  MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
   ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
   MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
 
   def dispatch
     headers = [email.in_reply_to, email.references].flatten.compact
+    subject = email.subject.to_s
     if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
       klass, object_id = $1, $2.to_i
       method_name = "receive_#{klass}_reply"
@@ -95,9 +133,9 @@
       else
         # ignoring it
       end
-    elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
+    elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
       receive_issue_reply(m[1].to_i)
-    elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
+    elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
       receive_message_reply(m[1].to_i)
     else
       dispatch_to_default
@@ -129,7 +167,7 @@
     issue = Issue.new(:author => user, :project => project)
     issue.safe_attributes = issue_attributes_from_keywords(issue)
     issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
-    issue.subject = email.subject.to_s.chomp[0,255]
+    issue.subject = cleaned_up_subject
     if issue.subject.blank?
       issue.subject = '(no subject)'
     end
@@ -144,24 +182,33 @@
   end
 
   # Adds a note to an existing issue
-  def receive_issue_reply(issue_id)
+  def receive_issue_reply(issue_id, from_journal=nil)
     issue = Issue.find_by_id(issue_id)
     return unless issue
     # check permission
     unless @@handler_options[:no_permission_check]
-      raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
+      unless user.allowed_to?(:add_issue_notes, issue.project) ||
+               user.allowed_to?(:edit_issues, issue.project)
+        raise UnauthorizedAction
+      end
     end
 
     # ignore CLI-supplied defaults for new issues
     @@handler_options[:issue].clear
 
     journal = issue.init_journal(user)
+    if from_journal && from_journal.private_notes?
+      # If the received email was a reply to a private note, make the added note private
+      issue.private_notes = true
+    end
     issue.safe_attributes = issue_attributes_from_keywords(issue)
     issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
     journal.notes = cleaned_up_text_body
     add_attachments(issue)
     issue.save!
-    logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
+    if logger && logger.info
+      logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
+    end
     journal
   end
 
@@ -169,7 +216,7 @@
   def receive_journal_reply(journal_id)
     journal = Journal.find_by_id(journal_id)
     if journal && journal.journalized_type == 'Issue'
-      receive_issue_reply(journal.journalized_id)
+      receive_issue_reply(journal.journalized_id, journal)
     end
   end
 
@@ -184,7 +231,7 @@
       end
 
       if !message.locked?
-        reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
+        reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
                             :content => cleaned_up_text_body)
         reply.author = user
         reply.board = message.board
@@ -192,7 +239,9 @@
         add_attachments(reply)
         reply
       else
-        logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" if logger && logger.info
+        if logger && logger.info
+          logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
+        end
       end
     end
   end
@@ -201,9 +250,10 @@
     if email.attachments && email.attachments.any?
       email.attachments.each do |attachment|
         obj.attachments << Attachment.create(:container => obj,
-                          :file => attachment,
+                          :file => attachment.decoded,
+                          :filename => attachment.filename,
                           :author => user,
-                          :content_type => attachment.content_type)
+                          :content_type => attachment.mime_type)
       end
     end
   end
@@ -226,7 +276,8 @@
       @keywords[attr]
     else
       @keywords[attr] = begin
-        if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && (v = extract_keyword!(plain_text_body, attr, options[:format]))
+        if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
+              (v = extract_keyword!(plain_text_body, attr, options[:format]))
           v
         elsif !@@handler_options[:issue][attr].blank?
           @@handler_options[:issue][attr]
@@ -240,14 +291,23 @@
   def extract_keyword!(text, attr, format=nil)
     keys = [attr.to_s.humanize]
     if attr.is_a?(Symbol)
-      keys << l("field_#{attr}", :default => '', :locale =>  user.language) if user && user.language.present?
-      keys << l("field_#{attr}", :default => '', :locale =>  Setting.default_language) if Setting.default_language.present?
+      if user && user.language.present?
+        keys << l("field_#{attr}", :default => '', :locale =>  user.language)
+      end
+      if Setting.default_language.present?
+        keys << l("field_#{attr}", :default => '', :locale =>  Setting.default_language)
+      end
     end
     keys.reject! {|k| k.blank?}
     keys.collect! {|k| Regexp.escape(k)}
     format ||= '.+'
-    text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '')
-    $2 && $2.strip
+    keyword = nil
+    regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
+    if m = text.match(regexp)
+      keyword = m[2].strip
+      text.gsub!(regexp, '')
+    end
+    keyword
   end
 
   def target_project
@@ -269,7 +329,8 @@
       'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
       'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
       'assigned_to_id' => assigned_to.try(:id),
-      'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && issue.project.shared_versions.named(k).first.try(:id),
+      'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
+                                issue.project.shared_versions.named(k).first.try(:id),
       'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
       'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
       'estimated_hours' => get_keyword(:estimated_hours, :override => true),
@@ -286,8 +347,8 @@
   # Returns a Hash of issue custom field values extracted from keywords in the email body
   def custom_field_values_from_keywords(customized)
     customized.custom_field_values.inject({}) do |h, v|
-      if value = get_keyword(v.custom_field.name, :override => true)
-        h[v.custom_field.id.to_s] = value
+      if keyword = get_keyword(v.custom_field.name, :override => true)
+        h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
       end
       h
     end
@@ -297,20 +358,13 @@
   # If not found (eg. HTML-only email), returns the body with tags removed
   def plain_text_body
     return @plain_text_body unless @plain_text_body.nil?
-    parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
-    if parts.empty?
-      parts << @email
-    end
-    plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
-    if plain_text_part.nil?
-      # no text/plain part found, assuming html-only email
-      # strip html tags and remove doctype directive
-      @plain_text_body = strip_tags(@email.body.to_s)
-      @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
-    else
-      @plain_text_body = plain_text_part.body.to_s
-    end
-    @plain_text_body.strip!
+
+    part = email.text_part || email.html_part || email
+    @plain_text_body = Redmine::CodesetUtil.to_utf8(part.body.decoded, part.charset)
+
+    # strip html tags and remove doctype directive
+    @plain_text_body = strip_tags(@plain_text_body.strip)
+    @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
     @plain_text_body
   end
 
@@ -318,12 +372,17 @@
     cleanup_body(plain_text_body)
   end
 
+  def cleaned_up_subject
+    subject = email.subject.to_s
+    subject.strip[0,255]
+  end
+
   def self.full_sanitizer
     @full_sanitizer ||= HTML::FullSanitizer.new
   end
 
-  def self.assign_string_attribute_with_limit(object, attribute, value)
-    limit = object.class.columns_hash[attribute.to_s].limit || 255
+  def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
+    limit ||= object.class.columns_hash[attribute.to_s].limit || 255
     value = value.to_s.slice(0, limit)
     object.send("#{attribute}=", value)
   end
@@ -334,7 +393,7 @@
 
     # Truncating the email address would result in an invalid format
     user.mail = email_address
-    assign_string_attribute_with_limit(user, 'login', email_address)
+    assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
 
     names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
     assign_string_attribute_with_limit(user, 'firstname', names.shift)
@@ -342,13 +401,13 @@
     user.lastname = '-' if user.lastname.blank?
 
     password_length = [Setting.password_min_length.to_i, 10].max
-    user.password = ActiveSupport::SecureRandom.hex(password_length / 2 + 1)
+    user.password = Redmine::Utils.random_hex(password_length / 2 + 1)
     user.language = Setting.default_language
 
     unless user.valid?
-      user.login = "user#{ActiveSupport::SecureRandom.hex(6)}" if user.errors.on(:login)
-      user.firstname = "-" if user.errors.on(:firstname)
-      user.lastname = "-" if user.errors.on(:lastname)
+      user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
+      user.firstname = "-" unless user.errors[:firstname].blank?
+      user.lastname  = "-" unless user.errors[:lastname].blank?
     end
 
     user
@@ -356,10 +415,14 @@
 
   # Creates a User for the +email+ sender
   # Returns the user or nil if it could not be created
-  def create_user_from_email(email)
-    addr = email.from_addrs.to_a.first
-    if addr && !addr.spec.blank?
-      user = self.class.new_user_from_attributes(addr.spec, addr.name)
+  def create_user_from_email
+    from = email.header['from'].to_s
+    addr, name = from, nil
+    if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
+      addr, name = m[2], m[1]
+    end
+    if addr.present?
+      user = self.class.new_user_from_attributes(addr, name)
       if user.save
         user
       else
@@ -372,8 +435,6 @@
     end
   end
 
-  private
-
   # Removes the email body of text after the truncation configurations.
   def cleanup_body(body)
     delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
@@ -388,13 +449,19 @@
     keyword = keyword.to_s.downcase
     assignable = issue.assignable_users
     assignee = nil
-    assignee ||= assignable.detect {|a| a.mail.to_s.downcase == keyword || a.login.to_s.downcase == keyword}
+    assignee ||= assignable.detect {|a|
+                   a.mail.to_s.downcase == keyword ||
+                     a.login.to_s.downcase == keyword
+                 }
     if assignee.nil? && keyword.match(/ /)
       firstname, lastname = *(keyword.split) # "First Last Throwaway"
-      assignee ||= assignable.detect {|a| a.is_a?(User) && a.firstname.to_s.downcase == firstname && a.lastname.to_s.downcase == lastname}
+      assignee ||= assignable.detect {|a| 
+                     a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
+                       a.lastname.to_s.downcase == lastname
+                   }
     end
     if assignee.nil?
-      assignee ||= assignable.detect {|a| a.is_a?(Group) && a.name.downcase == keyword}
+      assignee ||= assignable.detect {|a| a.name.downcase == keyword}
     end
     assignee
   end