2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2014-10-02 20:41:52 -04:00
|
|
|
# For some reason safe buffer is getting invalid encoding in some cases
|
|
|
|
# we work around the issue and log the problems
|
|
|
|
#
|
|
|
|
# The alternative is a broken website when this happens
|
|
|
|
|
|
|
|
class ActiveSupport::SafeBuffer
|
2017-07-27 21:20:09 -04:00
|
|
|
def concat(value, raise_encoding_err = false)
|
2014-10-02 20:41:52 -04:00
|
|
|
if !html_safe? || value.html_safe?
|
|
|
|
super(value)
|
|
|
|
else
|
|
|
|
super(ERB::Util.h(value))
|
|
|
|
end
|
|
|
|
rescue Encoding::CompatibilityError
|
|
|
|
if raise_encoding_err
|
|
|
|
raise
|
|
|
|
else
|
|
|
|
|
2019-05-02 18:17:27 -04:00
|
|
|
encoding_diags = +"internal encoding #{Encoding.default_internal}, external encoding #{Encoding.default_external}"
|
2014-10-03 05:45:42 -04:00
|
|
|
|
2019-05-02 18:17:27 -04:00
|
|
|
if encoding != Encoding::UTF_8
|
2014-10-30 02:48:31 -04:00
|
|
|
encoding_diags << " my encoding is #{encoding} "
|
|
|
|
|
2014-10-02 20:41:52 -04:00
|
|
|
self.force_encoding("UTF-8")
|
|
|
|
unless valid_encoding?
|
2017-07-27 21:20:09 -04:00
|
|
|
encode!("utf-16", "utf-8", invalid: :replace)
|
|
|
|
encode!("utf-8", "utf-16")
|
2014-10-02 20:41:52 -04:00
|
|
|
end
|
2014-10-03 05:45:42 -04:00
|
|
|
Rails.logger.warn("Encountered a non UTF-8 string in SafeBuffer - #{self} - #{encoding_diags}")
|
2014-10-02 20:41:52 -04:00
|
|
|
end
|
|
|
|
|
2019-05-02 18:17:27 -04:00
|
|
|
if value.encoding != Encoding::UTF_8
|
2014-10-30 02:48:31 -04:00
|
|
|
|
|
|
|
encoding_diags << " attempted to append encoding #{value.encoding} "
|
|
|
|
|
2014-10-02 20:41:52 -04:00
|
|
|
value = value.dup.force_encoding("UTF-8").scrub
|
2014-10-03 05:45:42 -04:00
|
|
|
Rails.logger.warn("Attempted to concat a non UTF-8 string in SafeBuffer - #{value} - #{encoding_diags}")
|
2014-10-02 20:41:52 -04:00
|
|
|
end
|
|
|
|
|
2017-07-27 21:20:09 -04:00
|
|
|
concat(value, _raise = true)
|
2014-10-02 20:41:52 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
alias << concat
|
|
|
|
end
|