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 /// @todo: do these need to be public?
41 /** @var Value[]|mixed */
43 /** @var int $mytype */
45 /** @var string|null $_php_class */
46 public $_php_class = null;
49 * Build an xmlrpc value.
51 * When no value or type is passed in, the value is left uninitialized, and the value can be added later.
53 * @param mixed $val if passing in an array, all array elements should be PhpXmlRpc\Value themselves
54 * @param string $type any valid xmlrpc type name (lowercase): i4, int, boolean, string, double, dateTime.iso8601,
55 * base64, array, struct, null.
56 * If null, 'string' is assumed.
57 * You should refer to http://www.xmlrpc.com/spec for more information on what each of these mean.
59 public function __construct($val = -1, $type = '')
61 // optimization creep - do not call addXX, do it all inline.
62 // downside: booleans will not be coerced anymore
63 if ($val !== -1 || $type != '') {
67 $this->me['string'] = $val;
75 case 'dateTime.iso8601':
79 $this->me[$type] = $val;
83 $this->me['array'] = $val;
87 $this->me['struct'] = $val;
90 Logger::instance()->errorLog("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
96 * Add a single php value to an xmlrpc value.
98 * If the xmlrpc value is an array, the php value is added as its last element.
99 * If the xmlrpc value is empty (uninitialized), this method makes it a scalar value, and sets that value.
100 * Fails if the xmlrpc value is not an array and already initialized.
103 * @param string $type allowed values: i4, i8, int, boolean, string, double, dateTime.iso8601, base64, null.
105 * @return int 1 or 0 on failure
107 public function addScalar($val, $type = 'string')
110 if (isset(static::$xmlrpcTypes[$type])) {
111 $typeOf = static::$xmlrpcTypes[$type];
115 Logger::instance()->errorLog("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
119 // coerce booleans into correct values
120 // NB: we should either do it for datetimes, integers, i8 and doubles, too,
121 // or just plain remove this check, implemented on booleans only...
122 if ($type == static::$xmlrpcBoolean) {
123 if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
130 switch ($this->mytype) {
132 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
135 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
138 // we're adding a scalar value to an array here
139 $this->me['array'][] = new Value($val, $type);
143 // a scalar, so set the value and remember we're scalar
144 $this->me[$type] = $val;
145 $this->mytype = $typeOf;
152 * Add an array of xmlrpc value objects to an xmlrpc value.
154 * If the xmlrpc value is an array, the elements are appended to the existing ones.
155 * If the xmlrpc value is empty (uninitialized), this method makes it an array value, and sets that value.
158 * @param Value[] $values
160 * @return int 1 or 0 on failure
162 * @todo add some checking for $values to be an array of xmlrpc values?
164 public function addArray($values)
166 if ($this->mytype == 0) {
167 $this->mytype = static::$xmlrpcTypes['array'];
168 $this->me['array'] = $values;
171 } elseif ($this->mytype == 2) {
172 // we're adding to an array here
173 $this->me['array'] = array_merge($this->me['array'], $values);
177 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
183 * Merges an array of named xmlrpc value objects into an xmlrpc value.
185 * If the xmlrpc value is a struct, the elements are merged with the existing ones (overwriting existing ones).
186 * If the xmlrpc value is empty (uninitialized), this method makes it a struct value, and sets that value.
189 * @param Value[] $values
191 * @return int 1 or 0 on failure
193 * @todo add some checking for $values to be an array?
195 public function addStruct($values)
197 if ($this->mytype == 0) {
198 $this->mytype = static::$xmlrpcTypes['struct'];
199 $this->me['struct'] = $values;
202 } elseif ($this->mytype == 3) {
203 // we're adding to a struct here
204 $this->me['struct'] = array_merge($this->me['struct'], $values);
208 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
214 * Returns a string containing either "struct", "array", "scalar" or "undef", describing the base type of the value.
218 public function kindOf()
220 switch ($this->mytype) {
232 protected function serializedata($typ, $val, $charsetEncoding = '')
236 if (!isset(static::$xmlrpcTypes[$typ])) {
240 switch (static::$xmlrpcTypes[$typ]) {
243 case static::$xmlrpcBase64:
244 $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
246 case static::$xmlrpcBoolean:
247 $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
249 case static::$xmlrpcString:
250 // Do NOT use htmlentities, since it will produce named html entities, which are invalid xml
251 $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</${typ}>";
253 case static::$xmlrpcInt:
254 case static::$xmlrpcI4:
255 case static::$xmlrpcI8:
256 $rs .= "<${typ}>" . (int)$val . "</${typ}>";
258 case static::$xmlrpcDouble:
259 // avoid using standard conversion of float to string because it is locale-dependent,
260 // and also because the xmlrpc spec forbids exponential notation.
261 // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
262 // The code below tries its best at keeping max precision while avoiding exp notation,
263 // but there is of course no limit in the number of decimal places to be used...
264 $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, PhpXmlRpc::$xmlpc_double_precision, '.', '')) . "</${typ}>";
266 case static::$xmlrpcDateTime:
267 if (is_string($val)) {
268 $rs .= "<${typ}>${val}</${typ}>";
269 } elseif (is_a($val, 'DateTime')) {
270 $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "</${typ}>";
271 } elseif (is_int($val)) {
272 $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "</${typ}>";
274 // not really a good idea here: but what shall we output anyway? left for backward compat...
275 $rs .= "<${typ}>${val}</${typ}>";
278 case static::$xmlrpcNull:
279 if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
286 // no standard type value should arrive here, but provide a possibility
287 // for xmlrpc values of unknown type...
288 $rs .= "<${typ}>${val}</${typ}>";
293 if ($this->_php_class) {
294 $rs .= '<struct php_class="' . $this->_php_class . "\">\n";
298 $charsetEncoder = Charset::instance();
299 /** @var Value $val2 */
300 foreach ($val as $key2 => $val2) {
301 $rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
302 //$rs.=$this->serializeval($val2);
303 $rs .= $val2->serialize($charsetEncoding);
304 $rs .= "</member>\n";
310 $rs .= "<array>\n<data>\n";
311 /** @var Value $element */
312 foreach ($val as $element) {
313 //$rs.=$this->serializeval($val[$i]);
314 $rs .= $element->serialize($charsetEncoding);
316 $rs .= "</data>\n</array>";
326 * Returns the xml representation of the value. XML prologue not included.
328 * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
332 public function serialize($charsetEncoding = '')
334 $val = reset($this->me);
335 $typ = key($this->me);
337 return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
341 * Checks whether a struct member with a given name is present.
343 * Works only on xmlrpc values of type struct.
345 * @param string $key the name of the struct member to be looked up
349 * @deprecated use array access, e.g. isset($val[$key])
351 public function structmemexists($key)
353 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
355 return array_key_exists($key, $this->me['struct']);
359 * Returns the value of a given struct member (an xmlrpc value object in itself).
360 * Will raise a php warning if struct member of given name does not exist.
362 * @param string $key the name of the struct member to be looked up
366 * @deprecated use array access, e.g. $val[$key]
368 public function structmem($key)
370 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
372 return $this->me['struct'][$key];
376 * Reset internal pointer for xmlrpc values of type struct.
377 * @deprecated iterate directly over the object using foreach instead
379 public function structreset()
381 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
383 reset($this->me['struct']);
387 * Return next member element for xmlrpc values of type struct.
390 * @throws \Error starting with php 8.0, this function should not be used, as it will always throw
392 * @deprecated iterate directly over the object using foreach instead
394 public function structeach()
396 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
398 return @each($this->me['struct']);
402 * Returns the value of a scalar xmlrpc value (base 64 decoding is automatically handled here)
406 public function scalarval()
408 $b = reset($this->me);
414 * Returns the type of the xmlrpc value.
416 * For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and returned as such
420 public function scalartyp()
424 if ($a == static::$xmlrpcI4) {
425 $a = static::$xmlrpcInt;
432 * Returns the m-th member of an xmlrpc value of array type.
434 * @param integer $key the index of the value to be retrieved (zero based)
438 * @deprecated use array access, e.g. $val[$key]
440 public function arraymem($key)
442 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
444 return $this->me['array'][$key];
448 * Returns the number of members in an xmlrpc value of array type.
452 * @deprecated use count() instead
454 public function arraysize()
456 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
458 return count($this->me['array']);
462 * Returns the number of members in an xmlrpc value of struct type.
466 * @deprecated use count() instead
468 public function structsize()
470 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
472 return count($this->me['struct']);
476 * Returns the number of members in an xmlrpc value:
477 * - 0 for uninitialized values
478 * - 1 for scalar values
479 * - the number of elements for struct and array values
483 public function count()
485 switch ($this->mytype) {
487 return count($this->me['struct']);
489 return count($this->me['array']);
498 * Implements the IteratorAggregate interface
500 * @return \ArrayIterator
502 public function getIterator()
504 switch ($this->mytype) {
506 return new \ArrayIterator($this->me['struct']);
508 return new \ArrayIterator($this->me['array']);
510 return new \ArrayIterator($this->me);
512 return new \ArrayIterator();
516 public function offsetSet($offset, $value)
518 switch ($this->mytype) {
520 if (!($value instanceof \PhpXmlRpc\Value)) {
521 throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct');
523 if (is_null($offset)) {
524 // disallow struct members with empty names
525 throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct');
527 $this->me['struct'][$offset] = $value;
531 if (!($value instanceof \PhpXmlRpc\Value)) {
532 throw new \Exception('It is only possible to add Value objects to an XML-RPC Array');
534 if (is_null($offset)) {
535 $this->me['array'][] = $value;
537 // nb: we are not checking that $offset is above the existing array range...
538 $this->me['array'][$offset] = $value;
542 // todo: handle i4 vs int
544 $type = key($this->me);
545 if ($type != $offset) {
546 throw new \Exception('');
548 $this->me[$type] = $value;
551 // 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
552 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be set using array index");
556 public function offsetExists($offset)
558 switch ($this->mytype) {
560 return isset($this->me['struct'][$offset]);
562 return isset($this->me['array'][$offset]);
564 // todo: handle i4 vs int
565 return $offset == $this->scalartyp();
571 public function offsetUnset($offset)
573 switch ($this->mytype) {
575 unset($this->me['struct'][$offset]);
578 unset($this->me['array'][$offset]);
581 // can not remove value from a scalar
582 throw new \Exception("XML-RPC Value is of type 'scalar' and its value can not be unset using array index");
584 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
588 public function offsetGet($offset)
590 switch ($this->mytype) {
592 return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null;
594 return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
596 // on bad type: null or exception?
597 $value = reset($this->me);
598 $type = key($this->me);
599 return $type == $offset ? $value : null;
601 // return null or exception?
602 throw new \Exception("XML-RPC Value is of type 'undef' and can not be accessed using array index");