Mercurial > hg > soundsoftware-site
comparison app/models/.svn/text-base/mail_handler.rb.svn-base @ 0:513646585e45
* Import Redmine trunk SVN rev 3859
author | Chris Cannam |
---|---|
date | Fri, 23 Jul 2010 15:52:44 +0100 |
parents | |
children | 94944d00e43c |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:513646585e45 |
---|---|
1 # redMine - project management software | |
2 # Copyright (C) 2006-2007 Jean-Philippe Lang | |
3 # | |
4 # This program is free software; you can redistribute it and/or | |
5 # modify it under the terms of the GNU General Public License | |
6 # as published by the Free Software Foundation; either version 2 | |
7 # of the License, or (at your option) any later version. | |
8 # | |
9 # This program is distributed in the hope that it will be useful, | |
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 # GNU General Public License for more details. | |
13 # | |
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 | |
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | |
17 | |
18 class MailHandler < ActionMailer::Base | |
19 include ActionView::Helpers::SanitizeHelper | |
20 | |
21 class UnauthorizedAction < StandardError; end | |
22 class MissingInformation < StandardError; end | |
23 | |
24 attr_reader :email, :user | |
25 | |
26 def self.receive(email, options={}) | |
27 @@handler_options = options.dup | |
28 | |
29 @@handler_options[:issue] ||= {} | |
30 | |
31 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String) | |
32 @@handler_options[:allow_override] ||= [] | |
33 # Project needs to be overridable if not specified | |
34 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project) | |
35 # Status overridable by default | |
36 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status) | |
37 | |
38 @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false) | |
39 super email | |
40 end | |
41 | |
42 # Processes incoming emails | |
43 # Returns the created object (eg. an issue, a message) or false | |
44 def receive(email) | |
45 @email = email | |
46 sender_email = email.from.to_a.first.to_s.strip | |
47 # Ignore emails received from the application emission address to avoid hell cycles | |
48 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase | |
49 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]" if logger && logger.info | |
50 return false | |
51 end | |
52 @user = User.find_by_mail(sender_email) if sender_email.present? | |
53 if @user && !@user.active? | |
54 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]" if logger && logger.info | |
55 return false | |
56 end | |
57 if @user.nil? | |
58 # Email was submitted by an unknown user | |
59 case @@handler_options[:unknown_user] | |
60 when 'accept' | |
61 @user = User.anonymous | |
62 when 'create' | |
63 @user = MailHandler.create_user_from_email(email) | |
64 if @user | |
65 logger.info "MailHandler: [#{@user.login}] account created" if logger && logger.info | |
66 Mailer.deliver_account_information(@user, @user.password) | |
67 else | |
68 logger.error "MailHandler: could not create account for [#{sender_email}]" if logger && logger.error | |
69 return false | |
70 end | |
71 else | |
72 # Default behaviour, emails from unknown users are ignored | |
73 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]" if logger && logger.info | |
74 return false | |
75 end | |
76 end | |
77 User.current = @user | |
78 dispatch | |
79 end | |
80 | |
81 private | |
82 | |
83 MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@} | |
84 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]} | |
85 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]} | |
86 | |
87 def dispatch | |
88 headers = [email.in_reply_to, email.references].flatten.compact | |
89 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE} | |
90 klass, object_id = $1, $2.to_i | |
91 method_name = "receive_#{klass}_reply" | |
92 if self.class.private_instance_methods.collect(&:to_s).include?(method_name) | |
93 send method_name, object_id | |
94 else | |
95 # ignoring it | |
96 end | |
97 elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE) | |
98 receive_issue_reply(m[1].to_i) | |
99 elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE) | |
100 receive_message_reply(m[1].to_i) | |
101 else | |
102 receive_issue | |
103 end | |
104 rescue ActiveRecord::RecordInvalid => e | |
105 # TODO: send a email to the user | |
106 logger.error e.message if logger | |
107 false | |
108 rescue MissingInformation => e | |
109 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger | |
110 false | |
111 rescue UnauthorizedAction => e | |
112 logger.error "MailHandler: unauthorized attempt from #{user}" if logger | |
113 false | |
114 end | |
115 | |
116 # Creates a new issue | |
117 def receive_issue | |
118 project = target_project | |
119 tracker = (get_keyword(:tracker) && project.trackers.find_by_name(get_keyword(:tracker))) || project.trackers.find(:first) | |
120 category = (get_keyword(:category) && project.issue_categories.find_by_name(get_keyword(:category))) | |
121 priority = (get_keyword(:priority) && IssuePriority.find_by_name(get_keyword(:priority))) | |
122 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status))) | |
123 assigned_to = (get_keyword(:assigned_to, :override => true) && find_user_from_keyword(get_keyword(:assigned_to, :override => true))) | |
124 due_date = get_keyword(:due_date, :override => true) | |
125 start_date = get_keyword(:start_date, :override => true) | |
126 | |
127 # check permission | |
128 unless @@handler_options[:no_permission_check] | |
129 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project) | |
130 end | |
131 | |
132 issue = Issue.new(:author => user, :project => project, :tracker => tracker, :category => category, :priority => priority, :due_date => due_date, :start_date => start_date, :assigned_to => assigned_to) | |
133 # check workflow | |
134 if status && issue.new_statuses_allowed_to(user).include?(status) | |
135 issue.status = status | |
136 end | |
137 issue.subject = email.subject.chomp[0,255] | |
138 if issue.subject.blank? | |
139 issue.subject = '(no subject)' | |
140 end | |
141 # custom fields | |
142 issue.custom_field_values = issue.available_custom_fields.inject({}) do |h, c| | |
143 if value = get_keyword(c.name, :override => true) | |
144 h[c.id] = value | |
145 end | |
146 h | |
147 end | |
148 issue.description = cleaned_up_text_body | |
149 # add To and Cc as watchers before saving so the watchers can reply to Redmine | |
150 add_watchers(issue) | |
151 issue.save! | |
152 add_attachments(issue) | |
153 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info | |
154 issue | |
155 end | |
156 | |
157 def target_project | |
158 # TODO: other ways to specify project: | |
159 # * parse the email To field | |
160 # * specific project (eg. Setting.mail_handler_target_project) | |
161 target = Project.find_by_identifier(get_keyword(:project)) | |
162 raise MissingInformation.new('Unable to determine target project') if target.nil? | |
163 target | |
164 end | |
165 | |
166 # Adds a note to an existing issue | |
167 def receive_issue_reply(issue_id) | |
168 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status))) | |
169 due_date = get_keyword(:due_date, :override => true) | |
170 start_date = get_keyword(:start_date, :override => true) | |
171 assigned_to = (get_keyword(:assigned_to, :override => true) && find_user_from_keyword(get_keyword(:assigned_to, :override => true))) | |
172 | |
173 issue = Issue.find_by_id(issue_id) | |
174 return unless issue | |
175 # check permission | |
176 unless @@handler_options[:no_permission_check] | |
177 raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project) | |
178 raise UnauthorizedAction unless status.nil? || user.allowed_to?(:edit_issues, issue.project) | |
179 end | |
180 | |
181 # add the note | |
182 journal = issue.init_journal(user, cleaned_up_text_body) | |
183 add_attachments(issue) | |
184 # check workflow | |
185 if status && issue.new_statuses_allowed_to(user).include?(status) | |
186 issue.status = status | |
187 end | |
188 issue.start_date = start_date if start_date | |
189 issue.due_date = due_date if due_date | |
190 issue.assigned_to = assigned_to if assigned_to | |
191 | |
192 issue.save! | |
193 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info | |
194 journal | |
195 end | |
196 | |
197 # Reply will be added to the issue | |
198 def receive_journal_reply(journal_id) | |
199 journal = Journal.find_by_id(journal_id) | |
200 if journal && journal.journalized_type == 'Issue' | |
201 receive_issue_reply(journal.journalized_id) | |
202 end | |
203 end | |
204 | |
205 # Receives a reply to a forum message | |
206 def receive_message_reply(message_id) | |
207 message = Message.find_by_id(message_id) | |
208 if message | |
209 message = message.root | |
210 | |
211 unless @@handler_options[:no_permission_check] | |
212 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project) | |
213 end | |
214 | |
215 if !message.locked? | |
216 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip, | |
217 :content => cleaned_up_text_body) | |
218 reply.author = user | |
219 reply.board = message.board | |
220 message.children << reply | |
221 add_attachments(reply) | |
222 reply | |
223 else | |
224 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" if logger && logger.info | |
225 end | |
226 end | |
227 end | |
228 | |
229 def add_attachments(obj) | |
230 if email.has_attachments? | |
231 email.attachments.each do |attachment| | |
232 Attachment.create(:container => obj, | |
233 :file => attachment, | |
234 :author => user, | |
235 :content_type => attachment.content_type) | |
236 end | |
237 end | |
238 end | |
239 | |
240 # Adds To and Cc as watchers of the given object if the sender has the | |
241 # appropriate permission | |
242 def add_watchers(obj) | |
243 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project) | |
244 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase} | |
245 unless addresses.empty? | |
246 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses]) | |
247 watchers.each {|w| obj.add_watcher(w)} | |
248 end | |
249 end | |
250 end | |
251 | |
252 def get_keyword(attr, options={}) | |
253 @keywords ||= {} | |
254 if @keywords.has_key?(attr) | |
255 @keywords[attr] | |
256 else | |
257 @keywords[attr] = begin | |
258 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && plain_text_body.gsub!(/^#{attr.to_s.humanize}[ \t]*:[ \t]*(.+)\s*$/i, '') | |
259 $1.strip | |
260 elsif !@@handler_options[:issue][attr].blank? | |
261 @@handler_options[:issue][attr] | |
262 end | |
263 end | |
264 end | |
265 end | |
266 | |
267 # Returns the text/plain part of the email | |
268 # If not found (eg. HTML-only email), returns the body with tags removed | |
269 def plain_text_body | |
270 return @plain_text_body unless @plain_text_body.nil? | |
271 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten | |
272 if parts.empty? | |
273 parts << @email | |
274 end | |
275 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'} | |
276 if plain_text_part.nil? | |
277 # no text/plain part found, assuming html-only email | |
278 # strip html tags and remove doctype directive | |
279 @plain_text_body = strip_tags(@email.body.to_s) | |
280 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, '' | |
281 else | |
282 @plain_text_body = plain_text_part.body.to_s | |
283 end | |
284 @plain_text_body.strip! | |
285 @plain_text_body | |
286 end | |
287 | |
288 def cleaned_up_text_body | |
289 cleanup_body(plain_text_body) | |
290 end | |
291 | |
292 def self.full_sanitizer | |
293 @full_sanitizer ||= HTML::FullSanitizer.new | |
294 end | |
295 | |
296 # Creates a user account for the +email+ sender | |
297 def self.create_user_from_email(email) | |
298 addr = email.from_addrs.to_a.first | |
299 if addr && !addr.spec.blank? | |
300 user = User.new | |
301 user.mail = addr.spec | |
302 | |
303 names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split | |
304 user.firstname = names.shift | |
305 user.lastname = names.join(' ') | |
306 user.lastname = '-' if user.lastname.blank? | |
307 | |
308 user.login = user.mail | |
309 user.password = ActiveSupport::SecureRandom.hex(5) | |
310 user.language = Setting.default_language | |
311 user.save ? user : nil | |
312 end | |
313 end | |
314 | |
315 private | |
316 | |
317 # Removes the email body of text after the truncation configurations. | |
318 def cleanup_body(body) | |
319 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)} | |
320 unless delimiters.empty? | |
321 regex = Regexp.new("^(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE) | |
322 body = body.gsub(regex, '') | |
323 end | |
324 body.strip | |
325 end | |
326 | |
327 def find_user_from_keyword(keyword) | |
328 user ||= User.find_by_mail(keyword) | |
329 user ||= User.find_by_login(keyword) | |
330 if user.nil? && keyword.match(/ /) | |
331 firstname, lastname = *(keyword.split) # "First Last Throwaway" | |
332 user ||= User.find_by_firstname_and_lastname(firstname, lastname) | |
333 end | |
334 user | |
335 end | |
336 end |