2013-02-07 09:09:31 +08:00
|
|
|
#
|
|
|
|
# Given a string, tell us whether or not is acceptable. Also, remove stuff we don't like
|
|
|
|
# such as leading / trailing space.
|
|
|
|
#
|
|
|
|
class TextSentinel
|
|
|
|
|
|
|
|
attr_accessor :text
|
|
|
|
|
|
|
|
def self.non_symbols_regexp
|
|
|
|
/[\ -\/\[-\`\:-\@\{-\~]/m
|
|
|
|
end
|
|
|
|
|
|
|
|
def initialize(text, opts=nil)
|
|
|
|
@opts = opts || {}
|
|
|
|
|
2013-02-16 05:36:19 +08:00
|
|
|
if text.present?
|
|
|
|
@text = text.encode('UTF-8', invalid: :replace, undef: :replace, replace: '')
|
2013-02-07 09:09:31 +08:00
|
|
|
@text.gsub!(/ +/m, ' ') if @opts[:remove_interior_spaces]
|
2013-02-16 09:58:33 +08:00
|
|
|
@text.strip! if @opts[:strip]
|
2013-02-07 09:09:31 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2013-02-09 05:55:40 +08:00
|
|
|
def self.title_sentinel(text)
|
|
|
|
TextSentinel.new(text,
|
|
|
|
min_entropy: SiteSetting.title_min_entropy,
|
|
|
|
max_word_length: SiteSetting.max_word_length,
|
2013-02-16 09:58:33 +08:00
|
|
|
remove_interior_spaces: true,
|
|
|
|
strip: true)
|
2013-02-09 05:55:40 +08:00
|
|
|
end
|
|
|
|
|
2013-02-07 09:09:31 +08:00
|
|
|
# Entropy is a number of how many unique characters the string needs.
|
|
|
|
def entropy
|
|
|
|
return 0 if @text.blank?
|
2013-02-16 09:58:33 +08:00
|
|
|
@entropy ||= @text.strip.each_char.to_a.uniq.size
|
2013-02-07 09:09:31 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def valid?
|
|
|
|
|
|
|
|
# Blank strings are not valid
|
2013-02-16 09:58:33 +08:00
|
|
|
return false if @text.blank? || @text.strip.blank?
|
2013-02-07 09:09:31 +08:00
|
|
|
|
|
|
|
# Entropy check if required
|
|
|
|
return false if @opts[:min_entropy].present? and (entropy < @opts[:min_entropy])
|
|
|
|
|
|
|
|
# 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
|
|
|
|
|
|
|
|
return false if @opts[:max_word_length] and @text =~ /\w{#{@opts[:max_word_length]},}(\s|$)/
|
|
|
|
|
2013-02-15 05:09:57 +08:00
|
|
|
# We don't allow all upper case content in english
|
|
|
|
return false if (@text =~ /[A-Z]+/) and (@text == @text.upcase)
|
2013-02-07 09:09:31 +08:00
|
|
|
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|