##// END OF EJS Templates
code layout cleanup app/models/mail_handler.rb...
Toshi MARUYAMA -
r8625:5dd08133ef39
parent child
Show More
@@ -1,401 +1,430
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2011 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 if @@handler_options[:allow_override].is_a?(String)
33 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip)
34 end
33 @@handler_options[:allow_override] ||= []
35 @@handler_options[:allow_override] ||= []
34 # Project needs to be overridable if not specified
36 # Project needs to be overridable if not specified
35 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
37 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
36 # Status overridable by default
38 # Status overridable by default
37 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
39 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
38
40
39 @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false)
41 @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false)
40 super email
42 super email
41 end
43 end
42
44
43 # Processes incoming emails
45 # Processes incoming emails
44 # Returns the created object (eg. an issue, a message) or false
46 # Returns the created object (eg. an issue, a message) or false
45 def receive(email)
47 def receive(email)
46 @email = email
48 @email = email
47 sender_email = email.from.to_a.first.to_s.strip
49 sender_email = email.from.to_a.first.to_s.strip
48 # Ignore emails received from the application emission address to avoid hell cycles
50 # Ignore emails received from the application emission address to avoid hell cycles
49 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
51 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
52 if logger && logger.info
53 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
54 end
51 return false
55 return false
52 end
56 end
53 @user = User.find_by_mail(sender_email) if sender_email.present?
57 @user = User.find_by_mail(sender_email) if sender_email.present?
54 if @user && !@user.active?
58 if @user && !@user.active?
55 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]" if logger && logger.info
59 if logger && logger.info
60 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]"
61 end
56 return false
62 return false
57 end
63 end
58 if @user.nil?
64 if @user.nil?
59 # Email was submitted by an unknown user
65 # Email was submitted by an unknown user
60 case @@handler_options[:unknown_user]
66 case @@handler_options[:unknown_user]
61 when 'accept'
67 when 'accept'
62 @user = User.anonymous
68 @user = User.anonymous
63 when 'create'
69 when 'create'
64 @user = create_user_from_email
70 @user = create_user_from_email
65 if @user
71 if @user
66 logger.info "MailHandler: [#{@user.login}] account created" if logger && logger.info
72 if logger && logger.info
73 logger.info "MailHandler: [#{@user.login}] account created"
74 end
67 Mailer.deliver_account_information(@user, @user.password)
75 Mailer.deliver_account_information(@user, @user.password)
68 else
76 else
69 logger.error "MailHandler: could not create account for [#{sender_email}]" if logger && logger.error
77 if logger && logger.error
78 logger.error "MailHandler: could not create account for [#{sender_email}]"
79 end
70 return false
80 return false
71 end
81 end
72 else
82 else
73 # Default behaviour, emails from unknown users are ignored
83 # Default behaviour, emails from unknown users are ignored
74 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]" if logger && logger.info
84 if logger && logger.info
85 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]"
86 end
75 return false
87 return false
76 end
88 end
77 end
89 end
78 User.current = @user
90 User.current = @user
79 dispatch
91 dispatch
80 end
92 end
81
93
82 private
94 private
83
95
84 MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
96 MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
85 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
97 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
86 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
98 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
87
99
88 def dispatch
100 def dispatch
89 headers = [email.in_reply_to, email.references].flatten.compact
101 headers = [email.in_reply_to, email.references].flatten.compact
90 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
102 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
91 klass, object_id = $1, $2.to_i
103 klass, object_id = $1, $2.to_i
92 method_name = "receive_#{klass}_reply"
104 method_name = "receive_#{klass}_reply"
93 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
105 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
94 send method_name, object_id
106 send method_name, object_id
95 else
107 else
96 # ignoring it
108 # ignoring it
97 end
109 end
98 elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
110 elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
99 receive_issue_reply(m[1].to_i)
111 receive_issue_reply(m[1].to_i)
100 elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
112 elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
101 receive_message_reply(m[1].to_i)
113 receive_message_reply(m[1].to_i)
102 else
114 else
103 dispatch_to_default
115 dispatch_to_default
104 end
116 end
105 rescue ActiveRecord::RecordInvalid => e
117 rescue ActiveRecord::RecordInvalid => e
106 # TODO: send a email to the user
118 # TODO: send a email to the user
107 logger.error e.message if logger
119 logger.error e.message if logger
108 false
120 false
109 rescue MissingInformation => e
121 rescue MissingInformation => e
110 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
122 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
111 false
123 false
112 rescue UnauthorizedAction => e
124 rescue UnauthorizedAction => e
113 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
125 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
114 false
126 false
115 end
127 end
116
128
117 def dispatch_to_default
129 def dispatch_to_default
118 receive_issue
130 receive_issue
119 end
131 end
120
132
121 # Creates a new issue
133 # Creates a new issue
122 def receive_issue
134 def receive_issue
123 project = target_project
135 project = target_project
124 # check permission
136 # check permission
125 unless @@handler_options[:no_permission_check]
137 unless @@handler_options[:no_permission_check]
126 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
138 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
127 end
139 end
128
140
129 issue = Issue.new(:author => user, :project => project)
141 issue = Issue.new(:author => user, :project => project)
130 issue.safe_attributes = issue_attributes_from_keywords(issue)
142 issue.safe_attributes = issue_attributes_from_keywords(issue)
131 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
143 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
132 issue.subject = email.subject.to_s.chomp[0,255]
144 issue.subject = email.subject.to_s.chomp[0,255]
133 if issue.subject.blank?
145 if issue.subject.blank?
134 issue.subject = '(no subject)'
146 issue.subject = '(no subject)'
135 end
147 end
136 issue.description = cleaned_up_text_body
148 issue.description = cleaned_up_text_body
137
149
138 # add To and Cc as watchers before saving so the watchers can reply to Redmine
150 # add To and Cc as watchers before saving so the watchers can reply to Redmine
139 add_watchers(issue)
151 add_watchers(issue)
140 issue.save!
152 issue.save!
141 add_attachments(issue)
153 add_attachments(issue)
142 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
154 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
143 issue
155 issue
144 end
156 end
145
157
146 # Adds a note to an existing issue
158 # Adds a note to an existing issue
147 def receive_issue_reply(issue_id)
159 def receive_issue_reply(issue_id)
148 issue = Issue.find_by_id(issue_id)
160 issue = Issue.find_by_id(issue_id)
149 return unless issue
161 return unless issue
150 # check permission
162 # check permission
151 unless @@handler_options[:no_permission_check]
163 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)
164 unless user.allowed_to?(:add_issue_notes, issue.project) ||
165 user.allowed_to?(:edit_issues, issue.project)
166 raise UnauthorizedAction
167 end
153 end
168 end
154
169
155 # ignore CLI-supplied defaults for new issues
170 # ignore CLI-supplied defaults for new issues
156 @@handler_options[:issue].clear
171 @@handler_options[:issue].clear
157
172
158 journal = issue.init_journal(user)
173 journal = issue.init_journal(user)
159 issue.safe_attributes = issue_attributes_from_keywords(issue)
174 issue.safe_attributes = issue_attributes_from_keywords(issue)
160 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
175 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
161 journal.notes = cleaned_up_text_body
176 journal.notes = cleaned_up_text_body
162 add_attachments(issue)
177 add_attachments(issue)
163 issue.save!
178 issue.save!
164 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
179 if logger && logger.info
180 logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
181 end
165 journal
182 journal
166 end
183 end
167
184
168 # Reply will be added to the issue
185 # Reply will be added to the issue
169 def receive_journal_reply(journal_id)
186 def receive_journal_reply(journal_id)
170 journal = Journal.find_by_id(journal_id)
187 journal = Journal.find_by_id(journal_id)
171 if journal && journal.journalized_type == 'Issue'
188 if journal && journal.journalized_type == 'Issue'
172 receive_issue_reply(journal.journalized_id)
189 receive_issue_reply(journal.journalized_id)
173 end
190 end
174 end
191 end
175
192
176 # Receives a reply to a forum message
193 # Receives a reply to a forum message
177 def receive_message_reply(message_id)
194 def receive_message_reply(message_id)
178 message = Message.find_by_id(message_id)
195 message = Message.find_by_id(message_id)
179 if message
196 if message
180 message = message.root
197 message = message.root
181
198
182 unless @@handler_options[:no_permission_check]
199 unless @@handler_options[:no_permission_check]
183 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
200 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
184 end
201 end
185
202
186 if !message.locked?
203 if !message.locked?
187 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
204 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
188 :content => cleaned_up_text_body)
205 :content => cleaned_up_text_body)
189 reply.author = user
206 reply.author = user
190 reply.board = message.board
207 reply.board = message.board
191 message.children << reply
208 message.children << reply
192 add_attachments(reply)
209 add_attachments(reply)
193 reply
210 reply
194 else
211 else
195 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" if logger && logger.info
212 if logger && logger.info
213 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
214 end
196 end
215 end
197 end
216 end
198 end
217 end
199
218
200 def add_attachments(obj)
219 def add_attachments(obj)
201 if email.attachments && email.attachments.any?
220 if email.attachments && email.attachments.any?
202 email.attachments.each do |attachment|
221 email.attachments.each do |attachment|
203 obj.attachments << Attachment.create(:container => obj,
222 obj.attachments << Attachment.create(:container => obj,
204 :file => attachment,
223 :file => attachment,
205 :author => user,
224 :author => user,
206 :content_type => attachment.content_type)
225 :content_type => attachment.content_type)
207 end
226 end
208 end
227 end
209 end
228 end
210
229
211 # Adds To and Cc as watchers of the given object if the sender has the
230 # Adds To and Cc as watchers of the given object if the sender has the
212 # appropriate permission
231 # appropriate permission
213 def add_watchers(obj)
232 def add_watchers(obj)
214 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
233 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
215 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
234 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
216 unless addresses.empty?
235 unless addresses.empty?
217 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
236 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
218 watchers.each {|w| obj.add_watcher(w)}
237 watchers.each {|w| obj.add_watcher(w)}
219 end
238 end
220 end
239 end
221 end
240 end
222
241
223 def get_keyword(attr, options={})
242 def get_keyword(attr, options={})
224 @keywords ||= {}
243 @keywords ||= {}
225 if @keywords.has_key?(attr)
244 if @keywords.has_key?(attr)
226 @keywords[attr]
245 @keywords[attr]
227 else
246 else
228 @keywords[attr] = begin
247 @keywords[attr] = begin
229 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
248 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
230 (v = extract_keyword!(plain_text_body, attr, options[:format]))
249 (v = extract_keyword!(plain_text_body, attr, options[:format]))
231 v
250 v
232 elsif !@@handler_options[:issue][attr].blank?
251 elsif !@@handler_options[:issue][attr].blank?
233 @@handler_options[:issue][attr]
252 @@handler_options[:issue][attr]
234 end
253 end
235 end
254 end
236 end
255 end
237 end
256 end
238
257
239 # Destructively extracts the value for +attr+ in +text+
258 # Destructively extracts the value for +attr+ in +text+
240 # Returns nil if no matching keyword found
259 # Returns nil if no matching keyword found
241 def extract_keyword!(text, attr, format=nil)
260 def extract_keyword!(text, attr, format=nil)
242 keys = [attr.to_s.humanize]
261 keys = [attr.to_s.humanize]
243 if attr.is_a?(Symbol)
262 if attr.is_a?(Symbol)
244 keys << l("field_#{attr}", :default => '', :locale => user.language) if user && user.language.present?
263 if user && user.language.present?
245 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language) if Setting.default_language.present?
264 keys << l("field_#{attr}", :default => '', :locale => user.language)
265 end
266 if Setting.default_language.present?
267 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
268 end
246 end
269 end
247 keys.reject! {|k| k.blank?}
270 keys.reject! {|k| k.blank?}
248 keys.collect! {|k| Regexp.escape(k)}
271 keys.collect! {|k| Regexp.escape(k)}
249 format ||= '.+'
272 format ||= '.+'
250 text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '')
273 text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '')
251 $2 && $2.strip
274 $2 && $2.strip
252 end
275 end
253
276
254 def target_project
277 def target_project
255 # TODO: other ways to specify project:
278 # TODO: other ways to specify project:
256 # * parse the email To field
279 # * parse the email To field
257 # * specific project (eg. Setting.mail_handler_target_project)
280 # * specific project (eg. Setting.mail_handler_target_project)
258 target = Project.find_by_identifier(get_keyword(:project))
281 target = Project.find_by_identifier(get_keyword(:project))
259 raise MissingInformation.new('Unable to determine target project') if target.nil?
282 raise MissingInformation.new('Unable to determine target project') if target.nil?
260 target
283 target
261 end
284 end
262
285
263 # Returns a Hash of issue attributes extracted from keywords in the email body
286 # Returns a Hash of issue attributes extracted from keywords in the email body
264 def issue_attributes_from_keywords(issue)
287 def issue_attributes_from_keywords(issue)
265 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
288 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
266
289
267 attrs = {
290 attrs = {
268 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
291 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
269 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
292 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
270 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
293 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
271 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
294 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
272 'assigned_to_id' => assigned_to.try(:id),
295 'assigned_to_id' => assigned_to.try(:id),
273 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
296 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
274 issue.project.shared_versions.named(k).first.try(:id),
297 issue.project.shared_versions.named(k).first.try(:id),
275 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
298 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
276 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
299 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
277 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
300 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
278 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
301 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
279 }.delete_if {|k, v| v.blank? }
302 }.delete_if {|k, v| v.blank? }
280
303
281 if issue.new_record? && attrs['tracker_id'].nil?
304 if issue.new_record? && attrs['tracker_id'].nil?
282 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
305 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
283 end
306 end
284
307
285 attrs
308 attrs
286 end
309 end
287
310
288 # Returns a Hash of issue custom field values extracted from keywords in the email body
311 # Returns a Hash of issue custom field values extracted from keywords in the email body
289 def custom_field_values_from_keywords(customized)
312 def custom_field_values_from_keywords(customized)
290 customized.custom_field_values.inject({}) do |h, v|
313 customized.custom_field_values.inject({}) do |h, v|
291 if value = get_keyword(v.custom_field.name, :override => true)
314 if value = get_keyword(v.custom_field.name, :override => true)
292 h[v.custom_field.id.to_s] = value
315 h[v.custom_field.id.to_s] = value
293 end
316 end
294 h
317 h
295 end
318 end
296 end
319 end
297
320
298 # Returns the text/plain part of the email
321 # Returns the text/plain part of the email
299 # If not found (eg. HTML-only email), returns the body with tags removed
322 # If not found (eg. HTML-only email), returns the body with tags removed
300 def plain_text_body
323 def plain_text_body
301 return @plain_text_body unless @plain_text_body.nil?
324 return @plain_text_body unless @plain_text_body.nil?
302 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
325 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
303 if parts.empty?
326 if parts.empty?
304 parts << @email
327 parts << @email
305 end
328 end
306 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
329 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
307 if plain_text_part.nil?
330 if plain_text_part.nil?
308 # no text/plain part found, assuming html-only email
331 # no text/plain part found, assuming html-only email
309 # strip html tags and remove doctype directive
332 # strip html tags and remove doctype directive
310 @plain_text_body = strip_tags(@email.body.to_s)
333 @plain_text_body = strip_tags(@email.body.to_s)
311 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
334 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
312 else
335 else
313 @plain_text_body = plain_text_part.body.to_s
336 @plain_text_body = plain_text_part.body.to_s
314 end
337 end
315 @plain_text_body.strip!
338 @plain_text_body.strip!
316 @plain_text_body
339 @plain_text_body
317 end
340 end
318
341
319 def cleaned_up_text_body
342 def cleaned_up_text_body
320 cleanup_body(plain_text_body)
343 cleanup_body(plain_text_body)
321 end
344 end
322
345
323 def self.full_sanitizer
346 def self.full_sanitizer
324 @full_sanitizer ||= HTML::FullSanitizer.new
347 @full_sanitizer ||= HTML::FullSanitizer.new
325 end
348 end
326
349
327 def self.assign_string_attribute_with_limit(object, attribute, value)
350 def self.assign_string_attribute_with_limit(object, attribute, value)
328 limit = object.class.columns_hash[attribute.to_s].limit || 255
351 limit = object.class.columns_hash[attribute.to_s].limit || 255
329 value = value.to_s.slice(0, limit)
352 value = value.to_s.slice(0, limit)
330 object.send("#{attribute}=", value)
353 object.send("#{attribute}=", value)
331 end
354 end
332
355
333 # Returns a User from an email address and a full name
356 # Returns a User from an email address and a full name
334 def self.new_user_from_attributes(email_address, fullname=nil)
357 def self.new_user_from_attributes(email_address, fullname=nil)
335 user = User.new
358 user = User.new
336
359
337 # Truncating the email address would result in an invalid format
360 # Truncating the email address would result in an invalid format
338 user.mail = email_address
361 user.mail = email_address
339 assign_string_attribute_with_limit(user, 'login', email_address)
362 assign_string_attribute_with_limit(user, 'login', email_address)
340
363
341 names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
364 names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
342 assign_string_attribute_with_limit(user, 'firstname', names.shift)
365 assign_string_attribute_with_limit(user, 'firstname', names.shift)
343 assign_string_attribute_with_limit(user, 'lastname', names.join(' '))
366 assign_string_attribute_with_limit(user, 'lastname', names.join(' '))
344 user.lastname = '-' if user.lastname.blank?
367 user.lastname = '-' if user.lastname.blank?
345
368
346 password_length = [Setting.password_min_length.to_i, 10].max
369 password_length = [Setting.password_min_length.to_i, 10].max
347 user.password = ActiveSupport::SecureRandom.hex(password_length / 2 + 1)
370 user.password = ActiveSupport::SecureRandom.hex(password_length / 2 + 1)
348 user.language = Setting.default_language
371 user.language = Setting.default_language
349
372
350 unless user.valid?
373 unless user.valid?
351 user.login = "user#{ActiveSupport::SecureRandom.hex(6)}" unless user.errors[:login].blank?
374 user.login = "user#{ActiveSupport::SecureRandom.hex(6)}" unless user.errors[:login].blank?
352 user.firstname = "-" unless user.errors[:firstname].blank?
375 user.firstname = "-" unless user.errors[:firstname].blank?
353 user.lastname = "-" unless user.errors[:lastname].blank?
376 user.lastname = "-" unless user.errors[:lastname].blank?
354 end
377 end
355
378
356 user
379 user
357 end
380 end
358
381
359 # Creates a User for the +email+ sender
382 # Creates a User for the +email+ sender
360 # Returns the user or nil if it could not be created
383 # Returns the user or nil if it could not be created
361 def create_user_from_email
384 def create_user_from_email
362 addr = email.from_addrs.to_a.first
385 addr = email.from_addrs.to_a.first
363 if addr && !addr.spec.blank?
386 if addr && !addr.spec.blank?
364 user = self.class.new_user_from_attributes(addr.spec, addr.name)
387 user = self.class.new_user_from_attributes(addr.spec, addr.name)
365 if user.save
388 if user.save
366 user
389 user
367 else
390 else
368 logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
391 logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
369 nil
392 nil
370 end
393 end
371 else
394 else
372 logger.error "MailHandler: failed to create User: no FROM address found" if logger
395 logger.error "MailHandler: failed to create User: no FROM address found" if logger
373 nil
396 nil
374 end
397 end
375 end
398 end
376
399
377 # Removes the email body of text after the truncation configurations.
400 # Removes the email body of text after the truncation configurations.
378 def cleanup_body(body)
401 def cleanup_body(body)
379 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
402 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
380 unless delimiters.empty?
403 unless delimiters.empty?
381 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
404 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
382 body = body.gsub(regex, '')
405 body = body.gsub(regex, '')
383 end
406 end
384 body.strip
407 body.strip
385 end
408 end
386
409
387 def find_assignee_from_keyword(keyword, issue)
410 def find_assignee_from_keyword(keyword, issue)
388 keyword = keyword.to_s.downcase
411 keyword = keyword.to_s.downcase
389 assignable = issue.assignable_users
412 assignable = issue.assignable_users
390 assignee = nil
413 assignee = nil
391 assignee ||= assignable.detect {|a| a.mail.to_s.downcase == keyword || a.login.to_s.downcase == keyword}
414 assignee ||= assignable.detect {|a|
415 a.mail.to_s.downcase == keyword ||
416 a.login.to_s.downcase == keyword
417 }
392 if assignee.nil? && keyword.match(/ /)
418 if assignee.nil? && keyword.match(/ /)
393 firstname, lastname = *(keyword.split) # "First Last Throwaway"
419 firstname, lastname = *(keyword.split) # "First Last Throwaway"
394 assignee ||= assignable.detect {|a| a.is_a?(User) && a.firstname.to_s.downcase == firstname && a.lastname.to_s.downcase == lastname}
420 assignee ||= assignable.detect {|a|
421 a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
422 a.lastname.to_s.downcase == lastname
423 }
395 end
424 end
396 if assignee.nil?
425 if assignee.nil?
397 assignee ||= assignable.detect {|a| a.is_a?(Group) && a.name.downcase == keyword}
426 assignee ||= assignable.detect {|a| a.is_a?(Group) && a.name.downcase == keyword}
398 end
427 end
399 assignee
428 assignee
400 end
429 end
401 end
430 end
General Comments 0
You need to be logged in to leave comments. Login now