2013-02-06 20:09:31 -05:00
|
|
|
#
|
2013-04-10 05:00:50 -04:00
|
|
|
# Given a string, tell us whether or not is acceptable.
|
2013-02-06 20:09:31 -05:00
|
|
|
#
|
|
|
|
class TextSentinel
|
|
|
|
|
|
|
|
attr_accessor :text
|
|
|
|
|
2013-04-10 05:00:50 -04:00
|
|
|
def initialize(text, opts=nil)
|
|
|
|
@opts = opts || {}
|
|
|
|
@text = text.encode('UTF-8', invalid: :replace, undef: :replace, replace: '') if text.present?
|
|
|
|
end
|
|
|
|
|
2013-02-06 20:09:31 -05:00
|
|
|
def self.non_symbols_regexp
|
|
|
|
/[\ -\/\[-\`\:-\@\{-\~]/m
|
|
|
|
end
|
|
|
|
|
2013-04-10 05:00:50 -04:00
|
|
|
def self.body_sentinel(text)
|
|
|
|
TextSentinel.new(text, min_entropy: SiteSetting.body_min_entropy)
|
2013-02-06 20:09:31 -05:00
|
|
|
end
|
|
|
|
|
2013-02-08 16:55:40 -05:00
|
|
|
def self.title_sentinel(text)
|
2013-02-25 11:42:20 -05:00
|
|
|
TextSentinel.new(text,
|
2013-02-08 16:55:40 -05:00
|
|
|
min_entropy: SiteSetting.title_min_entropy,
|
2013-04-10 05:00:50 -04:00
|
|
|
max_word_length: SiteSetting.max_word_length)
|
2013-02-08 16:55:40 -05:00
|
|
|
end
|
|
|
|
|
2013-02-25 11:42:20 -05:00
|
|
|
# Entropy is a number of how many unique characters the string needs.
|
2013-02-06 20:09:31 -05:00
|
|
|
def entropy
|
|
|
|
return 0 if @text.blank?
|
2013-02-15 20:58:33 -05:00
|
|
|
@entropy ||= @text.strip.each_char.to_a.uniq.size
|
2013-02-06 20:09:31 -05:00
|
|
|
end
|
|
|
|
|
2013-02-25 11:42:20 -05:00
|
|
|
def valid?
|
2013-02-06 20:09:31 -05:00
|
|
|
# Blank strings are not valid
|
2013-02-15 20:58:33 -05:00
|
|
|
return false if @text.blank? || @text.strip.blank?
|
2013-02-06 20:09:31 -05:00
|
|
|
|
|
|
|
# Entropy check if required
|
2013-03-04 19:42:44 -05:00
|
|
|
return false if @opts[:min_entropy].present? && (entropy < @opts[:min_entropy])
|
2013-02-06 20:09:31 -05:00
|
|
|
|
|
|
|
# We don't have a comprehensive list of symbols, but this will eliminate some noise
|
|
|
|
non_symbols = @text.gsub(TextSentinel.non_symbols_regexp, '').size
|
|
|
|
return false if non_symbols == 0
|
|
|
|
|
|
|
|
# Don't allow super long strings without spaces
|
2013-03-04 19:42:44 -05:00
|
|
|
return false if @opts[:max_word_length] && @text =~ /\w{#{@opts[:max_word_length]},}(\s|$)/
|
2013-02-06 20:09:31 -05:00
|
|
|
|
2013-02-14 16:09:57 -05:00
|
|
|
# We don't allow all upper case content in english
|
2013-03-04 19:42:44 -05:00
|
|
|
return false if (@text =~ /[A-Z]+/) && (@text == @text.upcase)
|
2013-02-06 20:09:31 -05:00
|
|
|
|
2013-04-10 05:00:50 -04:00
|
|
|
# It is valid
|
2013-02-06 20:09:31 -05:00
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|