##// END OF EJS Templates
Allow [#id] as subject to reply by email (#3653)....
Jean-Philippe Lang -
r2917:8267ded518d9
parent child
Show More
@@ -1,290 +1,290
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 sender_email = email.from.to_a.first.to_s.strip
45 45 # Ignore emails received from the application emission address to avoid hell cycles
46 46 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
47 47 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]" if logger && logger.info
48 48 return false
49 49 end
50 50 @user = User.find_by_mail(sender_email)
51 51 if @user && !@user.active?
52 52 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]" if logger && logger.info
53 53 return false
54 54 end
55 55 if @user.nil?
56 56 # Email was submitted by an unknown user
57 57 case @@handler_options[:unknown_user]
58 58 when 'accept'
59 59 @user = User.anonymous
60 60 when 'create'
61 61 @user = MailHandler.create_user_from_email(email)
62 62 if @user
63 63 logger.info "MailHandler: [#{@user.login}] account created" if logger && logger.info
64 64 Mailer.deliver_account_information(@user, @user.password)
65 65 else
66 66 logger.error "MailHandler: could not create account for [#{sender_email}]" if logger && logger.error
67 67 return false
68 68 end
69 69 else
70 70 # Default behaviour, emails from unknown users are ignored
71 71 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]" if logger && logger.info
72 72 return false
73 73 end
74 74 end
75 75 User.current = @user
76 76 dispatch
77 77 end
78 78
79 79 private
80 80
81 81 MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
82 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]+#(\d+)\]}
83 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]+msg(\d+)\]}
82 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
83 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
84 84
85 85 def dispatch
86 86 headers = [email.in_reply_to, email.references].flatten.compact
87 87 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
88 88 klass, object_id = $1, $2.to_i
89 89 method_name = "receive_#{klass}_reply"
90 90 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
91 91 send method_name, object_id
92 92 else
93 93 # ignoring it
94 94 end
95 95 elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
96 96 receive_issue_reply(m[1].to_i)
97 97 elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
98 98 receive_message_reply(m[1].to_i)
99 99 else
100 100 receive_issue
101 101 end
102 102 rescue ActiveRecord::RecordInvalid => e
103 103 # TODO: send a email to the user
104 104 logger.error e.message if logger
105 105 false
106 106 rescue MissingInformation => e
107 107 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
108 108 false
109 109 rescue UnauthorizedAction => e
110 110 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
111 111 false
112 112 end
113 113
114 114 # Creates a new issue
115 115 def receive_issue
116 116 project = target_project
117 117 tracker = (get_keyword(:tracker) && project.trackers.find_by_name(get_keyword(:tracker))) || project.trackers.find(:first)
118 118 category = (get_keyword(:category) && project.issue_categories.find_by_name(get_keyword(:category)))
119 119 priority = (get_keyword(:priority) && IssuePriority.find_by_name(get_keyword(:priority)))
120 120 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
121 121
122 122 # check permission
123 123 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
124 124 issue = Issue.new(:author => user, :project => project, :tracker => tracker, :category => category, :priority => priority)
125 125 # check workflow
126 126 if status && issue.new_statuses_allowed_to(user).include?(status)
127 127 issue.status = status
128 128 end
129 129 issue.subject = email.subject.chomp
130 130 issue.subject = issue.subject.toutf8 if issue.subject.respond_to?(:toutf8)
131 131 if issue.subject.blank?
132 132 issue.subject = '(no subject)'
133 133 end
134 134 issue.description = plain_text_body
135 135 # custom fields
136 136 issue.custom_field_values = issue.available_custom_fields.inject({}) do |h, c|
137 137 if value = get_keyword(c.name, :override => true)
138 138 h[c.id] = value
139 139 end
140 140 h
141 141 end
142 142 # add To and Cc as watchers before saving so the watchers can reply to Redmine
143 143 add_watchers(issue)
144 144 issue.save!
145 145 add_attachments(issue)
146 146 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
147 147 issue
148 148 end
149 149
150 150 def target_project
151 151 # TODO: other ways to specify project:
152 152 # * parse the email To field
153 153 # * specific project (eg. Setting.mail_handler_target_project)
154 154 target = Project.find_by_identifier(get_keyword(:project))
155 155 raise MissingInformation.new('Unable to determine target project') if target.nil?
156 156 target
157 157 end
158 158
159 159 # Adds a note to an existing issue
160 160 def receive_issue_reply(issue_id)
161 161 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
162 162
163 163 issue = Issue.find_by_id(issue_id)
164 164 return unless issue
165 165 # check permission
166 166 raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
167 167 raise UnauthorizedAction unless status.nil? || user.allowed_to?(:edit_issues, issue.project)
168 168
169 169 # add the note
170 170 journal = issue.init_journal(user, plain_text_body)
171 171 add_attachments(issue)
172 172 # check workflow
173 173 if status && issue.new_statuses_allowed_to(user).include?(status)
174 174 issue.status = status
175 175 end
176 176 issue.save!
177 177 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
178 178 journal
179 179 end
180 180
181 181 # Reply will be added to the issue
182 182 def receive_journal_reply(journal_id)
183 183 journal = Journal.find_by_id(journal_id)
184 184 if journal && journal.journalized_type == 'Issue'
185 185 receive_issue_reply(journal.journalized_id)
186 186 end
187 187 end
188 188
189 189 # Receives a reply to a forum message
190 190 def receive_message_reply(message_id)
191 191 message = Message.find_by_id(message_id)
192 192 if message
193 193 message = message.root
194 194 if user.allowed_to?(:add_messages, message.project) && !message.locked?
195 195 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
196 196 :content => plain_text_body)
197 197 reply.author = user
198 198 reply.board = message.board
199 199 message.children << reply
200 200 add_attachments(reply)
201 201 reply
202 202 else
203 203 raise UnauthorizedAction
204 204 end
205 205 end
206 206 end
207 207
208 208 def add_attachments(obj)
209 209 if email.has_attachments?
210 210 email.attachments.each do |attachment|
211 211 Attachment.create(:container => obj,
212 212 :file => attachment,
213 213 :author => user,
214 214 :content_type => attachment.content_type)
215 215 end
216 216 end
217 217 end
218 218
219 219 # Adds To and Cc as watchers of the given object if the sender has the
220 220 # appropriate permission
221 221 def add_watchers(obj)
222 222 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
223 223 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
224 224 unless addresses.empty?
225 225 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
226 226 watchers.each {|w| obj.add_watcher(w)}
227 227 end
228 228 end
229 229 end
230 230
231 231 def get_keyword(attr, options={})
232 232 @keywords ||= {}
233 233 if @keywords.has_key?(attr)
234 234 @keywords[attr]
235 235 else
236 236 @keywords[attr] = begin
237 237 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && plain_text_body.gsub!(/^#{attr}[ \t]*:[ \t]*(.+)\s*$/i, '')
238 238 $1.strip
239 239 elsif !@@handler_options[:issue][attr].blank?
240 240 @@handler_options[:issue][attr]
241 241 end
242 242 end
243 243 end
244 244 end
245 245
246 246 # Returns the text/plain part of the email
247 247 # If not found (eg. HTML-only email), returns the body with tags removed
248 248 def plain_text_body
249 249 return @plain_text_body unless @plain_text_body.nil?
250 250 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
251 251 if parts.empty?
252 252 parts << @email
253 253 end
254 254 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
255 255 if plain_text_part.nil?
256 256 # no text/plain part found, assuming html-only email
257 257 # strip html tags and remove doctype directive
258 258 @plain_text_body = strip_tags(@email.body.to_s)
259 259 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
260 260 else
261 261 @plain_text_body = plain_text_part.body.to_s
262 262 end
263 263 @plain_text_body.strip!
264 264 @plain_text_body
265 265 end
266 266
267 267
268 268 def self.full_sanitizer
269 269 @full_sanitizer ||= HTML::FullSanitizer.new
270 270 end
271 271
272 272 # Creates a user account for the +email+ sender
273 273 def self.create_user_from_email(email)
274 274 addr = email.from_addrs.to_a.first
275 275 if addr && !addr.spec.blank?
276 276 user = User.new
277 277 user.mail = addr.spec
278 278
279 279 names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split
280 280 user.firstname = names.shift
281 281 user.lastname = names.join(' ')
282 282 user.lastname = '-' if user.lastname.blank?
283 283
284 284 user.login = user.mail
285 285 user.password = ActiveSupport::SecureRandom.hex(5)
286 286 user.language = Setting.default_language
287 287 user.save ? user : nil
288 288 end
289 289 end
290 290 end
General Comments 0
You need to be logged in to leave comments. Login now