5 use PhpXmlRpc\Helper\Charset;
8 * This class enables the creation of values for XML-RPC, by encapsulating plain php values.
10 class Value implements \Countable, \IteratorAggregate, \ArrayAccess
12 public static $xmlrpcI4 = "i4";
13 public static $xmlrpcInt = "int";
14 public static $xmlrpcBoolean = "boolean";
15 public static $xmlrpcDouble = "double";
16 public static $xmlrpcString = "string";
17 public static $xmlrpcDateTime = "dateTime.iso8601";
18 public static $xmlrpcBase64 = "base64";
19 public static $xmlrpcArray = "array";
20 public static $xmlrpcStruct = "struct";
21 public static $xmlrpcValue = "undefined";
22 public static $xmlrpcNull = "null";
24 public static $xmlrpcTypes = array(
30 "dateTime.iso8601" => 1,
37 /// @todo: do these need to be public?
40 public $_php_class = null;
43 * Build an xmlrpc value.
45 * When no value or type is passed in, the value is left uninitialized, and the value can be added later.
47 * @param mixed $val if passing in an array, all array elements should be PhpXmlRpc\Value themselves
48 * @param string $type any valid xmlrpc type name (lowercase): i4, int, boolean, string, double, dateTime.iso8601,
49 * base64, array, struct, null.
50 * If null, 'string' is assumed.
51 * You should refer to http://www.xmlrpc.com/spec for more information on what each of these mean.
53 public function __construct($val = -1, $type = '')
55 // optimization creep - do not call addXX, do it all inline.
56 // downside: booleans will not be coerced anymore
57 if ($val !== -1 || $type != '') {
61 $this->me['string'] = $val;
68 case 'dateTime.iso8601':
72 $this->me[$type] = $val;
76 $this->me['array'] = $val;
80 $this->me['struct'] = $val;
83 error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
89 * Add a single php value to an xmlrpc value.
91 * If the xmlrpc value is an array, the php value is added as its last element.
92 * If the xmlrpc value is empty (uninitialized), this method makes it a scalar value, and sets that value.
93 * Fails if the xmlrpc value is not an array and already initialized.
96 * @param string $type allowed values: i4, int, boolean, string, double, dateTime.iso8601, base64, null.
98 * @return int 1 or 0 on failure
100 public function addScalar($val, $type = 'string')
103 if (isset(static::$xmlrpcTypes[$type])) {
104 $typeOf = static::$xmlrpcTypes[$type];
108 error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
112 // coerce booleans into correct values
113 // NB: we should either do it for datetimes, integers and doubles, too,
114 // or just plain remove this check, implemented on booleans only...
115 if ($type == static::$xmlrpcBoolean) {
116 if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
123 switch ($this->mytype) {
125 error_log('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
128 error_log('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
131 // we're adding a scalar value to an array here
132 $this->me['array'][] = new Value($val, $type);
136 // a scalar, so set the value and remember we're scalar
137 $this->me[$type] = $val;
138 $this->mytype = $typeOf;
145 * Add an array of xmlrpc value objects to an xmlrpc value.
147 * If the xmlrpc value is an array, the elements are appended to the existing ones.
148 * If the xmlrpc value is empty (uninitialized), this method makes it an array value, and sets that value.
151 * @param Value[] $values
153 * @return int 1 or 0 on failure
155 * @todo add some checking for $values to be an array of xmlrpc values?
157 public function addArray($values)
159 if ($this->mytype == 0) {
160 $this->mytype = static::$xmlrpcTypes['array'];
161 $this->me['array'] = $values;
164 } elseif ($this->mytype == 2) {
165 // we're adding to an array here
166 $this->me['array'] = array_merge($this->me['array'], $values);
170 error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
176 * Merges an array of named xmlrpc value objects into an xmlrpc value.
178 * If the xmlrpc value is a struct, the elements are merged with the existing ones (overwriting existing ones).
179 * If the xmlrpc value is empty (uninitialized), this method makes it a struct value, and sets that value.
182 * @param Value[] $values
184 * @return int 1 or 0 on failure
186 * @todo add some checking for $values to be an array?
188 public function addStruct($values)
190 if ($this->mytype == 0) {
191 $this->mytype = static::$xmlrpcTypes['struct'];
192 $this->me['struct'] = $values;
195 } elseif ($this->mytype == 3) {
196 // we're adding to a struct here
197 $this->me['struct'] = array_merge($this->me['struct'], $values);
201 error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
207 * Returns a string containing either "struct", "array", "scalar" or "undef", describing the base type of the value.
211 public function kindOf()
213 switch ($this->mytype) {
228 protected function serializedata($typ, $val, $charsetEncoding = '')
232 if (!isset(static::$xmlrpcTypes[$typ])) {
236 switch (static::$xmlrpcTypes[$typ]) {
239 case static::$xmlrpcBase64:
240 $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
242 case static::$xmlrpcBoolean:
243 $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
245 case static::$xmlrpcString:
246 // G. Giunta 2005/2/13: do NOT use htmlentities, since
247 // it will produce named html entities, which are invalid xml
248 $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</${typ}>";
250 case static::$xmlrpcInt:
251 case static::$xmlrpcI4:
252 $rs .= "<${typ}>" . (int)$val . "</${typ}>";
254 case static::$xmlrpcDouble:
255 // avoid using standard conversion of float to string because it is locale-dependent,
256 // and also because the xmlrpc spec forbids exponential notation.
257 // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
258 // The code below tries its best at keeping max precision while avoiding exp notation,
259 // but there is of course no limit in the number of decimal places to be used...
260 $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, 128, '.', '')) . "</${typ}>";
262 case static::$xmlrpcDateTime:
263 if (is_string($val)) {
264 $rs .= "<${typ}>${val}</${typ}>";
265 } elseif (is_a($val, 'DateTime')) {
266 $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "</${typ}>";
267 } elseif (is_int($val)) {
268 $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "</${typ}>";
270 // not really a good idea here: but what shall we output anyway? left for backward compat...
271 $rs .= "<${typ}>${val}</${typ}>";
274 case static::$xmlrpcNull:
275 if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
282 // no standard type value should arrive here, but provide a possibility
283 // for xmlrpc values of unknown type...
284 $rs .= "<${typ}>${val}</${typ}>";
289 if ($this->_php_class) {
290 $rs .= '<struct php_class="' . $this->_php_class . "\">\n";
294 $charsetEncoder = Charset::instance();
295 foreach ($val as $key2 => $val2) {
296 $rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
297 //$rs.=$this->serializeval($val2);
298 $rs .= $val2->serialize($charsetEncoding);
299 $rs .= "</member>\n";
305 $rs .= "<array>\n<data>\n";
306 foreach ($val as $element) {
307 //$rs.=$this->serializeval($val[$i]);
308 $rs .= $element->serialize($charsetEncoding);
310 $rs .= "</data>\n</array>";
320 * Returns the xml representation of the value. XML prologue not included.
322 * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
326 public function serialize($charsetEncoding = '')
328 // add check? slower, but helps to avoid recursion in serializing broken xmlrpc values...
329 //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
332 list($typ, $val) = each($this->me);
334 return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
339 * Checks whether a struct member with a given name is present.
341 * Works only on xmlrpc values of type struct.
343 * @param string $key the name of the struct member to be looked up
347 * @deprecated use array access, e.g. isset($val[$key])
349 public function structmemexists($key)
351 return array_key_exists($key, $this->me['struct']);
355 * Returns the value of a given struct member (an xmlrpc value object in itself).
356 * Will raise a php warning if struct member of given name does not exist.
358 * @param string $key the name of the struct member to be looked up
362 * @deprecated use array access, e.g. $val[$key]
364 public function structmem($key)
366 return $this->me['struct'][$key];
370 * Reset internal pointer for xmlrpc values of type struct.
371 * @deprecated iterate directly over the object using foreach instead
373 public function structreset()
375 reset($this->me['struct']);
379 * Return next member element for xmlrpc values of type struct.
383 * @deprecated iterate directly over the object using foreach instead
385 public function structeach()
387 return each($this->me['struct']);
391 * Returns the value of a scalar xmlrpc value (base 64 decoding is automatically handled here)
395 public function scalarval()
398 list(, $b) = each($this->me);
404 * Returns the type of the xmlrpc value.
406 * For integers, 'int' is always returned in place of 'i4'.
410 public function scalartyp()
413 list($a,) = each($this->me);
414 if ($a == static::$xmlrpcI4) {
415 $a = static::$xmlrpcInt;
422 * Returns the m-th member of an xmlrpc value of array type.
424 * @param integer $key the index of the value to be retrieved (zero based)
428 * @deprecated use array access, e.g. $val[$key]
430 public function arraymem($key)
432 return $this->me['array'][$key];
436 * Returns the number of members in an xmlrpc value of array type.
440 * @deprecated use count() instead
442 public function arraysize()
444 return count($this->me['array']);
448 * Returns the number of members in an xmlrpc value of struct type.
452 * @deprecated use count() instead
454 public function structsize()
456 return count($this->me['struct']);
460 * Returns the number of members in an xmlrpc value:
461 * - 0 for uninitialized values
462 * - 1 for scalar values
463 * - the number of elements for struct and array values
467 public function count()
469 switch ($this->mytype) {
471 return count($this->me['struct']);
473 return count($this->me['array']);
482 * Implements the IteratorAggregate interface
484 * @return ArrayIterator
486 public function getIterator() {
487 switch ($this->mytype) {
489 return new \ArrayIterator($this->me['struct']);
491 return new \ArrayIterator($this->me['array']);
493 return new \ArrayIterator($this->me);
495 return new \ArrayIterator();
497 return new \ArrayIterator();
501 public function offsetSet($offset, $value) {
503 switch ($this->mytype) {
505 if (!($value instanceof \PhpXmlRpc\Value)) {
506 throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct');
508 if (is_null($offset)) {
509 // disallow struct members with empty names
510 throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct');
512 $this->me['struct'][$offset] = $value;
516 if (!($value instanceof \PhpXmlRpc\Value)) {
517 throw new \Exception('It is only possible to add Value objects to an XML-RPC Array');
519 if (is_null($offset)) {
520 $this->me['array'][] = $value;
522 // nb: we are not checking that $offset is above the existing array range...
523 $this->me['array'][$offset] = $value;
527 // todo: handle i4 vs int
529 list($type,) = each($this->me);
530 if ($type != $offset) {
531 throw new \Exception('');
533 $this->me[$type] = $value;
536 // it would be nice to allow empty values to be be turned into non-empty ones this way, but we miss info to do so
537 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be set using array index");
541 public function offsetExists($offset) {
542 switch ($this->mytype) {
544 return isset($this->me['struct'][$offset]);
546 return isset($this->me['array'][$offset]);
548 // todo: handle i4 vs int
549 return $offset == $this->scalartyp();
555 public function offsetUnset($offset) {
556 switch ($this->mytype) {
558 unset($this->me['struct'][$offset]);
561 unset($this->me['array'][$offset]);
564 // can not remove value from a scalar
565 throw new \Exception("XML-RPC Value is of type 'scalar' and its value can not be unset using array index");
567 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
571 public function offsetGet($offset) {
572 switch ($this->mytype) {
574 return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null;
576 return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
578 // on bad type: null or exception?
580 list($type, $value) = each($this->me);
581 return $type == $offset ? $value : null;
583 // return null or exception?
584 throw new \Exception("XML-RPC Value is of type 'undef' and can not be accessed using array index");