You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mail_handler.rb 16KB

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