comparison app/models/mail_handler.rb @ 514:7eba09d624db live

Merge
author Chris Cannam
date Thu, 14 Jul 2011 10:50:53 +0100
parents 851510f1b535
children 5e80956cc792
comparison
equal deleted inserted replaced
512:b9aebdd7dd40 514:7eba09d624db
1 # redMine - project management software 1 # Redmine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 # 3 #
4 # This program is free software; you can redistribute it and/or 4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License 5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2 6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version. 7 # of the License, or (at your option) any later version.
8 # 8 #
9 # This program is distributed in the hope that it will be useful, 9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details. 12 # GNU General Public License for more details.
13 # 13 #
14 # You should have received a copy of the GNU General Public License 14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software 15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 class MailHandler < ActionMailer::Base 18 class MailHandler < ActionMailer::Base
19 include ActionView::Helpers::SanitizeHelper 19 include ActionView::Helpers::SanitizeHelper
20 include Redmine::I18n 20 include Redmine::I18n
21 21
22 class UnauthorizedAction < StandardError; end 22 class UnauthorizedAction < StandardError; end
23 class MissingInformation < StandardError; end 23 class MissingInformation < StandardError; end
24 24
25 attr_reader :email, :user 25 attr_reader :email, :user
26 26
27 def self.receive(email, options={}) 27 def self.receive(email, options={})
28 @@handler_options = options.dup 28 @@handler_options = options.dup
29 29
30 @@handler_options[:issue] ||= {} 30 @@handler_options[:issue] ||= {}
31 31
32 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String) 32 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String)
33 @@handler_options[:allow_override] ||= [] 33 @@handler_options[:allow_override] ||= []
34 # Project needs to be overridable if not specified 34 # Project needs to be overridable if not specified
35 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project) 35 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
36 # Status overridable by default 36 # Status overridable by default
37 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status) 37 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
38 38
39 @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false) 39 @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false)
40 super email 40 super email
41 end 41 end
42 42
43 # Processes incoming emails 43 # Processes incoming emails
44 # Returns the created object (eg. an issue, a message) or false 44 # Returns the created object (eg. an issue, a message) or false
45 def receive(email) 45 def receive(email)
46 @email = email 46 @email = email
47 sender_email = email.from.to_a.first.to_s.strip 47 sender_email = email.from.to_a.first.to_s.strip
76 end 76 end
77 end 77 end
78 User.current = @user 78 User.current = @user
79 dispatch 79 dispatch
80 end 80 end
81 81
82 private 82 private
83 83
84 MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@} 84 MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
85 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]} 85 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
86 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]} 86 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
87 87
88 def dispatch 88 def dispatch
89 headers = [email.in_reply_to, email.references].flatten.compact 89 headers = [email.in_reply_to, email.references].flatten.compact
90 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE} 90 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
91 klass, object_id = $1, $2.to_i 91 klass, object_id = $1, $2.to_i
92 method_name = "receive_#{klass}_reply" 92 method_name = "receive_#{klass}_reply"
98 elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE) 98 elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
99 receive_issue_reply(m[1].to_i) 99 receive_issue_reply(m[1].to_i)
100 elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE) 100 elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
101 receive_message_reply(m[1].to_i) 101 receive_message_reply(m[1].to_i)
102 else 102 else
103 receive_issue 103 dispatch_to_default
104 end 104 end
105 rescue ActiveRecord::RecordInvalid => e 105 rescue ActiveRecord::RecordInvalid => e
106 # TODO: send a email to the user 106 # TODO: send a email to the user
107 logger.error e.message if logger 107 logger.error e.message if logger
108 false 108 false
111 false 111 false
112 rescue UnauthorizedAction => e 112 rescue UnauthorizedAction => e
113 logger.error "MailHandler: unauthorized attempt from #{user}" if logger 113 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
114 false 114 false
115 end 115 end
116 116
117 def dispatch_to_default
118 receive_issue
119 end
120
117 # Creates a new issue 121 # Creates a new issue
118 def receive_issue 122 def receive_issue
119 project = target_project 123 project = target_project
120 # check permission 124 # check permission
121 unless @@handler_options[:no_permission_check] 125 unless @@handler_options[:no_permission_check]
128 issue.subject = email.subject.to_s.chomp[0,255] 132 issue.subject = email.subject.to_s.chomp[0,255]
129 if issue.subject.blank? 133 if issue.subject.blank?
130 issue.subject = '(no subject)' 134 issue.subject = '(no subject)'
131 end 135 end
132 issue.description = cleaned_up_text_body 136 issue.description = cleaned_up_text_body
133 137
134 # add To and Cc as watchers before saving so the watchers can reply to Redmine 138 # add To and Cc as watchers before saving so the watchers can reply to Redmine
135 add_watchers(issue) 139 add_watchers(issue)
136 issue.save! 140 issue.save!
137 add_attachments(issue) 141 add_attachments(issue)
138 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info 142 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
139 issue 143 issue
140 end 144 end
141 145
142 # Adds a note to an existing issue 146 # Adds a note to an existing issue
143 def receive_issue_reply(issue_id) 147 def receive_issue_reply(issue_id)
144 issue = Issue.find_by_id(issue_id) 148 issue = Issue.find_by_id(issue_id)
145 return unless issue 149 return unless issue
146 # check permission 150 # check permission
147 unless @@handler_options[:no_permission_check] 151 unless @@handler_options[:no_permission_check]
148 raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project) 152 raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
149 end 153 end
150 154
151 journal = issue.init_journal(user, cleaned_up_text_body) 155 # ignore CLI-supplied defaults for new issues
156 @@handler_options[:issue].clear
157
158 journal = issue.init_journal(user)
152 issue.safe_attributes = issue_attributes_from_keywords(issue) 159 issue.safe_attributes = issue_attributes_from_keywords(issue)
153 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)} 160 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
161 journal.notes = cleaned_up_text_body
154 add_attachments(issue) 162 add_attachments(issue)
155 issue.save! 163 issue.save!
156 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info 164 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
157 journal 165 journal
158 end 166 end
159 167
160 # Reply will be added to the issue 168 # Reply will be added to the issue
161 def receive_journal_reply(journal_id) 169 def receive_journal_reply(journal_id)
162 journal = Journal.find_by_id(journal_id) 170 journal = Journal.find_by_id(journal_id)
163 if journal && journal.journalized_type == 'Issue' 171 if journal && journal.journalized_type == 'Issue'
164 receive_issue_reply(journal.journalized_id) 172 receive_issue_reply(journal.journalized_id)
165 end 173 end
166 end 174 end
167 175
168 # Receives a reply to a forum message 176 # Receives a reply to a forum message
169 def receive_message_reply(message_id) 177 def receive_message_reply(message_id)
170 message = Message.find_by_id(message_id) 178 message = Message.find_by_id(message_id)
171 if message 179 if message
172 message = message.root 180 message = message.root
173 181
174 unless @@handler_options[:no_permission_check] 182 unless @@handler_options[:no_permission_check]
175 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project) 183 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
176 end 184 end
177 185
178 if !message.locked? 186 if !message.locked?
179 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip, 187 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
180 :content => cleaned_up_text_body) 188 :content => cleaned_up_text_body)
181 reply.author = user 189 reply.author = user
182 reply.board = message.board 190 reply.board = message.board
186 else 194 else
187 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" if logger && logger.info 195 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" if logger && logger.info
188 end 196 end
189 end 197 end
190 end 198 end
191 199
192 def add_attachments(obj) 200 def add_attachments(obj)
193 if email.has_attachments? 201 if email.has_attachments?
194 email.attachments.each do |attachment| 202 email.attachments.each do |attachment|
195 Attachment.create(:container => obj, 203 Attachment.create(:container => obj,
196 :file => attachment, 204 :file => attachment,
197 :author => user, 205 :author => user,
198 :content_type => attachment.content_type) 206 :content_type => attachment.content_type)
199 end 207 end
200 end 208 end
201 end 209 end
202 210
203 # Adds To and Cc as watchers of the given object if the sender has the 211 # Adds To and Cc as watchers of the given object if the sender has the
204 # appropriate permission 212 # appropriate permission
205 def add_watchers(obj) 213 def add_watchers(obj)
206 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project) 214 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
207 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase} 215 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
209 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses]) 217 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
210 watchers.each {|w| obj.add_watcher(w)} 218 watchers.each {|w| obj.add_watcher(w)}
211 end 219 end
212 end 220 end
213 end 221 end
214 222
215 def get_keyword(attr, options={}) 223 def get_keyword(attr, options={})
216 @keywords ||= {} 224 @keywords ||= {}
217 if @keywords.has_key?(attr) 225 if @keywords.has_key?(attr)
218 @keywords[attr] 226 @keywords[attr]
219 else 227 else
224 @@handler_options[:issue][attr] 232 @@handler_options[:issue][attr]
225 end 233 end
226 end 234 end
227 end 235 end
228 end 236 end
229 237
230 # Destructively extracts the value for +attr+ in +text+ 238 # Destructively extracts the value for +attr+ in +text+
231 # Returns nil if no matching keyword found 239 # Returns nil if no matching keyword found
232 def extract_keyword!(text, attr, format=nil) 240 def extract_keyword!(text, attr, format=nil)
233 keys = [attr.to_s.humanize] 241 keys = [attr.to_s.humanize]
234 if attr.is_a?(Symbol) 242 if attr.is_a?(Symbol)
235 keys << l("field_#{attr}", :default => '', :locale => user.language) if user 243 keys << l("field_#{attr}", :default => '', :locale => user.language) if user && user.language.present?
236 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language) 244 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language) if Setting.default_language.present?
237 end 245 end
238 keys.reject! {|k| k.blank?} 246 keys.reject! {|k| k.blank?}
239 keys.collect! {|k| Regexp.escape(k)} 247 keys.collect! {|k| Regexp.escape(k)}
240 format ||= '.+' 248 format ||= '.+'
241 text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '') 249 text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '')
248 # * specific project (eg. Setting.mail_handler_target_project) 256 # * specific project (eg. Setting.mail_handler_target_project)
249 target = Project.find_by_identifier(get_keyword(:project)) 257 target = Project.find_by_identifier(get_keyword(:project))
250 raise MissingInformation.new('Unable to determine target project') if target.nil? 258 raise MissingInformation.new('Unable to determine target project') if target.nil?
251 target 259 target
252 end 260 end
253 261
254 # Returns a Hash of issue attributes extracted from keywords in the email body 262 # Returns a Hash of issue attributes extracted from keywords in the email body
255 def issue_attributes_from_keywords(issue) 263 def issue_attributes_from_keywords(issue)
256 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_user_from_keyword(k) 264 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_user_from_keyword(k)
257 assigned_to = nil if assigned_to && !issue.assignable_users.include?(assigned_to) 265 assigned_to = nil if assigned_to && !issue.assignable_users.include?(assigned_to)
258 266
259 { 267 attrs = {
260 'tracker_id' => ((k = get_keyword(:tracker)) && issue.project.trackers.find_by_name(k).try(:id)) || issue.project.trackers.find(:first).try(:id), 268 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
261 'status_id' => (k = get_keyword(:status)) && IssueStatus.find_by_name(k).try(:id), 269 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
262 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.find_by_name(k).try(:id), 270 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
263 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.find_by_name(k).try(:id), 271 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
264 'assigned_to_id' => assigned_to.try(:id), 272 'assigned_to_id' => assigned_to.try(:id),
265 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && issue.project.shared_versions.find_by_name(k).try(:id), 273 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && issue.project.shared_versions.named(k).first.try(:id),
266 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'), 274 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
267 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'), 275 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
268 'estimated_hours' => get_keyword(:estimated_hours, :override => true), 276 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
269 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0') 277 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
270 }.delete_if {|k, v| v.blank? } 278 }.delete_if {|k, v| v.blank? }
271 end 279
272 280 if issue.new_record? && attrs['tracker_id'].nil?
281 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
282 end
283
284 attrs
285 end
286
273 # Returns a Hash of issue custom field values extracted from keywords in the email body 287 # Returns a Hash of issue custom field values extracted from keywords in the email body
274 def custom_field_values_from_keywords(customized) 288 def custom_field_values_from_keywords(customized)
275 customized.custom_field_values.inject({}) do |h, v| 289 customized.custom_field_values.inject({}) do |h, v|
276 if value = get_keyword(v.custom_field.name, :override => true) 290 if value = get_keyword(v.custom_field.name, :override => true)
277 h[v.custom_field.id.to_s] = value 291 h[v.custom_field.id.to_s] = value
278 end 292 end
279 h 293 h
280 end 294 end
281 end 295 end
282 296
283 # Returns the text/plain part of the email 297 # Returns the text/plain part of the email
284 # If not found (eg. HTML-only email), returns the body with tags removed 298 # If not found (eg. HTML-only email), returns the body with tags removed
285 def plain_text_body 299 def plain_text_body
286 return @plain_text_body unless @plain_text_body.nil? 300 return @plain_text_body unless @plain_text_body.nil?
287 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten 301 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
298 @plain_text_body = plain_text_part.body.to_s 312 @plain_text_body = plain_text_part.body.to_s
299 end 313 end
300 @plain_text_body.strip! 314 @plain_text_body.strip!
301 @plain_text_body 315 @plain_text_body
302 end 316 end
303 317
304 def cleaned_up_text_body 318 def cleaned_up_text_body
305 cleanup_body(plain_text_body) 319 cleanup_body(plain_text_body)
306 end 320 end
307 321
308 def self.full_sanitizer 322 def self.full_sanitizer
309 @full_sanitizer ||= HTML::FullSanitizer.new 323 @full_sanitizer ||= HTML::FullSanitizer.new
310 end 324 end
311 325
312 # Creates a user account for the +email+ sender 326 # Creates a user account for the +email+ sender
313 def self.create_user_from_email(email) 327 def self.create_user_from_email(email)
314 addr = email.from_addrs.to_a.first 328 addr = email.from_addrs.to_a.first
315 if addr && !addr.spec.blank? 329 if addr && !addr.spec.blank?
316 user = User.new 330 user = User.new
317 user.mail = addr.spec 331 user.mail = addr.spec
318 332
319 names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split 333 names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split
320 user.firstname = names.shift 334 user.firstname = names.shift
321 user.lastname = names.join(' ') 335 user.lastname = names.join(' ')
322 user.lastname = '-' if user.lastname.blank? 336 user.lastname = '-' if user.lastname.blank?
323 337
324 user.login = user.mail 338 user.login = user.mail
325 user.password = ActiveSupport::SecureRandom.hex(5) 339 user.password = ActiveSupport::SecureRandom.hex(5)
326 user.language = Setting.default_language 340 user.language = Setting.default_language
327 user.save ? user : nil 341 user.save ? user : nil
328 end 342 end
329 end 343 end
330 344
331 private 345 private
332 346
333 # Removes the email body of text after the truncation configurations. 347 # Removes the email body of text after the truncation configurations.
334 def cleanup_body(body) 348 def cleanup_body(body)
335 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)} 349 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
336 unless delimiters.empty? 350 unless delimiters.empty?
337 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE) 351 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)