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