class Sanitize
def clean!(html)
Performs clean in place, returning _html_, or +nil+ if no changes were
def clean!(html) fragment = Hpricot(html) fragment.traverse_element do |node| if node.bogusetag? || node.doctype? || node.procins? || node.xmldecl? node.swap('') next end if node.comment? node.swap('') unless @config[:allow_comments] elsif node.elem? name = node.name.downcase # Delete any element that isn't in the whitelist. unless @config[:elements].include?(name) node.parent.replace_child(node, node.children) next end if @config[:attributes].has_key?(name) # Delete any attribute that isn't in the whitelist for this element. node.raw_attributes.delete_if do |key, value| !@config[:attributes][name].include?(key.downcase) end # Delete remaining attributes that use unacceptable protocols. if @config[:protocols].has_key?(name) protocol = @config[:protocols][name] node.raw_attributes.delete_if do |key, value| next false unless protocol.has_key?(key) if value.downcase =~ /^([^:]+)(?:\:|�*58;|�*3a;)/ !protocol[key].include?($1.downcase) else !protocol[key].include?(:relative) end end end else # Delete all attributes from elements with no whitelisted # attributes. node.raw_attributes = {} end # Add required attributes. if @config[:add_attributes].has_key?(name) node.raw_attributes.merge!(@config[:add_attributes][name]) end end end # Make one last pass through the fragment and encode all special HTML chars # and non-ASCII chars as entities. This eliminates certain types of # maliciously-malformed nested tags and also compensates for Hpricot's # burning desire to decode all entities. coder = HTMLEntities.new fragment.traverse_element do |node| if node.text? node.swap(coder.encode(node.inner_text, :named)) end end result = fragment.to_s return result == html ? nil : html[0, html.length] = result end