Project

General

Profile

RE: Anonymous Email using Rake and IMAP ยป mail_handler.rb

mail_handler.rb - B. Taylor, 2012-06-14 21:43

 
1
# redMine - project management software
2
# Copyright (C) 2006-2007  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
    @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String)
33
    @@handler_options[:allow_override] ||= []
34
    # Project needs to be overridable if not specified
35
    @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
36
    # Status overridable by default
37
    @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
38

    
39
    @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false)
40
    super email
41
  end
42

    
43
  # Processes incoming emails
44
  # Returns the created object (eg. an issue, a message) or false
45
  def receive(email)
46
    @email = email
47
    sender_email = email.from.to_a.first.to_s.strip
48
    # Ignore emails received from the application emission address to avoid hell cycles
49
    if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
50
      logger.info  "MailHandler: ignoring email from Redmine emission address [#{sender_email}]" if logger && logger.info
51
      return false
52
    end
53
    @user = User.find_by_mail(email.from.to_a.first.to_s.strip)
54
    if @user && !@user.active?
55
      logger.info  "MailHandler: ignoring email from non-active user [#{@user.login}]" if logger && logger.info
56
      return false
57
    end
58
    if @user.nil?
59
      # Email was submitted by an unknown user
60
      case @@handler_options[:unknown_user]
61
      when 'accept'
62
        @user = User.anonymous
63
      when 'create'
64
        @user = MailHandler.create_user_from_email(email)
65
        if @user
66
          logger.info "MailHandler: [#{@user.login}] account created" if logger && logger.info
67
          Mailer.deliver_account_information(@user, @user.password)
68
        else
69
          logger.error "MailHandler: could not create account for [#{email.from.first}]" if logger && logger.error
70
          return false
71
        end
72
      else
73
        # Default behaviour, emails from unknown users are ignored
74
        logger.info  "MailHandler: ignoring email from unknown user [#{email.from.first}]" if logger && logger.info
75
        return false
76
      end
77
    end
78
 User.current = @user
79
    dispatch
80
  end
81

    
82
  private
83

    
84
  MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
85
  ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
86
  MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
87

    
88
  def dispatch
89
    headers = [email.in_reply_to, email.references].flatten.compact
90
    if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
91
      klass, object_id = $1, $2.to_i
92
      method_name = "receive_#{klass}_reply"
93
      if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
94
        send method_name, object_id
95
      else
96
        # ignoring it
97
      end
98
    elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
99
      receive_issue_reply(m[1].to_i)
100
    elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
101
      receive_message_reply(m[1].to_i)
102
    else
103
      dispatch_to_default
104
 end
105
  rescue ActiveRecord::RecordInvalid => e
106
    # TODO: send a email to the user
107
    logger.error e.message if logger
108
    false
109
  rescue MissingInformation => e
110
    logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
111
    false
112
  rescue UnauthorizedAction => e
113
    logger.error "MailHandler: unauthorized attempt from #{user}" if logger
114
    false
115
  end
116

    
117
  def dispatch_to_default
118
    receive_issue
119
  end
120

    
121
  # Creates a new issue
122
  def receive_issue
123
    project = target_project
124
    # check permission
125
    unless @@handler_options[:no_permission_check]
126
      raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
127
    end
128

    
129
    issue = Issue.new(:author => user, :project => project)
130
    issue.safe_attributes = issue_attributes_from_keywords(issue)
131
    issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
132
    issue.subject = email.subject.to_s.chomp[0,255]
133
    if issue.subject.blank?
134
      issue.subject = '(no subject)'
135
    end
136
    issue.description = cleaned_up_text_body
137

    
138
    # add To and Cc as watchers before saving so the watchers can reply to Redmine
139
    add_watchers(issue)
140
    issue.save!
141
    add_attachments(issue)
142
    logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
143
    issue
144
  end
145

    
146
  # Adds a note to an existing issue
147
  def receive_issue_reply(issue_id)
148
    issue = Issue.find_by_id(issue_id)
149
    return unless issue
150
    # check permission
151
    unless @@handler_options[:no_permission_check]
152
      raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
153
    end
154

    
155
    # ignore CLI-supplied defaults for new issues
156
    @@handler_options[:issue].clear
157

    
158
    journal = issue.init_journal(user, cleaned_up_text_body)
159
    issue.safe_attributes = issue_attributes_from_keywords(issue)
160
    issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
161
    add_attachments(issue)
162
    issue.save!
163
    logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
164
    journal
165
  end
166

    
167
  # Reply will be added to the issue
168
  def receive_journal_reply(journal_id)
169
    journal = Journal.find_by_id(journal_id)
170
    if journal && journal.journalized_type == 'Issue'
171
      receive_issue_reply(journal.journalized_id)
172
    end
173
  end
174

    
175
  # Receives a reply to a forum message
176
  def receive_message_reply(message_id)
177
    message = Message.find_by_id(message_id)
178
    if message
179
      message = message.root
180

    
181
      unless @@handler_options[:no_permission_check]
182
        raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
183
      end
184

    
185
      if !message.locked?
186
        reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
187
                            :content => cleaned_up_text_body)
188
        reply.author = user
189
        reply.board = message.board
190
        message.children << reply
191
        add_attachments(reply)
192
        reply
193
      else
194
        logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" if logger && logger.info
195
      end
196
    end
197
  end
198

    
199
  def add_attachments(obj)
200
    if email.has_attachments?
201
      email.attachments.each do |attachment|
202
        Attachment.create(:container => obj,
203
                          :file => attachment,
204
                          :author => user,
205
                          :content_type => attachment.content_type)
206
      end
207
    end
208
  end
209

    
210
  # Adds To and Cc as watchers of the given object if the sender has the
211
  # appropriate permission
212
  def add_watchers(obj)
213
    if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
214
      addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
215
      unless addresses.empty?
216
        watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
217
        watchers.each {|w| obj.add_watcher(w)}
218
      end
219
    end
220
  end
221

    
222
  def get_keyword(attr, options={})
223
    @keywords ||= {}
224
    if @keywords.has_key?(attr)
225
      @keywords[attr]
226
    else
227
      @keywords[attr] = begin
228
        if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && (v = extract_keyword!(plain_text_body, attr, options[:format]))
229
          v
230
        elsif !@@handler_options[:issue][attr].blank?
231
          @@handler_options[:issue][attr]
232
        end
233
      end
234
    end
235
  end
236

    
237
  # Destructively extracts the value for +attr+ in +text+
238
  # Returns nil if no matching keyword found
239
  def extract_keyword!(text, attr, format=nil)
240
    keys = [attr.to_s.humanize]
241
    if attr.is_a?(Symbol)
242
      keys << l("field_#{attr}", :default => '', :locale =>  user.language) if user
243
      keys << l("field_#{attr}", :default => '', :locale =>  Setting.default_language)
244
    end
245
    keys.reject! {|k| k.blank?}
246
    keys.collect! {|k| Regexp.escape(k)}
247
    format ||= '.+'
248
    text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '')
249
    $2 && $2.strip
250
  end
251

    
252
  def target_project
253
    # TODO: other ways to specify project:
254
    # * parse the email To field
255
    # * specific project (eg. Setting.mail_handler_target_project)
256
    target = Project.find_by_identifier(get_keyword(:project))
257
    raise MissingInformation.new('Unable to determine target project') if target.nil?
258
    target
259
  end
260

    
261
  # Returns a Hash of issue attributes extracted from keywords in the email body
262
  def issue_attributes_from_keywords(issue)
263
    assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_user_from_keyword(k)
264
    assigned_to = nil if assigned_to && !issue.assignable_users.include?(assigned_to)
265

    
266
    attrs = {
267
      'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.find_by_name(k).try(:id),
268
      'status_id' =>  (k = get_keyword(:status)) && IssueStatus.find_by_name(k).try(:id),
269
      'priority_id' => (k = get_keyword(:priority)) && IssuePriority.find_by_name(k).try(:id),
270
      'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.find_by_name(k).try(:id),
271
      'assigned_to_id' => assigned_to.try(:id),
272
      'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && issue.project.shared_versions.find_by_name(k).try(:id),
273
      'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
274
      'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
275
      'estimated_hours' => get_keyword(:estimated_hours, :override => true),
276
      'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
277
    }.delete_if {|k, v| v.blank? }
278

    
279
    if issue.new_record? && attrs['tracker_id'].nil?
280
      attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
281
    end
282

    
283
    attrs
284
  end
285

    
286
  # Returns a Hash of issue custom field values extracted from keywords in the email body
287
  def custom_field_values_from_keywords(customized)
288
    customized.custom_field_values.inject({}) do |h, v|
289
      if value = get_keyword(v.custom_field.name, :override => true)
290
        h[v.custom_field.id.to_s] = value
291
      end
292
      h
293
    end
294
  end
295

    
296
  # Returns the text/plain part of the email
297
  # If not found (eg. HTML-only email), returns the body with tags removed
298
  def plain_text_body
299
    return @plain_text_body unless @plain_text_body.nil?
300
    parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
301
    if parts.empty?
302
      parts << @email
303
    end
304
    plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
305
    if plain_text_part.nil?
306
      # no text/plain part found, assuming html-only email
307
      # strip html tags and remove doctype directive
308
      @plain_text_body = strip_tags(@email.body.to_s)
309
      @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
310
    else
311
      @plain_text_body = plain_text_part.body.to_s
312
	      end
313
    @plain_text_body.strip!
314
    @plain_text_body
315
  end
316

    
317
  def cleaned_up_text_body
318
    cleanup_body(plain_text_body)
319
  end
320

    
321
  def self.full_sanitizer
322
    @full_sanitizer ||= HTML::FullSanitizer.new
323
  end
324

    
325
# Creates a user account for the +email+ sender
326
  def self.create_user_from_email(email)
327
    addr = email.from_addrs.to_a.first
328
    if addr && !addr.spec.blank?
329
      user = User.new
330
      user.mail = addr.spec
331
      names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split
332
      user.firstname = names.shift
333
      user.lastname = names.join(' ')
334
      user.lastname = '-' if user.lastname.blank?
335
      user.login = user.mail
336
      user.password = ActiveSupport::SecureRandom.hex(5)
337
      user.language = Setting.default_language
338
      user.save ? user : nil
339
    end
340
  end
341

    
342
  private
343

    
344
  # Removes the email body of text after the truncation configurations.
345
  def cleanup_body(body)
346
    delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
347
    unless delimiters.empty?
348
      regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
349
      body = body.gsub(regex, '')
350
    end
351
    body.strip
352
  end
353

    
354
  def find_user_from_keyword(keyword)
355
    user ||= User.find_by_mail(keyword)
356
    user ||= User.find_by_login(keyword)
357
    if user.nil? && keyword.match(/ /)
358
      firstname, lastname = *(keyword.split) # "First Last Throwaway"
359
      user ||= User.find_by_firstname_and_lastname(firstname, lastname)
360
    end
361
    user
362
  end
363
end
    (1-1/1)