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 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006- Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. class MailHandler < ActionMailer::Base
  19. include ActionView::Helpers::SanitizeHelper
  20. include Redmine::I18n
  21. class UnauthorizedAction < StandardError; end
  22. class NotAllowedInProject < UnauthorizedAction; end
  23. class InsufficientPermissions < UnauthorizedAction; end
  24. class LockedTopic < UnauthorizedAction; end
  25. class MissingInformation < StandardError; end
  26. class MissingContainer < StandardError; end
  27. attr_reader :email, :user, :handler_options
  28. def self.receive(raw_mail, options={})
  29. options = options.deep_dup
  30. options[:issue] ||= {}
  31. options[:allow_override] ||= []
  32. if options[:allow_override].is_a?(String)
  33. options[:allow_override] = options[:allow_override].split(',')
  34. end
  35. options[:allow_override].map! {|s| s.strip.downcase.gsub(/\s+/, '_')}
  36. # Project needs to be overridable if not specified
  37. options[:allow_override] << 'project' unless options[:issue].has_key?(:project)
  38. options[:no_account_notice] = (options[:no_account_notice].to_s == '1')
  39. options[:no_notification] = (options[:no_notification].to_s == '1')
  40. options[:no_permission_check] = (options[:no_permission_check].to_s == '1')
  41. ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
  42. mail = Mail.new(raw_mail.b)
  43. set_payload_for_mail(payload, mail)
  44. new.receive(mail, options)
  45. end
  46. end
  47. # Receives an email and rescues any exception
  48. def self.safe_receive(*args)
  49. receive(*args)
  50. rescue => e
  51. Rails.logger.error "MailHandler: an unexpected error occurred when receiving email: #{e.message}"
  52. return false
  53. end
  54. # Extracts MailHandler options from environment variables
  55. # Use when receiving emails with rake tasks
  56. def self.extract_options_from_env(env)
  57. options = {:issue => {}}
  58. %w(project status tracker category priority assigned_to fixed_version).each do |option|
  59. options[:issue][option.to_sym] = env[option] if env[option]
  60. end
  61. %w(allow_override unknown_user no_permission_check no_account_notice no_notification default_group project_from_subaddress).each do |option|
  62. options[option.to_sym] = env[option] if env[option]
  63. end
  64. if env['private']
  65. options[:issue][:is_private] = '1'
  66. end
  67. options
  68. end
  69. def logger
  70. Rails.logger
  71. end
  72. cattr_accessor :ignored_emails_headers
  73. self.ignored_emails_headers = {
  74. 'Auto-Submitted' => /\Aauto-(replied|generated)/,
  75. 'X-Autoreply' => 'yes'
  76. }
  77. # Processes incoming emails
  78. # Returns the created object (eg. an issue, a message) or false
  79. def receive(email, options={})
  80. @email = email
  81. @handler_options = options
  82. sender_email = email.from.to_a.first.to_s.strip
  83. # Ignore emails received from the application emission address to avoid hell cycles
  84. emission_address = Setting.mail_from.to_s.gsub(/(?:.*<|>.*|\(.*\))/, '').strip
  85. if sender_email.casecmp(emission_address) == 0
  86. logger&.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
  87. return false
  88. end
  89. # Ignore auto generated emails
  90. self.class.ignored_emails_headers.each do |key, ignored_value|
  91. value = email.header[key]
  92. if value
  93. value = value.to_s.downcase
  94. if (ignored_value.is_a?(Regexp) && ignored_value.match?(value)) || value == ignored_value
  95. logger&.info "MailHandler: ignoring email with #{key}:#{value} header"
  96. return false
  97. end
  98. end
  99. end
  100. @user = User.find_by_mail(sender_email) if sender_email.present?
  101. if @user && !@user.active?
  102. logger&.info "MailHandler: ignoring email from non-active user [#{@user.login}]"
  103. return false
  104. end
  105. if @user.nil?
  106. # Email was submitted by an unknown user
  107. case handler_options[:unknown_user]
  108. when 'accept'
  109. @user = User.anonymous
  110. when 'create'
  111. @user = create_user_from_email
  112. if @user
  113. logger&.info "MailHandler: [#{@user.login}] account created"
  114. add_user_to_group(handler_options[:default_group])
  115. unless handler_options[:no_account_notice]
  116. ::Mailer.deliver_account_information(@user, @user.password)
  117. end
  118. else
  119. logger&.error "MailHandler: could not create account for [#{sender_email}]"
  120. return false
  121. end
  122. else
  123. # Default behaviour, emails from unknown users are ignored
  124. logger&.info "MailHandler: ignoring email from unknown user [#{sender_email}]"
  125. return false
  126. end
  127. end
  128. User.current = @user
  129. dispatch
  130. end
  131. private
  132. MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+(\.[a-f0-9]+)?@}
  133. ISSUE_REPLY_SUBJECT_RE = %r{\[(?:[^\]]*\s+)?#(\d+)\]}
  134. MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
  135. def dispatch
  136. headers = [email.in_reply_to, email.references].flatten.compact
  137. subject = email.subject.to_s
  138. if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
  139. klass, object_id = $1, $2.to_i
  140. method_name = "receive_#{klass}_reply"
  141. if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
  142. send method_name, object_id
  143. else
  144. # ignoring it
  145. end
  146. elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
  147. receive_issue_reply(m[1].to_i)
  148. elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
  149. receive_message_reply(m[1].to_i)
  150. else
  151. dispatch_to_default
  152. end
  153. rescue ActiveRecord::RecordInvalid => e
  154. # TODO: send a email to the user
  155. logger&.error "MailHandler: #{e.message}"
  156. false
  157. rescue MissingInformation => e
  158. logger&.error "MailHandler: missing information from #{user}: #{e.message}"
  159. false
  160. rescue MissingContainer => e
  161. logger&.error "MailHandler: reply to nonexistant object from #{user}: #{e.message}"
  162. false
  163. rescue UnauthorizedAction => e
  164. logger&.error "MailHandler: unauthorized attempt from #{user}: #{e.message}"
  165. false
  166. end
  167. def dispatch_to_default
  168. receive_issue
  169. end
  170. # Creates a new issue
  171. def receive_issue
  172. project = target_project
  173. # Never receive emails to projects where adding issues is not possible
  174. raise NotAllowedInProject, "not possible to add issues to project [#{project.name}]" unless project.allows_to?(:add_issues)
  175. # check permission
  176. unless handler_options[:no_permission_check]
  177. raise InsufficientPermissions, "not allowed to add issues to project [#{project.name}]" unless user.allowed_to?(:add_issues, project)
  178. end
  179. issue = Issue.new(:author => user, :project => project)
  180. attributes = issue_attributes_from_keywords(issue)
  181. if handler_options[:no_permission_check]
  182. issue.tracker_id = attributes['tracker_id']
  183. if project
  184. issue.tracker_id ||= project.trackers.first.try(:id)
  185. end
  186. end
  187. issue.safe_attributes = attributes
  188. issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
  189. issue.subject = cleaned_up_subject
  190. if issue.subject.blank?
  191. issue.subject = "(#{ll(Setting.default_language, :text_no_subject)})"
  192. end
  193. issue.description = cleaned_up_text_body
  194. issue.start_date ||= User.current.today if Setting.default_issue_start_date_to_creation_date?
  195. if handler_options[:issue][:is_private] == '1'
  196. issue.is_private = true
  197. end
  198. # add To and Cc as watchers before saving so the watchers can reply to Redmine
  199. add_watchers(issue)
  200. issue.save!
  201. add_attachments(issue)
  202. logger&.info "MailHandler: issue ##{issue.id} created by #{user}"
  203. issue
  204. end
  205. # Adds a note to an existing issue
  206. def receive_issue_reply(issue_id, from_journal=nil)
  207. issue = Issue.find_by(:id => issue_id)
  208. if issue.nil?
  209. raise MissingContainer, "reply to nonexistant issue [##{issue_id}]"
  210. end
  211. # Never receive emails to projects where adding issue notes is not possible
  212. project = issue.project
  213. raise NotAllowedInProject, "not possible to add notes to project [#{project.name}]" unless project.allows_to?(:add_issue_notes)
  214. # check permission
  215. unless handler_options[:no_permission_check]
  216. unless issue.notes_addable?
  217. raise InsufficientPermissions, "not allowed to add notes on issues to project [#{issue.project.name}]"
  218. end
  219. end
  220. # ignore CLI-supplied defaults for new issues
  221. handler_options[:issue] = {}
  222. journal = issue.init_journal(user)
  223. if from_journal && from_journal.private_notes?
  224. # If the received email was a reply to a private note, make the added note private
  225. issue.private_notes = true
  226. end
  227. issue.safe_attributes = issue_attributes_from_keywords(issue)
  228. issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
  229. journal.notes = cleaned_up_text_body
  230. # add To and Cc as watchers before saving so the watchers can reply to Redmine
  231. add_watchers(issue)
  232. issue.save!
  233. add_attachments(issue)
  234. logger&.info "MailHandler: issue ##{issue.id} updated by #{user}"
  235. journal
  236. end
  237. # Reply will be added to the issue
  238. def receive_journal_reply(journal_id)
  239. journal = Journal.find_by(:id => journal_id)
  240. if journal && journal.journalized_type == 'Issue'
  241. receive_issue_reply(journal.journalized_id, journal)
  242. elsif m = email.subject.to_s.match(ISSUE_REPLY_SUBJECT_RE)
  243. logger&.info "MailHandler: reply to a nonexistant journal, calling receive_issue_reply with issue from subject"
  244. receive_issue_reply(m[1].to_i)
  245. else
  246. raise MissingContainer, "reply to nonexistant journal [#{journal_id}]"
  247. end
  248. end
  249. # Receives a reply to a forum message
  250. def receive_message_reply(message_id)
  251. message = Message.find_by(:id => message_id)&.root
  252. if message.nil?
  253. raise MissingContainer, "reply to nonexistant message [#{message_id}]"
  254. end
  255. # Never receive emails to projects where adding messages is not possible
  256. project = message.project
  257. raise NotAllowedInProject, "not possible to add messages to project [#{project.name}]" unless project.allows_to?(:add_messages)
  258. unless handler_options[:no_permission_check]
  259. raise InsufficientPermissions, "not allowed to add messages to project [#{message.project.name}]" unless user.allowed_to?(:add_messages, message.project)
  260. end
  261. if !message.locked?
  262. reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
  263. :content => cleaned_up_text_body)
  264. reply.author = user
  265. reply.board = message.board
  266. message.children << reply
  267. add_attachments(reply)
  268. reply
  269. else
  270. raise LockedTopic, "ignoring reply to a locked message [#{message.id} #{message.subject}]"
  271. end
  272. end
  273. # Receives a reply to a news entry
  274. def receive_news_reply(news_id)
  275. news = News.find_by_id(news_id)
  276. if news.nil?
  277. raise MissingContainer, "reply to nonexistant news [#{news_id}]"
  278. end
  279. # Never receive emails to projects where adding news comments is not possible
  280. project = news.project
  281. raise NotAllowedInProject, "not possible to add news comments to project [#{project.name}]" unless project.allows_to?(:comment_news)
  282. unless handler_options[:no_permission_check]
  283. unless news.commentable?(user)
  284. raise InsufficientPermissions, "not allowed to comment on news item [#{news.id} #{news.title}]"
  285. end
  286. end
  287. comment = news.comments.new
  288. comment.author = user
  289. comment.comments = cleaned_up_text_body
  290. comment.save!
  291. comment
  292. end
  293. # Receives a reply to a comment to a news entry
  294. def receive_comment_reply(comment_id)
  295. comment = Comment.find_by_id(comment_id)
  296. if comment && comment.commented_type == 'News'
  297. receive_news_reply(comment.commented.id)
  298. else
  299. raise MissingContainer, "reply to nonexistant comment [#{comment_id}]"
  300. end
  301. end
  302. def add_attachments(obj)
  303. if email.attachments && email.attachments.any?
  304. email.attachments.each do |attachment|
  305. next unless accept_attachment?(attachment)
  306. next unless attachment.body.decoded.size > 0
  307. obj.attachments << Attachment.create(:container => obj,
  308. :file => attachment.body.decoded,
  309. :filename => attachment.filename,
  310. :author => user,
  311. :content_type => attachment.mime_type)
  312. end
  313. end
  314. end
  315. # Returns false if the +attachment+ of the incoming email should be ignored
  316. def accept_attachment?(attachment)
  317. @excluded ||= Setting.mail_handler_excluded_filenames.to_s.split(',').map(&:strip).reject(&:blank?)
  318. @excluded.each do |pattern|
  319. if Setting.mail_handler_enable_regex_excluded_filenames?
  320. regexp = %r{\A#{pattern}\z}i
  321. else
  322. regexp = %r{\A#{Regexp.escape(pattern).gsub("\\*", ".*")}\z}i
  323. end
  324. if regexp.match?(attachment.filename.to_s)
  325. logger.info "MailHandler: ignoring attachment #{attachment.filename} matching #{pattern}"
  326. return false
  327. end
  328. end
  329. true
  330. end
  331. # Adds To and Cc as watchers of the given object if the sender has the
  332. # appropriate permission
  333. def add_watchers(obj)
  334. if handler_options[:no_permission_check] || user.allowed_to?(:"add_#{obj.class.name.underscore}_watchers", obj.project)
  335. addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
  336. unless addresses.empty?
  337. users = User.active.having_mail(addresses).to_a
  338. users -= obj.watcher_users
  339. users.each do |u|
  340. obj.add_watcher(u)
  341. end
  342. end
  343. end
  344. end
  345. def get_keyword(attr, options={})
  346. @keywords ||= {}
  347. if @keywords.has_key?(attr)
  348. @keywords[attr]
  349. else
  350. @keywords[attr] = begin
  351. override =
  352. if options.key?(:override)
  353. options[:override]
  354. else
  355. (handler_options[:allow_override] & [attr.to_s.downcase.gsub(/\s+/, '_'), 'all']).present?
  356. end
  357. if override && (v = extract_keyword!(cleaned_up_text_body, attr, options[:format]))
  358. v
  359. elsif handler_options[:issue][attr].present?
  360. handler_options[:issue][attr]
  361. end
  362. end
  363. end
  364. end
  365. # Destructively extracts the value for +attr+ in +text+
  366. # Returns nil if no matching keyword found
  367. def extract_keyword!(text, attr, format=nil)
  368. keys = [attr.to_s.humanize]
  369. if attr.is_a?(Symbol)
  370. if user && user.language.present?
  371. keys << l("field_#{attr}", :default => '', :locale => user.language)
  372. end
  373. if Setting.default_language.present?
  374. keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
  375. end
  376. end
  377. keys.reject! {|k| k.blank?}
  378. keys.collect! {|k| Regexp.escape(k)}
  379. format ||= '.+'
  380. keyword = nil
  381. regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
  382. if m = text.match(regexp)
  383. keyword = m[2].strip
  384. text.sub!(regexp, '')
  385. end
  386. keyword
  387. end
  388. def get_project_from_receiver_addresses
  389. local, domain = handler_options[:project_from_subaddress].to_s.split("@")
  390. return nil unless local && domain
  391. local = Regexp.escape(local)
  392. [:to, :cc, :bcc].each do |field|
  393. header = @email[field]
  394. next if header.blank? || header.field.blank? || !header.field.respond_to?(:addrs)
  395. header.field.addrs.each do |addr|
  396. if addr.domain.to_s.casecmp(domain)==0 && addr.local.to_s =~ /\A#{local}\+([^+]+)\z/
  397. if project = Project.find_by_identifier($1)
  398. return project
  399. end
  400. end
  401. end
  402. end
  403. nil
  404. end
  405. def target_project
  406. # TODO: other ways to specify project:
  407. # * parse the email To field
  408. # * specific project (eg. Setting.mail_handler_target_project)
  409. target = get_project_from_receiver_addresses
  410. target ||= Project.find_by_identifier(get_keyword(:project))
  411. if target.nil?
  412. # Invalid project keyword, use the project specified as the default one
  413. default_project = handler_options[:issue][:project]
  414. if default_project.present?
  415. target = Project.find_by_identifier(default_project)
  416. end
  417. end
  418. raise MissingInformation, 'Unable to determine target project' if target.nil?
  419. target
  420. end
  421. # Returns a Hash of issue attributes extracted from keywords in the email body
  422. def issue_attributes_from_keywords(issue)
  423. attrs = {
  424. 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
  425. 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
  426. 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
  427. 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
  428. 'assigned_to_id' => (k = get_keyword(:assigned_to)) && find_assignee_from_keyword(k, issue).try(:id),
  429. 'fixed_version_id' => (k = get_keyword(:fixed_version)) && issue.project.shared_versions.named(k).first.try(:id),
  430. 'start_date' => get_keyword(:start_date, :format => '\d{4}-\d{2}-\d{2}'),
  431. 'due_date' => get_keyword(:due_date, :format => '\d{4}-\d{2}-\d{2}'),
  432. 'estimated_hours' => get_keyword(:estimated_hours),
  433. 'done_ratio' => get_keyword(:done_ratio, :format => '(\d|10)?0'),
  434. 'is_private' => get_keyword_bool(:is_private),
  435. 'parent_issue_id' => get_keyword(:parent_issue)
  436. }.delete_if {|k, v| v.blank?}
  437. attrs
  438. end
  439. def get_keyword_bool(attr)
  440. true_values = ["1"]
  441. false_values = ["0"]
  442. locales = [Setting.default_language]
  443. if user
  444. locales << user.language
  445. end
  446. locales.select(&:present?).each do |locale|
  447. true_values << l("general_text_yes", :default => '', :locale => locale)
  448. true_values << l("general_text_Yes", :default => '', :locale => locale)
  449. false_values << l("general_text_no", :default => '', :locale => locale)
  450. false_values << l("general_text_No", :default => '', :locale => locale)
  451. end
  452. values = (true_values + false_values).select(&:present?)
  453. format = Regexp.union values
  454. if value = get_keyword(attr, :format => format)
  455. if true_values.include?(value)
  456. return true
  457. elsif false_values.include?(value)
  458. return false
  459. end
  460. end
  461. nil
  462. end
  463. # Returns a Hash of issue custom field values extracted from keywords in the email body
  464. def custom_field_values_from_keywords(customized)
  465. customized.custom_field_values.inject({}) do |h, v|
  466. if keyword = get_keyword(v.custom_field.name)
  467. h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
  468. end
  469. h
  470. end
  471. end
  472. # Returns the text content of the email.
  473. # If the value of Setting.mail_handler_preferred_body_part is 'html',
  474. # it returns text converted from the text/html part of the email.
  475. # Otherwise, it returns text/plain part.
  476. def plain_text_body
  477. return @plain_text_body unless @plain_text_body.nil?
  478. parse_order =
  479. if Setting.mail_handler_preferred_body_part == 'html'
  480. ['text/html', 'text/plain']
  481. else
  482. ['text/plain', 'text/html']
  483. end
  484. parse_order.each do |mime_type|
  485. @plain_text_body ||= email_parts_to_text(email.all_parts.select {|p| p.mime_type == mime_type}).presence
  486. return @plain_text_body unless @plain_text_body.nil?
  487. end
  488. # If there is still no body found, and there are no mime-parts defined,
  489. # we use the whole raw mail body
  490. @plain_text_body ||= email_parts_to_text([email]).presence if email.all_parts.empty?
  491. # As a fallback we return an empty plain text body (e.g. if we have only
  492. # empty text parts but a non-text attachment)
  493. @plain_text_body ||= ""
  494. end
  495. def email_parts_to_text(parts)
  496. parts.reject! do |part|
  497. part.attachment?
  498. end
  499. parts.map do |p|
  500. body_charset = Mail::Utilities.pick_encoding(p.charset).to_s
  501. body = Redmine::CodesetUtil.to_utf8(p.body.decoded, body_charset)
  502. # convert html parts to text
  503. p.mime_type == 'text/html' ? self.class.html_body_to_text(body) : self.class.plain_text_body_to_text(body)
  504. end.join("\r\n")
  505. end
  506. def cleaned_up_text_body
  507. @cleaned_up_text_body ||= cleanup_body(plain_text_body)
  508. end
  509. def cleaned_up_subject
  510. subject = email.subject.to_s
  511. subject.strip[0, 255]
  512. end
  513. def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
  514. limit ||= object.class.columns_hash[attribute.to_s].limit || 255
  515. value = value.to_s.slice(0, limit)
  516. object.send(:"#{attribute}=", value)
  517. end
  518. private_class_method :assign_string_attribute_with_limit
  519. # Singleton class method is public
  520. class << self
  521. # Converts a HTML email body to text
  522. def html_body_to_text(html)
  523. Redmine::WikiFormatting.html_parser.to_text(html)
  524. end
  525. # Converts a plain/text email body to text
  526. def plain_text_body_to_text(text)
  527. # Removes leading spaces that would cause the line to be rendered as
  528. # preformatted text with textile
  529. text.gsub(/^ +(?![*#])/, '')
  530. end
  531. # Returns a User from an email address and a full name
  532. def new_user_from_attributes(email_address, fullname=nil)
  533. user = User.new
  534. # Truncating the email address would result in an invalid format
  535. user.mail = email_address
  536. assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
  537. names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
  538. assign_string_attribute_with_limit(user, 'firstname', names.shift, 30)
  539. assign_string_attribute_with_limit(user, 'lastname', names.join(' '), 30)
  540. user.lastname = '-' if user.lastname.blank?
  541. user.language = Setting.default_language
  542. user.generate_password = true
  543. user.mail_notification = 'only_my_events'
  544. unless user.valid?
  545. user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
  546. user.firstname = "-" unless user.errors[:firstname].blank?
  547. user.lastname = "-" unless user.errors[:lastname].blank?
  548. end
  549. user
  550. end
  551. end
  552. # Creates a User for the +email+ sender
  553. # Returns the user or nil if it could not be created
  554. def create_user_from_email
  555. if from_addr = email.header['from'].try(:addrs).to_a.first
  556. addr = from_addr.address
  557. name = from_addr.display_name || from_addr.comments.to_a.first
  558. user = self.class.new_user_from_attributes(addr, name)
  559. if handler_options[:no_notification]
  560. user.mail_notification = 'none'
  561. end
  562. if user.save
  563. user
  564. else
  565. logger&.error "MailHandler: failed to create User: #{user.errors.full_messages}"
  566. nil
  567. end
  568. else
  569. logger&.error "MailHandler: failed to create User: no FROM address found"
  570. nil
  571. end
  572. end
  573. # Adds the newly created user to default group
  574. def add_user_to_group(default_group)
  575. if default_group.present?
  576. default_group.split(',').each do |group_name|
  577. if group = Group.named(group_name).first
  578. group.users << @user
  579. elsif logger
  580. logger.warn "MailHandler: could not add user to [#{group_name}], group not found"
  581. end
  582. end
  583. end
  584. end
  585. # Removes the email body of text after the truncation configurations.
  586. def cleanup_body(body)
  587. delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?)
  588. if Setting.mail_handler_enable_regex_delimiters?
  589. begin
  590. delimiters = delimiters.map {|s| Regexp.new(s)}
  591. rescue RegexpError => e
  592. logger&.error "MailHandler: invalid regexp delimiter found in mail_handler_body_delimiters setting (#{e.message})"
  593. end
  594. else
  595. # In a "normal" delimiter, allow a single space from the originally
  596. # defined delimiter to match:
  597. # * any space-like character, or
  598. # * line-breaks and optional quoting with arbitrary spacing around it
  599. # in the mail in order to allow line breaks of delimiters.
  600. delimiters = delimiters.map do |delimiter|
  601. delimiter = Regexp.escape(delimiter).encode!(Encoding::UTF_8)
  602. delimiter = delimiter.gsub(/(\\ )+/, '\p{Space}*(\p{Space}|[\r\n](\p{Space}|>)*)')
  603. Regexp.new(delimiter)
  604. end
  605. end
  606. unless delimiters.empty?
  607. regex = Regexp.new("^(\\p{Space}|>)*(#{ Regexp.union(delimiters) })\\p{Space}*[\\r\\n].*", Regexp::MULTILINE)
  608. if Setting.text_formatting == "common_mark" && Redmine::Configuration['common_mark_enable_hardbreaks'] == false
  609. body = Redmine::WikiFormatting::CommonMark::AppendSpacesToLines.call(body)
  610. end
  611. body = body.gsub(regex, '')
  612. end
  613. body.strip
  614. end
  615. def find_assignee_from_keyword(keyword, issue)
  616. Principal.detect_by_keyword(issue.assignable_users, keyword)
  617. end
  618. end