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