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

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