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