1 : <?php
2 :
3 : /**
4 : * Validates the HTML attribute style, otherwise known as CSS.
5 : * @note We don't implement the whole CSS specification, so it might be
6 : * difficult to reuse this component in the context of validating
7 : * actual stylesheet declarations.
8 : * @note If we were really serious about validating the CSS, we would
9 : * tokenize the styles and then parse the tokens. Obviously, we
10 : * are not doing that. Doing that could seriously harm performance,
11 : * but would make these components a lot more viable for a CSS
12 : * filtering solution.
13 : */
14 1 : class HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef
15 : {
16 :
17 : public function validate($css, $config, $context) {
18 :
19 2 : $css = $this->parseCDATA($css);
20 :
21 2 : $definition = $config->getCSSDefinition();
22 :
23 : // we're going to break the spec and explode by semicolons.
24 : // This is because semicolon rarely appears in escaped form
25 : // Doing this is generally flaky but fast
26 : // IT MIGHT APPEAR IN URIs, see HTMLPurifier_AttrDef_CSSURI
27 : // for details
28 :
29 2 : $declarations = explode(';', $css);
30 2 : $propvalues = array();
31 :
32 : /**
33 : * Name of the current CSS property being validated.
34 : */
35 2 : $property = false;
36 2 : $context->register('CurrentCSSProperty', $property);
37 :
38 2 : foreach ($declarations as $declaration) {
39 2 : if (!$declaration) continue;
40 2 : if (!strpos($declaration, ':')) continue;
41 2 : list($property, $value) = explode(':', $declaration, 2);
42 2 : $property = trim($property);
43 2 : $value = trim($value);
44 2 : $ok = false;
45 : do {
46 2 : if (isset($definition->info[$property])) {
47 2 : $ok = true;
48 2 : break;
49 0 : }
50 1 : if (ctype_lower($property)) break;
51 1 : $property = strtolower($property);
52 1 : if (isset($definition->info[$property])) {
53 0 : $ok = true;
54 0 : break;
55 0 : }
56 0 : } while(0);
57 2 : if (!$ok) continue;
58 : // inefficient call, since the validator will do this again
59 2 : if (strtolower(trim($value)) !== 'inherit') {
60 : // inherit works for everything (but only on the base property)
61 2 : $result = $definition->info[$property]->validate(
62 2 : $value, $config, $context );
63 2 : } else {
64 0 : $result = 'inherit';
65 : }
66 2 : if ($result === false) continue;
67 2 : $propvalues[$property] = $result;
68 2 : }
69 :
70 2 : $context->destroy('CurrentCSSProperty');
71 :
72 : // procedure does not write the new CSS simultaneously, so it's
73 : // slightly inefficient, but it's the only way of getting rid of
74 : // duplicates. Perhaps config to optimize it, but not now.
75 :
76 2 : $new_declarations = '';
77 2 : foreach ($propvalues as $prop => $value) {
78 2 : $new_declarations .= "$prop:$value;";
79 2 : }
80 :
81 2 : return $new_declarations ? $new_declarations : false;
82 :
83 : }
84 :
85 : }
86 :
|