Sha256: a0e6823a89401e067c2cdcc89801fbc90e74bbd81ebd7922a7b2bd7988f7b8e3

Contents?: true

Size: 1.35 KB

Versions: 23

Compression:

Stored size: 1.35 KB

Contents

# Code from rubyonrails project (http://www.rubyonrails.com)
# Temporarily here.

require 'html/tokenizer'
require 'html/node'

VERBOTEN_TAGS = %w(form script) unless defined?(VERBOTEN_TAGS)
VERBOTEN_ATTRS = /^on/i unless defined?(VERBOTEN_ATTRS)

class String
  # Sanitizes the given HTML by making form and script tags into regular
  # text, and removing all "onxxx" attributes (so that arbitrary Javascript
  # cannot be executed). Also removes href attributes that start with
  # "javascript:".
  #
  # Returns the sanitized text.
  def self.sanitize(html)
    # only do this if absolutely necessary
    if html.index("<")
      tokenizer = HTML::Tokenizer.new(html)
      new_text = ""

      while token = tokenizer.next
        node = HTML::Node.parse(nil, 0, 0, token, false)
        new_text << case node
          when HTML::Tag
            if VERBOTEN_TAGS.include?(node.name)
              node.to_s.gsub(/</, "&lt;")
            else
              if node.closing != :close
                node.attributes.delete_if { |attr,v| attr =~ VERBOTEN_ATTRS }
                if node.attributes["href"] =~ /^javascript:/i
                  node.attributes.delete "href"
                end
              end
              node.to_s
            end
          else
            node.to_s.gsub(/</, "&lt;")
        end
      end

      html = new_text
    end

    html
  end
end

Version data entries

23 entries across 23 versions & 3 rubygems

Version Path
nitro-0.41.0 lib/nitro/sanitize.rb
facets-1.4.1 forge/more/sanitize.rb
facets-1.4.2 forge/more/sanitize.rb
facets-1.4.3 forge/more/sanitize.rb
facets-1.4.5 snip/more/sanitize.rb
facets-1.4.4 forge/more/sanitize.rb
facets-1.8.0 work/more/sanitize.rb
facets-1.8.20 work/more/sanitize.rb
facets-1.8.49 work/more/sanitize.rb
facets-1.8.8 work/more/sanitize.rb
glue-0.30.0 lib/glue/sanitize.rb
glue-0.21.2 lib/glue/sanitize.rb
glue-0.22.0 lib/glue/sanitize.rb
glue-0.25.0 lib/glue/sanitize.rb
glue-0.27.0 lib/glue/sanitize.rb
glue-0.28.0 lib/glue/sanitize.rb
glue-0.31.0 lib/glue/sanitize.rb
glue-0.23.0 lib/glue/sanitize.rb
glue-0.21.0 lib/glue/sanitize.rb
glue-0.24.0 lib/glue/sanitize.rb