4 * Parses string representations into their corresponding native PHP
7 class HTMLPurifier_VarParser
11 * Lookup table of allowed types.
13 public $types = array(
28 * Validate a variable according to type. Throws exception if invalid.
29 * It may return NULL as a valid type.
31 public function parse($var, $type, $allow_null = false) {
32 if (!isset($this->types
[$type])) {
33 throw new HTMLPurifier_VarParserException("Invalid type $type");
35 if ($allow_null && $var === null) return null;
37 // Note: if code "breaks" from the switch, it triggers a generic
38 // exception to be thrown. Specific errors can be specifically
41 //if (is_string($var)) $var = unserialize($var);
45 case 'text': // no difference, just is longer/multiple line string
47 if (!is_string($var)) break;
48 if ($type === 'istring' ||
$type === 'itext') $var = strtolower($var);
51 if (is_string($var) && ctype_digit($var)) $var = (int) $var;
52 elseif (!is_int($var)) break;
55 if (is_string($var) && is_numeric($var)) $var = (float) $var;
56 elseif (!is_float($var)) break;
59 if (is_int($var) && ($var === 0 ||
$var === 1)) {
61 } elseif (is_string($var)) {
62 if ($var == 'on' ||
$var == 'true' ||
$var == '1') {
64 } elseif ($var == 'off' ||
$var == 'false' ||
$var == '0') {
67 throw new HTMLPurifier_VarParserException("Unrecognized value '$var' for $type");
69 } elseif (!is_bool($var)) break;
74 if (is_string($var)) {
75 // special case: technically, this is an array with
76 // a single empty string item, but having an empty
77 // array is more intuitive
78 if ($var == '') return array();
79 if (strpos($var, "\n") === false && strpos($var, "\r") === false) {
80 // simplistic string to array method that only works
81 // for simple lists of tag names or alphanumeric characters
82 $var = explode(',',$var);
84 $var = preg_split('/(,|[\n\r]+)/', $var);
87 foreach ($var as $i => $j) $var[$i] = trim($j);
88 if ($type === 'hash') {
89 // key:value,key2:value2
91 foreach ($var as $keypair) {
92 $c = explode(':', $keypair, 2);
93 if (!isset($c[1])) continue;
99 if (!is_array($var)) break;
100 $keys = array_keys($var);
101 if ($keys === array_keys($keys)) {
102 if ($type == 'list') return $var;
103 elseif ($type == 'lookup') {
105 foreach ($var as $key) {
111 if ($type === 'lookup') {
112 foreach ($var as $key => $value) {
118 // This should not happen!
119 throw new HTMLPurifier_Exception("Inconsistency in HTMLPurifier_VarParser: $type is not implemented");
121 throw new HTMLPurifier_VarParserException("Invalid input for type $type");