PageRenderTime 42ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/app/models/mail_handler.rb

https://bitbucket.org/prdixit/redmine
Ruby | 475 lines | 371 code | 51 blank | 53 comment | 80 complexity | 4cf3683f7e23824d5036d583853dd032 MD5 | raw file
Possible License(s): GPL-2.0
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2012 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. if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
  114. klass, object_id = $1, $2.to_i
  115. method_name = "receive_#{klass}_reply"
  116. if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
  117. send method_name, object_id
  118. else
  119. # ignoring it
  120. end
  121. elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
  122. receive_issue_reply(m[1].to_i)
  123. elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
  124. receive_message_reply(m[1].to_i)
  125. else
  126. dispatch_to_default
  127. end
  128. rescue ActiveRecord::RecordInvalid => e
  129. # TODO: send a email to the user
  130. logger.error e.message if logger
  131. false
  132. rescue MissingInformation => e
  133. logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
  134. false
  135. rescue UnauthorizedAction => e
  136. logger.error "MailHandler: unauthorized attempt from #{user}" if logger
  137. false
  138. end
  139. def dispatch_to_default
  140. receive_issue
  141. end
  142. # Creates a new issue
  143. def receive_issue
  144. project = target_project
  145. # check permission
  146. unless @@handler_options[:no_permission_check]
  147. raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
  148. end
  149. issue = Issue.new(:author => user, :project => project)
  150. issue.safe_attributes = issue_attributes_from_keywords(issue)
  151. issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
  152. issue.subject = cleaned_up_subject
  153. if issue.subject.blank?
  154. issue.subject = '(no subject)'
  155. end
  156. issue.description = cleaned_up_text_body
  157. # add To and Cc as watchers before saving so the watchers can reply to Redmine
  158. add_watchers(issue)
  159. issue.save!
  160. add_attachments(issue)
  161. logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
  162. issue
  163. end
  164. # Adds a note to an existing issue
  165. def receive_issue_reply(issue_id)
  166. issue = Issue.find_by_id(issue_id)
  167. return unless issue
  168. # check permission
  169. unless @@handler_options[:no_permission_check]
  170. unless user.allowed_to?(:add_issue_notes, issue.project) ||
  171. user.allowed_to?(:edit_issues, issue.project)
  172. raise UnauthorizedAction
  173. end
  174. end
  175. # ignore CLI-supplied defaults for new issues
  176. @@handler_options[:issue].clear
  177. journal = issue.init_journal(user)
  178. issue.safe_attributes = issue_attributes_from_keywords(issue)
  179. issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
  180. journal.notes = cleaned_up_text_body
  181. add_attachments(issue)
  182. issue.save!
  183. if logger && logger.info
  184. logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
  185. end
  186. journal
  187. end
  188. # Reply will be added to the issue
  189. def receive_journal_reply(journal_id)
  190. journal = Journal.find_by_id(journal_id)
  191. if journal && journal.journalized_type == 'Issue'
  192. receive_issue_reply(journal.journalized_id)
  193. end
  194. end
  195. # Receives a reply to a forum message
  196. def receive_message_reply(message_id)
  197. message = Message.find_by_id(message_id)
  198. if message
  199. message = message.root
  200. unless @@handler_options[:no_permission_check]
  201. raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
  202. end
  203. if !message.locked?
  204. reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
  205. :content => cleaned_up_text_body)
  206. reply.author = user
  207. reply.board = message.board
  208. message.children << reply
  209. add_attachments(reply)
  210. reply
  211. else
  212. if logger && logger.info
  213. logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
  214. end
  215. end
  216. end
  217. end
  218. def add_attachments(obj)
  219. if email.attachments && email.attachments.any?
  220. email.attachments.each do |attachment|
  221. obj.attachments << Attachment.create(:container => obj,
  222. :file => attachment.decoded,
  223. :filename => attachment.filename,
  224. :author => user,
  225. :content_type => attachment.mime_type)
  226. end
  227. end
  228. end
  229. # Adds To and Cc as watchers of the given object if the sender has the
  230. # appropriate permission
  231. def add_watchers(obj)
  232. if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
  233. addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
  234. unless addresses.empty?
  235. watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
  236. watchers.each {|w| obj.add_watcher(w)}
  237. end
  238. end
  239. end
  240. def get_keyword(attr, options={})
  241. @keywords ||= {}
  242. if @keywords.has_key?(attr)
  243. @keywords[attr]
  244. else
  245. @keywords[attr] = begin
  246. if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
  247. (v = extract_keyword!(plain_text_body, attr, options[:format]))
  248. v
  249. elsif !@@handler_options[:issue][attr].blank?
  250. @@handler_options[:issue][attr]
  251. end
  252. end
  253. end
  254. end
  255. # Destructively extracts the value for +attr+ in +text+
  256. # Returns nil if no matching keyword found
  257. def extract_keyword!(text, attr, format=nil)
  258. keys = [attr.to_s.humanize]
  259. if attr.is_a?(Symbol)
  260. if user && user.language.present?
  261. keys << l("field_#{attr}", :default => '', :locale => user.language)
  262. end
  263. if Setting.default_language.present?
  264. keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
  265. end
  266. end
  267. keys.reject! {|k| k.blank?}
  268. keys.collect! {|k| Regexp.escape(k)}
  269. format ||= '.+'
  270. keyword = nil
  271. regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
  272. if m = text.match(regexp)
  273. keyword = m[2].strip
  274. text.gsub!(regexp, '')
  275. end
  276. keyword
  277. end
  278. def target_project
  279. # TODO: other ways to specify project:
  280. # * parse the email To field
  281. # * specific project (eg. Setting.mail_handler_target_project)
  282. target = Project.find_by_identifier(get_keyword(:project))
  283. raise MissingInformation.new('Unable to determine target project') if target.nil?
  284. target
  285. end
  286. # Returns a Hash of issue attributes extracted from keywords in the email body
  287. def issue_attributes_from_keywords(issue)
  288. assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
  289. attrs = {
  290. 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
  291. 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
  292. 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
  293. 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
  294. 'assigned_to_id' => assigned_to.try(:id),
  295. 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
  296. issue.project.shared_versions.named(k).first.try(:id),
  297. 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
  298. 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
  299. 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
  300. 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
  301. }.delete_if {|k, v| v.blank? }
  302. if issue.new_record? && attrs['tracker_id'].nil?
  303. attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
  304. end
  305. attrs
  306. end
  307. # Returns a Hash of issue custom field values extracted from keywords in the email body
  308. def custom_field_values_from_keywords(customized)
  309. customized.custom_field_values.inject({}) do |h, v|
  310. if keyword = get_keyword(v.custom_field.name, :override => true)
  311. h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
  312. end
  313. h
  314. end
  315. end
  316. # Returns the text/plain part of the email
  317. # If not found (eg. HTML-only email), returns the body with tags removed
  318. def plain_text_body
  319. return @plain_text_body unless @plain_text_body.nil?
  320. part = email.text_part || email.html_part || email
  321. @plain_text_body = Redmine::CodesetUtil.to_utf8(part.body.decoded, part.charset)
  322. # strip html tags and remove doctype directive
  323. @plain_text_body = strip_tags(@plain_text_body.strip)
  324. @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
  325. @plain_text_body
  326. end
  327. def cleaned_up_text_body
  328. cleanup_body(plain_text_body)
  329. end
  330. def cleaned_up_subject
  331. subject = email.subject.to_s
  332. unless subject.respond_to?(:encoding)
  333. # try to reencode to utf8 manually with ruby1.8
  334. begin
  335. if h = email.header[:subject]
  336. if m = h.value.match(/^=\?([^\?]+)\?/)
  337. subject = Redmine::CodesetUtil.to_utf8(subject, m[1])
  338. end
  339. end
  340. rescue
  341. # nop
  342. end
  343. end
  344. subject.strip[0,255]
  345. end
  346. def self.full_sanitizer
  347. @full_sanitizer ||= HTML::FullSanitizer.new
  348. end
  349. def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
  350. limit ||= object.class.columns_hash[attribute.to_s].limit || 255
  351. value = value.to_s.slice(0, limit)
  352. object.send("#{attribute}=", value)
  353. end
  354. # Returns a User from an email address and a full name
  355. def self.new_user_from_attributes(email_address, fullname=nil)
  356. user = User.new
  357. # Truncating the email address would result in an invalid format
  358. user.mail = email_address
  359. assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
  360. names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
  361. assign_string_attribute_with_limit(user, 'firstname', names.shift)
  362. assign_string_attribute_with_limit(user, 'lastname', names.join(' '))
  363. user.lastname = '-' if user.lastname.blank?
  364. password_length = [Setting.password_min_length.to_i, 10].max
  365. user.password = Redmine::Utils.random_hex(password_length / 2 + 1)
  366. user.language = Setting.default_language
  367. unless user.valid?
  368. user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
  369. user.firstname = "-" unless user.errors[:firstname].blank?
  370. user.lastname = "-" unless user.errors[:lastname].blank?
  371. end
  372. user
  373. end
  374. # Creates a User for the +email+ sender
  375. # Returns the user or nil if it could not be created
  376. def create_user_from_email
  377. from = email.header['from'].to_s
  378. addr, name = from, nil
  379. if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
  380. addr, name = m[2], m[1]
  381. end
  382. if addr.present?
  383. user = self.class.new_user_from_attributes(addr, name)
  384. if user.save
  385. user
  386. else
  387. logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
  388. nil
  389. end
  390. else
  391. logger.error "MailHandler: failed to create User: no FROM address found" if logger
  392. nil
  393. end
  394. end
  395. # Removes the email body of text after the truncation configurations.
  396. def cleanup_body(body)
  397. delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
  398. unless delimiters.empty?
  399. regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
  400. body = body.gsub(regex, '')
  401. end
  402. body.strip
  403. end
  404. def find_assignee_from_keyword(keyword, issue)
  405. keyword = keyword.to_s.downcase
  406. assignable = issue.assignable_users
  407. assignee = nil
  408. assignee ||= assignable.detect {|a|
  409. a.mail.to_s.downcase == keyword ||
  410. a.login.to_s.downcase == keyword
  411. }
  412. if assignee.nil? && keyword.match(/ /)
  413. firstname, lastname = *(keyword.split) # "First Last Throwaway"
  414. assignee ||= assignable.detect {|a|
  415. a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
  416. a.lastname.to_s.downcase == lastname
  417. }
  418. end
  419. if assignee.nil?
  420. assignee ||= assignable.detect {|a| a.name.downcase == keyword}
  421. end
  422. assignee
  423. end
  424. end