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