[3.0.0] [BACKPORT] More work for hire from Chris
[htmlpurifier/bfroehle.git] / library / HTMLPurifier / AttrDef / CSS / Color.php
blobb86dc0913fd9ed593b679c37c6f02f7b7d59c0a6
1 <?php
3 require_once 'HTMLPurifier/AttrDef.php';
5 HTMLPurifier_ConfigSchema::define(
6 'Core', 'ColorKeywords', array(
7 'maroon' => '#800000',
8 'red' => '#FF0000',
9 'orange' => '#FFA500',
10 'yellow' => '#FFFF00',
11 'olive' => '#808000',
12 'purple' => '#800080',
13 'fuchsia' => '#FF00FF',
14 'white' => '#FFFFFF',
15 'lime' => '#00FF00',
16 'green' => '#008000',
17 'navy' => '#000080',
18 'blue' => '#0000FF',
19 'aqua' => '#00FFFF',
20 'teal' => '#008080',
21 'black' => '#000000',
22 'silver' => '#C0C0C0',
23 'gray' => '#808080'
24 ), 'hash', '
25 Lookup array of color names to six digit hexadecimal number corresponding
26 to color, with preceding hash mark. Used when parsing colors.
27 This directive has been available since 2.0.0.
28 ');
30 /**
31 * Validates Color as defined by CSS.
33 class HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef
36 public function validate($color, $config, &$context) {
38 static $colors = null;
39 if ($colors === null) $colors = $config->get('Core', 'ColorKeywords');
41 $color = trim($color);
42 if ($color === '') return false;
44 $lower = strtolower($color);
45 if (isset($colors[$lower])) return $colors[$lower];
47 if (strpos($color, 'rgb(') !== false) {
48 // rgb literal handling
49 $length = strlen($color);
50 if (strpos($color, ')') !== $length - 1) return false;
51 $triad = substr($color, 4, $length - 4 - 1);
52 $parts = explode(',', $triad);
53 if (count($parts) !== 3) return false;
54 $type = false; // to ensure that they're all the same type
55 $new_parts = array();
56 foreach ($parts as $part) {
57 $part = trim($part);
58 if ($part === '') return false;
59 $length = strlen($part);
60 if ($part[$length - 1] === '%') {
61 // handle percents
62 if (!$type) {
63 $type = 'percentage';
64 } elseif ($type !== 'percentage') {
65 return false;
67 $num = (float) substr($part, 0, $length - 1);
68 if ($num < 0) $num = 0;
69 if ($num > 100) $num = 100;
70 $new_parts[] = "$num%";
71 } else {
72 // handle integers
73 if (!$type) {
74 $type = 'integer';
75 } elseif ($type !== 'integer') {
76 return false;
78 $num = (int) $part;
79 if ($num < 0) $num = 0;
80 if ($num > 255) $num = 255;
81 $new_parts[] = (string) $num;
84 $new_triad = implode(',', $new_parts);
85 $color = "rgb($new_triad)";
86 } else {
87 // hexadecimal handling
88 if ($color[0] === '#') {
89 $hex = substr($color, 1);
90 } else {
91 $hex = $color;
92 $color = '#' . $color;
94 $length = strlen($hex);
95 if ($length !== 3 && $length !== 6) return false;
96 if (!ctype_xdigit($hex)) return false;
99 return $color;