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