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 $xmlrpcI8 = "i8";
14 public static $xmlrpcInt = "int";
15 public static $xmlrpcBoolean = "boolean";
16 public static $xmlrpcDouble = "double";
17 public static $xmlrpcString = "string";
18 public static $xmlrpcDateTime = "dateTime.iso8601";
19 public static $xmlrpcBase64 = "base64";
20 public static $xmlrpcArray = "array";
21 public static $xmlrpcStruct = "struct";
22 public static $xmlrpcValue = "undefined";
23 public static $xmlrpcNull = "null";
25 public static $xmlrpcTypes = array(
32 "dateTime.iso8601" => 1,
39 /// @todo: do these need to be public?
42 public $_php_class = null;
45 * Build an xmlrpc value.
47 * When no value or type is passed in, the value is left uninitialized, and the value can be added later.
49 * @param mixed $val if passing in an array, all array elements should be PhpXmlRpc\Value themselves
50 * @param string $type any valid xmlrpc type name (lowercase): i4, int, boolean, string, double, dateTime.iso8601,
51 * base64, array, struct, null.
52 * If null, 'string' is assumed.
53 * You should refer to http://www.xmlrpc.com/spec for more information on what each of these mean.
55 public function __construct($val = -1, $type = '')
57 // optimization creep - do not call addXX, do it all inline.
58 // downside: booleans will not be coerced anymore
59 if ($val !== -1 || $type != '') {
63 $this->me['string'] = $val;
71 case 'dateTime.iso8601':
75 $this->me[$type] = $val;
79 $this->me['array'] = $val;
83 $this->me['struct'] = $val;
86 error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
92 * Add a single php value to an xmlrpc value.
94 * If the xmlrpc value is an array, the php value is added as its last element.
95 * If the xmlrpc value is empty (uninitialized), this method makes it a scalar value, and sets that value.
96 * Fails if the xmlrpc value is not an array and already initialized.
99 * @param string $type allowed values: i4, i8, int, boolean, string, double, dateTime.iso8601, base64, null.
101 * @return int 1 or 0 on failure
103 public function addScalar($val, $type = 'string')
106 if (isset(static::$xmlrpcTypes[$type])) {
107 $typeOf = static::$xmlrpcTypes[$type];
111 error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
115 // coerce booleans into correct values
116 // NB: we should either do it for datetimes, integers, i8 and doubles, too,
117 // or just plain remove this check, implemented on booleans only...
118 if ($type == static::$xmlrpcBoolean) {
119 if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
126 switch ($this->mytype) {
128 error_log('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
131 error_log('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
134 // we're adding a scalar value to an array here
135 $this->me['array'][] = new Value($val, $type);
139 // a scalar, so set the value and remember we're scalar
140 $this->me[$type] = $val;
141 $this->mytype = $typeOf;
148 * Add an array of xmlrpc value objects to an xmlrpc value.
150 * If the xmlrpc value is an array, the elements are appended to the existing ones.
151 * If the xmlrpc value is empty (uninitialized), this method makes it an array value, and sets that value.
154 * @param Value[] $values
156 * @return int 1 or 0 on failure
158 * @todo add some checking for $values to be an array of xmlrpc values?
160 public function addArray($values)
162 if ($this->mytype == 0) {
163 $this->mytype = static::$xmlrpcTypes['array'];
164 $this->me['array'] = $values;
167 } elseif ($this->mytype == 2) {
168 // we're adding to an array here
169 $this->me['array'] = array_merge($this->me['array'], $values);
173 error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
179 * Merges an array of named xmlrpc value objects into an xmlrpc value.
181 * If the xmlrpc value is a struct, the elements are merged with the existing ones (overwriting existing ones).
182 * If the xmlrpc value is empty (uninitialized), this method makes it a struct value, and sets that value.
185 * @param Value[] $values
187 * @return int 1 or 0 on failure
189 * @todo add some checking for $values to be an array?
191 public function addStruct($values)
193 if ($this->mytype == 0) {
194 $this->mytype = static::$xmlrpcTypes['struct'];
195 $this->me['struct'] = $values;
198 } elseif ($this->mytype == 3) {
199 // we're adding to a struct here
200 $this->me['struct'] = array_merge($this->me['struct'], $values);
204 error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
210 * Returns a string containing either "struct", "array", "scalar" or "undef", describing the base type of the value.
214 public function kindOf()
216 switch ($this->mytype) {
231 protected function serializedata($typ, $val, $charsetEncoding = '')
235 if (!isset(static::$xmlrpcTypes[$typ])) {
239 switch (static::$xmlrpcTypes[$typ]) {
242 case static::$xmlrpcBase64:
243 $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
245 case static::$xmlrpcBoolean:
246 $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
248 case static::$xmlrpcString:
249 // Do NOT use htmlentities, since it will produce named html entities, which are invalid xml
250 $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</${typ}>";
252 case static::$xmlrpcInt:
253 case static::$xmlrpcI4:
254 case static::$xmlrpcI8:
255 $rs .= "<${typ}>" . (int)$val . "</${typ}>";
257 case static::$xmlrpcDouble:
258 // avoid using standard conversion of float to string because it is locale-dependent,
259 // and also because the xmlrpc spec forbids exponential notation.
260 // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
261 // The code below tries its best at keeping max precision while avoiding exp notation,
262 // but there is of course no limit in the number of decimal places to be used...
263 $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, 128, '.', '')) . "</${typ}>";
265 case static::$xmlrpcDateTime:
266 if (is_string($val)) {
267 $rs .= "<${typ}>${val}</${typ}>";
268 } elseif (is_a($val, 'DateTime')) {
269 $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "</${typ}>";
270 } elseif (is_int($val)) {
271 $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "</${typ}>";
273 // not really a good idea here: but what shall we output anyway? left for backward compat...
274 $rs .= "<${typ}>${val}</${typ}>";
277 case static::$xmlrpcNull:
278 if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
285 // no standard type value should arrive here, but provide a possibility
286 // for xmlrpc values of unknown type...
287 $rs .= "<${typ}>${val}</${typ}>";
292 if ($this->_php_class) {
293 $rs .= '<struct php_class="' . $this->_php_class . "\">\n";
297 $charsetEncoder = Charset::instance();
298 /** @var Value $val2 */
299 foreach ($val as $key2 => $val2) {
300 $rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
301 //$rs.=$this->serializeval($val2);
302 $rs .= $val2->serialize($charsetEncoding);
303 $rs .= "</member>\n";
309 $rs .= "<array>\n<data>\n";
310 /** @var Value $element */
311 foreach ($val as $element) {
312 //$rs.=$this->serializeval($val[$i]);
313 $rs .= $element->serialize($charsetEncoding);
315 $rs .= "</data>\n</array>";
325 * Returns the xml representation of the value. XML prologue not included.
327 * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
331 public function serialize($charsetEncoding = '')
333 $val = reset($this->me);
334 $typ = key($this->me);
336 return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
340 * Checks whether a struct member with a given name is present.
342 * Works only on xmlrpc values of type struct.
344 * @param string $key the name of the struct member to be looked up
348 * @deprecated use array access, e.g. isset($val[$key])
350 public function structmemexists($key)
352 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
354 return array_key_exists($key, $this->me['struct']);
358 * Returns the value of a given struct member (an xmlrpc value object in itself).
359 * Will raise a php warning if struct member of given name does not exist.
361 * @param string $key the name of the struct member to be looked up
365 * @deprecated use array access, e.g. $val[$key]
367 public function structmem($key)
369 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
371 return $this->me['struct'][$key];
375 * Reset internal pointer for xmlrpc values of type struct.
376 * @deprecated iterate directly over the object using foreach instead
378 public function structreset()
380 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
382 reset($this->me['struct']);
386 * Return next member element for xmlrpc values of type struct.
390 * @deprecated iterate directly over the object using foreach instead
392 public function structeach()
394 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
396 return @each($this->me['struct']);
400 * Returns the value of a scalar xmlrpc value (base 64 decoding is automatically handled here)
404 public function scalarval()
406 $b = reset($this->me);
412 * Returns the type of the xmlrpc value.
414 * For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and returned as such
418 public function scalartyp()
422 if ($a == static::$xmlrpcI4) {
423 $a = static::$xmlrpcInt;
430 * Returns the m-th member of an xmlrpc value of array type.
432 * @param integer $key the index of the value to be retrieved (zero based)
436 * @deprecated use array access, e.g. $val[$key]
438 public function arraymem($key)
440 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
442 return $this->me['array'][$key];
446 * Returns the number of members in an xmlrpc value of array type.
450 * @deprecated use count() instead
452 public function arraysize()
454 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
456 return count($this->me['array']);
460 * Returns the number of members in an xmlrpc value of struct type.
464 * @deprecated use count() instead
466 public function structsize()
468 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
470 return count($this->me['struct']);
474 * Returns the number of members in an xmlrpc value:
475 * - 0 for uninitialized values
476 * - 1 for scalar values
477 * - the number of elements for struct and array values
481 public function count()
483 switch ($this->mytype) {
485 return count($this->me['struct']);
487 return count($this->me['array']);
496 * Implements the IteratorAggregate interface
498 * @return \ArrayIterator
500 public function getIterator() {
501 switch ($this->mytype) {
503 return new \ArrayIterator($this->me['struct']);
505 return new \ArrayIterator($this->me['array']);
507 return new \ArrayIterator($this->me);
509 return new \ArrayIterator();
513 public function offsetSet($offset, $value) {
515 switch ($this->mytype) {
517 if (!($value instanceof \PhpXmlRpc\Value)) {
518 throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct');
520 if (is_null($offset)) {
521 // disallow struct members with empty names
522 throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct');
524 $this->me['struct'][$offset] = $value;
528 if (!($value instanceof \PhpXmlRpc\Value)) {
529 throw new \Exception('It is only possible to add Value objects to an XML-RPC Array');
531 if (is_null($offset)) {
532 $this->me['array'][] = $value;
534 // nb: we are not checking that $offset is above the existing array range...
535 $this->me['array'][$offset] = $value;
539 // todo: handle i4 vs int
541 $type = key($this->me);
542 if ($type != $offset) {
543 throw new \Exception('');
545 $this->me[$type] = $value;
548 // 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
549 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be set using array index");
553 public function offsetExists($offset) {
554 switch ($this->mytype) {
556 return isset($this->me['struct'][$offset]);
558 return isset($this->me['array'][$offset]);
560 // todo: handle i4 vs int
561 return $offset == $this->scalartyp();
567 public function offsetUnset($offset) {
568 switch ($this->mytype) {
570 unset($this->me['struct'][$offset]);
573 unset($this->me['array'][$offset]);
576 // can not remove value from a scalar
577 throw new \Exception("XML-RPC Value is of type 'scalar' and its value can not be unset using array index");
579 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
583 public function offsetGet($offset) {
584 switch ($this->mytype) {
586 return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null;
588 return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
590 // on bad type: null or exception?
591 $value = reset($this->me);
592 $type = key($this->me);
593 return $type == $offset ? $value : null;
595 // return null or exception?
596 throw new \Exception("XML-RPC Value is of type 'undef' and can not be accessed using array index");