4 * Validates Color as defined by CSS.
6 class HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef
9 public function validate($color, $config, $context) {
11 static $colors = null;
12 if ($colors === null) $colors = $config->get('Core.ColorKeywords');
14 $color = trim($color);
15 if ($color === '') return false;
17 $lower = strtolower($color);
18 if (isset($colors[$lower])) return $colors[$lower];
20 if (strpos($color, 'rgb(') !== false) {
21 // rgb literal handling
22 $length = strlen($color);
23 if (strpos($color, ')') !== $length - 1) return false;
24 $triad = substr($color, 4, $length - 4 - 1);
25 $parts = explode(',', $triad);
26 if (count($parts) !== 3) return false;
27 $type = false; // to ensure that they're all the same type
29 foreach ($parts as $part) {
31 if ($part === '') return false;
32 $length = strlen($part);
33 if ($part[$length - 1] === '%') {
37 } elseif ($type !== 'percentage') {
40 $num = (float) substr($part, 0, $length - 1);
41 if ($num < 0) $num = 0;
42 if ($num > 100) $num = 100;
43 $new_parts[] = "$num%";
48 } elseif ($type !== 'integer') {
52 if ($num < 0) $num = 0;
53 if ($num > 255) $num = 255;
54 $new_parts[] = (string) $num;
57 $new_triad = implode(',', $new_parts);
58 $color = "rgb($new_triad)";
60 // hexadecimal handling
61 if ($color[0] === '#') {
62 $hex = substr($color, 1);
65 $color = '#' . $color;
67 $length = strlen($hex);
68 if ($length !== 3 && $length !== 6) return false;
69 if (!ctype_xdigit($hex)) return false;