Created
February 3, 2011 21:26
-
-
Save eladmeidar/810234 to your computer and use it in GitHub Desktop.
check text fields for links, check that they aren't evil and return
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module LinkChecker | |
def self.included(base) | |
base.class_eval do | |
require 'net/http' | |
require 'uri' | |
before_save :_check_for_evil_links | |
cattr_accessor :check_evil_links_on_attributes, :suspicious_callback, :retry_limit | |
extend ClassMethods | |
include InstanceMethods | |
end | |
end | |
module ClassMethods | |
def check_evil_links_on(options = {}) | |
options.assert_valid_keys :fields, :suspicious_callback, :retry_limit | |
raise "You need to specify a suspicious callback on 'check_evil_links_on'" if options[:suspicious_callback].blank? | |
self.check_evil_links_on_attributes = options[:fields].to_a.collect(&:to_s) & self.column_names | |
self.suspicious_callback = options[:suspicious_callback].to_sym | |
self.retry_limit = options[:retry_limit] | |
end | |
end | |
module InstanceMethods | |
protected | |
def _check_for_evil_links | |
raw_data = self.class.check_evil_links_on_attributes.collect {|attr_name| self.send(attr_name.to_sym) if self.respond_to?(attr_name.to_sym)}.compact.join(" ") | |
if links = raw_data.scan(/[a-z0-9]+(?:[\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(?:(?::[0-9]{1,5})?\/[^\s]*)?/) | |
if links.any? {|link| link_has_bad_words?(link) || link_is_evil?(link, self.class.retry_limit)} | |
begin | |
self.send(self.class.suspicious_callback.to_sym) #if self.respond_to?(self.class.suspicious_callback.to_sym) | |
rescue | |
end | |
end | |
end | |
end | |
def link_has_bad_words?(link = "") | |
return false if link.blank? | |
return (GlobalPreference.get('suspicious_words') + GlobalPreference.get('bad_words')).any? { |word| link =~ eval("/#{word.strip}/") } | |
end | |
def link_is_evil?(link = "", limit = 1) | |
return false if link.blank? | |
hoptoad_message("Link to #{link} redirected more than #{self.class.retry_limit} times on message ##{self.id}") if limit == 0 | |
link = "http://" + link unless link.start_with?("http") | |
begin | |
response = Net::HTTP.get_response(URI.parse(link)) | |
case response | |
when Net::HTTPSuccess, Net::HTTPOK | |
return link_has_bad_words?(link) | |
when Net::HTTPRedirection, HTTPMovedPermanently | |
puts "Redirected to #{response['location']}" | |
return link_has_bad_words?(response['location']) | |
else | |
end | |
rescue | |
return false | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment