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: class HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef
15: {
16:
17: public function validate($css, $config, $context) {
18:
19: $css = $this->parseCDATA($css);
20:
21: $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: $declarations = explode(';', $css);
30: $propvalues = array();
31:
32: /**
33: * Name of the current CSS property being validated.
34: */
35: $property = false;
36: $context->register('CurrentCSSProperty', $property);
37:
38: foreach ($declarations as $declaration) {
39: if (!$declaration) continue;
40: if (!strpos($declaration, ':')) continue;
41: list($property, $value) = explode(':', $declaration, 2);
42: $property = trim($property);
43: $value = trim($value);
44: $ok = false;
45: do {
46: if (isset($definition->info[$property])) {
47: $ok = true;
48: break;
49: }
50: if (ctype_lower($property)) break;
51: $property = strtolower($property);
52: if (isset($definition->info[$property])) {
53: $ok = true;
54: break;
55: }
56: } while(0);
57: if (!$ok) continue;
58: // inefficient call, since the validator will do this again
59: if (strtolower(trim($value)) !== 'inherit') {
60: // inherit works for everything (but only on the base property)
61: $result = $definition->info[$property]->validate(
62: $value, $config, $context );
63: } else {
64: $result = 'inherit';
65: }
66: if ($result === false) continue;
67: $propvalues[$property] = $result;
68: }
69:
70: $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: $new_declarations = '';
77: foreach ($propvalues as $prop => $value) {
78: $new_declarations .= "$prop:$value;";
79: }
80:
81: return $new_declarations ? $new_declarations : false;
82:
83: }
84:
85: }
86:
87: // vim: et sw=4 sts=4
88: