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