##// END OF EJS Templates
Introduced MailHandler#dispatch_to_default method to make MailHandler more extensible. #7598...
Jean-Baptiste Barth -
r4700:8b5ebd92c98a
parent child
Show More
@@ -1,361 +1,365
1 # redMine - project management software
1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
2 # Copyright (C) 2006-2007 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
48 # Ignore emails received from the application emission address to avoid hell cycles
48 # Ignore emails received from the application emission address to avoid hell cycles
49 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
49 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
50 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]" if logger && logger.info
50 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]" if logger && logger.info
51 return false
51 return false
52 end
52 end
53 @user = User.find_by_mail(sender_email) if sender_email.present?
53 @user = User.find_by_mail(sender_email) if sender_email.present?
54 if @user && !@user.active?
54 if @user && !@user.active?
55 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]" if logger && logger.info
55 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]" if logger && logger.info
56 return false
56 return false
57 end
57 end
58 if @user.nil?
58 if @user.nil?
59 # Email was submitted by an unknown user
59 # Email was submitted by an unknown user
60 case @@handler_options[:unknown_user]
60 case @@handler_options[:unknown_user]
61 when 'accept'
61 when 'accept'
62 @user = User.anonymous
62 @user = User.anonymous
63 when 'create'
63 when 'create'
64 @user = MailHandler.create_user_from_email(email)
64 @user = MailHandler.create_user_from_email(email)
65 if @user
65 if @user
66 logger.info "MailHandler: [#{@user.login}] account created" if logger && logger.info
66 logger.info "MailHandler: [#{@user.login}] account created" if logger && logger.info
67 Mailer.deliver_account_information(@user, @user.password)
67 Mailer.deliver_account_information(@user, @user.password)
68 else
68 else
69 logger.error "MailHandler: could not create account for [#{sender_email}]" if logger && logger.error
69 logger.error "MailHandler: could not create account for [#{sender_email}]" if logger && logger.error
70 return false
70 return false
71 end
71 end
72 else
72 else
73 # Default behaviour, emails from unknown users are ignored
73 # Default behaviour, emails from unknown users are ignored
74 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]" if logger && logger.info
74 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]" if logger && logger.info
75 return false
75 return false
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"
93 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
93 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
94 send method_name, object_id
94 send method_name, object_id
95 else
95 else
96 # ignoring it
96 # ignoring it
97 end
97 end
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
109 rescue MissingInformation => e
109 rescue MissingInformation => e
110 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
110 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
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]
122 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
126 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
123 end
127 end
124
128
125 issue = Issue.new(:author => user, :project => project)
129 issue = Issue.new(:author => user, :project => project)
126 issue.safe_attributes = issue_attributes_from_keywords(issue)
130 issue.safe_attributes = issue_attributes_from_keywords(issue)
127 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
131 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
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 # ignore CLI-supplied defaults for new issues
155 # ignore CLI-supplied defaults for new issues
152 @@handler_options[:issue].clear
156 @@handler_options[:issue].clear
153
157
154 journal = issue.init_journal(user, cleaned_up_text_body)
158 journal = issue.init_journal(user, cleaned_up_text_body)
155 issue.safe_attributes = issue_attributes_from_keywords(issue)
159 issue.safe_attributes = issue_attributes_from_keywords(issue)
156 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)}
157 add_attachments(issue)
161 add_attachments(issue)
158 issue.save!
162 issue.save!
159 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
163 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
160 journal
164 journal
161 end
165 end
162
166
163 # Reply will be added to the issue
167 # Reply will be added to the issue
164 def receive_journal_reply(journal_id)
168 def receive_journal_reply(journal_id)
165 journal = Journal.find_by_id(journal_id)
169 journal = Journal.find_by_id(journal_id)
166 if journal && journal.journalized_type == 'Issue'
170 if journal && journal.journalized_type == 'Issue'
167 receive_issue_reply(journal.journalized_id)
171 receive_issue_reply(journal.journalized_id)
168 end
172 end
169 end
173 end
170
174
171 # Receives a reply to a forum message
175 # Receives a reply to a forum message
172 def receive_message_reply(message_id)
176 def receive_message_reply(message_id)
173 message = Message.find_by_id(message_id)
177 message = Message.find_by_id(message_id)
174 if message
178 if message
175 message = message.root
179 message = message.root
176
180
177 unless @@handler_options[:no_permission_check]
181 unless @@handler_options[:no_permission_check]
178 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
182 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
179 end
183 end
180
184
181 if !message.locked?
185 if !message.locked?
182 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
186 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
183 :content => cleaned_up_text_body)
187 :content => cleaned_up_text_body)
184 reply.author = user
188 reply.author = user
185 reply.board = message.board
189 reply.board = message.board
186 message.children << reply
190 message.children << reply
187 add_attachments(reply)
191 add_attachments(reply)
188 reply
192 reply
189 else
193 else
190 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" if logger && logger.info
194 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" if logger && logger.info
191 end
195 end
192 end
196 end
193 end
197 end
194
198
195 def add_attachments(obj)
199 def add_attachments(obj)
196 if email.has_attachments?
200 if email.has_attachments?
197 email.attachments.each do |attachment|
201 email.attachments.each do |attachment|
198 Attachment.create(:container => obj,
202 Attachment.create(:container => obj,
199 :file => attachment,
203 :file => attachment,
200 :author => user,
204 :author => user,
201 :content_type => attachment.content_type)
205 :content_type => attachment.content_type)
202 end
206 end
203 end
207 end
204 end
208 end
205
209
206 # Adds To and Cc as watchers of the given object if the sender has the
210 # Adds To and Cc as watchers of the given object if the sender has the
207 # appropriate permission
211 # appropriate permission
208 def add_watchers(obj)
212 def add_watchers(obj)
209 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
213 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
210 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
214 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
211 unless addresses.empty?
215 unless addresses.empty?
212 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
216 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
213 watchers.each {|w| obj.add_watcher(w)}
217 watchers.each {|w| obj.add_watcher(w)}
214 end
218 end
215 end
219 end
216 end
220 end
217
221
218 def get_keyword(attr, options={})
222 def get_keyword(attr, options={})
219 @keywords ||= {}
223 @keywords ||= {}
220 if @keywords.has_key?(attr)
224 if @keywords.has_key?(attr)
221 @keywords[attr]
225 @keywords[attr]
222 else
226 else
223 @keywords[attr] = begin
227 @keywords[attr] = begin
224 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && (v = extract_keyword!(plain_text_body, attr, options[:format]))
228 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && (v = extract_keyword!(plain_text_body, attr, options[:format]))
225 v
229 v
226 elsif !@@handler_options[:issue][attr].blank?
230 elsif !@@handler_options[:issue][attr].blank?
227 @@handler_options[:issue][attr]
231 @@handler_options[:issue][attr]
228 end
232 end
229 end
233 end
230 end
234 end
231 end
235 end
232
236
233 # Destructively extracts the value for +attr+ in +text+
237 # Destructively extracts the value for +attr+ in +text+
234 # Returns nil if no matching keyword found
238 # Returns nil if no matching keyword found
235 def extract_keyword!(text, attr, format=nil)
239 def extract_keyword!(text, attr, format=nil)
236 keys = [attr.to_s.humanize]
240 keys = [attr.to_s.humanize]
237 if attr.is_a?(Symbol)
241 if attr.is_a?(Symbol)
238 keys << l("field_#{attr}", :default => '', :locale => user.language) if user && user.language.present?
242 keys << l("field_#{attr}", :default => '', :locale => user.language) if user && user.language.present?
239 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language) if Setting.default_language.present?
243 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language) if Setting.default_language.present?
240 end
244 end
241 keys.reject! {|k| k.blank?}
245 keys.reject! {|k| k.blank?}
242 keys.collect! {|k| Regexp.escape(k)}
246 keys.collect! {|k| Regexp.escape(k)}
243 format ||= '.+'
247 format ||= '.+'
244 text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '')
248 text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '')
245 $2 && $2.strip
249 $2 && $2.strip
246 end
250 end
247
251
248 def target_project
252 def target_project
249 # TODO: other ways to specify project:
253 # TODO: other ways to specify project:
250 # * parse the email To field
254 # * parse the email To field
251 # * specific project (eg. Setting.mail_handler_target_project)
255 # * specific project (eg. Setting.mail_handler_target_project)
252 target = Project.find_by_identifier(get_keyword(:project))
256 target = Project.find_by_identifier(get_keyword(:project))
253 raise MissingInformation.new('Unable to determine target project') if target.nil?
257 raise MissingInformation.new('Unable to determine target project') if target.nil?
254 target
258 target
255 end
259 end
256
260
257 # Returns a Hash of issue attributes extracted from keywords in the email body
261 # Returns a Hash of issue attributes extracted from keywords in the email body
258 def issue_attributes_from_keywords(issue)
262 def issue_attributes_from_keywords(issue)
259 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_user_from_keyword(k)
263 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_user_from_keyword(k)
260 assigned_to = nil if assigned_to && !issue.assignable_users.include?(assigned_to)
264 assigned_to = nil if assigned_to && !issue.assignable_users.include?(assigned_to)
261
265
262 attrs = {
266 attrs = {
263 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.find_by_name(k).try(:id),
267 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.find_by_name(k).try(:id),
264 'status_id' => (k = get_keyword(:status)) && IssueStatus.find_by_name(k).try(:id),
268 'status_id' => (k = get_keyword(:status)) && IssueStatus.find_by_name(k).try(:id),
265 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.find_by_name(k).try(:id),
269 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.find_by_name(k).try(:id),
266 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.find_by_name(k).try(:id),
270 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.find_by_name(k).try(:id),
267 'assigned_to_id' => assigned_to.try(:id),
271 'assigned_to_id' => assigned_to.try(:id),
268 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && issue.project.shared_versions.find_by_name(k).try(:id),
272 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && issue.project.shared_versions.find_by_name(k).try(:id),
269 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
273 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
270 'due_date' => get_keyword(:due_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}'),
271 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
275 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
272 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
276 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
273 }.delete_if {|k, v| v.blank? }
277 }.delete_if {|k, v| v.blank? }
274
278
275 if issue.new_record? && attrs['tracker_id'].nil?
279 if issue.new_record? && attrs['tracker_id'].nil?
276 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
280 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
277 end
281 end
278
282
279 attrs
283 attrs
280 end
284 end
281
285
282 # Returns a Hash of issue custom field values extracted from keywords in the email body
286 # Returns a Hash of issue custom field values extracted from keywords in the email body
283 def custom_field_values_from_keywords(customized)
287 def custom_field_values_from_keywords(customized)
284 customized.custom_field_values.inject({}) do |h, v|
288 customized.custom_field_values.inject({}) do |h, v|
285 if value = get_keyword(v.custom_field.name, :override => true)
289 if value = get_keyword(v.custom_field.name, :override => true)
286 h[v.custom_field.id.to_s] = value
290 h[v.custom_field.id.to_s] = value
287 end
291 end
288 h
292 h
289 end
293 end
290 end
294 end
291
295
292 # Returns the text/plain part of the email
296 # Returns the text/plain part of the email
293 # If not found (eg. HTML-only email), returns the body with tags removed
297 # If not found (eg. HTML-only email), returns the body with tags removed
294 def plain_text_body
298 def plain_text_body
295 return @plain_text_body unless @plain_text_body.nil?
299 return @plain_text_body unless @plain_text_body.nil?
296 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
300 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
297 if parts.empty?
301 if parts.empty?
298 parts << @email
302 parts << @email
299 end
303 end
300 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
304 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
301 if plain_text_part.nil?
305 if plain_text_part.nil?
302 # no text/plain part found, assuming html-only email
306 # no text/plain part found, assuming html-only email
303 # strip html tags and remove doctype directive
307 # strip html tags and remove doctype directive
304 @plain_text_body = strip_tags(@email.body.to_s)
308 @plain_text_body = strip_tags(@email.body.to_s)
305 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
309 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
306 else
310 else
307 @plain_text_body = plain_text_part.body.to_s
311 @plain_text_body = plain_text_part.body.to_s
308 end
312 end
309 @plain_text_body.strip!
313 @plain_text_body.strip!
310 @plain_text_body
314 @plain_text_body
311 end
315 end
312
316
313 def cleaned_up_text_body
317 def cleaned_up_text_body
314 cleanup_body(plain_text_body)
318 cleanup_body(plain_text_body)
315 end
319 end
316
320
317 def self.full_sanitizer
321 def self.full_sanitizer
318 @full_sanitizer ||= HTML::FullSanitizer.new
322 @full_sanitizer ||= HTML::FullSanitizer.new
319 end
323 end
320
324
321 # Creates a user account for the +email+ sender
325 # Creates a user account for the +email+ sender
322 def self.create_user_from_email(email)
326 def self.create_user_from_email(email)
323 addr = email.from_addrs.to_a.first
327 addr = email.from_addrs.to_a.first
324 if addr && !addr.spec.blank?
328 if addr && !addr.spec.blank?
325 user = User.new
329 user = User.new
326 user.mail = addr.spec
330 user.mail = addr.spec
327
331
328 names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split
332 names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split
329 user.firstname = names.shift
333 user.firstname = names.shift
330 user.lastname = names.join(' ')
334 user.lastname = names.join(' ')
331 user.lastname = '-' if user.lastname.blank?
335 user.lastname = '-' if user.lastname.blank?
332
336
333 user.login = user.mail
337 user.login = user.mail
334 user.password = ActiveSupport::SecureRandom.hex(5)
338 user.password = ActiveSupport::SecureRandom.hex(5)
335 user.language = Setting.default_language
339 user.language = Setting.default_language
336 user.save ? user : nil
340 user.save ? user : nil
337 end
341 end
338 end
342 end
339
343
340 private
344 private
341
345
342 # Removes the email body of text after the truncation configurations.
346 # Removes the email body of text after the truncation configurations.
343 def cleanup_body(body)
347 def cleanup_body(body)
344 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
348 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
345 unless delimiters.empty?
349 unless delimiters.empty?
346 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
350 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
347 body = body.gsub(regex, '')
351 body = body.gsub(regex, '')
348 end
352 end
349 body.strip
353 body.strip
350 end
354 end
351
355
352 def find_user_from_keyword(keyword)
356 def find_user_from_keyword(keyword)
353 user ||= User.find_by_mail(keyword)
357 user ||= User.find_by_mail(keyword)
354 user ||= User.find_by_login(keyword)
358 user ||= User.find_by_login(keyword)
355 if user.nil? && keyword.match(/ /)
359 if user.nil? && keyword.match(/ /)
356 firstname, lastname = *(keyword.split) # "First Last Throwaway"
360 firstname, lastname = *(keyword.split) # "First Last Throwaway"
357 user ||= User.find_by_firstname_and_lastname(firstname, lastname)
361 user ||= User.find_by_firstname_and_lastname(firstname, lastname)
358 end
362 end
359 user
363 user
360 end
364 end
361 end
365 end
General Comments 0
You need to be logged in to leave comments. Login now