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