##// END OF EJS Templates
fix broken tests on Rails 3.2.13 with Ruby 1.8 (#12399, #12375)...
Toshi MARUYAMA -
r11420:cc5f59abd40e
parent child
Show More
@@ -1,518 +1,488
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 filename = attachment.filename
258 unless filename.respond_to?(:encoding)
259 # try to reencode to utf8 manually with ruby1.8
260 h = attachment.header['Content-Disposition']
261 unless h.nil?
262 begin
263 if m = h.value.match(/filename\*[0-9\*]*=([^=']+)'/)
264 filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
265 elsif m = h.value.match(/filename=.*=\?([^\?]+)\?[BbQq]\?/)
266 # http://tools.ietf.org/html/rfc2047#section-4
267 filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
268 end
269 rescue
270 # nop
271 end
272 end
273 end
274 257 obj.attachments << Attachment.create(:container => obj,
275 258 :file => attachment.decoded,
276 :filename => filename,
259 :filename => attachment.filename,
277 260 :author => user,
278 261 :content_type => attachment.mime_type)
279 262 end
280 263 end
281 264 end
282 265
283 266 # Adds To and Cc as watchers of the given object if the sender has the
284 267 # appropriate permission
285 268 def add_watchers(obj)
286 269 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
287 270 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
288 271 unless addresses.empty?
289 272 watchers = User.active.where('LOWER(mail) IN (?)', addresses).all
290 273 watchers.each {|w| obj.add_watcher(w)}
291 274 end
292 275 end
293 276 end
294 277
295 278 def get_keyword(attr, options={})
296 279 @keywords ||= {}
297 280 if @keywords.has_key?(attr)
298 281 @keywords[attr]
299 282 else
300 283 @keywords[attr] = begin
301 284 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
302 285 (v = extract_keyword!(plain_text_body, attr, options[:format]))
303 286 v
304 287 elsif !@@handler_options[:issue][attr].blank?
305 288 @@handler_options[:issue][attr]
306 289 end
307 290 end
308 291 end
309 292 end
310 293
311 294 # Destructively extracts the value for +attr+ in +text+
312 295 # Returns nil if no matching keyword found
313 296 def extract_keyword!(text, attr, format=nil)
314 297 keys = [attr.to_s.humanize]
315 298 if attr.is_a?(Symbol)
316 299 if user && user.language.present?
317 300 keys << l("field_#{attr}", :default => '', :locale => user.language)
318 301 end
319 302 if Setting.default_language.present?
320 303 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
321 304 end
322 305 end
323 306 keys.reject! {|k| k.blank?}
324 307 keys.collect! {|k| Regexp.escape(k)}
325 308 format ||= '.+'
326 309 keyword = nil
327 310 regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
328 311 if m = text.match(regexp)
329 312 keyword = m[2].strip
330 313 text.gsub!(regexp, '')
331 314 end
332 315 keyword
333 316 end
334 317
335 318 def target_project
336 319 # TODO: other ways to specify project:
337 320 # * parse the email To field
338 321 # * specific project (eg. Setting.mail_handler_target_project)
339 322 target = Project.find_by_identifier(get_keyword(:project))
340 323 raise MissingInformation.new('Unable to determine target project') if target.nil?
341 324 target
342 325 end
343 326
344 327 # Returns a Hash of issue attributes extracted from keywords in the email body
345 328 def issue_attributes_from_keywords(issue)
346 329 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
347 330
348 331 attrs = {
349 332 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
350 333 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
351 334 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
352 335 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
353 336 'assigned_to_id' => assigned_to.try(:id),
354 337 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
355 338 issue.project.shared_versions.named(k).first.try(:id),
356 339 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
357 340 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
358 341 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
359 342 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
360 343 }.delete_if {|k, v| v.blank? }
361 344
362 345 if issue.new_record? && attrs['tracker_id'].nil?
363 346 attrs['tracker_id'] = issue.project.trackers.first.try(:id)
364 347 end
365 348
366 349 attrs
367 350 end
368 351
369 352 # Returns a Hash of issue custom field values extracted from keywords in the email body
370 353 def custom_field_values_from_keywords(customized)
371 354 customized.custom_field_values.inject({}) do |h, v|
372 355 if keyword = get_keyword(v.custom_field.name, :override => true)
373 356 h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
374 357 end
375 358 h
376 359 end
377 360 end
378 361
379 362 # Returns the text/plain part of the email
380 363 # If not found (eg. HTML-only email), returns the body with tags removed
381 364 def plain_text_body
382 365 return @plain_text_body unless @plain_text_body.nil?
383 366
384 367 part = email.text_part || email.html_part || email
385 368 @plain_text_body = Redmine::CodesetUtil.to_utf8(part.body.decoded, part.charset)
386 369
387 370 # strip html tags and remove doctype directive
388 371 @plain_text_body = strip_tags(@plain_text_body.strip)
389 372 @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
390 373 @plain_text_body
391 374 end
392 375
393 376 def cleaned_up_text_body
394 377 cleanup_body(plain_text_body)
395 378 end
396 379
397 380 def cleaned_up_subject
398 381 subject = email.subject.to_s
399 unless subject.respond_to?(:encoding)
400 # try to reencode to utf8 manually with ruby1.8
401 begin
402 if h = email.header[:subject]
403 # http://tools.ietf.org/html/rfc2047#section-4
404 if m = h.value.match(/=\?([^\?]+)\?[BbQq]\?/)
405 subject = Redmine::CodesetUtil.to_utf8(subject, m[1])
406 end
407 end
408 rescue
409 # nop
410 end
411 end
412 382 subject.strip[0,255]
413 383 end
414 384
415 385 def self.full_sanitizer
416 386 @full_sanitizer ||= HTML::FullSanitizer.new
417 387 end
418 388
419 389 def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
420 390 limit ||= object.class.columns_hash[attribute.to_s].limit || 255
421 391 value = value.to_s.slice(0, limit)
422 392 object.send("#{attribute}=", value)
423 393 end
424 394
425 395 # Returns a User from an email address and a full name
426 396 def self.new_user_from_attributes(email_address, fullname=nil)
427 397 user = User.new
428 398
429 399 # Truncating the email address would result in an invalid format
430 400 user.mail = email_address
431 401 assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
432 402
433 403 names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
434 404 assign_string_attribute_with_limit(user, 'firstname', names.shift, 30)
435 405 assign_string_attribute_with_limit(user, 'lastname', names.join(' '), 30)
436 406 user.lastname = '-' if user.lastname.blank?
437 407 user.language = Setting.default_language
438 408 user.generate_password = true
439 409 user.mail_notification = 'only_my_events'
440 410
441 411 unless user.valid?
442 412 user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
443 413 user.firstname = "-" unless user.errors[:firstname].blank?
444 414 (puts user.errors[:lastname];user.lastname = "-") unless user.errors[:lastname].blank?
445 415 end
446 416
447 417 user
448 418 end
449 419
450 420 # Creates a User for the +email+ sender
451 421 # Returns the user or nil if it could not be created
452 422 def create_user_from_email
453 423 from = email.header['from'].to_s
454 424 addr, name = from, nil
455 425 if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
456 426 addr, name = m[2], m[1]
457 427 end
458 428 if addr.present?
459 429 user = self.class.new_user_from_attributes(addr, name)
460 430 if @@handler_options[:no_notification]
461 431 user.mail_notification = 'none'
462 432 end
463 433 if user.save
464 434 user
465 435 else
466 436 logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
467 437 nil
468 438 end
469 439 else
470 440 logger.error "MailHandler: failed to create User: no FROM address found" if logger
471 441 nil
472 442 end
473 443 end
474 444
475 445 # Adds the newly created user to default group
476 446 def add_user_to_group(default_group)
477 447 if default_group.present?
478 448 default_group.split(',').each do |group_name|
479 449 if group = Group.named(group_name).first
480 450 group.users << @user
481 451 elsif logger
482 452 logger.warn "MailHandler: could not add user to [#{group_name}], group not found"
483 453 end
484 454 end
485 455 end
486 456 end
487 457
488 458 # Removes the email body of text after the truncation configurations.
489 459 def cleanup_body(body)
490 460 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
491 461 unless delimiters.empty?
492 462 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
493 463 body = body.gsub(regex, '')
494 464 end
495 465 body.strip
496 466 end
497 467
498 468 def find_assignee_from_keyword(keyword, issue)
499 469 keyword = keyword.to_s.downcase
500 470 assignable = issue.assignable_users
501 471 assignee = nil
502 472 assignee ||= assignable.detect {|a|
503 473 a.mail.to_s.downcase == keyword ||
504 474 a.login.to_s.downcase == keyword
505 475 }
506 476 if assignee.nil? && keyword.match(/ /)
507 477 firstname, lastname = *(keyword.split) # "First Last Throwaway"
508 478 assignee ||= assignable.detect {|a|
509 479 a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
510 480 a.lastname.to_s.downcase == lastname
511 481 }
512 482 end
513 483 if assignee.nil?
514 484 assignee ||= assignable.detect {|a| a.name.downcase == keyword}
515 485 end
516 486 assignee
517 487 end
518 488 end
General Comments 0
You need to be logged in to leave comments. Login now