Class: Sanitize

Inherits:
Object
  • Object
show all
Defined in:
lib/sanitize/config.rb,
lib/sanitize.rb,
lib/sanitize/version.rb,
lib/sanitize/config/basic.rb,
lib/sanitize/config/relaxed.rb,
lib/sanitize/config/restricted.rb

Overview

– Copyright © 2010 Ryan Grove <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ++

Defined Under Namespace

Modules: Config Classes: Error

Constant Summary collapse

REGEX_PROTOCOL =

Matches an attribute value that could be treated by a browser as a URL with a protocol prefix, such as “http:” or “javascript:”. Any string of zero or more characters followed by a colon is considered a match, even if the colon is encoded as an entity and even if it’s an incomplete entity (which IE6 and Opera will still parse).

/^([A-Za-z0-9\+\-\.\&\;\#\s]*?)(?:\:|&#0*58|&#x0*3a)/i
VERSION =
'1.2.1.1'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Sanitize

Returns a new Sanitize object initialized with the settings in config.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/sanitize.rb', line 70

def initialize(config = {})
  # Sanitize configuration.
  @config = Config::DEFAULT.merge(config)
  @config[:transformers] = Array(@config[:transformers].dup)

  # Convert the list of allowed elements to a Hash for faster lookup.
  @allowed_elements = {}
  @config[:elements].each {|el| @allowed_elements[el] = true }

  # Convert the list of :remove_contents elements to a Hash for faster lookup.
  @remove_all_contents     = false
  @remove_element_contents = {}

  if @config[:remove_contents].is_a?(Array)
    @config[:remove_contents].each {|el| @remove_element_contents[el] = true }
  else
    @remove_all_contents = !!@config[:remove_contents]
  end

  # Specific nodes to whitelist (along with all their attributes). This array
  # is generated at runtime by transformers, and is cleared before and after
  # a fragment is cleaned (so it applies only to a specific fragment).
  @whitelist_nodes = []
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



32
33
34
# File 'lib/sanitize.rb', line 32

def config
  @config
end

Class Method Details

.clean(html, config = {}) ⇒ Object

Returns a sanitized copy of html, using the settings in config if specified.



47
48
49
50
# File 'lib/sanitize.rb', line 47

def self.clean(html, config = {})
  sanitize = Sanitize.new(config)
  sanitize.clean(html)
end

.clean!(html, config = {}) ⇒ Object

Performs Sanitize#clean in place, returning html, or nil if no changes were made.



54
55
56
57
# File 'lib/sanitize.rb', line 54

def self.clean!(html, config = {})
  sanitize = Sanitize.new(config)
  sanitize.clean!(html)
end

.clean_node!(node, config = {}) ⇒ Object

Sanitizes the specified Nokogiri::XML::Node and all its children.



60
61
62
63
# File 'lib/sanitize.rb', line 60

def self.clean_node!(node, config = {})
  sanitize = Sanitize.new(config)
  sanitize.clean_node!(node)
end

Instance Method Details

#clean(html) ⇒ Object

Returns a sanitized copy of html.



96
97
98
99
100
101
# File 'lib/sanitize.rb', line 96

def clean(html)
  if html
    dupe = html.dup
    clean!(dupe) || dupe
  end
end

#clean!(html) ⇒ Object

Performs clean in place, returning html, or nil if no changes were made.



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/sanitize.rb', line 105

def clean!(html)
  fragment = Nokogiri::HTML::DocumentFragment.parse(html)
  clean_node!(fragment)

  output_method_params = {:encoding => @config[:output_encoding], :indent => 0}

  if @config[:output] == :xhtml
    output_method = fragment.method(:to_xhtml)
    output_method_params[:save_with] = Nokogiri::XML::Node::SaveOptions::AS_XHTML
  elsif @config[:output] == :html
    output_method = fragment.method(:to_html)
  else
    raise Error, "unsupported output format: #{@config[:output]}"
  end

  result = output_method.call(output_method_params)

  return result == html ? nil : html[0, html.length] = result
end

#clean_node!(node) ⇒ Object

Sanitizes the specified Nokogiri::XML::Node and all its children.

Raises:

  • (ArgumentError)


126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/sanitize.rb', line 126

def clean_node!(node)
  raise ArgumentError unless node.is_a?(Nokogiri::XML::Node)

  @whitelist_nodes = []

  node.traverse do |child|
    if child.element?
      clean_element!(child)
    elsif child.comment?
      child.unlink unless @config[:allow_comments]
    elsif child.cdata?
      child.replace(Nokogiri::XML::Text.new(child.text, child.document))
    end
  end

  @whitelist_nodes = []

  node
end