5 use PhpXmlRpc\Helper\Charset;
6 use PhpXmlRpc\Helper\Logger;
9 * This class enables the creation of values for XML-RPC, by encapsulating plain php values.
11 class Value implements \Countable, \IteratorAggregate, \ArrayAccess
13 public static $xmlrpcI4 = "i4";
14 public static $xmlrpcI8 = "i8";
15 public static $xmlrpcInt = "int";
16 public static $xmlrpcBoolean = "boolean";
17 public static $xmlrpcDouble = "double";
18 public static $xmlrpcString = "string";
19 public static $xmlrpcDateTime = "dateTime.iso8601";
20 public static $xmlrpcBase64 = "base64";
21 public static $xmlrpcArray = "array";
22 public static $xmlrpcStruct = "struct";
23 public static $xmlrpcValue = "undefined";
24 public static $xmlrpcNull = "null";
26 public static $xmlrpcTypes = array(
33 "dateTime.iso8601" => 1,
40 protected static $logger;
41 protected static $charsetEncoder;
43 /// @todo: do these need to be public?
44 /** @var Value[]|mixed */
51 /** @var string|null $_php_class */
52 public $_php_class = null;
54 public function getLogger()
56 if (self::$logger === null) {
57 self::$logger = Logger::instance();
62 public static function setLogger($logger)
64 self::$logger = $logger;
67 public function getCharsetEncoder()
69 if (self::$charsetEncoder === null) {
70 self::$charsetEncoder = Charset::instance();
72 return self::$charsetEncoder;
75 public function setCharsetEncoder($charsetEncoder)
77 self::$charsetEncoder = $charsetEncoder;
81 * Build an xmlrpc value.
83 * When no value or type is passed in, the value is left uninitialized, and the value can be added later.
85 * @param Value[]|mixed $val if passing in an array, all array elements should be PhpXmlRpc\Value themselves
86 * @param string $type any valid xmlrpc type name (lowercase): i4, int, boolean, string, double, dateTime.iso8601,
87 * base64, array, struct, null.
88 * If null, 'string' is assumed.
89 * You should refer to http://www.xmlrpc.com/spec for more information on what each of these mean.
91 public function __construct($val = -1, $type = '')
93 // optimization creep - do not call addXX, do it all inline.
94 // downside: booleans will not be coerced anymore
95 if ($val !== -1 || $type != '') {
99 $this->me['string'] = $val;
107 case 'dateTime.iso8601':
111 $this->me[$type] = $val;
115 $this->me['array'] = $val;
119 $this->me['struct'] = $val;
122 $this->getLogger()->errorLog("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
128 * Add a single php value to an xmlrpc value.
130 * If the xmlrpc value is an array, the php value is added as its last element.
131 * If the xmlrpc value is empty (uninitialized), this method makes it a scalar value, and sets that value.
132 * Fails if the xmlrpc value is not an array and already initialized.
135 * @param string $type allowed values: i4, i8, int, boolean, string, double, dateTime.iso8601, base64, null.
137 * @return int 1 or 0 on failure
139 public function addScalar($val, $type = 'string')
142 if (isset(static::$xmlrpcTypes[$type])) {
143 $typeOf = static::$xmlrpcTypes[$type];
147 $this->getLogger()->errorLog("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
151 // coerce booleans into correct values
152 // NB: we should either do it for datetimes, integers, i8 and doubles, too,
153 // or just plain remove this check, implemented on booleans only...
154 if ($type == static::$xmlrpcBoolean) {
155 if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
162 switch ($this->mytype) {
164 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
167 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
170 // we're adding a scalar value to an array here
171 $this->me['array'][] = new Value($val, $type);
175 // a scalar, so set the value and remember we're scalar
176 $this->me[$type] = $val;
177 $this->mytype = $typeOf;
184 * Add an array of xmlrpc value objects to an xmlrpc value.
186 * If the xmlrpc value is an array, the elements are appended to the existing ones.
187 * If the xmlrpc value is empty (uninitialized), this method makes it an array value, and sets that value.
190 * @param Value[] $values
192 * @return int 1 or 0 on failure
194 * @todo add some checking for $values to be an array of xmlrpc values?
196 public function addArray($values)
198 if ($this->mytype == 0) {
199 $this->mytype = static::$xmlrpcTypes['array'];
200 $this->me['array'] = $values;
203 } elseif ($this->mytype == 2) {
204 // we're adding to an array here
205 $this->me['array'] = array_merge($this->me['array'], $values);
209 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
215 * Merges an array of named xmlrpc value objects into an xmlrpc value.
217 * If the xmlrpc value is a struct, the elements are merged with the existing ones (overwriting existing ones).
218 * If the xmlrpc value is empty (uninitialized), this method makes it a struct value, and sets that value.
221 * @param Value[] $values
223 * @return int 1 or 0 on failure
225 * @todo add some checking for $values to be an array?
227 public function addStruct($values)
229 if ($this->mytype == 0) {
230 $this->mytype = static::$xmlrpcTypes['struct'];
231 $this->me['struct'] = $values;
234 } elseif ($this->mytype == 3) {
235 // we're adding to a struct here
236 $this->me['struct'] = array_merge($this->me['struct'], $values);
240 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
246 * Returns a string containing either "struct", "array", "scalar" or "undef", describing the base type of the value.
250 public function kindOf()
252 switch ($this->mytype) {
266 * @param Value[]|mixed $val
267 * @param string $charsetEncoding
270 protected function serializedata($typ, $val, $charsetEncoding = '')
274 if (!isset(static::$xmlrpcTypes[$typ])) {
278 switch (static::$xmlrpcTypes[$typ]) {
281 case static::$xmlrpcBase64:
282 $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
284 case static::$xmlrpcBoolean:
285 $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
287 case static::$xmlrpcString:
288 // Do NOT use htmlentities, since it will produce named html entities, which are invalid xml
289 $rs .= "<${typ}>" . $this->getCharsetEncoder()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</${typ}>";
291 case static::$xmlrpcInt:
292 case static::$xmlrpcI4:
293 case static::$xmlrpcI8:
294 $rs .= "<${typ}>" . (int)$val . "</${typ}>";
296 case static::$xmlrpcDouble:
297 // avoid using standard conversion of float to string because it is locale-dependent,
298 // and also because the xmlrpc spec forbids exponential notation.
299 // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
300 // The code below tries its best at keeping max precision while avoiding exp notation,
301 // but there is of course no limit in the number of decimal places to be used...
302 $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, PhpXmlRpc::$xmlpc_double_precision, '.', '')) . "</${typ}>";
304 case static::$xmlrpcDateTime:
305 if (is_string($val)) {
306 $rs .= "<${typ}>${val}</${typ}>";
307 } elseif (is_a($val, 'DateTime')) {
308 $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "</${typ}>";
309 } elseif (is_int($val)) {
310 $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "</${typ}>";
312 // not really a good idea here: but what shall we output anyway? left for backward compat...
313 $rs .= "<${typ}>${val}</${typ}>";
316 case static::$xmlrpcNull:
317 if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
324 // no standard type value should arrive here, but provide a possibility
325 // for xmlrpc values of unknown type...
326 $rs .= "<${typ}>${val}</${typ}>";
331 if ($this->_php_class) {
332 $rs .= '<struct php_class="' . $this->_php_class . "\">\n";
336 $charsetEncoder = $this->getCharsetEncoder();
337 /** @var Value $val2 */
338 foreach ($val as $key2 => $val2) {
339 $rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
340 //$rs.=$this->serializeval($val2);
341 $rs .= $val2->serialize($charsetEncoding);
342 $rs .= "</member>\n";
348 $rs .= "<array>\n<data>\n";
349 /** @var Value $element */
350 foreach ($val as $element) {
351 //$rs.=$this->serializeval($val[$i]);
352 $rs .= $element->serialize($charsetEncoding);
354 $rs .= "</data>\n</array>";
364 * Returns the xml representation of the value. XML prologue not included.
366 * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
370 public function serialize($charsetEncoding = '')
372 $val = reset($this->me);
373 $typ = key($this->me);
375 return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
379 * Checks whether a struct member with a given name is present.
381 * Works only on xmlrpc values of type struct.
383 * @param string $key the name of the struct member to be looked up
387 * @deprecated use array access, e.g. isset($val[$key])
389 public function structmemexists($key)
391 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
393 return array_key_exists($key, $this->me['struct']);
397 * Returns the value of a given struct member (an xmlrpc value object in itself).
398 * Will raise a php warning if struct member of given name does not exist.
400 * @param string $key the name of the struct member to be looked up
404 * @deprecated use array access, e.g. $val[$key]
406 public function structmem($key)
408 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
410 return $this->me['struct'][$key];
414 * Reset internal pointer for xmlrpc values of type struct.
415 * @deprecated iterate directly over the object using foreach instead
417 public function structreset()
419 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
421 reset($this->me['struct']);
425 * Return next member element for xmlrpc values of type struct.
428 * @throws \Error starting with php 8.0, this function should not be used, as it will always throw
430 * @deprecated iterate directly over the object using foreach instead
432 public function structeach()
434 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
436 return @each($this->me['struct']);
440 * Returns the value of a scalar xmlrpc value (base 64 decoding is automatically handled here)
444 public function scalarval()
446 $b = reset($this->me);
452 * Returns the type of the xmlrpc value.
454 * For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and returned as such
458 public function scalartyp()
462 if ($a == static::$xmlrpcI4) {
463 $a = static::$xmlrpcInt;
470 * Returns the m-th member of an xmlrpc value of array type.
472 * @param integer $key the index of the value to be retrieved (zero based)
476 * @deprecated use array access, e.g. $val[$key]
478 public function arraymem($key)
480 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
482 return $this->me['array'][$key];
486 * Returns the number of members in an xmlrpc value of array type.
490 * @deprecated use count() instead
492 public function arraysize()
494 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
496 return count($this->me['array']);
500 * Returns the number of members in an xmlrpc value of struct type.
504 * @deprecated use count() instead
506 public function structsize()
508 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
510 return count($this->me['struct']);
514 * Returns the number of members in an xmlrpc value:
515 * - 0 for uninitialized values
516 * - 1 for scalar values
517 * - the number of elements for struct and array values
521 #[\ReturnTypeWillChange]
522 public function count()
524 switch ($this->mytype) {
526 return count($this->me['struct']);
528 return count($this->me['array']);
537 * Implements the IteratorAggregate interface
539 * @return \ArrayIterator
540 * @internal required to be public to implement an Interface
542 #[\ReturnTypeWillChange]
543 public function getIterator()
545 switch ($this->mytype) {
547 return new \ArrayIterator($this->me['struct']);
549 return new \ArrayIterator($this->me['array']);
551 return new \ArrayIterator($this->me);
553 return new \ArrayIterator();
558 * @internal required to be public to implement an Interface
559 * @param mixed $offset
560 * @param mixed $value
563 #[\ReturnTypeWillChange]
564 public function offsetSet($offset, $value)
566 switch ($this->mytype) {
568 if (!($value instanceof \PhpXmlRpc\Value)) {
569 throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct');
571 if (is_null($offset)) {
572 // disallow struct members with empty names
573 throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct');
575 $this->me['struct'][$offset] = $value;
579 if (!($value instanceof \PhpXmlRpc\Value)) {
580 throw new \Exception('It is only possible to add Value objects to an XML-RPC Array');
582 if (is_null($offset)) {
583 $this->me['array'][] = $value;
585 // nb: we are not checking that $offset is above the existing array range...
586 $this->me['array'][$offset] = $value;
590 // todo: handle i4 vs int
592 $type = key($this->me);
593 if ($type != $offset) {
594 throw new \Exception('');
596 $this->me[$type] = $value;
599 // 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
600 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be set using array index");
605 * @internal required to be public to implement an Interface
606 * @param mixed $offset
609 #[\ReturnTypeWillChange]
610 public function offsetExists($offset)
612 switch ($this->mytype) {
614 return isset($this->me['struct'][$offset]);
616 return isset($this->me['array'][$offset]);
618 // todo: handle i4 vs int
619 return $offset == $this->scalartyp();
626 * @internal required to be public to implement an Interface
627 * @param mixed $offset
630 #[\ReturnTypeWillChange]
631 public function offsetUnset($offset)
633 switch ($this->mytype) {
635 unset($this->me['struct'][$offset]);
638 unset($this->me['array'][$offset]);
641 // can not remove value from a scalar
642 throw new \Exception("XML-RPC Value is of type 'scalar' and its value can not be unset using array index");
644 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
649 * @internal required to be public to implement an Interface
650 * @param mixed $offset
651 * @return mixed|Value|null
654 #[\ReturnTypeWillChange]
655 public function offsetGet($offset)
657 switch ($this->mytype) {
659 return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null;
661 return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
663 // on bad type: null or exception?
664 $value = reset($this->me);
665 $type = key($this->me);
666 return $type == $offset ? $value : null;
668 // return null or exception?
669 throw new \Exception("XML-RPC Value is of type 'undef' and can not be accessed using array index");