blob: 3c8ed6f420f4e0b454ade24f1b294e74f97d5269 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
# === PermitScrubber
#
# PermitScrubber allows you to permit only your own tags and/or attributes.
#
# Supplied tags and attributes should be Enumerables
#
# +tags=+
# If this value is set all other elements will be stripped (their inner elements will be kept).
# If not set elements for which HTML5::Scrub.allowed_element? is false will be stripped.
#
# +attributes=+
# Contain an elements allowed attributes.
# If none is set HTML5::Scrub.scrub_attributes implementation will be used.
#
# Subclass PermitScrubber to provide your own definition of:
#
# When a node is allowed via +allowed_node?+
# When a node should be skipped via +should_skip_node?+
# Which attributes should be scrubbed via +should_scrub_attributes?+
class PermitScrubber < Loofah::Scrubber
# :nodoc:
attr_reader :tags, :attributes
def tags=(tags)
@tags = validate!(tags, :tags)
end
def attributes=(attributes)
@attributes = validate!(attributes, :attributes)
end
def scrub(node)
return CONTINUE if should_skip_node?(node)
unless allowed_node?(node)
node.before node.children # strip
node.remove
return STOP
end
scrub_attributes(node)
end
protected
def allowed_node?(node)
if @tags
@tags.include?(node.name)
else
Loofah::HTML5::Scrub.allowed_element?(node.name)
end
end
def should_skip_node?(node)
text_or_cdata_node?(node)
end
def should_scrub_attributes?(name)
@attributes.exclude?(name)
end
def scrub_attributes(node)
if @attributes
node.attributes.each do |name, _|
node.remove_attribute(name) if should_scrub_attributes?(name)
end
else
Loofah::HTML5::Scrub.scrub_attributes(node)
end
end
def text_or_cdata_node?(node)
case node.type
when Nokogiri::XML::Node::TEXT_NODE, Nokogiri::XML::Node::CDATA_SECTION_NODE
return true
end
false
end
def validate!(var, name)
if var && !var.is_a?(Enumerable)
raise ArgumentError, "You should pass :#{name} as an Enumerable"
end
var
end
end
# TargetScrubber - The bizarro PermitScrubber
#
# With PermitScrubber you choose elements you don't want removed,
# with TargetScrubber you choose want you want gone.
#
# +tags=+ and +attributes=+ has the same behavior as PermitScrubber
# except they select what to get rid of.
class TargetScrubber < PermitScrubber
def allowed_node?(node)
return super unless @tags
@tags.exclude?(node.name)
end
def should_scrub_attributes?(name)
@attributes.include?(name)
end
end
|