3 require_once 'HTMLPurifier/AttrDef.php';
6 * Validates Color as defined by CSS.
8 class HTMLPurifier_AttrDef_CSS_Color
extends HTMLPurifier_AttrDef
12 * Color keyword lookup table.
13 * @todo Extend it to include all usually allowed colors.
16 'maroon' => '#800000',
18 'orange' => '#FFA500',
21 'purple' => '#800080',
31 'silver' => '#C0C0C0',
35 function validate($color, $config, &$context) {
37 $color = trim($color);
38 if (!$color) return false;
40 $lower = strtolower($color);
41 if (isset($this->colors
[$lower])) return $this->colors
[$lower];
43 if ($color[0] === '#') {
44 // hexadecimal handling
45 $hex = substr($color, 1);
46 $length = strlen($hex);
47 if ($length !== 3 && $length !== 6) return false;
48 if (!ctype_xdigit($hex)) return false;
50 // rgb literal handling
51 if (strpos($color, 'rgb(')) return false;
52 $length = strlen($color);
53 if (strpos($color, ')') !== $length - 1) return false;
54 $triad = substr($color, 4, $length - 4 - 1);
55 $parts = explode(',', $triad);
56 if (count($parts) !== 3) return false;
57 $type = false; // to ensure that they're all the same type
59 foreach ($parts as $part) {
61 if ($part === '') return false;
62 $length = strlen($part);
63 if ($part[$length - 1] === '%') {
67 } elseif ($type !== 'percentage') {
70 $num = (float) substr($part, 0, $length - 1);
71 if ($num < 0) $num = 0;
72 if ($num > 100) $num = 100;
73 $new_parts[] = "$num%";
78 } elseif ($type !== 'integer') {
82 if ($num < 0) $num = 0;
83 if ($num > 255) $num = 255;
84 $new_parts[] = (string) $num;
87 $new_triad = implode(',', $new_parts);
88 $color = "rgb($new_triad)";