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