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