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