comparison app/models/.svn/text-base/mail_handler.rb.svn-base @ 441:cbce1fd3b1b7 redmine-1.2

Update to Redmine 1.2-stable branch (Redmine SVN rev 6000)
author Chris Cannam
date Mon, 06 Jun 2011 14:24:13 +0100
parents 051f544170fe
children 753f1380d6bc 0c939c159af4
comparison
equal deleted inserted replaced
245:051f544170fe 441:cbce1fd3b1b7
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"
115 end 115 end
116 116
117 def dispatch_to_default 117 def dispatch_to_default
118 receive_issue 118 receive_issue
119 end 119 end
120 120
121 # Creates a new issue 121 # Creates a new issue
122 def receive_issue 122 def receive_issue
123 project = target_project 123 project = target_project
124 # check permission 124 # check permission
125 unless @@handler_options[:no_permission_check] 125 unless @@handler_options[:no_permission_check]
132 issue.subject = email.subject.to_s.chomp[0,255] 132 issue.subject = email.subject.to_s.chomp[0,255]
133 if issue.subject.blank? 133 if issue.subject.blank?
134 issue.subject = '(no subject)' 134 issue.subject = '(no subject)'
135 end 135 end
136 issue.description = cleaned_up_text_body 136 issue.description = cleaned_up_text_body
137 137
138 # 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
139 add_watchers(issue) 139 add_watchers(issue)
140 issue.save! 140 issue.save!
141 add_attachments(issue) 141 add_attachments(issue)
142 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
143 issue 143 issue
144 end 144 end
145 145
146 # Adds a note to an existing issue 146 # Adds a note to an existing issue
147 def receive_issue_reply(issue_id) 147 def receive_issue_reply(issue_id)
148 issue = Issue.find_by_id(issue_id) 148 issue = Issue.find_by_id(issue_id)
149 return unless issue 149 return unless issue
150 # check permission 150 # check permission
151 unless @@handler_options[:no_permission_check] 151 unless @@handler_options[:no_permission_check]
152 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)
153 end 153 end
154 154
155 # ignore CLI-supplied defaults for new issues 155 # ignore CLI-supplied defaults for new issues
156 @@handler_options[:issue].clear 156 @@handler_options[:issue].clear
157 157
158 journal = issue.init_journal(user, cleaned_up_text_body) 158 journal = issue.init_journal(user)
159 issue.safe_attributes = issue_attributes_from_keywords(issue) 159 issue.safe_attributes = issue_attributes_from_keywords(issue)
160 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
161 add_attachments(issue) 162 add_attachments(issue)
162 issue.save! 163 issue.save!
163 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
164 journal 165 journal
165 end 166 end
166 167
167 # Reply will be added to the issue 168 # Reply will be added to the issue
168 def receive_journal_reply(journal_id) 169 def receive_journal_reply(journal_id)
169 journal = Journal.find_by_id(journal_id) 170 journal = Journal.find_by_id(journal_id)
170 if journal && journal.journalized_type == 'Issue' 171 if journal && journal.journalized_type == 'Issue'
171 receive_issue_reply(journal.journalized_id) 172 receive_issue_reply(journal.journalized_id)
172 end 173 end
173 end 174 end
174 175
175 # Receives a reply to a forum message 176 # Receives a reply to a forum message
176 def receive_message_reply(message_id) 177 def receive_message_reply(message_id)
177 message = Message.find_by_id(message_id) 178 message = Message.find_by_id(message_id)
178 if message 179 if message
179 message = message.root 180 message = message.root
180 181
181 unless @@handler_options[:no_permission_check] 182 unless @@handler_options[:no_permission_check]
182 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project) 183 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
183 end 184 end
184 185
185 if !message.locked? 186 if !message.locked?
186 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip, 187 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
187 :content => cleaned_up_text_body) 188 :content => cleaned_up_text_body)
188 reply.author = user 189 reply.author = user
189 reply.board = message.board 190 reply.board = message.board
193 else 194 else
194 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
195 end 196 end
196 end 197 end
197 end 198 end
198 199
199 def add_attachments(obj) 200 def add_attachments(obj)
200 if email.has_attachments? 201 if email.has_attachments?
201 email.attachments.each do |attachment| 202 email.attachments.each do |attachment|
202 Attachment.create(:container => obj, 203 Attachment.create(:container => obj,
203 :file => attachment, 204 :file => attachment,
204 :author => user, 205 :author => user,
205 :content_type => attachment.content_type) 206 :content_type => attachment.content_type)
206 end 207 end
207 end 208 end
208 end 209 end
209 210
210 # 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
211 # appropriate permission 212 # appropriate permission
212 def add_watchers(obj) 213 def add_watchers(obj)
213 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)
214 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}
216 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses]) 217 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
217 watchers.each {|w| obj.add_watcher(w)} 218 watchers.each {|w| obj.add_watcher(w)}
218 end 219 end
219 end 220 end
220 end 221 end
221 222
222 def get_keyword(attr, options={}) 223 def get_keyword(attr, options={})
223 @keywords ||= {} 224 @keywords ||= {}
224 if @keywords.has_key?(attr) 225 if @keywords.has_key?(attr)
225 @keywords[attr] 226 @keywords[attr]
226 else 227 else
231 @@handler_options[:issue][attr] 232 @@handler_options[:issue][attr]
232 end 233 end
233 end 234 end
234 end 235 end
235 end 236 end
236 237
237 # Destructively extracts the value for +attr+ in +text+ 238 # Destructively extracts the value for +attr+ in +text+
238 # Returns nil if no matching keyword found 239 # Returns nil if no matching keyword found
239 def extract_keyword!(text, attr, format=nil) 240 def extract_keyword!(text, attr, format=nil)
240 keys = [attr.to_s.humanize] 241 keys = [attr.to_s.humanize]
241 if attr.is_a?(Symbol) 242 if attr.is_a?(Symbol)
255 # * specific project (eg. Setting.mail_handler_target_project) 256 # * specific project (eg. Setting.mail_handler_target_project)
256 target = Project.find_by_identifier(get_keyword(:project)) 257 target = Project.find_by_identifier(get_keyword(:project))
257 raise MissingInformation.new('Unable to determine target project') if target.nil? 258 raise MissingInformation.new('Unable to determine target project') if target.nil?
258 target 259 target
259 end 260 end
260 261
261 # 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
262 def issue_attributes_from_keywords(issue) 263 def issue_attributes_from_keywords(issue)
263 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)
264 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)
265 266
266 attrs = { 267 attrs = {
267 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.find_by_name(k).try(:id), 268 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.find_by_name(k).try(:id),
268 'status_id' => (k = get_keyword(:status)) && IssueStatus.find_by_name(k).try(:id), 269 'status_id' => (k = get_keyword(:status)) && IssueStatus.find_by_name(k).try(:id),
269 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.find_by_name(k).try(:id), 270 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.find_by_name(k).try(:id),
270 '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.find_by_name(k).try(:id),
273 '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}'),
274 '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}'),
275 'estimated_hours' => get_keyword(:estimated_hours, :override => true), 276 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
276 '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')
277 }.delete_if {|k, v| v.blank? } 278 }.delete_if {|k, v| v.blank? }
278 279
279 if issue.new_record? && attrs['tracker_id'].nil? 280 if issue.new_record? && attrs['tracker_id'].nil?
280 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id) 281 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
281 end 282 end
282 283
283 attrs 284 attrs
284 end 285 end
285 286
286 # 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
287 def custom_field_values_from_keywords(customized) 288 def custom_field_values_from_keywords(customized)
288 customized.custom_field_values.inject({}) do |h, v| 289 customized.custom_field_values.inject({}) do |h, v|
289 if value = get_keyword(v.custom_field.name, :override => true) 290 if value = get_keyword(v.custom_field.name, :override => true)
290 h[v.custom_field.id.to_s] = value 291 h[v.custom_field.id.to_s] = value
291 end 292 end
292 h 293 h
293 end 294 end
294 end 295 end
295 296
296 # Returns the text/plain part of the email 297 # Returns the text/plain part of the email
297 # 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
298 def plain_text_body 299 def plain_text_body
299 return @plain_text_body unless @plain_text_body.nil? 300 return @plain_text_body unless @plain_text_body.nil?
300 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
311 @plain_text_body = plain_text_part.body.to_s 312 @plain_text_body = plain_text_part.body.to_s
312 end 313 end
313 @plain_text_body.strip! 314 @plain_text_body.strip!
314 @plain_text_body 315 @plain_text_body
315 end 316 end
316 317
317 def cleaned_up_text_body 318 def cleaned_up_text_body
318 cleanup_body(plain_text_body) 319 cleanup_body(plain_text_body)
319 end 320 end
320 321
321 def self.full_sanitizer 322 def self.full_sanitizer
322 @full_sanitizer ||= HTML::FullSanitizer.new 323 @full_sanitizer ||= HTML::FullSanitizer.new
323 end 324 end
324 325
325 # Creates a user account for the +email+ sender 326 # Creates a user account for the +email+ sender
326 def self.create_user_from_email(email) 327 def self.create_user_from_email(email)
327 addr = email.from_addrs.to_a.first 328 addr = email.from_addrs.to_a.first
328 if addr && !addr.spec.blank? 329 if addr && !addr.spec.blank?
329 user = User.new 330 user = User.new
330 user.mail = addr.spec 331 user.mail = addr.spec
331 332
332 names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split 333 names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split
333 user.firstname = names.shift 334 user.firstname = names.shift
334 user.lastname = names.join(' ') 335 user.lastname = names.join(' ')
335 user.lastname = '-' if user.lastname.blank? 336 user.lastname = '-' if user.lastname.blank?
336 337
337 user.login = user.mail 338 user.login = user.mail
338 user.password = ActiveSupport::SecureRandom.hex(5) 339 user.password = ActiveSupport::SecureRandom.hex(5)
339 user.language = Setting.default_language 340 user.language = Setting.default_language
340 user.save ? user : nil 341 user.save ? user : nil
341 end 342 end
342 end 343 end
343 344
344 private 345 private
345 346
346 # Removes the email body of text after the truncation configurations. 347 # Removes the email body of text after the truncation configurations.
347 def cleanup_body(body) 348 def cleanup_body(body)
348 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)}
349 unless delimiters.empty? 350 unless delimiters.empty?
350 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE) 351 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)