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