annotate .svn/pristine/c3/c336c255f0c991cc835201626f5e37be82ee02c6.svn-base @ 1628:9c5f8e24dadc live tip

Quieten this cron script
author Chris Cannam
date Tue, 25 Aug 2020 11:38:49 +0100
parents e248c7af89ec
children
rev   line source
Chris@1494 1 # Redmine - project management software
Chris@1494 2 # Copyright (C) 2006-2014 Jean-Philippe Lang
Chris@1494 3 #
Chris@1494 4 # This program is free software; you can redistribute it and/or
Chris@1494 5 # modify it under the terms of the GNU General Public License
Chris@1494 6 # as published by the Free Software Foundation; either version 2
Chris@1494 7 # of the License, or (at your option) any later version.
Chris@1494 8 #
Chris@1494 9 # This program is distributed in the hope that it will be useful,
Chris@1494 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@1494 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@1494 12 # GNU General Public License for more details.
Chris@1494 13 #
Chris@1494 14 # You should have received a copy of the GNU General Public License
Chris@1494 15 # along with this program; if not, write to the Free Software
Chris@1494 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@1494 17
Chris@1494 18 class MailHandler < ActionMailer::Base
Chris@1494 19 include ActionView::Helpers::SanitizeHelper
Chris@1494 20 include Redmine::I18n
Chris@1494 21
Chris@1494 22 class UnauthorizedAction < StandardError; end
Chris@1494 23 class MissingInformation < StandardError; end
Chris@1494 24
Chris@1494 25 attr_reader :email, :user
Chris@1494 26
Chris@1494 27 def self.receive(email, options={})
Chris@1494 28 @@handler_options = options.dup
Chris@1494 29
Chris@1494 30 @@handler_options[:issue] ||= {}
Chris@1494 31
Chris@1494 32 if @@handler_options[:allow_override].is_a?(String)
Chris@1494 33 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip)
Chris@1494 34 end
Chris@1494 35 @@handler_options[:allow_override] ||= []
Chris@1494 36 # Project needs to be overridable if not specified
Chris@1494 37 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
Chris@1494 38 # Status overridable by default
Chris@1494 39 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
Chris@1494 40
Chris@1494 41 @@handler_options[:no_account_notice] = (@@handler_options[:no_account_notice].to_s == '1')
Chris@1494 42 @@handler_options[:no_notification] = (@@handler_options[:no_notification].to_s == '1')
Chris@1494 43 @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1')
Chris@1494 44
Chris@1494 45 email.force_encoding('ASCII-8BIT') if email.respond_to?(:force_encoding)
Chris@1494 46 super(email)
Chris@1494 47 end
Chris@1494 48
Chris@1494 49 # Extracts MailHandler options from environment variables
Chris@1494 50 # Use when receiving emails with rake tasks
Chris@1494 51 def self.extract_options_from_env(env)
Chris@1494 52 options = {:issue => {}}
Chris@1494 53 %w(project status tracker category priority).each do |option|
Chris@1494 54 options[:issue][option.to_sym] = env[option] if env[option]
Chris@1494 55 end
Chris@1494 56 %w(allow_override unknown_user no_permission_check no_account_notice default_group).each do |option|
Chris@1494 57 options[option.to_sym] = env[option] if env[option]
Chris@1494 58 end
Chris@1494 59 options
Chris@1494 60 end
Chris@1494 61
Chris@1494 62 def logger
Chris@1494 63 Rails.logger
Chris@1494 64 end
Chris@1494 65
Chris@1494 66 cattr_accessor :ignored_emails_headers
Chris@1494 67 @@ignored_emails_headers = {
Chris@1494 68 'X-Auto-Response-Suppress' => 'oof',
Chris@1494 69 'Auto-Submitted' => /^auto-/
Chris@1494 70 }
Chris@1494 71
Chris@1494 72 # Processes incoming emails
Chris@1494 73 # Returns the created object (eg. an issue, a message) or false
Chris@1494 74 def receive(email)
Chris@1494 75 @email = email
Chris@1494 76 sender_email = email.from.to_a.first.to_s.strip
Chris@1494 77 # Ignore emails received from the application emission address to avoid hell cycles
Chris@1494 78 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
Chris@1494 79 if logger
Chris@1494 80 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
Chris@1494 81 end
Chris@1494 82 return false
Chris@1494 83 end
Chris@1494 84 # Ignore auto generated emails
Chris@1494 85 self.class.ignored_emails_headers.each do |key, ignored_value|
Chris@1494 86 value = email.header[key]
Chris@1494 87 if value
Chris@1494 88 value = value.to_s.downcase
Chris@1494 89 if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
Chris@1494 90 if logger
Chris@1494 91 logger.info "MailHandler: ignoring email with #{key}:#{value} header"
Chris@1494 92 end
Chris@1494 93 return false
Chris@1494 94 end
Chris@1494 95 end
Chris@1494 96 end
Chris@1494 97 @user = User.find_by_mail(sender_email) if sender_email.present?
Chris@1494 98 if @user && !@user.active?
Chris@1494 99 if logger
Chris@1494 100 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]"
Chris@1494 101 end
Chris@1494 102 return false
Chris@1494 103 end
Chris@1494 104 if @user.nil?
Chris@1494 105 # Email was submitted by an unknown user
Chris@1494 106 case @@handler_options[:unknown_user]
Chris@1494 107 when 'accept'
Chris@1494 108 @user = User.anonymous
Chris@1494 109 when 'create'
Chris@1494 110 @user = create_user_from_email
Chris@1494 111 if @user
Chris@1494 112 if logger
Chris@1494 113 logger.info "MailHandler: [#{@user.login}] account created"
Chris@1494 114 end
Chris@1494 115 add_user_to_group(@@handler_options[:default_group])
Chris@1494 116 unless @@handler_options[:no_account_notice]
Chris@1494 117 Mailer.account_information(@user, @user.password).deliver
Chris@1494 118 end
Chris@1494 119 else
Chris@1494 120 if logger
Chris@1494 121 logger.error "MailHandler: could not create account for [#{sender_email}]"
Chris@1494 122 end
Chris@1494 123 return false
Chris@1494 124 end
Chris@1494 125 else
Chris@1494 126 # Default behaviour, emails from unknown users are ignored
Chris@1494 127 if logger
Chris@1494 128 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]"
Chris@1494 129 end
Chris@1494 130 return false
Chris@1494 131 end
Chris@1494 132 end
Chris@1494 133 User.current = @user
Chris@1494 134 dispatch
Chris@1494 135 end
Chris@1494 136
Chris@1494 137 private
Chris@1494 138
Chris@1494 139 MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+(\.[a-f0-9]+)?@}
Chris@1494 140 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
Chris@1494 141 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
Chris@1494 142
Chris@1494 143 def dispatch
Chris@1494 144 headers = [email.in_reply_to, email.references].flatten.compact
Chris@1494 145 subject = email.subject.to_s
Chris@1494 146 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
Chris@1494 147 klass, object_id = $1, $2.to_i
Chris@1494 148 method_name = "receive_#{klass}_reply"
Chris@1494 149 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
Chris@1494 150 send method_name, object_id
Chris@1494 151 else
Chris@1494 152 # ignoring it
Chris@1494 153 end
Chris@1494 154 elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
Chris@1494 155 receive_issue_reply(m[1].to_i)
Chris@1494 156 elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
Chris@1494 157 receive_message_reply(m[1].to_i)
Chris@1494 158 else
Chris@1494 159 dispatch_to_default
Chris@1494 160 end
Chris@1494 161 rescue ActiveRecord::RecordInvalid => e
Chris@1494 162 # TODO: send a email to the user
Chris@1494 163 logger.error e.message if logger
Chris@1494 164 false
Chris@1494 165 rescue MissingInformation => e
Chris@1494 166 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
Chris@1494 167 false
Chris@1494 168 rescue UnauthorizedAction => e
Chris@1494 169 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
Chris@1494 170 false
Chris@1494 171 end
Chris@1494 172
Chris@1494 173 def dispatch_to_default
Chris@1494 174 receive_issue
Chris@1494 175 end
Chris@1494 176
Chris@1494 177 # Creates a new issue
Chris@1494 178 def receive_issue
Chris@1494 179 project = target_project
Chris@1494 180 # check permission
Chris@1494 181 unless @@handler_options[:no_permission_check]
Chris@1494 182 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
Chris@1494 183 end
Chris@1494 184
Chris@1494 185 issue = Issue.new(:author => user, :project => project)
Chris@1494 186 issue.safe_attributes = issue_attributes_from_keywords(issue)
Chris@1494 187 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
Chris@1494 188 issue.subject = cleaned_up_subject
Chris@1494 189 if issue.subject.blank?
Chris@1494 190 issue.subject = '(no subject)'
Chris@1494 191 end
Chris@1494 192 issue.description = cleaned_up_text_body
Chris@1494 193
Chris@1494 194 # add To and Cc as watchers before saving so the watchers can reply to Redmine
Chris@1494 195 add_watchers(issue)
Chris@1494 196 issue.save!
Chris@1494 197 add_attachments(issue)
Chris@1494 198 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger
Chris@1494 199 issue
Chris@1494 200 end
Chris@1494 201
Chris@1494 202 # Adds a note to an existing issue
Chris@1494 203 def receive_issue_reply(issue_id, from_journal=nil)
Chris@1494 204 issue = Issue.find_by_id(issue_id)
Chris@1494 205 return unless issue
Chris@1494 206 # check permission
Chris@1494 207 unless @@handler_options[:no_permission_check]
Chris@1494 208 unless user.allowed_to?(:add_issue_notes, issue.project) ||
Chris@1494 209 user.allowed_to?(:edit_issues, issue.project)
Chris@1494 210 raise UnauthorizedAction
Chris@1494 211 end
Chris@1494 212 end
Chris@1494 213
Chris@1494 214 # ignore CLI-supplied defaults for new issues
Chris@1494 215 @@handler_options[:issue].clear
Chris@1494 216
Chris@1494 217 journal = issue.init_journal(user)
Chris@1494 218 if from_journal && from_journal.private_notes?
Chris@1494 219 # If the received email was a reply to a private note, make the added note private
Chris@1494 220 issue.private_notes = true
Chris@1494 221 end
Chris@1494 222 issue.safe_attributes = issue_attributes_from_keywords(issue)
Chris@1494 223 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
Chris@1494 224 journal.notes = cleaned_up_text_body
Chris@1494 225 add_attachments(issue)
Chris@1494 226 issue.save!
Chris@1494 227 if logger
Chris@1494 228 logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
Chris@1494 229 end
Chris@1494 230 journal
Chris@1494 231 end
Chris@1494 232
Chris@1494 233 # Reply will be added to the issue
Chris@1494 234 def receive_journal_reply(journal_id)
Chris@1494 235 journal = Journal.find_by_id(journal_id)
Chris@1494 236 if journal && journal.journalized_type == 'Issue'
Chris@1494 237 receive_issue_reply(journal.journalized_id, journal)
Chris@1494 238 end
Chris@1494 239 end
Chris@1494 240
Chris@1494 241 # Receives a reply to a forum message
Chris@1494 242 def receive_message_reply(message_id)
Chris@1494 243 message = Message.find_by_id(message_id)
Chris@1494 244 if message
Chris@1494 245 message = message.root
Chris@1494 246
Chris@1494 247 unless @@handler_options[:no_permission_check]
Chris@1494 248 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
Chris@1494 249 end
Chris@1494 250
Chris@1494 251 if !message.locked?
Chris@1494 252 reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
Chris@1494 253 :content => cleaned_up_text_body)
Chris@1494 254 reply.author = user
Chris@1494 255 reply.board = message.board
Chris@1494 256 message.children << reply
Chris@1494 257 add_attachments(reply)
Chris@1494 258 reply
Chris@1494 259 else
Chris@1494 260 if logger
Chris@1494 261 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
Chris@1494 262 end
Chris@1494 263 end
Chris@1494 264 end
Chris@1494 265 end
Chris@1494 266
Chris@1494 267 def add_attachments(obj)
Chris@1494 268 if email.attachments && email.attachments.any?
Chris@1494 269 email.attachments.each do |attachment|
Chris@1494 270 next unless accept_attachment?(attachment)
Chris@1494 271 obj.attachments << Attachment.create(:container => obj,
Chris@1494 272 :file => attachment.decoded,
Chris@1494 273 :filename => attachment.filename,
Chris@1494 274 :author => user,
Chris@1494 275 :content_type => attachment.mime_type)
Chris@1494 276 end
Chris@1494 277 end
Chris@1494 278 end
Chris@1494 279
Chris@1494 280 # Returns false if the +attachment+ of the incoming email should be ignored
Chris@1494 281 def accept_attachment?(attachment)
Chris@1494 282 @excluded ||= Setting.mail_handler_excluded_filenames.to_s.split(',').map(&:strip).reject(&:blank?)
Chris@1494 283 @excluded.each do |pattern|
Chris@1494 284 regexp = %r{\A#{Regexp.escape(pattern).gsub("\\*", ".*")}\z}i
Chris@1494 285 if attachment.filename.to_s =~ regexp
Chris@1494 286 logger.info "MailHandler: ignoring attachment #{attachment.filename} matching #{pattern}"
Chris@1494 287 return false
Chris@1494 288 end
Chris@1494 289 end
Chris@1494 290 true
Chris@1494 291 end
Chris@1494 292
Chris@1494 293 # Adds To and Cc as watchers of the given object if the sender has the
Chris@1494 294 # appropriate permission
Chris@1494 295 def add_watchers(obj)
Chris@1494 296 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
Chris@1494 297 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
Chris@1494 298 unless addresses.empty?
Chris@1494 299 watchers = User.active.where('LOWER(mail) IN (?)', addresses).all
Chris@1494 300 watchers.each {|w| obj.add_watcher(w)}
Chris@1494 301 end
Chris@1494 302 end
Chris@1494 303 end
Chris@1494 304
Chris@1494 305 def get_keyword(attr, options={})
Chris@1494 306 @keywords ||= {}
Chris@1494 307 if @keywords.has_key?(attr)
Chris@1494 308 @keywords[attr]
Chris@1494 309 else
Chris@1494 310 @keywords[attr] = begin
Chris@1494 311 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
Chris@1494 312 (v = extract_keyword!(plain_text_body, attr, options[:format]))
Chris@1494 313 v
Chris@1494 314 elsif !@@handler_options[:issue][attr].blank?
Chris@1494 315 @@handler_options[:issue][attr]
Chris@1494 316 end
Chris@1494 317 end
Chris@1494 318 end
Chris@1494 319 end
Chris@1494 320
Chris@1494 321 # Destructively extracts the value for +attr+ in +text+
Chris@1494 322 # Returns nil if no matching keyword found
Chris@1494 323 def extract_keyword!(text, attr, format=nil)
Chris@1494 324 keys = [attr.to_s.humanize]
Chris@1494 325 if attr.is_a?(Symbol)
Chris@1494 326 if user && user.language.present?
Chris@1494 327 keys << l("field_#{attr}", :default => '', :locale => user.language)
Chris@1494 328 end
Chris@1494 329 if Setting.default_language.present?
Chris@1494 330 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
Chris@1494 331 end
Chris@1494 332 end
Chris@1494 333 keys.reject! {|k| k.blank?}
Chris@1494 334 keys.collect! {|k| Regexp.escape(k)}
Chris@1494 335 format ||= '.+'
Chris@1494 336 keyword = nil
Chris@1494 337 regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
Chris@1494 338 if m = text.match(regexp)
Chris@1494 339 keyword = m[2].strip
Chris@1494 340 text.gsub!(regexp, '')
Chris@1494 341 end
Chris@1494 342 keyword
Chris@1494 343 end
Chris@1494 344
Chris@1494 345 def target_project
Chris@1494 346 # TODO: other ways to specify project:
Chris@1494 347 # * parse the email To field
Chris@1494 348 # * specific project (eg. Setting.mail_handler_target_project)
Chris@1494 349 target = Project.find_by_identifier(get_keyword(:project))
Chris@1494 350 if target.nil?
Chris@1494 351 # Invalid project keyword, use the project specified as the default one
Chris@1494 352 default_project = @@handler_options[:issue][:project]
Chris@1494 353 if default_project.present?
Chris@1494 354 target = Project.find_by_identifier(default_project)
Chris@1494 355 end
Chris@1494 356 end
Chris@1494 357 raise MissingInformation.new('Unable to determine target project') if target.nil?
Chris@1494 358 target
Chris@1494 359 end
Chris@1494 360
Chris@1494 361 # Returns a Hash of issue attributes extracted from keywords in the email body
Chris@1494 362 def issue_attributes_from_keywords(issue)
Chris@1494 363 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
Chris@1494 364
Chris@1494 365 attrs = {
Chris@1494 366 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
Chris@1494 367 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
Chris@1494 368 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
Chris@1494 369 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
Chris@1494 370 'assigned_to_id' => assigned_to.try(:id),
Chris@1494 371 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
Chris@1494 372 issue.project.shared_versions.named(k).first.try(:id),
Chris@1494 373 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
Chris@1494 374 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
Chris@1494 375 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
Chris@1494 376 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
Chris@1494 377 }.delete_if {|k, v| v.blank? }
Chris@1494 378
Chris@1494 379 if issue.new_record? && attrs['tracker_id'].nil?
Chris@1494 380 attrs['tracker_id'] = issue.project.trackers.first.try(:id)
Chris@1494 381 end
Chris@1494 382
Chris@1494 383 attrs
Chris@1494 384 end
Chris@1494 385
Chris@1494 386 # Returns a Hash of issue custom field values extracted from keywords in the email body
Chris@1494 387 def custom_field_values_from_keywords(customized)
Chris@1494 388 customized.custom_field_values.inject({}) do |h, v|
Chris@1494 389 if keyword = get_keyword(v.custom_field.name, :override => true)
Chris@1494 390 h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
Chris@1494 391 end
Chris@1494 392 h
Chris@1494 393 end
Chris@1494 394 end
Chris@1494 395
Chris@1494 396 # Returns the text/plain part of the email
Chris@1494 397 # If not found (eg. HTML-only email), returns the body with tags removed
Chris@1494 398 def plain_text_body
Chris@1494 399 return @plain_text_body unless @plain_text_body.nil?
Chris@1494 400
Chris@1494 401 parts = if (text_parts = email.all_parts.select {|p| p.mime_type == 'text/plain'}).present?
Chris@1494 402 text_parts
Chris@1494 403 elsif (html_parts = email.all_parts.select {|p| p.mime_type == 'text/html'}).present?
Chris@1494 404 html_parts
Chris@1494 405 else
Chris@1494 406 [email]
Chris@1494 407 end
Chris@1494 408
Chris@1494 409 parts.reject! do |part|
Chris@1494 410 part.header[:content_disposition].try(:disposition_type) == 'attachment'
Chris@1494 411 end
Chris@1494 412
Chris@1494 413 @plain_text_body = parts.map {|p| Redmine::CodesetUtil.to_utf8(p.body.decoded, p.charset)}.join("\r\n")
Chris@1494 414
Chris@1494 415 # strip html tags and remove doctype directive
Chris@1494 416 if parts.any? {|p| p.mime_type == 'text/html'}
Chris@1494 417 @plain_text_body = strip_tags(@plain_text_body.strip)
Chris@1494 418 @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
Chris@1494 419 end
Chris@1494 420
Chris@1494 421 @plain_text_body
Chris@1494 422 end
Chris@1494 423
Chris@1494 424 def cleaned_up_text_body
Chris@1494 425 cleanup_body(plain_text_body)
Chris@1494 426 end
Chris@1494 427
Chris@1494 428 def cleaned_up_subject
Chris@1494 429 subject = email.subject.to_s
Chris@1494 430 subject.strip[0,255]
Chris@1494 431 end
Chris@1494 432
Chris@1494 433 def self.full_sanitizer
Chris@1494 434 @full_sanitizer ||= HTML::FullSanitizer.new
Chris@1494 435 end
Chris@1494 436
Chris@1494 437 def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
Chris@1494 438 limit ||= object.class.columns_hash[attribute.to_s].limit || 255
Chris@1494 439 value = value.to_s.slice(0, limit)
Chris@1494 440 object.send("#{attribute}=", value)
Chris@1494 441 end
Chris@1494 442
Chris@1494 443 # Returns a User from an email address and a full name
Chris@1494 444 def self.new_user_from_attributes(email_address, fullname=nil)
Chris@1494 445 user = User.new
Chris@1494 446
Chris@1494 447 # Truncating the email address would result in an invalid format
Chris@1494 448 user.mail = email_address
Chris@1494 449 assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
Chris@1494 450
Chris@1494 451 names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
Chris@1494 452 assign_string_attribute_with_limit(user, 'firstname', names.shift, 30)
Chris@1494 453 assign_string_attribute_with_limit(user, 'lastname', names.join(' '), 30)
Chris@1494 454 user.lastname = '-' if user.lastname.blank?
Chris@1494 455 user.language = Setting.default_language
Chris@1494 456 user.generate_password = true
Chris@1494 457 user.mail_notification = 'only_my_events'
Chris@1494 458
Chris@1494 459 unless user.valid?
Chris@1494 460 user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
Chris@1494 461 user.firstname = "-" unless user.errors[:firstname].blank?
Chris@1494 462 (puts user.errors[:lastname];user.lastname = "-") unless user.errors[:lastname].blank?
Chris@1494 463 end
Chris@1494 464
Chris@1494 465 user
Chris@1494 466 end
Chris@1494 467
Chris@1494 468 # Creates a User for the +email+ sender
Chris@1494 469 # Returns the user or nil if it could not be created
Chris@1494 470 def create_user_from_email
Chris@1494 471 from = email.header['from'].to_s
Chris@1494 472 addr, name = from, nil
Chris@1494 473 if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
Chris@1494 474 addr, name = m[2], m[1]
Chris@1494 475 end
Chris@1494 476 if addr.present?
Chris@1494 477 user = self.class.new_user_from_attributes(addr, name)
Chris@1494 478 if @@handler_options[:no_notification]
Chris@1494 479 user.mail_notification = 'none'
Chris@1494 480 end
Chris@1494 481 if user.save
Chris@1494 482 user
Chris@1494 483 else
Chris@1494 484 logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
Chris@1494 485 nil
Chris@1494 486 end
Chris@1494 487 else
Chris@1494 488 logger.error "MailHandler: failed to create User: no FROM address found" if logger
Chris@1494 489 nil
Chris@1494 490 end
Chris@1494 491 end
Chris@1494 492
Chris@1494 493 # Adds the newly created user to default group
Chris@1494 494 def add_user_to_group(default_group)
Chris@1494 495 if default_group.present?
Chris@1494 496 default_group.split(',').each do |group_name|
Chris@1494 497 if group = Group.named(group_name).first
Chris@1494 498 group.users << @user
Chris@1494 499 elsif logger
Chris@1494 500 logger.warn "MailHandler: could not add user to [#{group_name}], group not found"
Chris@1494 501 end
Chris@1494 502 end
Chris@1494 503 end
Chris@1494 504 end
Chris@1494 505
Chris@1494 506 # Removes the email body of text after the truncation configurations.
Chris@1494 507 def cleanup_body(body)
Chris@1494 508 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
Chris@1494 509 unless delimiters.empty?
Chris@1494 510 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
Chris@1494 511 body = body.gsub(regex, '')
Chris@1494 512 end
Chris@1494 513 body.strip
Chris@1494 514 end
Chris@1494 515
Chris@1494 516 def find_assignee_from_keyword(keyword, issue)
Chris@1494 517 keyword = keyword.to_s.downcase
Chris@1494 518 assignable = issue.assignable_users
Chris@1494 519 assignee = nil
Chris@1494 520 assignee ||= assignable.detect {|a|
Chris@1494 521 a.mail.to_s.downcase == keyword ||
Chris@1494 522 a.login.to_s.downcase == keyword
Chris@1494 523 }
Chris@1494 524 if assignee.nil? && keyword.match(/ /)
Chris@1494 525 firstname, lastname = *(keyword.split) # "First Last Throwaway"
Chris@1494 526 assignee ||= assignable.detect {|a|
Chris@1494 527 a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
Chris@1494 528 a.lastname.to_s.downcase == lastname
Chris@1494 529 }
Chris@1494 530 end
Chris@1494 531 if assignee.nil?
Chris@1494 532 assignee ||= assignable.detect {|a| a.name.downcase == keyword}
Chris@1494 533 end
Chris@1494 534 assignee
Chris@1494 535 end
Chris@1494 536 end