Chris@1296: # Redmine - project management software Chris@1296: # Copyright (C) 2006-2012 Jean-Philippe Lang Chris@1296: # Chris@1296: # This program is free software; you can redistribute it and/or Chris@1296: # modify it under the terms of the GNU General Public License Chris@1296: # as published by the Free Software Foundation; either version 2 Chris@1296: # of the License, or (at your option) any later version. Chris@1296: # Chris@1296: # This program is distributed in the hope that it will be useful, Chris@1296: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@1296: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@1296: # GNU General Public License for more details. Chris@1296: # Chris@1296: # You should have received a copy of the GNU General Public License Chris@1296: # along with this program; if not, write to the Free Software Chris@1296: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@1296: Chris@1296: class MailHandler < ActionMailer::Base Chris@1296: include ActionView::Helpers::SanitizeHelper Chris@1296: include Redmine::I18n Chris@1296: Chris@1296: class UnauthorizedAction < StandardError; end Chris@1296: class MissingInformation < StandardError; end Chris@1296: Chris@1296: attr_reader :email, :user Chris@1296: Chris@1296: def self.receive(email, options={}) Chris@1296: @@handler_options = options.dup Chris@1296: Chris@1296: @@handler_options[:issue] ||= {} Chris@1296: Chris@1296: if @@handler_options[:allow_override].is_a?(String) Chris@1296: @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) Chris@1296: end Chris@1296: @@handler_options[:allow_override] ||= [] Chris@1296: # Project needs to be overridable if not specified Chris@1296: @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project) Chris@1296: # Status overridable by default Chris@1296: @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status) Chris@1296: Chris@1296: @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false) Chris@1296: Chris@1296: email.force_encoding('ASCII-8BIT') if email.respond_to?(:force_encoding) Chris@1296: super(email) Chris@1296: end Chris@1296: Chris@1296: def logger Chris@1296: Rails.logger Chris@1296: end Chris@1296: Chris@1296: cattr_accessor :ignored_emails_headers Chris@1296: @@ignored_emails_headers = { Chris@1296: 'X-Auto-Response-Suppress' => 'oof', Chris@1296: 'Auto-Submitted' => /^auto-/ Chris@1296: } Chris@1296: Chris@1296: # Processes incoming emails Chris@1296: # Returns the created object (eg. an issue, a message) or false Chris@1296: def receive(email) Chris@1296: @email = email Chris@1296: sender_email = email.from.to_a.first.to_s.strip Chris@1296: # Ignore emails received from the application emission address to avoid hell cycles Chris@1296: if sender_email.downcase == Setting.mail_from.to_s.strip.downcase Chris@1296: if logger && logger.info Chris@1296: logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]" Chris@1296: end Chris@1296: return false Chris@1296: end Chris@1296: # Ignore auto generated emails Chris@1296: self.class.ignored_emails_headers.each do |key, ignored_value| Chris@1296: value = email.header[key] Chris@1296: if value Chris@1296: value = value.to_s.downcase Chris@1296: if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value Chris@1296: if logger && logger.info Chris@1296: logger.info "MailHandler: ignoring email with #{key}:#{value} header" Chris@1296: end Chris@1296: return false Chris@1296: end Chris@1296: end Chris@1296: end Chris@1296: @user = User.find_by_mail(sender_email) if sender_email.present? Chris@1296: if @user && !@user.active? Chris@1296: if logger && logger.info Chris@1296: logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]" Chris@1296: end Chris@1296: return false Chris@1296: end Chris@1296: if @user.nil? Chris@1296: # Email was submitted by an unknown user Chris@1296: case @@handler_options[:unknown_user] Chris@1296: when 'accept' Chris@1296: @user = User.anonymous Chris@1296: when 'create' Chris@1296: @user = create_user_from_email Chris@1296: if @user Chris@1296: if logger && logger.info Chris@1296: logger.info "MailHandler: [#{@user.login}] account created" Chris@1296: end Chris@1296: Mailer.account_information(@user, @user.password).deliver Chris@1296: else Chris@1296: if logger && logger.error Chris@1296: logger.error "MailHandler: could not create account for [#{sender_email}]" Chris@1296: end Chris@1296: return false Chris@1296: end Chris@1296: else Chris@1296: # Default behaviour, emails from unknown users are ignored Chris@1296: if logger && logger.info Chris@1296: logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]" Chris@1296: end Chris@1296: return false Chris@1296: end Chris@1296: end Chris@1296: User.current = @user Chris@1296: dispatch Chris@1296: end Chris@1296: Chris@1296: private Chris@1296: Chris@1296: MESSAGE_ID_RE = %r{^ e Chris@1296: # TODO: send a email to the user Chris@1296: logger.error e.message if logger Chris@1296: false Chris@1296: rescue MissingInformation => e Chris@1296: logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger Chris@1296: false Chris@1296: rescue UnauthorizedAction => e Chris@1296: logger.error "MailHandler: unauthorized attempt from #{user}" if logger Chris@1296: false Chris@1296: end Chris@1296: Chris@1296: def dispatch_to_default Chris@1296: receive_issue Chris@1296: end Chris@1296: Chris@1296: # Creates a new issue Chris@1296: def receive_issue Chris@1296: project = target_project Chris@1296: # check permission Chris@1296: unless @@handler_options[:no_permission_check] Chris@1296: raise UnauthorizedAction unless user.allowed_to?(:add_issues, project) Chris@1296: end Chris@1296: Chris@1296: issue = Issue.new(:author => user, :project => project) Chris@1296: issue.safe_attributes = issue_attributes_from_keywords(issue) Chris@1296: issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)} Chris@1296: issue.subject = cleaned_up_subject Chris@1296: if issue.subject.blank? Chris@1296: issue.subject = '(no subject)' Chris@1296: end Chris@1296: issue.description = cleaned_up_text_body Chris@1296: Chris@1296: # add To and Cc as watchers before saving so the watchers can reply to Redmine Chris@1296: add_watchers(issue) Chris@1296: issue.save! Chris@1296: add_attachments(issue) Chris@1296: logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info Chris@1296: issue Chris@1296: end Chris@1296: Chris@1296: # Adds a note to an existing issue Chris@1296: def receive_issue_reply(issue_id, from_journal=nil) Chris@1296: issue = Issue.find_by_id(issue_id) Chris@1296: return unless issue Chris@1296: # check permission Chris@1296: unless @@handler_options[:no_permission_check] Chris@1296: unless user.allowed_to?(:add_issue_notes, issue.project) || Chris@1296: user.allowed_to?(:edit_issues, issue.project) Chris@1296: raise UnauthorizedAction Chris@1296: end Chris@1296: end Chris@1296: Chris@1296: # ignore CLI-supplied defaults for new issues Chris@1296: @@handler_options[:issue].clear Chris@1296: Chris@1296: journal = issue.init_journal(user) Chris@1296: if from_journal && from_journal.private_notes? Chris@1296: # If the received email was a reply to a private note, make the added note private Chris@1296: issue.private_notes = true Chris@1296: end Chris@1296: issue.safe_attributes = issue_attributes_from_keywords(issue) Chris@1296: issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)} Chris@1296: journal.notes = cleaned_up_text_body Chris@1296: add_attachments(issue) Chris@1296: issue.save! Chris@1296: if logger && logger.info Chris@1296: logger.info "MailHandler: issue ##{issue.id} updated by #{user}" Chris@1296: end Chris@1296: journal Chris@1296: end Chris@1296: Chris@1296: # Reply will be added to the issue Chris@1296: def receive_journal_reply(journal_id) Chris@1296: journal = Journal.find_by_id(journal_id) Chris@1296: if journal && journal.journalized_type == 'Issue' Chris@1296: receive_issue_reply(journal.journalized_id, journal) Chris@1296: end Chris@1296: end Chris@1296: Chris@1296: # Receives a reply to a forum message Chris@1296: def receive_message_reply(message_id) Chris@1296: message = Message.find_by_id(message_id) Chris@1296: if message Chris@1296: message = message.root Chris@1296: Chris@1296: unless @@handler_options[:no_permission_check] Chris@1296: raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project) Chris@1296: end Chris@1296: Chris@1296: if !message.locked? Chris@1296: reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip, Chris@1296: :content => cleaned_up_text_body) Chris@1296: reply.author = user Chris@1296: reply.board = message.board Chris@1296: message.children << reply Chris@1296: add_attachments(reply) Chris@1296: reply Chris@1296: else Chris@1296: if logger && logger.info Chris@1296: logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" Chris@1296: end Chris@1296: end Chris@1296: end Chris@1296: end Chris@1296: Chris@1296: def add_attachments(obj) Chris@1296: if email.attachments && email.attachments.any? Chris@1296: email.attachments.each do |attachment| Chris@1296: obj.attachments << Attachment.create(:container => obj, Chris@1296: :file => attachment.decoded, Chris@1296: :filename => attachment.filename, Chris@1296: :author => user, Chris@1296: :content_type => attachment.mime_type) Chris@1296: end Chris@1296: end Chris@1296: end Chris@1296: Chris@1296: # Adds To and Cc as watchers of the given object if the sender has the Chris@1296: # appropriate permission Chris@1296: def add_watchers(obj) Chris@1296: if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project) Chris@1296: addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase} Chris@1296: unless addresses.empty? Chris@1296: watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses]) Chris@1296: watchers.each {|w| obj.add_watcher(w)} Chris@1296: end Chris@1296: end Chris@1296: end Chris@1296: Chris@1296: def get_keyword(attr, options={}) Chris@1296: @keywords ||= {} Chris@1296: if @keywords.has_key?(attr) Chris@1296: @keywords[attr] Chris@1296: else Chris@1296: @keywords[attr] = begin Chris@1296: if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && Chris@1296: (v = extract_keyword!(plain_text_body, attr, options[:format])) Chris@1296: v Chris@1296: elsif !@@handler_options[:issue][attr].blank? Chris@1296: @@handler_options[:issue][attr] Chris@1296: end Chris@1296: end Chris@1296: end Chris@1296: end Chris@1296: Chris@1296: # Destructively extracts the value for +attr+ in +text+ Chris@1296: # Returns nil if no matching keyword found Chris@1296: def extract_keyword!(text, attr, format=nil) Chris@1296: keys = [attr.to_s.humanize] Chris@1296: if attr.is_a?(Symbol) Chris@1296: if user && user.language.present? Chris@1296: keys << l("field_#{attr}", :default => '', :locale => user.language) Chris@1296: end Chris@1296: if Setting.default_language.present? Chris@1296: keys << l("field_#{attr}", :default => '', :locale => Setting.default_language) Chris@1296: end Chris@1296: end Chris@1296: keys.reject! {|k| k.blank?} Chris@1296: keys.collect! {|k| Regexp.escape(k)} Chris@1296: format ||= '.+' Chris@1296: keyword = nil Chris@1296: regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i Chris@1296: if m = text.match(regexp) Chris@1296: keyword = m[2].strip Chris@1296: text.gsub!(regexp, '') Chris@1296: end Chris@1296: keyword Chris@1296: end Chris@1296: Chris@1296: def target_project Chris@1296: # TODO: other ways to specify project: Chris@1296: # * parse the email To field Chris@1296: # * specific project (eg. Setting.mail_handler_target_project) Chris@1296: target = Project.find_by_identifier(get_keyword(:project)) Chris@1296: raise MissingInformation.new('Unable to determine target project') if target.nil? Chris@1296: target Chris@1296: end Chris@1296: Chris@1296: # Returns a Hash of issue attributes extracted from keywords in the email body Chris@1296: def issue_attributes_from_keywords(issue) Chris@1296: assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue) Chris@1296: Chris@1296: attrs = { Chris@1296: 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id), Chris@1296: 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id), Chris@1296: 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id), Chris@1296: 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id), Chris@1296: 'assigned_to_id' => assigned_to.try(:id), Chris@1296: 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && Chris@1296: issue.project.shared_versions.named(k).first.try(:id), Chris@1296: 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'), Chris@1296: 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'), Chris@1296: 'estimated_hours' => get_keyword(:estimated_hours, :override => true), Chris@1296: 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0') Chris@1296: }.delete_if {|k, v| v.blank? } Chris@1296: Chris@1296: if issue.new_record? && attrs['tracker_id'].nil? Chris@1296: attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id) Chris@1296: end Chris@1296: Chris@1296: attrs Chris@1296: end Chris@1296: Chris@1296: # Returns a Hash of issue custom field values extracted from keywords in the email body Chris@1296: def custom_field_values_from_keywords(customized) Chris@1296: customized.custom_field_values.inject({}) do |h, v| Chris@1296: if keyword = get_keyword(v.custom_field.name, :override => true) Chris@1296: h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized) Chris@1296: end Chris@1296: h Chris@1296: end Chris@1296: end Chris@1296: Chris@1296: # Returns the text/plain part of the email Chris@1296: # If not found (eg. HTML-only email), returns the body with tags removed Chris@1296: def plain_text_body Chris@1296: return @plain_text_body unless @plain_text_body.nil? Chris@1296: Chris@1296: part = email.text_part || email.html_part || email Chris@1296: @plain_text_body = Redmine::CodesetUtil.to_utf8(part.body.decoded, part.charset) Chris@1296: Chris@1296: # strip html tags and remove doctype directive Chris@1296: @plain_text_body = strip_tags(@plain_text_body.strip) Chris@1296: @plain_text_body.sub! %r{^$/) Chris@1296: addr, name = m[2], m[1] Chris@1296: end Chris@1296: if addr.present? Chris@1296: user = self.class.new_user_from_attributes(addr, name) Chris@1296: if user.save Chris@1296: user Chris@1296: else Chris@1296: logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger Chris@1296: nil Chris@1296: end Chris@1296: else Chris@1296: logger.error "MailHandler: failed to create User: no FROM address found" if logger Chris@1296: nil Chris@1296: end Chris@1296: end Chris@1296: Chris@1296: # Removes the email body of text after the truncation configurations. Chris@1296: def cleanup_body(body) Chris@1296: delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)} Chris@1296: unless delimiters.empty? Chris@1296: regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE) Chris@1296: body = body.gsub(regex, '') Chris@1296: end Chris@1296: body.strip Chris@1296: end Chris@1296: Chris@1296: def find_assignee_from_keyword(keyword, issue) Chris@1296: keyword = keyword.to_s.downcase Chris@1296: assignable = issue.assignable_users Chris@1296: assignee = nil Chris@1296: assignee ||= assignable.detect {|a| Chris@1296: a.mail.to_s.downcase == keyword || Chris@1296: a.login.to_s.downcase == keyword Chris@1296: } Chris@1296: if assignee.nil? && keyword.match(/ /) Chris@1296: firstname, lastname = *(keyword.split) # "First Last Throwaway" Chris@1296: assignee ||= assignable.detect {|a| Chris@1296: a.is_a?(User) && a.firstname.to_s.downcase == firstname && Chris@1296: a.lastname.to_s.downcase == lastname Chris@1296: } Chris@1296: end Chris@1296: if assignee.nil? Chris@1296: assignee ||= assignable.detect {|a| a.name.downcase == keyword} Chris@1296: end Chris@1296: assignee Chris@1296: end Chris@1296: end