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