3 // why is this a top level function? Because PHP 5.2.0 doesn't seem to
4 // understand how to interpret this filter if it's a static method.
5 // It's all really silly, but if we go this route it might be reasonable
6 // to coalesce all of these methods into one.
7 function htmlpurifier_filter_extractstyleblocks_muteerrorhandler()
12 * This filter extracts <style> blocks from input HTML, cleans them up
13 * using CSSTidy, and then places them in $purifier->context->get('StyleBlocks')
14 * so they can be used elsewhere in the document.
17 * See tests/HTMLPurifier/Filter/ExtractStyleBlocksTest.php for
21 * This filter can also be used on stylesheets not included in the
22 * document--something purists would probably prefer. Just directly
23 * call HTMLPurifier_Filter_ExtractStyleBlocks->cleanCSS()
25 class HTMLPurifier_Filter_ExtractStyleBlocks
extends HTMLPurifier_Filter
30 public $name = 'ExtractStyleBlocks';
35 private $_styleMatches = array();
43 * @type HTMLPurifier_AttrDef_HTML_ID
48 * @type HTMLPurifier_AttrDef_CSS_Ident
50 private $_class_attrdef;
53 * @type HTMLPurifier_AttrDef_Enum
55 private $_enum_attrdef;
57 public function __construct()
59 $this->_tidy
= new csstidy();
60 $this->_tidy
->set_cfg('lowercase_s', false);
61 $this->_id_attrdef
= new HTMLPurifier_AttrDef_HTML_ID(true);
62 $this->_class_attrdef
= new HTMLPurifier_AttrDef_CSS_Ident();
63 $this->_enum_attrdef
= new HTMLPurifier_AttrDef_Enum(
76 * Save the contents of CSS blocks to style matches
77 * @param array $matches preg_replace style $matches array
79 protected function styleCallback($matches)
81 $this->_styleMatches
[] = $matches[1];
85 * Removes inline <style> tags from HTML, saves them for later use
87 * @param HTMLPurifier_Config $config
88 * @param HTMLPurifier_Context $context
90 * @todo Extend to indicate non-text/css style blocks
92 public function preFilter($html, $config, $context)
94 $tidy = $config->get('Filter.ExtractStyleBlocks.TidyImpl');
98 $html = preg_replace_callback('#<style(?:\s.*)?>(.+)</style>#isU', array($this, 'styleCallback'), $html);
99 $style_blocks = $this->_styleMatches
;
100 $this->_styleMatches
= array(); // reset
101 $context->register('StyleBlocks', $style_blocks); // $context must not be reused
103 foreach ($style_blocks as &$style) {
104 $style = $this->cleanCSS($style, $config, $context);
111 * Takes CSS (the stuff found in <style>) and cleans it.
112 * @warning Requires CSSTidy <http://csstidy.sourceforge.net/>
113 * @param string $css CSS styling to clean
114 * @param HTMLPurifier_Config $config
115 * @param HTMLPurifier_Context $context
116 * @throws HTMLPurifier_Exception
117 * @return string Cleaned CSS
119 public function cleanCSS($css, $config, $context)
122 $scope = $config->get('Filter.ExtractStyleBlocks.Scope');
123 if ($scope !== null) {
124 $scopes = array_map('trim', explode(',', $scope));
128 // remove comments from CSS
130 if (strncmp('<!--', $css, 4) === 0) {
131 $css = substr($css, 4);
133 if (strlen($css) > 3 && substr($css, -3) == '-->') {
134 $css = substr($css, 0, -3);
137 set_error_handler('htmlpurifier_filter_extractstyleblocks_muteerrorhandler');
138 $this->_tidy
->parse($css);
139 restore_error_handler();
140 $css_definition = $config->getDefinition('CSS');
141 $html_definition = $config->getDefinition('HTML');
143 foreach ($this->_tidy
->css
as $k => $decls) {
144 // $decls are all CSS declarations inside an @ selector
145 $new_decls = array();
146 foreach ($decls as $selector => $style) {
147 $selector = trim($selector);
148 if ($selector === '') {
150 } // should not happen
151 // Parse the selector
152 // Here is the relevant part of the CSS grammar:
155 // : selector [ ',' S* selector ]* '{' ...
157 // : simple_selector [ combinator selector | S+ [ combinator? selector ]? ]?
162 // : element_name [ HASH | class | attrib | pseudo ]*
163 // | [ HASH | class | attrib | pseudo ]+
171 // : '[' S* IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S*
172 // [ IDENT | STRING ] S* ]? ']'
175 // : ':' [ IDENT | FUNCTION S* [IDENT S*]? ')' ]
178 // For reference, here are the relevant tokens:
185 // FUNCTION {ident}\(
187 // And the lexical scanner tokens
190 // nmchar [_a-z0-9-]|{nonascii}|{escape}
191 // nonascii [\240-\377]
192 // escape {unicode}|\\[^\r\n\f0-9a-f]
193 // unicode \\{h}}{1,6}(\r\n|[ \t\r\n\f])?
194 // ident -?{nmstart}{nmchar*}
195 // nmstart [_a-z]|{nonascii}|{escape}
196 // string {string1}|{string2}
197 // string1 \"([^\n\r\f\\"]|\\{nl}|{escape})*\"
198 // string2 \'([^\n\r\f\\"]|\\{nl}|{escape})*\'
200 // We'll implement a subset (in order to reduce attack
201 // surface); in particular:
203 // - No Unicode support
204 // - No escapes support
205 // - No string support (by proxy no attrib support)
206 // - element_name is matched against allowed
207 // elements (some people might find this
209 // - Pseudo-elements one of :first-child, :link,
210 // :visited, :active, :hover, :focus
213 $selectors = array_map('trim', explode(',', $selector));
214 $new_selectors = array();
215 foreach ($selectors as $sel) {
216 // split on +, > and spaces
217 $basic_selectors = preg_split('/\s*([+> ])\s*/', $sel, -1, PREG_SPLIT_DELIM_CAPTURE
);
218 // even indices are chunks, odd indices are
221 $delim = null; // guaranteed to be non-null after
222 // two loop iterations
223 for ($i = 0, $c = count($basic_selectors); $i < $c; $i++
) {
224 $x = $basic_selectors[$i];
230 $delim = ' ' . $x . ' ';
234 $components = preg_split('/([#.:])/', $x, -1, PREG_SPLIT_DELIM_CAPTURE
);
237 for ($j = 0, $cc = count($components); $j < $cc; $j++
) {
238 $y = $components[$j];
240 if ($y === '*' ||
isset($html_definition->info
[$y = strtolower($y)])) {
243 // $nx stays null; this matters
244 // if we don't manage to find
245 // any valid selector content,
246 // in which case we ignore the
254 if ($sdelim === '#') {
255 $attrdef = $this->_id_attrdef
;
256 } elseif ($sdelim === '.') {
257 $attrdef = $this->_class_attrdef
;
258 } elseif ($sdelim === ':') {
259 $attrdef = $this->_enum_attrdef
;
261 throw new HTMLPurifier_Exception('broken invariant sdelim and preg_split');
263 $r = $attrdef->validate($y, $config, $context);
276 if ($nsel === null) {
279 $nsel .= $delim . $nx;
282 // delimiters to the left of invalid
283 // basic selector ignored
287 if ($nsel !== null) {
288 if (!empty($scopes)) {
289 foreach ($scopes as $s) {
290 $new_selectors[] = "$s $nsel";
293 $new_selectors[] = $nsel;
297 if (empty($new_selectors)) {
300 $selector = implode(', ', $new_selectors);
301 foreach ($style as $name => $value) {
302 if (!isset($css_definition->info
[$name])) {
303 unset($style[$name]);
306 $def = $css_definition->info
[$name];
307 $ret = $def->validate($value, $config, $context);
308 if ($ret === false) {
309 unset($style[$name]);
311 $style[$name] = $ret;
314 $new_decls[$selector] = $style;
316 $new_css[$k] = $new_decls;
318 // remove stuff that shouldn't be used, could be reenabled
319 // after security risks are analyzed
320 $this->_tidy
->css
= $new_css;
321 $this->_tidy
->import
= array();
322 $this->_tidy
->charset
= null;
323 $this->_tidy
->namespace = null;
324 $css = $this->_tidy
->print->plain();
325 // we are going to escape any special characters <>& to ensure
326 // that no funny business occurs (i.e. </style> in a font-family prop).
327 if ($config->get('Filter.ExtractStyleBlocks.Escaping')) {
329 array('<', '>', '&'),
330 array('\3C ', '\3E ', '\26 '),
338 // vim: et sw=4 sts=4