checks_attribute_values_and_length.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. module ApplicationModel::ChecksAttributeValuesAndLength
  3. extend ActiveSupport::Concern
  4. included do
  5. before_create :check_attribute_values_and_length
  6. before_update :check_attribute_values_and_length
  7. end
  8. =begin
  9. 1) check string/varchar size and cut them if needed
  10. 2) check string for null byte \u0000 and remove it
  11. =end
  12. def check_attribute_values_and_length
  13. columns = self.class.columns_hash
  14. attributes.each do |name, value|
  15. next if !value.instance_of?(String)
  16. column = columns[name]
  17. next if !column
  18. if column.type == :binary
  19. self[name].force_encoding('BINARY')
  20. end
  21. next if value.blank?
  22. # strip null byte chars (postgresql will complain about it)
  23. if column.type == :text
  24. if Rails.application.config.db_null_byte == false
  25. self[name].delete!("\u0000")
  26. end
  27. end
  28. # for varchar check length and replace null bytes
  29. limit = column.limit
  30. if limit
  31. current_length = value.length
  32. if limit < current_length
  33. logger.warn "WARNING: cut string because of database length #{self.class}.#{name}(#{limit} but is #{current_length}:#{value})"
  34. self[name] = value[0, limit]
  35. end
  36. # strip null byte chars (postgresql will complain about it)
  37. if Rails.application.config.db_null_byte == false
  38. self[name].delete!("\u0000")
  39. end
  40. end
  41. # strip 4 bytes utf8 chars if needed (mysql/mariadb will complain it)
  42. next if self[name].blank?
  43. self[name] = self[name].utf8_to_3bytesutf8
  44. end
  45. true
  46. end
  47. end