Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

mail_handler.rb 16KB

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