PageRenderTime 54ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/app/models/mail_handler.rb

https://bitbucket.org/eimajenthat/redmine
Ruby | 498 lines | 389 code | 51 blank | 58 comment | 83 complexity | 5fececdc9ca314e15b5b9a9825a8e1ef MD5 | raw file
Possible License(s): GPL-2.0
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2013 Jean-Philippe Lang
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  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
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. class MailHandler < ActionMailer::Base
  18. include ActionView::Helpers::SanitizeHelper
  19. include Redmine::I18n
  20. class UnauthorizedAction < StandardError; end
  21. class MissingInformation < StandardError; end
  22. attr_reader :email, :user
  23. def self.receive(email, options={})
  24. @@handler_options = options.dup
  25. @@handler_options[:issue] ||= {}
  26. if @@handler_options[:allow_override].is_a?(String)
  27. @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip)
  28. end
  29. @@handler_options[:allow_override] ||= []
  30. # Project needs to be overridable if not specified
  31. @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
  32. # Status overridable by default
  33. @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
  34. @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false)
  35. email.force_encoding('ASCII-8BIT') if email.respond_to?(:force_encoding)
  36. super(email)
  37. end
  38. def logger
  39. Rails.logger
  40. end
  41. cattr_accessor :ignored_emails_headers
  42. @@ignored_emails_headers = {
  43. 'X-Auto-Response-Suppress' => 'oof',
  44. 'Auto-Submitted' => /^auto-/
  45. }
  46. # Processes incoming emails
  47. # Returns the created object (eg. an issue, a message) or false
  48. def receive(email)
  49. @email = email
  50. sender_email = email.from.to_a.first.to_s.strip
  51. # Ignore emails received from the application emission address to avoid hell cycles
  52. if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
  53. if logger && logger.info
  54. logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
  55. end
  56. return false
  57. end
  58. # Ignore auto generated emails
  59. self.class.ignored_emails_headers.each do |key, ignored_value|
  60. value = email.header[key]
  61. if value
  62. value = value.to_s.downcase
  63. if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
  64. if logger && logger.info
  65. logger.info "MailHandler: ignoring email with #{key}:#{value} header"
  66. end
  67. return false
  68. end
  69. end
  70. end
  71. @user = User.find_by_mail(sender_email) if sender_email.present?
  72. if @user && !@user.active?
  73. if logger && logger.info
  74. logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]"
  75. end
  76. return false
  77. end
  78. if @user.nil?
  79. # Email was submitted by an unknown user
  80. case @@handler_options[:unknown_user]
  81. when 'accept'
  82. @user = User.anonymous
  83. when 'create'
  84. @user = create_user_from_email
  85. if @user
  86. if logger && logger.info
  87. logger.info "MailHandler: [#{@user.login}] account created"
  88. end
  89. Mailer.account_information(@user, @user.password).deliver
  90. else
  91. if logger && logger.error
  92. logger.error "MailHandler: could not create account for [#{sender_email}]"
  93. end
  94. return false
  95. end
  96. else
  97. # Default behaviour, emails from unknown users are ignored
  98. if logger && logger.info
  99. logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]"
  100. end
  101. return false
  102. end
  103. end
  104. User.current = @user
  105. dispatch
  106. end
  107. private
  108. MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
  109. ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
  110. MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
  111. def dispatch
  112. headers = [email.in_reply_to, email.references].flatten.compact
  113. subject = email.subject.to_s
  114. if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
  115. klass, object_id = $1, $2.to_i
  116. method_name = "receive_#{klass}_reply"
  117. if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
  118. send method_name, object_id
  119. else
  120. # ignoring it
  121. end
  122. elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
  123. receive_issue_reply(m[1].to_i)
  124. elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
  125. receive_message_reply(m[1].to_i)
  126. else
  127. dispatch_to_default
  128. end
  129. rescue ActiveRecord::RecordInvalid => e
  130. # TODO: send a email to the user
  131. logger.error e.message if logger
  132. false
  133. rescue MissingInformation => e
  134. logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
  135. false
  136. rescue UnauthorizedAction => e
  137. logger.error "MailHandler: unauthorized attempt from #{user}" if logger
  138. false
  139. end
  140. def dispatch_to_default
  141. receive_issue
  142. end
  143. # Creates a new issue
  144. def receive_issue
  145. project = target_project
  146. # check permission
  147. unless @@handler_options[:no_permission_check]
  148. raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
  149. end
  150. issue = Issue.new(:author => user, :project => project)
  151. issue.safe_attributes = issue_attributes_from_keywords(issue)
  152. issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
  153. issue.subject = cleaned_up_subject
  154. if issue.subject.blank?
  155. issue.subject = '(no subject)'
  156. end
  157. issue.description = cleaned_up_text_body
  158. # add To and Cc as watchers before saving so the watchers can reply to Redmine
  159. add_watchers(issue)
  160. issue.save!
  161. add_attachments(issue)
  162. logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
  163. issue
  164. end
  165. # Adds a note to an existing issue
  166. def receive_issue_reply(issue_id, from_journal=nil)
  167. issue = Issue.find_by_id(issue_id)
  168. return unless issue
  169. # check permission
  170. unless @@handler_options[:no_permission_check]
  171. unless user.allowed_to?(:add_issue_notes, issue.project) ||
  172. user.allowed_to?(:edit_issues, issue.project)
  173. raise UnauthorizedAction
  174. end
  175. end
  176. # ignore CLI-supplied defaults for new issues
  177. @@handler_options[:issue].clear
  178. journal = issue.init_journal(user)
  179. if from_journal && from_journal.private_notes?
  180. # If the received email was a reply to a private note, make the added note private
  181. issue.private_notes = true
  182. end
  183. issue.safe_attributes = issue_attributes_from_keywords(issue)
  184. issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
  185. journal.notes = cleaned_up_text_body
  186. add_attachments(issue)
  187. issue.save!
  188. if logger && logger.info
  189. logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
  190. end
  191. journal
  192. end
  193. # Reply will be added to the issue
  194. def receive_journal_reply(journal_id)
  195. journal = Journal.find_by_id(journal_id)
  196. if journal && journal.journalized_type == 'Issue'
  197. receive_issue_reply(journal.journalized_id, journal)
  198. end
  199. end
  200. # Receives a reply to a forum message
  201. def receive_message_reply(message_id)
  202. message = Message.find_by_id(message_id)
  203. if message
  204. message = message.root
  205. unless @@handler_options[:no_permission_check]
  206. raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
  207. end
  208. if !message.locked?
  209. reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
  210. :content => cleaned_up_text_body)
  211. reply.author = user
  212. reply.board = message.board
  213. message.children << reply
  214. add_attachments(reply)
  215. reply
  216. else
  217. if logger && logger.info
  218. logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
  219. end
  220. end
  221. end
  222. end
  223. def add_attachments(obj)
  224. if email.attachments && email.attachments.any?
  225. email.attachments.each do |attachment|
  226. filename = attachment.filename
  227. unless filename.respond_to?(:encoding)
  228. # try to reencode to utf8 manually with ruby1.8
  229. h = attachment.header['Content-Disposition']
  230. unless h.nil?
  231. begin
  232. if m = h.value.match(/filename\*[0-9\*]*=([^=']+)'/)
  233. filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
  234. elsif m = h.value.match(/filename=.*=\?([^\?]+)\?[BbQq]\?/)
  235. # http://tools.ietf.org/html/rfc2047#section-4
  236. filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
  237. end
  238. rescue
  239. # nop
  240. end
  241. end
  242. end
  243. obj.attachments << Attachment.create(:container => obj,
  244. :file => attachment.decoded,
  245. :filename => filename,
  246. :author => user,
  247. :content_type => attachment.mime_type)
  248. end
  249. end
  250. end
  251. # Adds To and Cc as watchers of the given object if the sender has the
  252. # appropriate permission
  253. def add_watchers(obj)
  254. if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
  255. addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
  256. unless addresses.empty?
  257. watchers = User.active.where('LOWER(mail) IN (?)', addresses).all
  258. watchers.each {|w| obj.add_watcher(w)}
  259. end
  260. end
  261. end
  262. def get_keyword(attr, options={})
  263. @keywords ||= {}
  264. if @keywords.has_key?(attr)
  265. @keywords[attr]
  266. else
  267. @keywords[attr] = begin
  268. if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
  269. (v = extract_keyword!(plain_text_body, attr, options[:format]))
  270. v
  271. elsif !@@handler_options[:issue][attr].blank?
  272. @@handler_options[:issue][attr]
  273. end
  274. end
  275. end
  276. end
  277. # Destructively extracts the value for +attr+ in +text+
  278. # Returns nil if no matching keyword found
  279. def extract_keyword!(text, attr, format=nil)
  280. keys = [attr.to_s.humanize]
  281. if attr.is_a?(Symbol)
  282. if user && user.language.present?
  283. keys << l("field_#{attr}", :default => '', :locale => user.language)
  284. end
  285. if Setting.default_language.present?
  286. keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
  287. end
  288. end
  289. keys.reject! {|k| k.blank?}
  290. keys.collect! {|k| Regexp.escape(k)}
  291. format ||= '.+'
  292. keyword = nil
  293. regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
  294. if m = text.match(regexp)
  295. keyword = m[2].strip
  296. text.gsub!(regexp, '')
  297. end
  298. keyword
  299. end
  300. def target_project
  301. # TODO: other ways to specify project:
  302. # * parse the email To field
  303. # * specific project (eg. Setting.mail_handler_target_project)
  304. target = Project.find_by_identifier(get_keyword(:project))
  305. raise MissingInformation.new('Unable to determine target project') if target.nil?
  306. target
  307. end
  308. # Returns a Hash of issue attributes extracted from keywords in the email body
  309. def issue_attributes_from_keywords(issue)
  310. assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
  311. attrs = {
  312. 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
  313. 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
  314. 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
  315. 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
  316. 'assigned_to_id' => assigned_to.try(:id),
  317. 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
  318. issue.project.shared_versions.named(k).first.try(:id),
  319. 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
  320. 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
  321. 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
  322. 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
  323. }.delete_if {|k, v| v.blank? }
  324. if issue.new_record? && attrs['tracker_id'].nil?
  325. attrs['tracker_id'] = issue.project.trackers.first.try(:id)
  326. end
  327. attrs
  328. end
  329. # Returns a Hash of issue custom field values extracted from keywords in the email body
  330. def custom_field_values_from_keywords(customized)
  331. customized.custom_field_values.inject({}) do |h, v|
  332. if keyword = get_keyword(v.custom_field.name, :override => true)
  333. h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
  334. end
  335. h
  336. end
  337. end
  338. # Returns the text/plain part of the email
  339. # If not found (eg. HTML-only email), returns the body with tags removed
  340. def plain_text_body
  341. return @plain_text_body unless @plain_text_body.nil?
  342. part = email.text_part || email.html_part || email
  343. @plain_text_body = Redmine::CodesetUtil.to_utf8(part.body.decoded, part.charset)
  344. # strip html tags and remove doctype directive
  345. @plain_text_body = strip_tags(@plain_text_body.strip)
  346. @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
  347. @plain_text_body
  348. end
  349. def cleaned_up_text_body
  350. cleanup_body(plain_text_body)
  351. end
  352. def cleaned_up_subject
  353. subject = email.subject.to_s
  354. unless subject.respond_to?(:encoding)
  355. # try to reencode to utf8 manually with ruby1.8
  356. begin
  357. if h = email.header[:subject]
  358. # http://tools.ietf.org/html/rfc2047#section-4
  359. if m = h.value.match(/=\?([^\?]+)\?[BbQq]\?/)
  360. subject = Redmine::CodesetUtil.to_utf8(subject, m[1])
  361. end
  362. end
  363. rescue
  364. # nop
  365. end
  366. end
  367. subject.strip[0,255]
  368. end
  369. def self.full_sanitizer
  370. @full_sanitizer ||= HTML::FullSanitizer.new
  371. end
  372. def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
  373. limit ||= object.class.columns_hash[attribute.to_s].limit || 255
  374. value = value.to_s.slice(0, limit)
  375. object.send("#{attribute}=", value)
  376. end
  377. # Returns a User from an email address and a full name
  378. def self.new_user_from_attributes(email_address, fullname=nil)
  379. user = User.new
  380. # Truncating the email address would result in an invalid format
  381. user.mail = email_address
  382. assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
  383. names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
  384. assign_string_attribute_with_limit(user, 'firstname', names.shift)
  385. assign_string_attribute_with_limit(user, 'lastname', names.join(' '))
  386. user.lastname = '-' if user.lastname.blank?
  387. password_length = [Setting.password_min_length.to_i, 10].max
  388. user.password = Redmine::Utils.random_hex(password_length / 2 + 1)
  389. user.language = Setting.default_language
  390. unless user.valid?
  391. user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
  392. user.firstname = "-" unless user.errors[:firstname].blank?
  393. user.lastname = "-" unless user.errors[:lastname].blank?
  394. end
  395. user
  396. end
  397. # Creates a User for the +email+ sender
  398. # Returns the user or nil if it could not be created
  399. def create_user_from_email
  400. from = email.header['from'].to_s
  401. addr, name = from, nil
  402. if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
  403. addr, name = m[2], m[1]
  404. end
  405. if addr.present?
  406. user = self.class.new_user_from_attributes(addr, name)
  407. if user.save
  408. user
  409. else
  410. logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
  411. nil
  412. end
  413. else
  414. logger.error "MailHandler: failed to create User: no FROM address found" if logger
  415. nil
  416. end
  417. end
  418. # Removes the email body of text after the truncation configurations.
  419. def cleanup_body(body)
  420. delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
  421. unless delimiters.empty?
  422. regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
  423. body = body.gsub(regex, '')
  424. end
  425. body.strip
  426. end
  427. def find_assignee_from_keyword(keyword, issue)
  428. keyword = keyword.to_s.downcase
  429. assignable = issue.assignable_users
  430. assignee = nil
  431. assignee ||= assignable.detect {|a|
  432. a.mail.to_s.downcase == keyword ||
  433. a.login.to_s.downcase == keyword
  434. }
  435. if assignee.nil? && keyword.match(/ /)
  436. firstname, lastname = *(keyword.split) # "First Last Throwaway"
  437. assignee ||= assignable.detect {|a|
  438. a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
  439. a.lastname.to_s.downcase == lastname
  440. }
  441. end
  442. if assignee.nil?
  443. assignee ||= assignable.detect {|a| a.name.downcase == keyword}
  444. end
  445. assignee
  446. end
  447. end