File: app/models/mail_handler.rb

Overview
Module Structure
Class Hierarchy
Code

Overview

Module Structure

  module: <Toplevel Module>
  class: MailHandler#18
includes
  SanitizeHelper ( ActionView::Helpers )
  I18n ( Redmine )
inherits from
  Base ( ActionMailer )
has properties
attribute: email [R] #25
attribute: user [R] #25
class method: receive (1/2) / 2 #27
method: receive (2/E) / 1 #53
constant: MESSAGE_ID_RE #112
constant: ISSUE_REPLY_SUBJECT_RE #113
constant: MESSAGE_REPLY_SUBJECT_RE #114
method: dispatch #116
method: dispatch_to_default #145
method: receive_issue #150
method: receive_issue_reply / 1 #175
method: receive_journal_reply / 1 #202
method: receive_message_reply / 1 #210
method: add_attachments / 1 #235
method: add_watchers / 1 #248
method: get_keyword / 2 #258
method: extract_keyword! / 3 #276
method: target_project #293
method: issue_attributes_from_keywords / 1 #303
method: custom_field_values_from_keywords / 1 #328
method: plain_text_body #339
method: cleaned_up_text_body #358
class method: full_sanitizer #362
class method: assign_string_attribute_with_limit / 4 #366
class method: new_user_from_attributes / 2 #373
method: create_user_from_email #400
method: cleanup_body / 1 #417
method: find_assignee_from_keyword / 2 #426
  class: UnauthorizedAction#22
inherits from
  StandardError ( Builtin-Module )
  class: MissingInformation#23
inherits from
  StandardError ( Builtin-Module )

Class Hierarchy

Code

   1  # Redmine - project management software
   2  # Copyright (C) 2006-2011  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      super email
  43    end
  44 
  45    cattr_accessor :ignored_emails_headers
  46    @@ignored_emails_headers = {
  47      'X-Auto-Response-Suppress' => 'OOF',
  48      'Auto-Submitted' => 'auto-replied'
  49    }
  50 
  51    # Processes incoming emails
  52    # Returns the created object (eg. an issue, a message) or false
  53    def receive(email)
  54      @email = email
  55      sender_email = email.from.to_a.first.to_s.strip
  56      # Ignore emails received from the application emission address to avoid hell cycles
  57      if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
  58        if logger && logger.info
  59          logger.info  "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
  60        end
  61        return false
  62      end
  63      # Ignore auto generated emails
  64      self.class.ignored_emails_headers.each do |key, ignored_value|
  65        value = email.header_string(key)
  66        if value && value.to_s.downcase == ignored_value.downcase
  67          if logger && logger.info
  68            logger.info "MailHandler: ignoring email with #{key}:#{value} header"
  69          end
  70          return false
  71        end
  72      end
  73      @user = User.find_by_mail(sender_email) if sender_email.present?
  74      if @user && !@user.active?
  75        if logger && logger.info
  76          logger.info  "MailHandler: ignoring email from non-active user [#{@user.login}]"
  77        end
  78        return false
  79      end
  80      if @user.nil?
  81        # Email was submitted by an unknown user
  82        case @@handler_options[:unknown_user]
  83        when 'accept'
  84          @user = User.anonymous
  85        when 'create'
  86          @user = create_user_from_email
  87          if @user
  88            if logger && logger.info
  89              logger.info "MailHandler: [#{@user.login}] account created"
  90            end
  91            Mailer.deliver_account_information(@user, @user.password)
  92          else
  93            if logger && logger.error
  94              logger.error "MailHandler: could not create account for [#{sender_email}]"
  95            end
  96            return false
  97          end
  98        else
  99          # Default behaviour, emails from unknown users are ignored
 100          if logger && logger.info
 101            logger.info  "MailHandler: ignoring email from unknown user [#{sender_email}]" 
 102          end
 103          return false
 104        end
 105      end
 106      User.current = @user
 107      dispatch
 108    end
 109 
 110    private
 111 
 112    MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
 113    ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
 114    MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
 115 
 116    def dispatch
 117      headers = [email.in_reply_to, email.references].flatten.compact
 118      if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
 119        klass, object_id = $1, $2.to_i
 120        method_name = "receive_#{klass}_reply"
 121        if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
 122          send method_name, object_id
 123        else
 124          # ignoring it
 125        end
 126      elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
 127        receive_issue_reply(m[1].to_i)
 128      elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
 129        receive_message_reply(m[1].to_i)
 130      else
 131        dispatch_to_default
 132      end
 133    rescue ActiveRecord::RecordInvalid => e
 134      # TODO: send a email to the user
 135      logger.error e.message if logger
 136      false
 137    rescue MissingInformation => e
 138      logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
 139      false
 140    rescue UnauthorizedAction => e
 141      logger.error "MailHandler: unauthorized attempt from #{user}" if logger
 142      false
 143    end
 144 
 145    def dispatch_to_default
 146      receive_issue
 147    end
 148 
 149    # Creates a new issue
 150    def receive_issue
 151      project = target_project
 152      # check permission
 153      unless @@handler_options[:no_permission_check]
 154        raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
 155      end
 156 
 157      issue = Issue.new(:author => user, :project => project)
 158      issue.safe_attributes = issue_attributes_from_keywords(issue)
 159      issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
 160      issue.subject = email.subject.to_s.chomp[0,255]
 161      if issue.subject.blank?
 162        issue.subject = '(no subject)'
 163      end
 164      issue.description = cleaned_up_text_body
 165 
 166      # add To and Cc as watchers before saving so the watchers can reply to Redmine
 167      add_watchers(issue)
 168      issue.save!
 169      add_attachments(issue)
 170      logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
 171      issue
 172    end
 173 
 174    # Adds a note to an existing issue
 175    def receive_issue_reply(issue_id)
 176      issue = Issue.find_by_id(issue_id)
 177      return unless issue
 178      # check permission
 179      unless @@handler_options[:no_permission_check]
 180        unless user.allowed_to?(:add_issue_notes, issue.project) ||
 181                 user.allowed_to?(:edit_issues, issue.project)
 182          raise UnauthorizedAction
 183        end
 184      end
 185 
 186      # ignore CLI-supplied defaults for new issues
 187      @@handler_options[:issue].clear
 188 
 189      journal = issue.init_journal(user)
 190      issue.safe_attributes = issue_attributes_from_keywords(issue)
 191      issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
 192      journal.notes = cleaned_up_text_body
 193      add_attachments(issue)
 194      issue.save!
 195      if logger && logger.info
 196        logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
 197      end
 198      journal
 199    end
 200 
 201    # Reply will be added to the issue
 202    def receive_journal_reply(journal_id)
 203      journal = Journal.find_by_id(journal_id)
 204      if journal && journal.journalized_type == 'Issue'
 205        receive_issue_reply(journal.journalized_id)
 206      end
 207    end
 208 
 209    # Receives a reply to a forum message
 210    def receive_message_reply(message_id)
 211      message = Message.find_by_id(message_id)
 212      if message
 213        message = message.root
 214 
 215        unless @@handler_options[:no_permission_check]
 216          raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
 217        end
 218 
 219        if !message.locked?
 220          reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
 221                              :content => cleaned_up_text_body)
 222          reply.author = user
 223          reply.board = message.board
 224          message.children << reply
 225          add_attachments(reply)
 226          reply
 227        else
 228          if logger && logger.info
 229            logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
 230          end
 231        end
 232      end
 233    end
 234 
 235    def add_attachments(obj)
 236      if email.attachments && email.attachments.any?
 237        email.attachments.each do |attachment|
 238          obj.attachments << Attachment.create(:container => obj,
 239                            :file => attachment,
 240                            :author => user,
 241                            :content_type => attachment.content_type)
 242        end
 243      end
 244    end
 245 
 246    # Adds To and Cc as watchers of the given object if the sender has the
 247    # appropriate permission
 248    def add_watchers(obj)
 249      if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
 250        addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
 251        unless addresses.empty?
 252          watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
 253          watchers.each {|w| obj.add_watcher(w)}
 254        end
 255      end
 256    end
 257 
 258    def get_keyword(attr, options={})
 259      @keywords ||= {}
 260      if @keywords.has_key?(attr)
 261        @keywords[attr]
 262      else
 263        @keywords[attr] = begin
 264          if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
 265                (v = extract_keyword!(plain_text_body, attr, options[:format]))
 266            v
 267          elsif !@@handler_options[:issue][attr].blank?
 268            @@handler_options[:issue][attr]
 269          end
 270        end
 271      end
 272    end
 273 
 274    # Destructively extracts the value for +attr+ in +text+
 275    # Returns nil if no matching keyword found
 276    def extract_keyword!(text, attr, format=nil)
 277      keys = [attr.to_s.humanize]
 278      if attr.is_a?(Symbol)
 279        if user && user.language.present?
 280          keys << l("field_#{attr}", :default => '', :locale =>  user.language)
 281        end
 282        if Setting.default_language.present?
 283          keys << l("field_#{attr}", :default => '', :locale =>  Setting.default_language)
 284        end
 285      end
 286      keys.reject! {|k| k.blank?}
 287      keys.collect! {|k| Regexp.escape(k)}
 288      format ||= '.+'
 289      text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '')
 290      $2 && $2.strip
 291    end
 292 
 293    def target_project
 294      # TODO: other ways to specify project:
 295      # * parse the email To field
 296      # * specific project (eg. Setting.mail_handler_target_project)
 297      target = Project.find_by_identifier(get_keyword(:project))
 298      raise MissingInformation.new('Unable to determine target project') if target.nil?
 299      target
 300    end
 301 
 302    # Returns a Hash of issue attributes extracted from keywords in the email body
 303    def issue_attributes_from_keywords(issue)
 304      assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
 305 
 306      attrs = {
 307        'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
 308        'status_id' =>  (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
 309        'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
 310        'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
 311        'assigned_to_id' => assigned_to.try(:id),
 312        'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
 313                                  issue.project.shared_versions.named(k).first.try(:id),
 314        'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
 315        'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
 316        'estimated_hours' => get_keyword(:estimated_hours, :override => true),
 317        'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
 318      }.delete_if {|k, v| v.blank? }
 319 
 320      if issue.new_record? && attrs['tracker_id'].nil?
 321        attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
 322      end
 323 
 324      attrs
 325    end
 326 
 327    # Returns a Hash of issue custom field values extracted from keywords in the email body
 328    def custom_field_values_from_keywords(customized)
 329      customized.custom_field_values.inject({}) do |h, v|
 330        if value = get_keyword(v.custom_field.name, :override => true)
 331          h[v.custom_field.id.to_s] = value
 332        end
 333        h
 334      end
 335    end
 336 
 337    # Returns the text/plain part of the email
 338    # If not found (eg. HTML-only email), returns the body with tags removed
 339    def plain_text_body
 340      return @plain_text_body unless @plain_text_body.nil?
 341      parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
 342      if parts.empty?
 343        parts << @email
 344      end
 345      plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
 346      if plain_text_part.nil?
 347        # no text/plain part found, assuming html-only email
 348        # strip html tags and remove doctype directive
 349        @plain_text_body = strip_tags(@email.body.to_s)
 350        @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
 351      else
 352        @plain_text_body = plain_text_part.body.to_s
 353      end
 354      @plain_text_body.strip!
 355      @plain_text_body
 356    end
 357 
 358    def cleaned_up_text_body
 359      cleanup_body(plain_text_body)
 360    end
 361 
 362    def self.full_sanitizer
 363      @full_sanitizer ||= HTML::FullSanitizer.new
 364    end
 365 
 366    def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
 367      limit ||= object.class.columns_hash[attribute.to_s].limit || 255
 368      value = value.to_s.slice(0, limit)
 369      object.send("#{attribute}=", value)
 370    end
 371 
 372    # Returns a User from an email address and a full name
 373    def self.new_user_from_attributes(email_address, fullname=nil)
 374      user = User.new
 375 
 376      # Truncating the email address would result in an invalid format
 377      user.mail = email_address
 378      assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
 379 
 380      names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
 381      assign_string_attribute_with_limit(user, 'firstname', names.shift)
 382      assign_string_attribute_with_limit(user, 'lastname', names.join(' '))
 383      user.lastname = '-' if user.lastname.blank?
 384 
 385      password_length = [Setting.password_min_length.to_i, 10].max
 386      user.password = Redmine::Utils.random_hex(password_length / 2 + 1)
 387      user.language = Setting.default_language
 388 
 389      unless user.valid?
 390        user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
 391        user.firstname = "-" unless user.errors[:firstname].blank?
 392        user.lastname  = "-" unless user.errors[:lastname].blank?
 393      end
 394 
 395      user
 396    end
 397 
 398    # Creates a User for the +email+ sender
 399    # Returns the user or nil if it could not be created
 400    def create_user_from_email
 401      addr = email.from_addrs.to_a.first
 402      if addr && !addr.spec.blank?
 403        user = self.class.new_user_from_attributes(addr.spec, TMail::Unquoter.unquote_and_convert_to(addr.name, 'utf-8'))
 404        if user.save
 405          user
 406        else
 407          logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
 408          nil
 409        end
 410      else
 411        logger.error "MailHandler: failed to create User: no FROM address found" if logger
 412        nil
 413      end
 414    end
 415 
 416    # Removes the email body of text after the truncation configurations.
 417    def cleanup_body(body)
 418      delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
 419      unless delimiters.empty?
 420        regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
 421        body = body.gsub(regex, '')
 422      end
 423      body.strip
 424    end
 425 
 426    def find_assignee_from_keyword(keyword, issue)
 427      keyword = keyword.to_s.downcase
 428      assignable = issue.assignable_users
 429      assignee = nil
 430      assignee ||= assignable.detect {|a|
 431                     a.mail.to_s.downcase == keyword ||
 432                       a.login.to_s.downcase == keyword
 433                   }
 434      if assignee.nil? && keyword.match(/ /)
 435        firstname, lastname = *(keyword.split) # "First Last Throwaway"
 436        assignee ||= assignable.detect {|a| 
 437                       a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
 438                         a.lastname.to_s.downcase == lastname
 439                     }
 440      end
 441      if assignee.nil?
 442        assignee ||= assignable.detect {|a| a.is_a?(Group) && a.name.downcase == keyword}
 443      end
 444      assignee
 445    end
 446  end