annotate .svn/pristine/16/167405f8fc306f6d744a19a6721080ccc76c8dbc.svn-base @ 1524:82fac3dcf466 redmine-2.5-integration

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