2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2014-10-03 08:41:52 +08: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
|
|
|
|
|
2022-04-05 18:08:28 +08:00
|
|
|
module FreedomPatches
|
|
|
|
module SafeBuffer
|
|
|
|
def concat(value, raise_encoding_err = false)
|
2014-10-03 08:41:52 +08:00
|
|
|
super(value)
|
2022-04-05 18:08:28 +08:00
|
|
|
rescue Encoding::CompatibilityError
|
|
|
|
raise if raise_encoding_err
|
2014-10-03 08:41:52 +08:00
|
|
|
|
2019-05-03 06:17:27 +08:00
|
|
|
encoding_diags =
|
|
|
|
+"internal encoding #{Encoding.default_internal}, external encoding #{Encoding.default_external}"
|
|
|
|
if encoding != Encoding::UTF_8
|
2014-10-30 14:48:31 +08:00
|
|
|
encoding_diags << " my encoding is #{encoding} "
|
2022-04-05 18:08:28 +08:00
|
|
|
force_encoding("UTF-8")
|
2014-10-03 08:41:52 +08:00
|
|
|
unless valid_encoding?
|
|
|
|
encode!("utf-16", "utf-8", invalid: :replace)
|
|
|
|
encode!("utf-8", "utf-16")
|
|
|
|
end
|
2014-10-03 17:45:42 +08:00
|
|
|
Rails.logger.warn(
|
|
|
|
"Encountered a non UTF-8 string in SafeBuffer - #{self} - #{encoding_diags}",
|
|
|
|
)
|
2014-10-03 08:41:52 +08:00
|
|
|
end
|
2019-05-03 06:17:27 +08:00
|
|
|
if value.encoding != Encoding::UTF_8
|
2014-10-30 14:48:31 +08:00
|
|
|
encoding_diags << " attempted to append encoding #{value.encoding} "
|
2014-10-03 08:41:52 +08:00
|
|
|
value = value.dup.force_encoding("UTF-8").scrub
|
2014-10-03 17:45:42 +08:00
|
|
|
Rails.logger.warn(
|
|
|
|
"Attempted to concat a non UTF-8 string in SafeBuffer - #{value} - #{encoding_diags}",
|
|
|
|
)
|
2014-10-03 08:41:52 +08:00
|
|
|
end
|
|
|
|
concat(value, _raise = true)
|
|
|
|
end
|
|
|
|
|
2022-04-05 18:08:28 +08:00
|
|
|
ActiveSupport::SafeBuffer.prepend(self)
|
|
|
|
ActiveSupport::SafeBuffer.class_eval("alias << concat")
|
|
|
|
end
|
2014-10-03 08:41:52 +08:00
|
|
|
end
|