##// END OF EJS Templates
Merged r11648, r11649, r11650 from trunk to 2.2-stable....
Toshi MARUYAMA -
r11423:504a767028ec
parent child
Show More
@@ -1,95 +1,95
1 source 'http://rubygems.org'
1 source 'http://rubygems.org'
2
2
3 gem 'rails', '3.2.12'
3 gem "rails", "3.2.13"
4 gem "jquery-rails", "~> 2.0.2"
4 gem "jquery-rails", "~> 2.0.2"
5 gem "i18n", "~> 0.6.0"
5 gem "i18n", "~> 0.6.0"
6 gem "coderay", "~> 1.0.6"
6 gem "coderay", "~> 1.0.6"
7 gem "fastercsv", "~> 1.5.0", :platforms => [:mri_18, :mingw_18, :jruby]
7 gem "fastercsv", "~> 1.5.0", :platforms => [:mri_18, :mingw_18, :jruby]
8 gem "builder", "3.0.0"
8 gem "builder", "3.0.0"
9
9
10 # Optional gem for LDAP authentication
10 # Optional gem for LDAP authentication
11 group :ldap do
11 group :ldap do
12 gem "net-ldap", "~> 0.3.1"
12 gem "net-ldap", "~> 0.3.1"
13 end
13 end
14
14
15 # Optional gem for OpenID authentication
15 # Optional gem for OpenID authentication
16 group :openid do
16 group :openid do
17 gem "ruby-openid", "~> 2.1.4", :require => "openid"
17 gem "ruby-openid", "~> 2.1.4", :require => "openid"
18 gem "rack-openid"
18 gem "rack-openid"
19 end
19 end
20
20
21 # Optional gem for exporting the gantt to a PNG file, not supported with jruby
21 # Optional gem for exporting the gantt to a PNG file, not supported with jruby
22 platforms :mri, :mingw do
22 platforms :mri, :mingw do
23 group :rmagick do
23 group :rmagick do
24 # RMagick 2 supports ruby 1.9
24 # RMagick 2 supports ruby 1.9
25 # RMagick 1 would be fine for ruby 1.8 but Bundler does not support
25 # RMagick 1 would be fine for ruby 1.8 but Bundler does not support
26 # different requirements for the same gem on different platforms
26 # different requirements for the same gem on different platforms
27 gem "rmagick", ">= 2.0.0"
27 gem "rmagick", ">= 2.0.0"
28 end
28 end
29 end
29 end
30
30
31 # Database gems
31 # Database gems
32 platforms :mri, :mingw do
32 platforms :mri, :mingw do
33 group :postgresql do
33 group :postgresql do
34 gem "pg", ">= 0.11.0"
34 gem "pg", ">= 0.11.0"
35 end
35 end
36
36
37 group :sqlite do
37 group :sqlite do
38 gem "sqlite3"
38 gem "sqlite3"
39 end
39 end
40 end
40 end
41
41
42 platforms :mri_18, :mingw_18 do
42 platforms :mri_18, :mingw_18 do
43 group :mysql do
43 group :mysql do
44 gem "mysql", "~> 2.8.1"
44 gem "mysql", "~> 2.8.1"
45 end
45 end
46 end
46 end
47
47
48 platforms :mri_19, :mingw_19 do
48 platforms :mri_19, :mingw_19 do
49 group :mysql do
49 group :mysql do
50 gem "mysql2", "~> 0.3.11"
50 gem "mysql2", "~> 0.3.11"
51 end
51 end
52 end
52 end
53
53
54 platforms :jruby do
54 platforms :jruby do
55 gem "jruby-openssl"
55 gem "jruby-openssl"
56
56
57 group :mysql do
57 group :mysql do
58 gem "activerecord-jdbcmysql-adapter"
58 gem "activerecord-jdbcmysql-adapter"
59 end
59 end
60
60
61 group :postgresql do
61 group :postgresql do
62 gem "activerecord-jdbcpostgresql-adapter"
62 gem "activerecord-jdbcpostgresql-adapter"
63 end
63 end
64
64
65 group :sqlite do
65 group :sqlite do
66 gem "activerecord-jdbcsqlite3-adapter"
66 gem "activerecord-jdbcsqlite3-adapter"
67 end
67 end
68 end
68 end
69
69
70 group :development do
70 group :development do
71 gem "rdoc", ">= 2.4.2"
71 gem "rdoc", ">= 2.4.2"
72 gem "yard"
72 gem "yard"
73 end
73 end
74
74
75 group :test do
75 group :test do
76 gem "shoulda", "~> 2.11"
76 gem "shoulda", "~> 2.11"
77 # Shoulda does not work nice on Ruby 1.9.3 and JRuby 1.7.
77 # Shoulda does not work nice on Ruby 1.9.3 and JRuby 1.7.
78 # It seems to need test-unit explicitely.
78 # It seems to need test-unit explicitely.
79 platforms = [:mri_19]
79 platforms = [:mri_19]
80 platforms << :jruby if defined?(JRUBY_VERSION) && JRUBY_VERSION >= "1.7"
80 platforms << :jruby if defined?(JRUBY_VERSION) && JRUBY_VERSION >= "1.7"
81 gem "test-unit", :platforms => platforms
81 gem "test-unit", :platforms => platforms
82 gem "mocha", "0.12.3"
82 gem "mocha", "~> 0.13.3"
83 end
83 end
84
84
85 local_gemfile = File.join(File.dirname(__FILE__), "Gemfile.local")
85 local_gemfile = File.join(File.dirname(__FILE__), "Gemfile.local")
86 if File.exists?(local_gemfile)
86 if File.exists?(local_gemfile)
87 puts "Loading Gemfile.local ..." if $DEBUG # `ruby -d` or `bundle -v`
87 puts "Loading Gemfile.local ..." if $DEBUG # `ruby -d` or `bundle -v`
88 instance_eval File.read(local_gemfile)
88 instance_eval File.read(local_gemfile)
89 end
89 end
90
90
91 # Load plugins' Gemfiles
91 # Load plugins' Gemfiles
92 Dir.glob File.expand_path("../plugins/*/Gemfile", __FILE__) do |file|
92 Dir.glob File.expand_path("../plugins/*/Gemfile", __FILE__) do |file|
93 puts "Loading #{file} ..." if $DEBUG # `ruby -d` or `bundle -v`
93 puts "Loading #{file} ..." if $DEBUG # `ruby -d` or `bundle -v`
94 instance_eval File.read(file)
94 instance_eval File.read(file)
95 end
95 end
@@ -1,498 +1,468
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
2 # Copyright (C) 2006-2012 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 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)
33 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip)
34 end
34 end
35 @@handler_options[:allow_override] ||= []
35 @@handler_options[:allow_override] ||= []
36 # Project needs to be overridable if not specified
36 # Project needs to be overridable if not specified
37 @@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)
38 # Status overridable by default
38 # Status overridable by default
39 @@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)
40
40
41 @@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)
42
42
43 email.force_encoding('ASCII-8BIT') if email.respond_to?(:force_encoding)
43 email.force_encoding('ASCII-8BIT') if email.respond_to?(:force_encoding)
44 super(email)
44 super(email)
45 end
45 end
46
46
47 def logger
47 def logger
48 Rails.logger
48 Rails.logger
49 end
49 end
50
50
51 cattr_accessor :ignored_emails_headers
51 cattr_accessor :ignored_emails_headers
52 @@ignored_emails_headers = {
52 @@ignored_emails_headers = {
53 'X-Auto-Response-Suppress' => 'oof',
53 'X-Auto-Response-Suppress' => 'oof',
54 'Auto-Submitted' => /^auto-/
54 'Auto-Submitted' => /^auto-/
55 }
55 }
56
56
57 # Processes incoming emails
57 # Processes incoming emails
58 # Returns the created object (eg. an issue, a message) or false
58 # Returns the created object (eg. an issue, a message) or false
59 def receive(email)
59 def receive(email)
60 @email = email
60 @email = email
61 sender_email = email.from.to_a.first.to_s.strip
61 sender_email = email.from.to_a.first.to_s.strip
62 # Ignore emails received from the application emission address to avoid hell cycles
62 # Ignore emails received from the application emission address to avoid hell cycles
63 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
63 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
64 if logger && logger.info
64 if logger && logger.info
65 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
65 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
66 end
66 end
67 return false
67 return false
68 end
68 end
69 # Ignore auto generated emails
69 # Ignore auto generated emails
70 self.class.ignored_emails_headers.each do |key, ignored_value|
70 self.class.ignored_emails_headers.each do |key, ignored_value|
71 value = email.header[key]
71 value = email.header[key]
72 if value
72 if value
73 value = value.to_s.downcase
73 value = value.to_s.downcase
74 if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
74 if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
75 if logger && logger.info
75 if logger && logger.info
76 logger.info "MailHandler: ignoring email with #{key}:#{value} header"
76 logger.info "MailHandler: ignoring email with #{key}:#{value} header"
77 end
77 end
78 return false
78 return false
79 end
79 end
80 end
80 end
81 end
81 end
82 @user = User.find_by_mail(sender_email) if sender_email.present?
82 @user = User.find_by_mail(sender_email) if sender_email.present?
83 if @user && !@user.active?
83 if @user && !@user.active?
84 if logger && logger.info
84 if logger && logger.info
85 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]"
85 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]"
86 end
86 end
87 return false
87 return false
88 end
88 end
89 if @user.nil?
89 if @user.nil?
90 # Email was submitted by an unknown user
90 # Email was submitted by an unknown user
91 case @@handler_options[:unknown_user]
91 case @@handler_options[:unknown_user]
92 when 'accept'
92 when 'accept'
93 @user = User.anonymous
93 @user = User.anonymous
94 when 'create'
94 when 'create'
95 @user = create_user_from_email
95 @user = create_user_from_email
96 if @user
96 if @user
97 if logger && logger.info
97 if logger && logger.info
98 logger.info "MailHandler: [#{@user.login}] account created"
98 logger.info "MailHandler: [#{@user.login}] account created"
99 end
99 end
100 Mailer.account_information(@user, @user.password).deliver
100 Mailer.account_information(@user, @user.password).deliver
101 else
101 else
102 if logger && logger.error
102 if logger && logger.error
103 logger.error "MailHandler: could not create account for [#{sender_email}]"
103 logger.error "MailHandler: could not create account for [#{sender_email}]"
104 end
104 end
105 return false
105 return false
106 end
106 end
107 else
107 else
108 # Default behaviour, emails from unknown users are ignored
108 # Default behaviour, emails from unknown users are ignored
109 if logger && logger.info
109 if logger && logger.info
110 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]"
110 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]"
111 end
111 end
112 return false
112 return false
113 end
113 end
114 end
114 end
115 User.current = @user
115 User.current = @user
116 dispatch
116 dispatch
117 end
117 end
118
118
119 private
119 private
120
120
121 MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
121 MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
122 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
122 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
123 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
123 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
124
124
125 def dispatch
125 def dispatch
126 headers = [email.in_reply_to, email.references].flatten.compact
126 headers = [email.in_reply_to, email.references].flatten.compact
127 subject = email.subject.to_s
127 subject = email.subject.to_s
128 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
128 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
129 klass, object_id = $1, $2.to_i
129 klass, object_id = $1, $2.to_i
130 method_name = "receive_#{klass}_reply"
130 method_name = "receive_#{klass}_reply"
131 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
131 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
132 send method_name, object_id
132 send method_name, object_id
133 else
133 else
134 # ignoring it
134 # ignoring it
135 end
135 end
136 elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
136 elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
137 receive_issue_reply(m[1].to_i)
137 receive_issue_reply(m[1].to_i)
138 elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
138 elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
139 receive_message_reply(m[1].to_i)
139 receive_message_reply(m[1].to_i)
140 else
140 else
141 dispatch_to_default
141 dispatch_to_default
142 end
142 end
143 rescue ActiveRecord::RecordInvalid => e
143 rescue ActiveRecord::RecordInvalid => e
144 # TODO: send a email to the user
144 # TODO: send a email to the user
145 logger.error e.message if logger
145 logger.error e.message if logger
146 false
146 false
147 rescue MissingInformation => e
147 rescue MissingInformation => e
148 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
148 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
149 false
149 false
150 rescue UnauthorizedAction => e
150 rescue UnauthorizedAction => e
151 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
151 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
152 false
152 false
153 end
153 end
154
154
155 def dispatch_to_default
155 def dispatch_to_default
156 receive_issue
156 receive_issue
157 end
157 end
158
158
159 # Creates a new issue
159 # Creates a new issue
160 def receive_issue
160 def receive_issue
161 project = target_project
161 project = target_project
162 # check permission
162 # check permission
163 unless @@handler_options[:no_permission_check]
163 unless @@handler_options[:no_permission_check]
164 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
164 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
165 end
165 end
166
166
167 issue = Issue.new(:author => user, :project => project)
167 issue = Issue.new(:author => user, :project => project)
168 issue.safe_attributes = issue_attributes_from_keywords(issue)
168 issue.safe_attributes = issue_attributes_from_keywords(issue)
169 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
169 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
170 issue.subject = cleaned_up_subject
170 issue.subject = cleaned_up_subject
171 if issue.subject.blank?
171 if issue.subject.blank?
172 issue.subject = '(no subject)'
172 issue.subject = '(no subject)'
173 end
173 end
174 issue.description = cleaned_up_text_body
174 issue.description = cleaned_up_text_body
175
175
176 # add To and Cc as watchers before saving so the watchers can reply to Redmine
176 # add To and Cc as watchers before saving so the watchers can reply to Redmine
177 add_watchers(issue)
177 add_watchers(issue)
178 issue.save!
178 issue.save!
179 add_attachments(issue)
179 add_attachments(issue)
180 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
180 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
181 issue
181 issue
182 end
182 end
183
183
184 # Adds a note to an existing issue
184 # Adds a note to an existing issue
185 def receive_issue_reply(issue_id, from_journal=nil)
185 def receive_issue_reply(issue_id, from_journal=nil)
186 issue = Issue.find_by_id(issue_id)
186 issue = Issue.find_by_id(issue_id)
187 return unless issue
187 return unless issue
188 # check permission
188 # check permission
189 unless @@handler_options[:no_permission_check]
189 unless @@handler_options[:no_permission_check]
190 unless user.allowed_to?(:add_issue_notes, issue.project) ||
190 unless user.allowed_to?(:add_issue_notes, issue.project) ||
191 user.allowed_to?(:edit_issues, issue.project)
191 user.allowed_to?(:edit_issues, issue.project)
192 raise UnauthorizedAction
192 raise UnauthorizedAction
193 end
193 end
194 end
194 end
195
195
196 # ignore CLI-supplied defaults for new issues
196 # ignore CLI-supplied defaults for new issues
197 @@handler_options[:issue].clear
197 @@handler_options[:issue].clear
198
198
199 journal = issue.init_journal(user)
199 journal = issue.init_journal(user)
200 if from_journal && from_journal.private_notes?
200 if from_journal && from_journal.private_notes?
201 # If the received email was a reply to a private note, make the added note private
201 # If the received email was a reply to a private note, make the added note private
202 issue.private_notes = true
202 issue.private_notes = true
203 end
203 end
204 issue.safe_attributes = issue_attributes_from_keywords(issue)
204 issue.safe_attributes = issue_attributes_from_keywords(issue)
205 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
205 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
206 journal.notes = cleaned_up_text_body
206 journal.notes = cleaned_up_text_body
207 add_attachments(issue)
207 add_attachments(issue)
208 issue.save!
208 issue.save!
209 if logger && logger.info
209 if logger && logger.info
210 logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
210 logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
211 end
211 end
212 journal
212 journal
213 end
213 end
214
214
215 # Reply will be added to the issue
215 # Reply will be added to the issue
216 def receive_journal_reply(journal_id)
216 def receive_journal_reply(journal_id)
217 journal = Journal.find_by_id(journal_id)
217 journal = Journal.find_by_id(journal_id)
218 if journal && journal.journalized_type == 'Issue'
218 if journal && journal.journalized_type == 'Issue'
219 receive_issue_reply(journal.journalized_id, journal)
219 receive_issue_reply(journal.journalized_id, journal)
220 end
220 end
221 end
221 end
222
222
223 # Receives a reply to a forum message
223 # Receives a reply to a forum message
224 def receive_message_reply(message_id)
224 def receive_message_reply(message_id)
225 message = Message.find_by_id(message_id)
225 message = Message.find_by_id(message_id)
226 if message
226 if message
227 message = message.root
227 message = message.root
228
228
229 unless @@handler_options[:no_permission_check]
229 unless @@handler_options[:no_permission_check]
230 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
230 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
231 end
231 end
232
232
233 if !message.locked?
233 if !message.locked?
234 reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
234 reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
235 :content => cleaned_up_text_body)
235 :content => cleaned_up_text_body)
236 reply.author = user
236 reply.author = user
237 reply.board = message.board
237 reply.board = message.board
238 message.children << reply
238 message.children << reply
239 add_attachments(reply)
239 add_attachments(reply)
240 reply
240 reply
241 else
241 else
242 if logger && logger.info
242 if logger && logger.info
243 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
243 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
244 end
244 end
245 end
245 end
246 end
246 end
247 end
247 end
248
248
249 def add_attachments(obj)
249 def add_attachments(obj)
250 if email.attachments && email.attachments.any?
250 if email.attachments && email.attachments.any?
251 email.attachments.each do |attachment|
251 email.attachments.each do |attachment|
252 filename = attachment.filename
253 unless filename.respond_to?(:encoding)
254 # try to reencode to utf8 manually with ruby1.8
255 h = attachment.header['Content-Disposition']
256 unless h.nil?
257 begin
258 if m = h.value.match(/filename\*[0-9\*]*=([^=']+)'/)
259 filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
260 elsif m = h.value.match(/filename=.*=\?([^\?]+)\?[BbQq]\?/)
261 # http://tools.ietf.org/html/rfc2047#section-4
262 filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
263 end
264 rescue
265 # nop
266 end
267 end
268 end
269 obj.attachments << Attachment.create(:container => obj,
252 obj.attachments << Attachment.create(:container => obj,
270 :file => attachment.decoded,
253 :file => attachment.decoded,
271 :filename => filename,
254 :filename => attachment.filename,
272 :author => user,
255 :author => user,
273 :content_type => attachment.mime_type)
256 :content_type => attachment.mime_type)
274 end
257 end
275 end
258 end
276 end
259 end
277
260
278 # Adds To and Cc as watchers of the given object if the sender has the
261 # Adds To and Cc as watchers of the given object if the sender has the
279 # appropriate permission
262 # appropriate permission
280 def add_watchers(obj)
263 def add_watchers(obj)
281 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
264 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
282 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
265 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
283 unless addresses.empty?
266 unless addresses.empty?
284 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
267 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
285 watchers.each {|w| obj.add_watcher(w)}
268 watchers.each {|w| obj.add_watcher(w)}
286 end
269 end
287 end
270 end
288 end
271 end
289
272
290 def get_keyword(attr, options={})
273 def get_keyword(attr, options={})
291 @keywords ||= {}
274 @keywords ||= {}
292 if @keywords.has_key?(attr)
275 if @keywords.has_key?(attr)
293 @keywords[attr]
276 @keywords[attr]
294 else
277 else
295 @keywords[attr] = begin
278 @keywords[attr] = begin
296 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
279 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
297 (v = extract_keyword!(plain_text_body, attr, options[:format]))
280 (v = extract_keyword!(plain_text_body, attr, options[:format]))
298 v
281 v
299 elsif !@@handler_options[:issue][attr].blank?
282 elsif !@@handler_options[:issue][attr].blank?
300 @@handler_options[:issue][attr]
283 @@handler_options[:issue][attr]
301 end
284 end
302 end
285 end
303 end
286 end
304 end
287 end
305
288
306 # Destructively extracts the value for +attr+ in +text+
289 # Destructively extracts the value for +attr+ in +text+
307 # Returns nil if no matching keyword found
290 # Returns nil if no matching keyword found
308 def extract_keyword!(text, attr, format=nil)
291 def extract_keyword!(text, attr, format=nil)
309 keys = [attr.to_s.humanize]
292 keys = [attr.to_s.humanize]
310 if attr.is_a?(Symbol)
293 if attr.is_a?(Symbol)
311 if user && user.language.present?
294 if user && user.language.present?
312 keys << l("field_#{attr}", :default => '', :locale => user.language)
295 keys << l("field_#{attr}", :default => '', :locale => user.language)
313 end
296 end
314 if Setting.default_language.present?
297 if Setting.default_language.present?
315 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
298 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
316 end
299 end
317 end
300 end
318 keys.reject! {|k| k.blank?}
301 keys.reject! {|k| k.blank?}
319 keys.collect! {|k| Regexp.escape(k)}
302 keys.collect! {|k| Regexp.escape(k)}
320 format ||= '.+'
303 format ||= '.+'
321 keyword = nil
304 keyword = nil
322 regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
305 regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
323 if m = text.match(regexp)
306 if m = text.match(regexp)
324 keyword = m[2].strip
307 keyword = m[2].strip
325 text.gsub!(regexp, '')
308 text.gsub!(regexp, '')
326 end
309 end
327 keyword
310 keyword
328 end
311 end
329
312
330 def target_project
313 def target_project
331 # TODO: other ways to specify project:
314 # TODO: other ways to specify project:
332 # * parse the email To field
315 # * parse the email To field
333 # * specific project (eg. Setting.mail_handler_target_project)
316 # * specific project (eg. Setting.mail_handler_target_project)
334 target = Project.find_by_identifier(get_keyword(:project))
317 target = Project.find_by_identifier(get_keyword(:project))
335 raise MissingInformation.new('Unable to determine target project') if target.nil?
318 raise MissingInformation.new('Unable to determine target project') if target.nil?
336 target
319 target
337 end
320 end
338
321
339 # Returns a Hash of issue attributes extracted from keywords in the email body
322 # Returns a Hash of issue attributes extracted from keywords in the email body
340 def issue_attributes_from_keywords(issue)
323 def issue_attributes_from_keywords(issue)
341 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
324 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
342
325
343 attrs = {
326 attrs = {
344 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
327 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
345 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
328 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
346 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
329 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
347 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
330 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
348 'assigned_to_id' => assigned_to.try(:id),
331 'assigned_to_id' => assigned_to.try(:id),
349 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
332 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
350 issue.project.shared_versions.named(k).first.try(:id),
333 issue.project.shared_versions.named(k).first.try(:id),
351 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
334 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
352 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
335 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
353 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
336 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
354 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
337 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
355 }.delete_if {|k, v| v.blank? }
338 }.delete_if {|k, v| v.blank? }
356
339
357 if issue.new_record? && attrs['tracker_id'].nil?
340 if issue.new_record? && attrs['tracker_id'].nil?
358 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
341 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
359 end
342 end
360
343
361 attrs
344 attrs
362 end
345 end
363
346
364 # Returns a Hash of issue custom field values extracted from keywords in the email body
347 # Returns a Hash of issue custom field values extracted from keywords in the email body
365 def custom_field_values_from_keywords(customized)
348 def custom_field_values_from_keywords(customized)
366 customized.custom_field_values.inject({}) do |h, v|
349 customized.custom_field_values.inject({}) do |h, v|
367 if keyword = get_keyword(v.custom_field.name, :override => true)
350 if keyword = get_keyword(v.custom_field.name, :override => true)
368 h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
351 h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
369 end
352 end
370 h
353 h
371 end
354 end
372 end
355 end
373
356
374 # Returns the text/plain part of the email
357 # Returns the text/plain part of the email
375 # If not found (eg. HTML-only email), returns the body with tags removed
358 # If not found (eg. HTML-only email), returns the body with tags removed
376 def plain_text_body
359 def plain_text_body
377 return @plain_text_body unless @plain_text_body.nil?
360 return @plain_text_body unless @plain_text_body.nil?
378
361
379 part = email.text_part || email.html_part || email
362 part = email.text_part || email.html_part || email
380 @plain_text_body = Redmine::CodesetUtil.to_utf8(part.body.decoded, part.charset)
363 @plain_text_body = Redmine::CodesetUtil.to_utf8(part.body.decoded, part.charset)
381
364
382 # strip html tags and remove doctype directive
365 # strip html tags and remove doctype directive
383 @plain_text_body = strip_tags(@plain_text_body.strip)
366 @plain_text_body = strip_tags(@plain_text_body.strip)
384 @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
367 @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
385 @plain_text_body
368 @plain_text_body
386 end
369 end
387
370
388 def cleaned_up_text_body
371 def cleaned_up_text_body
389 cleanup_body(plain_text_body)
372 cleanup_body(plain_text_body)
390 end
373 end
391
374
392 def cleaned_up_subject
375 def cleaned_up_subject
393 subject = email.subject.to_s
376 subject = email.subject.to_s
394 unless subject.respond_to?(:encoding)
395 # try to reencode to utf8 manually with ruby1.8
396 begin
397 if h = email.header[:subject]
398 # http://tools.ietf.org/html/rfc2047#section-4
399 if m = h.value.match(/=\?([^\?]+)\?[BbQq]\?/)
400 subject = Redmine::CodesetUtil.to_utf8(subject, m[1])
401 end
402 end
403 rescue
404 # nop
405 end
406 end
407 subject.strip[0,255]
377 subject.strip[0,255]
408 end
378 end
409
379
410 def self.full_sanitizer
380 def self.full_sanitizer
411 @full_sanitizer ||= HTML::FullSanitizer.new
381 @full_sanitizer ||= HTML::FullSanitizer.new
412 end
382 end
413
383
414 def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
384 def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
415 limit ||= object.class.columns_hash[attribute.to_s].limit || 255
385 limit ||= object.class.columns_hash[attribute.to_s].limit || 255
416 value = value.to_s.slice(0, limit)
386 value = value.to_s.slice(0, limit)
417 object.send("#{attribute}=", value)
387 object.send("#{attribute}=", value)
418 end
388 end
419
389
420 # Returns a User from an email address and a full name
390 # Returns a User from an email address and a full name
421 def self.new_user_from_attributes(email_address, fullname=nil)
391 def self.new_user_from_attributes(email_address, fullname=nil)
422 user = User.new
392 user = User.new
423
393
424 # Truncating the email address would result in an invalid format
394 # Truncating the email address would result in an invalid format
425 user.mail = email_address
395 user.mail = email_address
426 assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
396 assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
427
397
428 names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
398 names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
429 assign_string_attribute_with_limit(user, 'firstname', names.shift)
399 assign_string_attribute_with_limit(user, 'firstname', names.shift)
430 assign_string_attribute_with_limit(user, 'lastname', names.join(' '))
400 assign_string_attribute_with_limit(user, 'lastname', names.join(' '))
431 user.lastname = '-' if user.lastname.blank?
401 user.lastname = '-' if user.lastname.blank?
432
402
433 password_length = [Setting.password_min_length.to_i, 10].max
403 password_length = [Setting.password_min_length.to_i, 10].max
434 user.password = Redmine::Utils.random_hex(password_length / 2 + 1)
404 user.password = Redmine::Utils.random_hex(password_length / 2 + 1)
435 user.language = Setting.default_language
405 user.language = Setting.default_language
436
406
437 unless user.valid?
407 unless user.valid?
438 user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
408 user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
439 user.firstname = "-" unless user.errors[:firstname].blank?
409 user.firstname = "-" unless user.errors[:firstname].blank?
440 user.lastname = "-" unless user.errors[:lastname].blank?
410 user.lastname = "-" unless user.errors[:lastname].blank?
441 end
411 end
442
412
443 user
413 user
444 end
414 end
445
415
446 # Creates a User for the +email+ sender
416 # Creates a User for the +email+ sender
447 # Returns the user or nil if it could not be created
417 # Returns the user or nil if it could not be created
448 def create_user_from_email
418 def create_user_from_email
449 from = email.header['from'].to_s
419 from = email.header['from'].to_s
450 addr, name = from, nil
420 addr, name = from, nil
451 if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
421 if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
452 addr, name = m[2], m[1]
422 addr, name = m[2], m[1]
453 end
423 end
454 if addr.present?
424 if addr.present?
455 user = self.class.new_user_from_attributes(addr, name)
425 user = self.class.new_user_from_attributes(addr, name)
456 if user.save
426 if user.save
457 user
427 user
458 else
428 else
459 logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
429 logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
460 nil
430 nil
461 end
431 end
462 else
432 else
463 logger.error "MailHandler: failed to create User: no FROM address found" if logger
433 logger.error "MailHandler: failed to create User: no FROM address found" if logger
464 nil
434 nil
465 end
435 end
466 end
436 end
467
437
468 # Removes the email body of text after the truncation configurations.
438 # Removes the email body of text after the truncation configurations.
469 def cleanup_body(body)
439 def cleanup_body(body)
470 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
440 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
471 unless delimiters.empty?
441 unless delimiters.empty?
472 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
442 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
473 body = body.gsub(regex, '')
443 body = body.gsub(regex, '')
474 end
444 end
475 body.strip
445 body.strip
476 end
446 end
477
447
478 def find_assignee_from_keyword(keyword, issue)
448 def find_assignee_from_keyword(keyword, issue)
479 keyword = keyword.to_s.downcase
449 keyword = keyword.to_s.downcase
480 assignable = issue.assignable_users
450 assignable = issue.assignable_users
481 assignee = nil
451 assignee = nil
482 assignee ||= assignable.detect {|a|
452 assignee ||= assignable.detect {|a|
483 a.mail.to_s.downcase == keyword ||
453 a.mail.to_s.downcase == keyword ||
484 a.login.to_s.downcase == keyword
454 a.login.to_s.downcase == keyword
485 }
455 }
486 if assignee.nil? && keyword.match(/ /)
456 if assignee.nil? && keyword.match(/ /)
487 firstname, lastname = *(keyword.split) # "First Last Throwaway"
457 firstname, lastname = *(keyword.split) # "First Last Throwaway"
488 assignee ||= assignable.detect {|a|
458 assignee ||= assignable.detect {|a|
489 a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
459 a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
490 a.lastname.to_s.downcase == lastname
460 a.lastname.to_s.downcase == lastname
491 }
461 }
492 end
462 end
493 if assignee.nil?
463 if assignee.nil?
494 assignee ||= assignable.detect {|a| a.name.downcase == keyword}
464 assignee ||= assignable.detect {|a| a.name.downcase == keyword}
495 end
465 end
496 assignee
466 assignee
497 end
467 end
498 end
468 end
General Comments 0
You need to be logged in to leave comments. Login now