Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
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()
8
{
9
}
10
 
11
/**
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.
15
 *
16
 * @note
17
 *      See tests/HTMLPurifier/Filter/ExtractStyleBlocksTest.php for
18
 *      sample usage.
19
 *
20
 * @note
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()
24
 */
25
class HTMLPurifier_Filter_ExtractStyleBlocks extends HTMLPurifier_Filter
26
{
27
    /**
28
     * @type string
29
     */
30
    public $name = 'ExtractStyleBlocks';
31
 
32
    /**
33
     * @type array
34
     */
35
    private $_styleMatches = array();
36
 
37
    /**
38
     * @type csstidy
39
     */
40
    private $_tidy;
41
 
42
    /**
43
     * @type HTMLPurifier_AttrDef_HTML_ID
44
     */
45
    private $_id_attrdef;
46
 
47
    /**
48
     * @type HTMLPurifier_AttrDef_CSS_Ident
49
     */
50
    private $_class_attrdef;
51
 
52
    /**
53
     * @type HTMLPurifier_AttrDef_Enum
54
     */
55
    private $_enum_attrdef;
56
 
57
    public function __construct()
58
    {
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(
64
            array(
65
                'first-child',
66
                'link',
67
                'visited',
68
                'active',
69
                'hover',
70
                'focus'
71
            )
72
        );
73
    }
74
 
75
    /**
76
     * Save the contents of CSS blocks to style matches
77
     * @param array $matches preg_replace style $matches array
78
     */
79
    protected function styleCallback($matches)
80
    {
81
        $this->_styleMatches[] = $matches[1];
82
    }
83
 
84
    /**
85
     * Removes inline <style> tags from HTML, saves them for later use
86
     * @param string $html
87
     * @param HTMLPurifier_Config $config
88
     * @param HTMLPurifier_Context $context
89
     * @return string
90
     * @todo Extend to indicate non-text/css style blocks
91
     */
92
    public function preFilter($html, $config, $context)
93
    {
94
        $tidy = $config->get('Filter.ExtractStyleBlocks.TidyImpl');
95
        if ($tidy !== null) {
96
            $this->_tidy = $tidy;
97
        }
98
        // NB: this must be NON-greedy because if we have
99
        // <style>foo</style>  <style>bar</style>
100
        // we must not grab foo</style>  <style>bar
101
        $html = preg_replace_callback('#<style(?:\s.*)?>(.*)<\/style>#isU', array($this, 'styleCallback'), $html);
102
        $style_blocks = $this->_styleMatches;
103
        $this->_styleMatches = array(); // reset
104
        $context->register('StyleBlocks', $style_blocks); // $context must not be reused
105
        if ($this->_tidy) {
106
            foreach ($style_blocks as &$style) {
107
                $style = $this->cleanCSS($style, $config, $context);
108
            }
109
        }
110
        return $html;
111
    }
112
 
113
    /**
114
     * Takes CSS (the stuff found in <style>) and cleans it.
115
     * @warning Requires CSSTidy <http://csstidy.sourceforge.net/>
116
     * @param string $css CSS styling to clean
117
     * @param HTMLPurifier_Config $config
118
     * @param HTMLPurifier_Context $context
119
     * @throws HTMLPurifier_Exception
120
     * @return string Cleaned CSS
121
     */
122
    public function cleanCSS($css, $config, $context)
123
    {
124
        // prepare scope
125
        $scope = $config->get('Filter.ExtractStyleBlocks.Scope');
126
        if ($scope !== null) {
127
            $scopes = array_map('trim', explode(',', $scope));
128
        } else {
129
            $scopes = array();
130
        }
131
        // remove comments from CSS
132
        $css = trim($css);
133
        if (strncmp('<!--', $css, 4) === 0) {
134
            $css = substr($css, 4);
135
        }
136
        if (strlen($css) > 3 && substr($css, -3) == '-->') {
137
            $css = substr($css, 0, -3);
138
        }
139
        $css = trim($css);
140
        set_error_handler('htmlpurifier_filter_extractstyleblocks_muteerrorhandler');
141
        $this->_tidy->parse($css);
142
        restore_error_handler();
143
        $css_definition = $config->getDefinition('CSS');
144
        $html_definition = $config->getDefinition('HTML');
145
        $new_css = array();
146
        foreach ($this->_tidy->css as $k => $decls) {
147
            // $decls are all CSS declarations inside an @ selector
148
            $new_decls = array();
149
            if (is_array($decls)) {
150
                foreach ($decls as $selector => $style) {
151
                    $selector = trim($selector);
152
                    if ($selector === '') {
153
                        continue;
154
                    } // should not happen
155
                    // Parse the selector
156
                    // Here is the relevant part of the CSS grammar:
157
                    //
158
                    // ruleset
159
                    //   : selector [ ',' S* selector ]* '{' ...
160
                    // selector
161
                    //   : simple_selector [ combinator selector | S+ [ combinator? selector ]? ]?
162
                    // combinator
163
                    //   : '+' S*
164
                    //   : '>' S*
165
                    // simple_selector
166
                    //   : element_name [ HASH | class | attrib | pseudo ]*
167
                    //   | [ HASH | class | attrib | pseudo ]+
168
                    // element_name
169
                    //   : IDENT | '*'
170
                    //   ;
171
                    // class
172
                    //   : '.' IDENT
173
                    //   ;
174
                    // attrib
175
                    //   : '[' S* IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S*
176
                    //     [ IDENT | STRING ] S* ]? ']'
177
                    //   ;
178
                    // pseudo
179
                    //   : ':' [ IDENT | FUNCTION S* [IDENT S*]? ')' ]
180
                    //   ;
181
                    //
182
                    // For reference, here are the relevant tokens:
183
                    //
184
                    // HASH         #{name}
185
                    // IDENT        {ident}
186
                    // INCLUDES     ==
187
                    // DASHMATCH    |=
188
                    // STRING       {string}
189
                    // FUNCTION     {ident}\(
190
                    //
191
                    // And the lexical scanner tokens
192
                    //
193
                    // name         {nmchar}+
194
                    // nmchar       [_a-z0-9-]|{nonascii}|{escape}
195
                    // nonascii     [\240-\377]
196
                    // escape       {unicode}|\\[^\r\n\f0-9a-f]
197
                    // unicode      \\{h}}{1,6}(\r\n|[ \t\r\n\f])?
198
                    // ident        -?{nmstart}{nmchar*}
199
                    // nmstart      [_a-z]|{nonascii}|{escape}
200
                    // string       {string1}|{string2}
201
                    // string1      \"([^\n\r\f\\"]|\\{nl}|{escape})*\"
202
                    // string2      \'([^\n\r\f\\"]|\\{nl}|{escape})*\'
203
                    //
204
                    // We'll implement a subset (in order to reduce attack
205
                    // surface); in particular:
206
                    //
207
                    //      - No Unicode support
208
                    //      - No escapes support
209
                    //      - No string support (by proxy no attrib support)
210
                    //      - element_name is matched against allowed
211
                    //        elements (some people might find this
212
                    //        annoying...)
213
                    //      - Pseudo-elements one of :first-child, :link,
214
                    //        :visited, :active, :hover, :focus
215
 
216
                    // handle ruleset
217
                    $selectors = array_map('trim', explode(',', $selector));
218
                    $new_selectors = array();
219
                    foreach ($selectors as $sel) {
220
                        // split on +, > and spaces
221
                        $basic_selectors = preg_split('/\s*([+> ])\s*/', $sel, -1, PREG_SPLIT_DELIM_CAPTURE);
222
                        // even indices are chunks, odd indices are
223
                        // delimiters
224
                        $nsel = null;
225
                        $delim = null; // guaranteed to be non-null after
226
                        // two loop iterations
227
                        for ($i = 0, $c = count($basic_selectors); $i < $c; $i++) {
228
                            $x = $basic_selectors[$i];
229
                            if ($i % 2) {
230
                                // delimiter
231
                                if ($x === ' ') {
232
                                    $delim = ' ';
233
                                } else {
234
                                    $delim = ' ' . $x . ' ';
235
                                }
236
                            } else {
237
                                // simple selector
238
                                $components = preg_split('/([#.:])/', $x, -1, PREG_SPLIT_DELIM_CAPTURE);
239
                                $sdelim = null;
240
                                $nx = null;
241
                                for ($j = 0, $cc = count($components); $j < $cc; $j++) {
242
                                    $y = $components[$j];
243
                                    if ($j === 0) {
244
                                        if ($y === '*' || isset($html_definition->info[$y = strtolower($y)])) {
245
                                            $nx = $y;
246
                                        } else {
247
                                            // $nx stays null; this matters
248
                                            // if we don't manage to find
249
                                            // any valid selector content,
250
                                            // in which case we ignore the
251
                                            // outer $delim
252
                                        }
253
                                    } elseif ($j % 2) {
254
                                        // set delimiter
255
                                        $sdelim = $y;
256
                                    } else {
257
                                        $attrdef = null;
258
                                        if ($sdelim === '#') {
259
                                            $attrdef = $this->_id_attrdef;
260
                                        } elseif ($sdelim === '.') {
261
                                            $attrdef = $this->_class_attrdef;
262
                                        } elseif ($sdelim === ':') {
263
                                            $attrdef = $this->_enum_attrdef;
264
                                        } else {
265
                                            throw new HTMLPurifier_Exception('broken invariant sdelim and preg_split');
266
                                        }
267
                                        $r = $attrdef->validate($y, $config, $context);
268
                                        if ($r !== false) {
269
                                            if ($r !== true) {
270
                                                $y = $r;
271
                                            }
272
                                            if ($nx === null) {
273
                                                $nx = '';
274
                                            }
275
                                            $nx .= $sdelim . $y;
276
                                        }
277
                                    }
278
                                }
279
                                if ($nx !== null) {
280
                                    if ($nsel === null) {
281
                                        $nsel = $nx;
282
                                    } else {
283
                                        $nsel .= $delim . $nx;
284
                                    }
285
                                } else {
286
                                    // delimiters to the left of invalid
287
                                    // basic selector ignored
288
                                }
289
                            }
290
                        }
291
                        if ($nsel !== null) {
292
                            if (!empty($scopes)) {
293
                                foreach ($scopes as $s) {
294
                                    $new_selectors[] = "$s $nsel";
295
                                }
296
                            } else {
297
                                $new_selectors[] = $nsel;
298
                            }
299
                        }
300
                    }
301
                    if (empty($new_selectors)) {
302
                        continue;
303
                    }
304
                    $selector = implode(', ', $new_selectors);
305
                    foreach ($style as $name => $value) {
306
                        if (!isset($css_definition->info[$name])) {
307
                            unset($style[$name]);
308
                            continue;
309
                        }
310
                        $def = $css_definition->info[$name];
311
                        $ret = $def->validate($value, $config, $context);
312
                        if ($ret === false) {
313
                            unset($style[$name]);
314
                        } else {
315
                            $style[$name] = $ret;
316
                        }
317
                    }
318
                    $new_decls[$selector] = $style;
319
                }
320
            } else {
321
                continue;
322
            }
323
            $new_css[$k] = $new_decls;
324
        }
325
        // remove stuff that shouldn't be used, could be reenabled
326
        // after security risks are analyzed
327
        $this->_tidy->css = $new_css;
328
        $this->_tidy->import = array();
329
        $this->_tidy->charset = null;
330
        $this->_tidy->namespace = null;
331
        $css = $this->_tidy->print->plain();
332
        // we are going to escape any special characters <>& to ensure
333
        // that no funny business occurs (i.e. </style> in a font-family prop).
334
        if ($config->get('Filter.ExtractStyleBlocks.Escaping')) {
335
            $css = str_replace(
336
                array('<', '>', '&'),
337
                array('\3C ', '\3E ', '\26 '),
338
                $css
339
            );
340
        }
341
        return $css;
342
    }
343
}
344
 
345
// vim: et sw=4 sts=4