##// END OF EJS Templates
Don't use a class variable for mail handler options....
Jean-Philippe Lang -
r13846:efe67602c616
parent child
Show More
@@ -1,546 +1,552
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2015 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class MailHandler < ActionMailer::Base
19 19 include ActionView::Helpers::SanitizeHelper
20 20 include Redmine::I18n
21 21
22 22 class UnauthorizedAction < StandardError; end
23 23 class MissingInformation < StandardError; end
24 24
25 attr_reader :email, :user
25 attr_reader :email, :user, :handler_options
26 26
27 def self.receive(email, options={})
28 @@handler_options = options.deep_dup
27 def self.receive(raw_mail, options={})
28 options = options.deep_dup
29 29
30 @@handler_options[:issue] ||= {}
30 options[:issue] ||= {}
31 31
32 if @@handler_options[:allow_override].is_a?(String)
33 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip)
32 if options[:allow_override].is_a?(String)
33 options[:allow_override] = options[:allow_override].split(',').collect(&:strip)
34 34 end
35 @@handler_options[:allow_override] ||= []
35 options[:allow_override] ||= []
36 36 # Project needs to be overridable if not specified
37 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
37 options[:allow_override] << 'project' unless options[:issue].has_key?(:project)
38 38 # Status overridable by default
39 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
39 options[:allow_override] << 'status' unless options[:issue].has_key?(:status)
40 40
41 @@handler_options[:no_account_notice] = (@@handler_options[:no_account_notice].to_s == '1')
42 @@handler_options[:no_notification] = (@@handler_options[:no_notification].to_s == '1')
43 @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1')
41 options[:no_account_notice] = (options[:no_account_notice].to_s == '1')
42 options[:no_notification] = (options[:no_notification].to_s == '1')
43 options[:no_permission_check] = (options[:no_permission_check].to_s == '1')
44 44
45 email.force_encoding('ASCII-8BIT')
46 super(email)
45 raw_mail.force_encoding('ASCII-8BIT')
46
47 ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
48 mail = Mail.new(raw_mail)
49 set_payload_for_mail(payload, mail)
50 new.receive(mail, options)
51 end
47 52 end
48 53
49 54 # Receives an email and rescues any exception
50 55 def self.safe_receive(*args)
51 56 receive(*args)
52 57 rescue Exception => e
53 58 logger.error "An unexpected error occurred when receiving email: #{e.message}" if logger
54 59 return false
55 60 end
56 61
57 62 # Extracts MailHandler options from environment variables
58 63 # Use when receiving emails with rake tasks
59 64 def self.extract_options_from_env(env)
60 65 options = {:issue => {}}
61 66 %w(project status tracker category priority).each do |option|
62 67 options[:issue][option.to_sym] = env[option] if env[option]
63 68 end
64 69 %w(allow_override unknown_user no_permission_check no_account_notice default_group).each do |option|
65 70 options[option.to_sym] = env[option] if env[option]
66 71 end
67 72 options
68 73 end
69 74
70 75 def logger
71 76 Rails.logger
72 77 end
73 78
74 79 cattr_accessor :ignored_emails_headers
75 80 @@ignored_emails_headers = {
76 81 'Auto-Submitted' => /\Aauto-(replied|generated)/,
77 82 'X-Autoreply' => 'yes'
78 83 }
79 84
80 85 # Processes incoming emails
81 86 # Returns the created object (eg. an issue, a message) or false
82 def receive(email)
87 def receive(email, options={})
83 88 @email = email
89 @handler_options = options
84 90 sender_email = email.from.to_a.first.to_s.strip
85 91 # Ignore emails received from the application emission address to avoid hell cycles
86 92 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
87 93 if logger
88 94 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
89 95 end
90 96 return false
91 97 end
92 98 # Ignore auto generated emails
93 99 self.class.ignored_emails_headers.each do |key, ignored_value|
94 100 value = email.header[key]
95 101 if value
96 102 value = value.to_s.downcase
97 103 if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
98 104 if logger
99 105 logger.info "MailHandler: ignoring email with #{key}:#{value} header"
100 106 end
101 107 return false
102 108 end
103 109 end
104 110 end
105 111 @user = User.find_by_mail(sender_email) if sender_email.present?
106 112 if @user && !@user.active?
107 113 if logger
108 114 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]"
109 115 end
110 116 return false
111 117 end
112 118 if @user.nil?
113 119 # Email was submitted by an unknown user
114 case @@handler_options[:unknown_user]
120 case handler_options[:unknown_user]
115 121 when 'accept'
116 122 @user = User.anonymous
117 123 when 'create'
118 124 @user = create_user_from_email
119 125 if @user
120 126 if logger
121 127 logger.info "MailHandler: [#{@user.login}] account created"
122 128 end
123 add_user_to_group(@@handler_options[:default_group])
124 unless @@handler_options[:no_account_notice]
129 add_user_to_group(handler_options[:default_group])
130 unless handler_options[:no_account_notice]
125 131 Mailer.account_information(@user, @user.password).deliver
126 132 end
127 133 else
128 134 if logger
129 135 logger.error "MailHandler: could not create account for [#{sender_email}]"
130 136 end
131 137 return false
132 138 end
133 139 else
134 140 # Default behaviour, emails from unknown users are ignored
135 141 if logger
136 142 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]"
137 143 end
138 144 return false
139 145 end
140 146 end
141 147 User.current = @user
142 148 dispatch
143 149 end
144 150
145 151 private
146 152
147 153 MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+(\.[a-f0-9]+)?@}
148 154 ISSUE_REPLY_SUBJECT_RE = %r{\[(?:[^\]]*\s+)?#(\d+)\]}
149 155 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
150 156
151 157 def dispatch
152 158 headers = [email.in_reply_to, email.references].flatten.compact
153 159 subject = email.subject.to_s
154 160 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
155 161 klass, object_id = $1, $2.to_i
156 162 method_name = "receive_#{klass}_reply"
157 163 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
158 164 send method_name, object_id
159 165 else
160 166 # ignoring it
161 167 end
162 168 elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
163 169 receive_issue_reply(m[1].to_i)
164 170 elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
165 171 receive_message_reply(m[1].to_i)
166 172 else
167 173 dispatch_to_default
168 174 end
169 175 rescue ActiveRecord::RecordInvalid => e
170 176 # TODO: send a email to the user
171 177 logger.error e.message if logger
172 178 false
173 179 rescue MissingInformation => e
174 180 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
175 181 false
176 182 rescue UnauthorizedAction => e
177 183 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
178 184 false
179 185 end
180 186
181 187 def dispatch_to_default
182 188 receive_issue
183 189 end
184 190
185 191 # Creates a new issue
186 192 def receive_issue
187 193 project = target_project
188 194 # check permission
189 unless @@handler_options[:no_permission_check]
195 unless handler_options[:no_permission_check]
190 196 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
191 197 end
192 198
193 199 issue = Issue.new(:author => user, :project => project)
194 200 issue.safe_attributes = issue_attributes_from_keywords(issue)
195 201 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
196 202 issue.subject = cleaned_up_subject
197 203 if issue.subject.blank?
198 204 issue.subject = '(no subject)'
199 205 end
200 206 issue.description = cleaned_up_text_body
201 207 issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
202 208
203 209 # add To and Cc as watchers before saving so the watchers can reply to Redmine
204 210 add_watchers(issue)
205 211 issue.save!
206 212 add_attachments(issue)
207 213 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger
208 214 issue
209 215 end
210 216
211 217 # Adds a note to an existing issue
212 218 def receive_issue_reply(issue_id, from_journal=nil)
213 219 issue = Issue.find_by_id(issue_id)
214 220 return unless issue
215 221 # check permission
216 unless @@handler_options[:no_permission_check]
222 unless handler_options[:no_permission_check]
217 223 unless user.allowed_to?(:add_issue_notes, issue.project) ||
218 224 user.allowed_to?(:edit_issues, issue.project)
219 225 raise UnauthorizedAction
220 226 end
221 227 end
222 228
223 229 # ignore CLI-supplied defaults for new issues
224 @@handler_options[:issue].clear
230 handler_options[:issue].clear
225 231
226 232 journal = issue.init_journal(user)
227 233 if from_journal && from_journal.private_notes?
228 234 # If the received email was a reply to a private note, make the added note private
229 235 issue.private_notes = true
230 236 end
231 237 issue.safe_attributes = issue_attributes_from_keywords(issue)
232 238 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
233 239 journal.notes = cleaned_up_text_body
234 240 add_attachments(issue)
235 241 issue.save!
236 242 if logger
237 243 logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
238 244 end
239 245 journal
240 246 end
241 247
242 248 # Reply will be added to the issue
243 249 def receive_journal_reply(journal_id)
244 250 journal = Journal.find_by_id(journal_id)
245 251 if journal && journal.journalized_type == 'Issue'
246 252 receive_issue_reply(journal.journalized_id, journal)
247 253 end
248 254 end
249 255
250 256 # Receives a reply to a forum message
251 257 def receive_message_reply(message_id)
252 258 message = Message.find_by_id(message_id)
253 259 if message
254 260 message = message.root
255 261
256 unless @@handler_options[:no_permission_check]
262 unless handler_options[:no_permission_check]
257 263 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
258 264 end
259 265
260 266 if !message.locked?
261 267 reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
262 268 :content => cleaned_up_text_body)
263 269 reply.author = user
264 270 reply.board = message.board
265 271 message.children << reply
266 272 add_attachments(reply)
267 273 reply
268 274 else
269 275 if logger
270 276 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
271 277 end
272 278 end
273 279 end
274 280 end
275 281
276 282 def add_attachments(obj)
277 283 if email.attachments && email.attachments.any?
278 284 email.attachments.each do |attachment|
279 285 next unless accept_attachment?(attachment)
280 286 obj.attachments << Attachment.create(:container => obj,
281 287 :file => attachment.decoded,
282 288 :filename => attachment.filename,
283 289 :author => user,
284 290 :content_type => attachment.mime_type)
285 291 end
286 292 end
287 293 end
288 294
289 295 # Returns false if the +attachment+ of the incoming email should be ignored
290 296 def accept_attachment?(attachment)
291 297 @excluded ||= Setting.mail_handler_excluded_filenames.to_s.split(',').map(&:strip).reject(&:blank?)
292 298 @excluded.each do |pattern|
293 299 regexp = %r{\A#{Regexp.escape(pattern).gsub("\\*", ".*")}\z}i
294 300 if attachment.filename.to_s =~ regexp
295 301 logger.info "MailHandler: ignoring attachment #{attachment.filename} matching #{pattern}"
296 302 return false
297 303 end
298 304 end
299 305 true
300 306 end
301 307
302 308 # Adds To and Cc as watchers of the given object if the sender has the
303 309 # appropriate permission
304 310 def add_watchers(obj)
305 311 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
306 312 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
307 313 unless addresses.empty?
308 314 User.active.having_mail(addresses).each do |w|
309 315 obj.add_watcher(w)
310 316 end
311 317 end
312 318 end
313 319 end
314 320
315 321 def get_keyword(attr, options={})
316 322 @keywords ||= {}
317 323 if @keywords.has_key?(attr)
318 324 @keywords[attr]
319 325 else
320 326 @keywords[attr] = begin
321 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
327 if (options[:override] || handler_options[:allow_override].include?(attr.to_s)) &&
322 328 (v = extract_keyword!(cleaned_up_text_body, attr, options[:format]))
323 329 v
324 elsif !@@handler_options[:issue][attr].blank?
325 @@handler_options[:issue][attr]
330 elsif !handler_options[:issue][attr].blank?
331 handler_options[:issue][attr]
326 332 end
327 333 end
328 334 end
329 335 end
330 336
331 337 # Destructively extracts the value for +attr+ in +text+
332 338 # Returns nil if no matching keyword found
333 339 def extract_keyword!(text, attr, format=nil)
334 340 keys = [attr.to_s.humanize]
335 341 if attr.is_a?(Symbol)
336 342 if user && user.language.present?
337 343 keys << l("field_#{attr}", :default => '', :locale => user.language)
338 344 end
339 345 if Setting.default_language.present?
340 346 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
341 347 end
342 348 end
343 349 keys.reject! {|k| k.blank?}
344 350 keys.collect! {|k| Regexp.escape(k)}
345 351 format ||= '.+'
346 352 keyword = nil
347 353 regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
348 354 if m = text.match(regexp)
349 355 keyword = m[2].strip
350 356 text.sub!(regexp, '')
351 357 end
352 358 keyword
353 359 end
354 360
355 361 def target_project
356 362 # TODO: other ways to specify project:
357 363 # * parse the email To field
358 364 # * specific project (eg. Setting.mail_handler_target_project)
359 365 target = Project.find_by_identifier(get_keyword(:project))
360 366 if target.nil?
361 367 # Invalid project keyword, use the project specified as the default one
362 default_project = @@handler_options[:issue][:project]
368 default_project = handler_options[:issue][:project]
363 369 if default_project.present?
364 370 target = Project.find_by_identifier(default_project)
365 371 end
366 372 end
367 373 raise MissingInformation.new('Unable to determine target project') if target.nil?
368 374 target
369 375 end
370 376
371 377 # Returns a Hash of issue attributes extracted from keywords in the email body
372 378 def issue_attributes_from_keywords(issue)
373 379 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
374 380
375 381 attrs = {
376 382 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
377 383 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
378 384 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
379 385 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
380 386 'assigned_to_id' => assigned_to.try(:id),
381 387 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
382 388 issue.project.shared_versions.named(k).first.try(:id),
383 389 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
384 390 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
385 391 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
386 392 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
387 393 }.delete_if {|k, v| v.blank? }
388 394
389 395 if issue.new_record? && attrs['tracker_id'].nil?
390 396 attrs['tracker_id'] = issue.project.trackers.first.try(:id)
391 397 end
392 398
393 399 attrs
394 400 end
395 401
396 402 # Returns a Hash of issue custom field values extracted from keywords in the email body
397 403 def custom_field_values_from_keywords(customized)
398 404 customized.custom_field_values.inject({}) do |h, v|
399 405 if keyword = get_keyword(v.custom_field.name, :override => true)
400 406 h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
401 407 end
402 408 h
403 409 end
404 410 end
405 411
406 412 # Returns the text/plain part of the email
407 413 # If not found (eg. HTML-only email), returns the body with tags removed
408 414 def plain_text_body
409 415 return @plain_text_body unless @plain_text_body.nil?
410 416
411 417 parts = if (text_parts = email.all_parts.select {|p| p.mime_type == 'text/plain'}).present?
412 418 text_parts
413 419 elsif (html_parts = email.all_parts.select {|p| p.mime_type == 'text/html'}).present?
414 420 html_parts
415 421 else
416 422 [email]
417 423 end
418 424
419 425 parts.reject! do |part|
420 426 part.attachment?
421 427 end
422 428
423 429 @plain_text_body = parts.map do |p|
424 430 body_charset = Mail::RubyVer.respond_to?(:pick_encoding) ?
425 431 Mail::RubyVer.pick_encoding(p.charset).to_s : p.charset
426 432 Redmine::CodesetUtil.to_utf8(p.body.decoded, body_charset)
427 433 end.join("\r\n")
428 434
429 435 # strip html tags and remove doctype directive
430 436 if parts.any? {|p| p.mime_type == 'text/html'}
431 437 @plain_text_body = strip_tags(@plain_text_body.strip)
432 438 @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
433 439 end
434 440
435 441 @plain_text_body
436 442 end
437 443
438 444 def cleaned_up_text_body
439 445 @cleaned_up_text_body ||= cleanup_body(plain_text_body)
440 446 end
441 447
442 448 def cleaned_up_subject
443 449 subject = email.subject.to_s
444 450 subject.strip[0,255]
445 451 end
446 452
447 453 def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
448 454 limit ||= object.class.columns_hash[attribute.to_s].limit || 255
449 455 value = value.to_s.slice(0, limit)
450 456 object.send("#{attribute}=", value)
451 457 end
452 458
453 459 # Returns a User from an email address and a full name
454 460 def self.new_user_from_attributes(email_address, fullname=nil)
455 461 user = User.new
456 462
457 463 # Truncating the email address would result in an invalid format
458 464 user.mail = email_address
459 465 assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
460 466
461 467 names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
462 468 assign_string_attribute_with_limit(user, 'firstname', names.shift, 30)
463 469 assign_string_attribute_with_limit(user, 'lastname', names.join(' '), 30)
464 470 user.lastname = '-' if user.lastname.blank?
465 471 user.language = Setting.default_language
466 472 user.generate_password = true
467 473 user.mail_notification = 'only_my_events'
468 474
469 475 unless user.valid?
470 476 user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
471 477 user.firstname = "-" unless user.errors[:firstname].blank?
472 478 (puts user.errors[:lastname];user.lastname = "-") unless user.errors[:lastname].blank?
473 479 end
474 480
475 481 user
476 482 end
477 483
478 484 # Creates a User for the +email+ sender
479 485 # Returns the user or nil if it could not be created
480 486 def create_user_from_email
481 487 from = email.header['from'].to_s
482 488 addr, name = from, nil
483 489 if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
484 490 addr, name = m[2], m[1]
485 491 end
486 492 if addr.present?
487 493 user = self.class.new_user_from_attributes(addr, name)
488 if @@handler_options[:no_notification]
494 if handler_options[:no_notification]
489 495 user.mail_notification = 'none'
490 496 end
491 497 if user.save
492 498 user
493 499 else
494 500 logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
495 501 nil
496 502 end
497 503 else
498 504 logger.error "MailHandler: failed to create User: no FROM address found" if logger
499 505 nil
500 506 end
501 507 end
502 508
503 509 # Adds the newly created user to default group
504 510 def add_user_to_group(default_group)
505 511 if default_group.present?
506 512 default_group.split(',').each do |group_name|
507 513 if group = Group.named(group_name).first
508 514 group.users << @user
509 515 elsif logger
510 516 logger.warn "MailHandler: could not add user to [#{group_name}], group not found"
511 517 end
512 518 end
513 519 end
514 520 end
515 521
516 522 # Removes the email body of text after the truncation configurations.
517 523 def cleanup_body(body)
518 524 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
519 525 unless delimiters.empty?
520 526 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
521 527 body = body.gsub(regex, '')
522 528 end
523 529 body.strip
524 530 end
525 531
526 532 def find_assignee_from_keyword(keyword, issue)
527 533 keyword = keyword.to_s.downcase
528 534 assignable = issue.assignable_users
529 535 assignee = nil
530 536 assignee ||= assignable.detect {|a|
531 537 a.mail.to_s.downcase == keyword ||
532 538 a.login.to_s.downcase == keyword
533 539 }
534 540 if assignee.nil? && keyword.match(/ /)
535 541 firstname, lastname = *(keyword.split) # "First Last Throwaway"
536 542 assignee ||= assignable.detect {|a|
537 543 a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
538 544 a.lastname.to_s.downcase == lastname
539 545 }
540 546 end
541 547 if assignee.nil?
542 548 assignee ||= assignable.detect {|a| a.name.downcase == keyword}
543 549 end
544 550 assignee
545 551 end
546 552 end
General Comments 0
You need to be logged in to leave comments. Login now