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 */
48 /** @var string|null $_php_class */
49 public $_php_class = null;
52 * Build an xmlrpc value.
54 * When no value or type is passed in, the value is left uninitialized, and the value can be added later.
56 * @param mixed $val if passing in an array, all array elements should be PhpXmlRpc\Value themselves
57 * @param string $type any valid xmlrpc type name (lowercase): i4, int, boolean, string, double, dateTime.iso8601,
58 * base64, array, struct, null.
59 * If null, 'string' is assumed.
60 * You should refer to http://www.xmlrpc.com/spec for more information on what each of these mean.
62 public function __construct($val = -1, $type = '')
64 // optimization creep - do not call addXX, do it all inline.
65 // downside: booleans will not be coerced anymore
66 if ($val !== -1 || $type != '') {
70 $this->me['string'] = $val;
78 case 'dateTime.iso8601':
82 $this->me[$type] = $val;
86 $this->me['array'] = $val;
90 $this->me['struct'] = $val;
93 Logger::instance()->errorLog("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
99 * Add a single php value to an xmlrpc value.
101 * If the xmlrpc value is an array, the php value is added as its last element.
102 * If the xmlrpc value is empty (uninitialized), this method makes it a scalar value, and sets that value.
103 * Fails if the xmlrpc value is not an array and already initialized.
106 * @param string $type allowed values: i4, i8, int, boolean, string, double, dateTime.iso8601, base64, null.
108 * @return int 1 or 0 on failure
110 public function addScalar($val, $type = 'string')
113 if (isset(static::$xmlrpcTypes[$type])) {
114 $typeOf = static::$xmlrpcTypes[$type];
118 Logger::instance()->errorLog("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
122 // coerce booleans into correct values
123 // NB: we should either do it for datetimes, integers, i8 and doubles, too,
124 // or just plain remove this check, implemented on booleans only...
125 if ($type == static::$xmlrpcBoolean) {
126 if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
133 switch ($this->mytype) {
135 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
138 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
141 // we're adding a scalar value to an array here
142 $this->me['array'][] = new Value($val, $type);
146 // a scalar, so set the value and remember we're scalar
147 $this->me[$type] = $val;
148 $this->mytype = $typeOf;
155 * Add an array of xmlrpc value objects to an xmlrpc value.
157 * If the xmlrpc value is an array, the elements are appended to the existing ones.
158 * If the xmlrpc value is empty (uninitialized), this method makes it an array value, and sets that value.
161 * @param Value[] $values
163 * @return int 1 or 0 on failure
165 * @todo add some checking for $values to be an array of xmlrpc values?
167 public function addArray($values)
169 if ($this->mytype == 0) {
170 $this->mytype = static::$xmlrpcTypes['array'];
171 $this->me['array'] = $values;
174 } elseif ($this->mytype == 2) {
175 // we're adding to an array here
176 $this->me['array'] = array_merge($this->me['array'], $values);
180 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
186 * Merges an array of named xmlrpc value objects into an xmlrpc value.
188 * If the xmlrpc value is a struct, the elements are merged with the existing ones (overwriting existing ones).
189 * If the xmlrpc value is empty (uninitialized), this method makes it a struct value, and sets that value.
192 * @param Value[] $values
194 * @return int 1 or 0 on failure
196 * @todo add some checking for $values to be an array?
198 public function addStruct($values)
200 if ($this->mytype == 0) {
201 $this->mytype = static::$xmlrpcTypes['struct'];
202 $this->me['struct'] = $values;
205 } elseif ($this->mytype == 3) {
206 // we're adding to a struct here
207 $this->me['struct'] = array_merge($this->me['struct'], $values);
211 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
217 * Returns a string containing either "struct", "array", "scalar" or "undef", describing the base type of the value.
221 public function kindOf()
223 switch ($this->mytype) {
235 protected function serializedata($typ, $val, $charsetEncoding = '')
239 if (!isset(static::$xmlrpcTypes[$typ])) {
243 switch (static::$xmlrpcTypes[$typ]) {
246 case static::$xmlrpcBase64:
247 $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
249 case static::$xmlrpcBoolean:
250 $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
252 case static::$xmlrpcString:
253 // Do NOT use htmlentities, since it will produce named html entities, which are invalid xml
254 $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</${typ}>";
256 case static::$xmlrpcInt:
257 case static::$xmlrpcI4:
258 case static::$xmlrpcI8:
259 $rs .= "<${typ}>" . (int)$val . "</${typ}>";
261 case static::$xmlrpcDouble:
262 // avoid using standard conversion of float to string because it is locale-dependent,
263 // and also because the xmlrpc spec forbids exponential notation.
264 // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
265 // The code below tries its best at keeping max precision while avoiding exp notation,
266 // but there is of course no limit in the number of decimal places to be used...
267 $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, PhpXmlRpc::$xmlpc_double_precision, '.', '')) . "</${typ}>";
269 case static::$xmlrpcDateTime:
270 if (is_string($val)) {
271 $rs .= "<${typ}>${val}</${typ}>";
272 } elseif (is_a($val, 'DateTime')) {
273 $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "</${typ}>";
274 } elseif (is_int($val)) {
275 $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "</${typ}>";
277 // not really a good idea here: but what shall we output anyway? left for backward compat...
278 $rs .= "<${typ}>${val}</${typ}>";
281 case static::$xmlrpcNull:
282 if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
289 // no standard type value should arrive here, but provide a possibility
290 // for xmlrpc values of unknown type...
291 $rs .= "<${typ}>${val}</${typ}>";
296 if ($this->_php_class) {
297 $rs .= '<struct php_class="' . $this->_php_class . "\">\n";
301 $charsetEncoder = Charset::instance();
302 /** @var Value $val2 */
303 foreach ($val as $key2 => $val2) {
304 $rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
305 //$rs.=$this->serializeval($val2);
306 $rs .= $val2->serialize($charsetEncoding);
307 $rs .= "</member>\n";
313 $rs .= "<array>\n<data>\n";
314 /** @var Value $element */
315 foreach ($val as $element) {
316 //$rs.=$this->serializeval($val[$i]);
317 $rs .= $element->serialize($charsetEncoding);
319 $rs .= "</data>\n</array>";
329 * Returns the xml representation of the value. XML prologue not included.
331 * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
335 public function serialize($charsetEncoding = '')
337 $val = reset($this->me);
338 $typ = key($this->me);
340 return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
344 * Checks whether a struct member with a given name is present.
346 * Works only on xmlrpc values of type struct.
348 * @param string $key the name of the struct member to be looked up
352 * @deprecated use array access, e.g. isset($val[$key])
354 public function structmemexists($key)
356 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
358 return array_key_exists($key, $this->me['struct']);
362 * Returns the value of a given struct member (an xmlrpc value object in itself).
363 * Will raise a php warning if struct member of given name does not exist.
365 * @param string $key the name of the struct member to be looked up
369 * @deprecated use array access, e.g. $val[$key]
371 public function structmem($key)
373 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
375 return $this->me['struct'][$key];
379 * Reset internal pointer for xmlrpc values of type struct.
380 * @deprecated iterate directly over the object using foreach instead
382 public function structreset()
384 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
386 reset($this->me['struct']);
390 * Return next member element for xmlrpc values of type struct.
393 * @throws \Error starting with php 8.0, this function should not be used, as it will always throw
395 * @deprecated iterate directly over the object using foreach instead
397 public function structeach()
399 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
401 return @each($this->me['struct']);
405 * Returns the value of a scalar xmlrpc value (base 64 decoding is automatically handled here)
409 public function scalarval()
411 $b = reset($this->me);
417 * Returns the type of the xmlrpc value.
419 * For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and returned as such
423 public function scalartyp()
427 if ($a == static::$xmlrpcI4) {
428 $a = static::$xmlrpcInt;
435 * Returns the m-th member of an xmlrpc value of array type.
437 * @param integer $key the index of the value to be retrieved (zero based)
441 * @deprecated use array access, e.g. $val[$key]
443 public function arraymem($key)
445 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
447 return $this->me['array'][$key];
451 * Returns the number of members in an xmlrpc value of array type.
455 * @deprecated use count() instead
457 public function arraysize()
459 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
461 return count($this->me['array']);
465 * Returns the number of members in an xmlrpc value of struct type.
469 * @deprecated use count() instead
471 public function structsize()
473 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
475 return count($this->me['struct']);
479 * Returns the number of members in an xmlrpc value:
480 * - 0 for uninitialized values
481 * - 1 for scalar values
482 * - the number of elements for struct and array values
486 public function count()
488 switch ($this->mytype) {
490 return count($this->me['struct']);
492 return count($this->me['array']);
501 * Implements the IteratorAggregate interface
503 * @return \ArrayIterator
505 public function getIterator()
507 switch ($this->mytype) {
509 return new \ArrayIterator($this->me['struct']);
511 return new \ArrayIterator($this->me['array']);
513 return new \ArrayIterator($this->me);
515 return new \ArrayIterator();
520 * @internal required to be public to implement an Interface
521 * @param mixed $offset
522 * @param mixed $value
525 public function offsetSet($offset, $value)
527 switch ($this->mytype) {
529 if (!($value instanceof \PhpXmlRpc\Value)) {
530 throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct');
532 if (is_null($offset)) {
533 // disallow struct members with empty names
534 throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct');
536 $this->me['struct'][$offset] = $value;
540 if (!($value instanceof \PhpXmlRpc\Value)) {
541 throw new \Exception('It is only possible to add Value objects to an XML-RPC Array');
543 if (is_null($offset)) {
544 $this->me['array'][] = $value;
546 // nb: we are not checking that $offset is above the existing array range...
547 $this->me['array'][$offset] = $value;
551 // todo: handle i4 vs int
553 $type = key($this->me);
554 if ($type != $offset) {
555 throw new \Exception('');
557 $this->me[$type] = $value;
560 // 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
561 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be set using array index");
566 * @internal required to be public to implement an Interface
567 * @param mixed $offset
570 public function offsetExists($offset)
572 switch ($this->mytype) {
574 return isset($this->me['struct'][$offset]);
576 return isset($this->me['array'][$offset]);
578 // todo: handle i4 vs int
579 return $offset == $this->scalartyp();
586 * @internal required to be public to implement an Interface
587 * @param mixed $offset
590 public function offsetUnset($offset)
592 switch ($this->mytype) {
594 unset($this->me['struct'][$offset]);
597 unset($this->me['array'][$offset]);
600 // can not remove value from a scalar
601 throw new \Exception("XML-RPC Value is of type 'scalar' and its value can not be unset using array index");
603 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
608 * @internal required to be public to implement an Interface
609 * @param mixed $offset
610 * @return mixed|Value|null
613 public function offsetGet($offset)
615 switch ($this->mytype) {
617 return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null;
619 return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
621 // on bad type: null or exception?
622 $value = reset($this->me);
623 $type = key($this->me);
624 return $type == $offset ? $value : null;
626 // return null or exception?
627 throw new \Exception("XML-RPC Value is of type 'undef' and can not be accessed using array index");