1 : <?php
2 :
3 : /**
4 : * Validates Color as defined by CSS.
5 : */
6 1 : class HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef
7 : {
8 :
9 : public function validate($color, $config, $context) {
10 :
11 0 : static $colors = null;
12 0 : if ($colors === null) $colors = $config->get('Core', 'ColorKeywords');
13 :
14 0 : $color = trim($color);
15 0 : if ($color === '') return false;
16 :
17 0 : $lower = strtolower($color);
18 0 : if (isset($colors[$lower])) return $colors[$lower];
19 :
20 0 : if (strpos($color, 'rgb(') !== false) {
21 : // rgb literal handling
22 0 : $length = strlen($color);
23 0 : if (strpos($color, ')') !== $length - 1) return false;
24 0 : $triad = substr($color, 4, $length - 4 - 1);
25 0 : $parts = explode(',', $triad);
26 0 : if (count($parts) !== 3) return false;
27 0 : $type = false; // to ensure that they're all the same type
28 0 : $new_parts = array();
29 0 : foreach ($parts as $part) {
30 0 : $part = trim($part);
31 0 : if ($part === '') return false;
32 0 : $length = strlen($part);
33 0 : if ($part[$length - 1] === '%') {
34 : // handle percents
35 0 : if (!$type) {
36 0 : $type = 'percentage';
37 0 : } elseif ($type !== 'percentage') {
38 0 : return false;
39 : }
40 0 : $num = (float) substr($part, 0, $length - 1);
41 0 : if ($num < 0) $num = 0;
42 0 : if ($num > 100) $num = 100;
43 0 : $new_parts[] = "$num%";
44 0 : } else {
45 : // handle integers
46 0 : if (!$type) {
47 0 : $type = 'integer';
48 0 : } elseif ($type !== 'integer') {
49 0 : return false;
50 : }
51 0 : $num = (int) $part;
52 0 : if ($num < 0) $num = 0;
53 0 : if ($num > 255) $num = 255;
54 0 : $new_parts[] = (string) $num;
55 : }
56 0 : }
57 0 : $new_triad = implode(',', $new_parts);
58 0 : $color = "rgb($new_triad)";
59 0 : } else {
60 : // hexadecimal handling
61 0 : if ($color[0] === '#') {
62 0 : $hex = substr($color, 1);
63 0 : } else {
64 0 : $hex = $color;
65 0 : $color = '#' . $color;
66 : }
67 0 : $length = strlen($hex);
68 0 : if ($length !== 3 && $length !== 6) return false;
69 0 : if (!ctype_xdigit($hex)) return false;
70 : }
71 :
72 0 : return $color;
73 :
74 : }
75 :
76 : }
77 :
|