##// END OF EJS Templates
Merged r2520 from trunk....
Jean-Philippe Lang -
r2457:69b99aa518b4
parent child
Show More
@@ -1,199 +1,200
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
20
21 class UnauthorizedAction < StandardError; end
21 class UnauthorizedAction < StandardError; end
22 class MissingInformation < StandardError; end
22 class MissingInformation < StandardError; end
23
23
24 attr_reader :email, :user
24 attr_reader :email, :user
25
25
26 def self.receive(email, options={})
26 def self.receive(email, options={})
27 @@handler_options = options.dup
27 @@handler_options = options.dup
28
28
29 @@handler_options[:issue] ||= {}
29 @@handler_options[:issue] ||= {}
30
30
31 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String)
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] ||= []
32 @@handler_options[:allow_override] ||= []
33 # Project needs to be overridable if not specified
33 # Project needs to be overridable if not specified
34 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
34 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
35 # Status overridable by default
35 # Status overridable by default
36 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
36 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
37 super email
37 super email
38 end
38 end
39
39
40 # Processes incoming emails
40 # Processes incoming emails
41 def receive(email)
41 def receive(email)
42 @email = email
42 @email = email
43 @user = User.active.find(:first, :conditions => ["LOWER(mail) = ?", email.from.first.to_s.strip.downcase])
43 @user = User.active.find(:first, :conditions => ["LOWER(mail) = ?", email.from.first.to_s.strip.downcase])
44 unless @user
44 unless @user
45 # Unknown user => the email is ignored
45 # Unknown user => the email is ignored
46 # TODO: ability to create the user's account
46 # TODO: ability to create the user's account
47 logger.info "MailHandler: email submitted by unknown user [#{email.from.first}]" if logger && logger.info
47 logger.info "MailHandler: email submitted by unknown user [#{email.from.first}]" if logger && logger.info
48 return false
48 return false
49 end
49 end
50 User.current = @user
50 User.current = @user
51 dispatch
51 dispatch
52 end
52 end
53
53
54 private
54 private
55
55
56 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]+#(\d+)\]}
56 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]+#(\d+)\]}
57
57
58 def dispatch
58 def dispatch
59 if m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
59 if m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
60 receive_issue_update(m[1].to_i)
60 receive_issue_update(m[1].to_i)
61 else
61 else
62 receive_issue
62 receive_issue
63 end
63 end
64 rescue ActiveRecord::RecordInvalid => e
64 rescue ActiveRecord::RecordInvalid => e
65 # TODO: send a email to the user
65 # TODO: send a email to the user
66 logger.error e.message if logger
66 logger.error e.message if logger
67 false
67 false
68 rescue MissingInformation => e
68 rescue MissingInformation => e
69 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
69 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
70 false
70 false
71 rescue UnauthorizedAction => e
71 rescue UnauthorizedAction => e
72 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
72 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
73 false
73 false
74 end
74 end
75
75
76 # Creates a new issue
76 # Creates a new issue
77 def receive_issue
77 def receive_issue
78 project = target_project
78 project = target_project
79 tracker = (get_keyword(:tracker) && project.trackers.find_by_name(get_keyword(:tracker))) || project.trackers.find(:first)
79 tracker = (get_keyword(:tracker) && project.trackers.find_by_name(get_keyword(:tracker))) || project.trackers.find(:first)
80 category = (get_keyword(:category) && project.issue_categories.find_by_name(get_keyword(:category)))
80 category = (get_keyword(:category) && project.issue_categories.find_by_name(get_keyword(:category)))
81 priority = (get_keyword(:priority) && Enumeration.find_by_opt_and_name('IPRI', get_keyword(:priority)))
81 priority = (get_keyword(:priority) && Enumeration.find_by_opt_and_name('IPRI', get_keyword(:priority)))
82 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
82 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
83
83
84 # check permission
84 # check permission
85 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
85 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
86 issue = Issue.new(:author => user, :project => project, :tracker => tracker, :category => category, :priority => priority)
86 issue = Issue.new(:author => user, :project => project, :tracker => tracker, :category => category, :priority => priority)
87 # check workflow
87 # check workflow
88 if status && issue.new_statuses_allowed_to(user).include?(status)
88 if status && issue.new_statuses_allowed_to(user).include?(status)
89 issue.status = status
89 issue.status = status
90 end
90 end
91 issue.subject = email.subject.chomp.toutf8
91 issue.subject = email.subject.chomp.toutf8
92 issue.description = plain_text_body
92 issue.description = plain_text_body
93 # custom fields
93 # custom fields
94 issue.custom_field_values = issue.available_custom_fields.inject({}) do |h, c|
94 issue.custom_field_values = issue.available_custom_fields.inject({}) do |h, c|
95 if value = get_keyword(c.name, :override => true)
95 if value = get_keyword(c.name, :override => true)
96 h[c.id] = value
96 h[c.id] = value
97 end
97 end
98 h
98 h
99 end
99 end
100 issue.save!
100 issue.save!
101 add_attachments(issue)
101 add_attachments(issue)
102 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
102 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
103 # add To and Cc as watchers
103 # add To and Cc as watchers
104 add_watchers(issue)
104 add_watchers(issue)
105 # send notification after adding watchers so that they can reply to Redmine
105 # send notification after adding watchers so that they can reply to Redmine
106 Mailer.deliver_issue_add(issue) if Setting.notified_events.include?('issue_added')
106 Mailer.deliver_issue_add(issue) if Setting.notified_events.include?('issue_added')
107 issue
107 issue
108 end
108 end
109
109
110 def target_project
110 def target_project
111 # TODO: other ways to specify project:
111 # TODO: other ways to specify project:
112 # * parse the email To field
112 # * parse the email To field
113 # * specific project (eg. Setting.mail_handler_target_project)
113 # * specific project (eg. Setting.mail_handler_target_project)
114 target = Project.find_by_identifier(get_keyword(:project))
114 target = Project.find_by_identifier(get_keyword(:project))
115 raise MissingInformation.new('Unable to determine target project') if target.nil?
115 raise MissingInformation.new('Unable to determine target project') if target.nil?
116 target
116 target
117 end
117 end
118
118
119 # Adds a note to an existing issue
119 # Adds a note to an existing issue
120 def receive_issue_update(issue_id)
120 def receive_issue_update(issue_id)
121 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
121 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
122
122
123 issue = Issue.find_by_id(issue_id)
123 issue = Issue.find_by_id(issue_id)
124 return unless issue
124 return unless issue
125 # check permission
125 # check permission
126 raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
126 raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
127 raise UnauthorizedAction unless status.nil? || user.allowed_to?(:edit_issues, issue.project)
127 raise UnauthorizedAction unless status.nil? || user.allowed_to?(:edit_issues, issue.project)
128
128
129 # add the note
129 # add the note
130 journal = issue.init_journal(user, plain_text_body)
130 journal = issue.init_journal(user, plain_text_body)
131 add_attachments(issue)
131 add_attachments(issue)
132 # check workflow
132 # check workflow
133 if status && issue.new_statuses_allowed_to(user).include?(status)
133 if status && issue.new_statuses_allowed_to(user).include?(status)
134 issue.status = status
134 issue.status = status
135 end
135 end
136 issue.save!
136 issue.save!
137 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
137 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
138 Mailer.deliver_issue_edit(journal) if Setting.notified_events.include?('issue_updated')
138 Mailer.deliver_issue_edit(journal) if Setting.notified_events.include?('issue_updated')
139 journal
139 journal
140 end
140 end
141
141
142 def add_attachments(obj)
142 def add_attachments(obj)
143 if email.has_attachments?
143 if email.has_attachments?
144 email.attachments.each do |attachment|
144 email.attachments.each do |attachment|
145 Attachment.create(:container => obj,
145 Attachment.create(:container => obj,
146 :file => attachment,
146 :file => attachment,
147 :author => user,
147 :author => user,
148 :content_type => attachment.content_type)
148 :content_type => attachment.content_type)
149 end
149 end
150 end
150 end
151 end
151 end
152
152
153 # Adds To and Cc as watchers of the given object if the sender has the
153 # Adds To and Cc as watchers of the given object if the sender has the
154 # appropriate permission
154 # appropriate permission
155 def add_watchers(obj)
155 def add_watchers(obj)
156 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
156 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
157 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
157 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
158 unless addresses.empty?
158 unless addresses.empty?
159 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
159 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
160 watchers.each {|w| obj.add_watcher(w)}
160 watchers.each {|w| obj.add_watcher(w)}
161 end
161 end
162 end
162 end
163 end
163 end
164
164
165 def get_keyword(attr, options={})
165 def get_keyword(attr, options={})
166 @keywords ||= {}
166 @keywords ||= {}
167 if @keywords.has_key?(attr)
167 if @keywords.has_key?(attr)
168 @keywords[attr]
168 @keywords[attr]
169 else
169 else
170 @keywords[attr] = begin
170 @keywords[attr] = begin
171 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && plain_text_body.gsub!(/^#{attr}:[ \t]*(.+)\s*$/i, '')
171 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && plain_text_body.gsub!(/^#{attr}:[ \t]*(.+)\s*$/i, '')
172 $1.strip
172 $1.strip
173 elsif !@@handler_options[:issue][attr].blank?
173 elsif !@@handler_options[:issue][attr].blank?
174 @@handler_options[:issue][attr]
174 @@handler_options[:issue][attr]
175 end
175 end
176 end
176 end
177 end
177 end
178 end
178 end
179
179
180 # Returns the text/plain part of the email
180 # Returns the text/plain part of the email
181 # If not found (eg. HTML-only email), returns the body with tags removed
181 # If not found (eg. HTML-only email), returns the body with tags removed
182 def plain_text_body
182 def plain_text_body
183 return @plain_text_body unless @plain_text_body.nil?
183 return @plain_text_body unless @plain_text_body.nil?
184 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
184 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
185 if parts.empty?
185 if parts.empty?
186 parts << @email
186 parts << @email
187 end
187 end
188 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
188 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
189 if plain_text_part.nil?
189 if plain_text_part.nil?
190 # no text/plain part found, assuming html-only email
190 # no text/plain part found, assuming html-only email
191 # strip html tags and remove doctype directive
191 # strip html tags and remove doctype directive
192 @plain_text_body = strip_tags(@email.body.to_s)
192 @plain_text_body = strip_tags(@email.body.to_s)
193 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
193 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
194 else
194 else
195 @plain_text_body = plain_text_part.body.to_s
195 @plain_text_body = plain_text_part.body.to_s
196 end
196 end
197 @plain_text_body.strip!
197 @plain_text_body.strip!
198 @plain_text_body
198 end
199 end
199 end
200 end
General Comments 0
You need to be logged in to leave comments. Login now