Remove usages of 'each', as it is deprecated in php 7.2
[plcapi.git] / src / Value.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\Charset;
6
7 /**
8  * This class enables the creation of values for XML-RPC, by encapsulating plain php values.
9  */
10 class Value implements \Countable, \IteratorAggregate, \ArrayAccess
11 {
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";
24
25     public static $xmlrpcTypes = array(
26         "i4" => 1,
27         "i8" => 1,
28         "int" => 1,
29         "boolean" => 1,
30         "double" => 1,
31         "string" => 1,
32         "dateTime.iso8601" => 1,
33         "base64" => 1,
34         "array" => 2,
35         "struct" => 3,
36         "null" => 1,
37     );
38
39     /// @todo: do these need to be public?
40     public $me = array();
41     public $mytype = 0;
42     public $_php_class = null;
43
44     /**
45      * Build an xmlrpc value.
46      *
47      * When no value or type is passed in, the value is left uninitialized, and the value can be added later.
48      *
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.
54      */
55     public function __construct($val = -1, $type = '')
56     {
57         // optimization creep - do not call addXX, do it all inline.
58         // downside: booleans will not be coerced anymore
59         if ($val !== -1 || $type != '') {
60             switch ($type) {
61                 case '':
62                     $this->mytype = 1;
63                     $this->me['string'] = $val;
64                     break;
65                 case 'i4':
66                 case 'i8':
67                 case 'int':
68                 case 'double':
69                 case 'string':
70                 case 'boolean':
71                 case 'dateTime.iso8601':
72                 case 'base64':
73                 case 'null':
74                     $this->mytype = 1;
75                     $this->me[$type] = $val;
76                     break;
77                 case 'array':
78                     $this->mytype = 2;
79                     $this->me['array'] = $val;
80                     break;
81                 case 'struct':
82                     $this->mytype = 3;
83                     $this->me['struct'] = $val;
84                     break;
85                 default:
86                     error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
87             }
88         }
89     }
90
91     /**
92      * Add a single php value to an xmlrpc value.
93      *
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.
97      *
98      * @param mixed $val
99      * @param string $type allowed values: i4, i8, int, boolean, string, double, dateTime.iso8601, base64, null.
100      *
101      * @return int 1 or 0 on failure
102      */
103     public function addScalar($val, $type = 'string')
104     {
105         $typeOf = null;
106         if (isset(static::$xmlrpcTypes[$type])) {
107             $typeOf = static::$xmlrpcTypes[$type];
108         }
109
110         if ($typeOf !== 1) {
111             error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
112             return 0;
113         }
114
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'))) {
120                 $val = true;
121             } else {
122                 $val = false;
123             }
124         }
125
126         switch ($this->mytype) {
127             case 1:
128                 error_log('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
129                 return 0;
130             case 3:
131                 error_log('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
132                 return 0;
133             case 2:
134                 // we're adding a scalar value to an array here
135                 $this->me['array'][] = new Value($val, $type);
136
137                 return 1;
138             default:
139                 // a scalar, so set the value and remember we're scalar
140                 $this->me[$type] = $val;
141                 $this->mytype = $typeOf;
142
143                 return 1;
144         }
145     }
146
147     /**
148      * Add an array of xmlrpc value objects to an xmlrpc value.
149      *
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.
152      * Fails otherwise.
153      *
154      * @param Value[] $values
155      *
156      * @return int 1 or 0 on failure
157      *
158      * @todo add some checking for $values to be an array of xmlrpc values?
159      */
160     public function addArray($values)
161     {
162         if ($this->mytype == 0) {
163             $this->mytype = static::$xmlrpcTypes['array'];
164             $this->me['array'] = $values;
165
166             return 1;
167         } elseif ($this->mytype == 2) {
168             // we're adding to an array here
169             $this->me['array'] = array_merge($this->me['array'], $values);
170
171             return 1;
172         } else {
173             error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
174             return 0;
175         }
176     }
177
178     /**
179      * Merges an array of named xmlrpc value objects into an xmlrpc value.
180      *
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.
183      * Fails otherwise.
184      *
185      * @param Value[] $values
186      *
187      * @return int 1 or 0 on failure
188      *
189      * @todo add some checking for $values to be an array?
190      */
191     public function addStruct($values)
192     {
193         if ($this->mytype == 0) {
194             $this->mytype = static::$xmlrpcTypes['struct'];
195             $this->me['struct'] = $values;
196
197             return 1;
198         } elseif ($this->mytype == 3) {
199             // we're adding to a struct here
200             $this->me['struct'] = array_merge($this->me['struct'], $values);
201
202             return 1;
203         } else {
204             error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
205             return 0;
206         }
207     }
208
209     /**
210      * Returns a string containing either "struct", "array", "scalar" or "undef", describing the base type of the value.
211      *
212      * @return string
213      */
214     public function kindOf()
215     {
216         switch ($this->mytype) {
217             case 3:
218                 return 'struct';
219                 break;
220             case 2:
221                 return 'array';
222                 break;
223             case 1:
224                 return 'scalar';
225                 break;
226             default:
227                 return 'undef';
228         }
229     }
230
231     protected function serializedata($typ, $val, $charsetEncoding = '')
232     {
233         $rs = '';
234
235         if (!isset(static::$xmlrpcTypes[$typ])) {
236             return $rs;
237         }
238
239         switch (static::$xmlrpcTypes[$typ]) {
240             case 1:
241                 switch ($typ) {
242                     case static::$xmlrpcBase64:
243                         $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
244                         break;
245                     case static::$xmlrpcBoolean:
246                         $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
247                         break;
248                     case static::$xmlrpcString:
249                         // G. Giunta 2005/2/13: do NOT use htmlentities, since
250                         // it will produce named html entities, which are invalid xml
251                         $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</${typ}>";
252                         break;
253                     case static::$xmlrpcInt:
254                     case static::$xmlrpcI4:
255                     case static::$xmlrpcI8:
256                         $rs .= "<${typ}>" . (int)$val . "</${typ}>";
257                         break;
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, 128, '.', '')) . "</${typ}>";
265                         break;
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}>";
273                         } else {
274                             // not really a good idea here: but what shall we output anyway? left for backward compat...
275                             $rs .= "<${typ}>${val}</${typ}>";
276                         }
277                         break;
278                     case static::$xmlrpcNull:
279                         if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
280                             $rs .= "<ex:nil/>";
281                         } else {
282                             $rs .= "<nil/>";
283                         }
284                         break;
285                     default:
286                         // no standard type value should arrive here, but provide a possibility
287                         // for xmlrpc values of unknown type...
288                         $rs .= "<${typ}>${val}</${typ}>";
289                 }
290                 break;
291             case 3:
292                 // struct
293                 if ($this->_php_class) {
294                     $rs .= '<struct php_class="' . $this->_php_class . "\">\n";
295                 } else {
296                     $rs .= "<struct>\n";
297                 }
298                 $charsetEncoder = Charset::instance();
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";
304                 }
305                 $rs .= '</struct>';
306                 break;
307             case 2:
308                 // array
309                 $rs .= "<array>\n<data>\n";
310                 foreach ($val as $element) {
311                     //$rs.=$this->serializeval($val[$i]);
312                     $rs .= $element->serialize($charsetEncoding);
313                 }
314                 $rs .= "</data>\n</array>";
315                 break;
316             default:
317                 break;
318         }
319
320         return $rs;
321     }
322
323     /**
324      * Returns the xml representation of the value. XML prologue not included.
325      *
326      * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
327      *
328      * @return string
329      */
330     public function serialize($charsetEncoding = '')
331     {
332         $val = reset($this->me);
333         $typ = key($this->me);
334
335         return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
336     }
337
338     /**
339      * Checks whether a struct member with a given name is present.
340      *
341      * Works only on xmlrpc values of type struct.
342      *
343      * @param string $key the name of the struct member to be looked up
344      *
345      * @return boolean
346      *
347      * @deprecated use array access, e.g. isset($val[$key])
348      */
349     public function structmemexists($key)
350     {
351         return array_key_exists($key, $this->me['struct']);
352     }
353
354     /**
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.
357      *
358      * @param string $key the name of the struct member to be looked up
359      *
360      * @return Value
361      *
362      * @deprecated use array access, e.g. $val[$key]
363      */
364     public function structmem($key)
365     {
366         return $this->me['struct'][$key];
367     }
368
369     /**
370      * Reset internal pointer for xmlrpc values of type struct.
371      * @deprecated iterate directly over the object using foreach instead
372      */
373     public function structreset()
374     {
375         reset($this->me['struct']);
376     }
377
378     /**
379      * Return next member element for xmlrpc values of type struct.
380      *
381      * @return Value
382      *
383      * @deprecated iterate directly over the object using foreach instead
384      */
385     public function structeach()
386     {
387         return each($this->me['struct']);
388     }
389
390     /**
391      * Returns the value of a scalar xmlrpc value (base 64 decoding is automatically handled here)
392      *
393      * @return mixed
394      */
395     public function scalarval()
396     {
397         $b = reset($this->me);
398
399         return $b;
400     }
401
402     /**
403      * Returns the type of the xmlrpc value.
404      *
405      * For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and returned as such
406      *
407      * @return string
408      */
409     public function scalartyp()
410     {
411         reset($this->me);
412         $a = key($this->me);
413         if ($a == static::$xmlrpcI4) {
414             $a = static::$xmlrpcInt;
415         }
416
417         return $a;
418     }
419
420     /**
421      * Returns the m-th member of an xmlrpc value of array type.
422      *
423      * @param integer $key the index of the value to be retrieved (zero based)
424      *
425      * @return Value
426      *
427      * @deprecated use array access, e.g. $val[$key]
428      */
429     public function arraymem($key)
430     {
431         return $this->me['array'][$key];
432     }
433
434     /**
435      * Returns the number of members in an xmlrpc value of array type.
436      *
437      * @return integer
438      *
439      * @deprecated use count() instead
440      */
441     public function arraysize()
442     {
443         return count($this->me['array']);
444     }
445
446     /**
447      * Returns the number of members in an xmlrpc value of struct type.
448      *
449      * @return integer
450      *
451      * @deprecated use count() instead
452      */
453     public function structsize()
454     {
455         return count($this->me['struct']);
456     }
457
458     /**
459      * Returns the number of members in an xmlrpc value:
460      * - 0 for uninitialized values
461      * - 1 for scalar values
462      * - the number of elements for struct and array values
463      *
464      * @return integer
465      */
466     public function count()
467     {
468         switch ($this->mytype) {
469             case 3:
470                 return count($this->me['struct']);
471             case 2:
472                 return count($this->me['array']);
473             case 1:
474                 return 1;
475             default:
476                 return 0;
477         }
478     }
479
480     /**
481      * Implements the IteratorAggregate interface
482      *
483      * @return ArrayIterator
484      */
485     public function getIterator() {
486         switch ($this->mytype) {
487             case 3:
488                 return new \ArrayIterator($this->me['struct']);
489             case 2:
490                 return new \ArrayIterator($this->me['array']);
491             case 1:
492                 return new \ArrayIterator($this->me);
493             default:
494                 return new \ArrayIterator();
495         }
496         return new \ArrayIterator();
497     }
498
499     public function offsetSet($offset, $value) {
500
501         switch ($this->mytype) {
502             case 3:
503                 if (!($value instanceof \PhpXmlRpc\Value)) {
504                     throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct');
505                 }
506                 if (is_null($offset)) {
507                     // disallow struct members with empty names
508                     throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct');
509                 } else {
510                     $this->me['struct'][$offset] = $value;
511                 }
512                 return;
513             case 2:
514                 if (!($value instanceof \PhpXmlRpc\Value)) {
515                     throw new \Exception('It is only possible to add Value objects to an XML-RPC Array');
516                 }
517                 if (is_null($offset)) {
518                     $this->me['array'][] = $value;
519                 } else {
520                     // nb: we are not checking that $offset is above the existing array range...
521                     $this->me['array'][$offset] = $value;
522                 }
523                 return;
524             case 1:
525 // todo: handle i4 vs int
526                 reset($this->me);
527                 $type = key($this->me);
528                 if ($type != $offset) {
529                     throw new \Exception('');
530                 }
531                 $this->me[$type] = $value;
532                 return;
533             default:
534                 // 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
535                 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be set using array index");
536         }
537     }
538
539     public function offsetExists($offset) {
540         switch ($this->mytype) {
541             case 3:
542                 return isset($this->me['struct'][$offset]);
543             case 2:
544                 return isset($this->me['array'][$offset]);
545             case 1:
546 // todo: handle i4 vs int
547                 return $offset == $this->scalartyp();
548             default:
549                 return false;
550         }
551     }
552
553     public function offsetUnset($offset) {
554         switch ($this->mytype) {
555             case 3:
556                 unset($this->me['struct'][$offset]);
557                 return;
558             case 2:
559                 unset($this->me['array'][$offset]);
560                 return;
561             case 1:
562                 // can not remove value from a scalar
563                 throw new \Exception("XML-RPC Value is of type 'scalar' and its value can not be unset using array index");
564             default:
565                 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
566         }
567     }
568
569     public function offsetGet($offset) {
570         switch ($this->mytype) {
571             case 3:
572                 return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null;
573             case 2:
574                 return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
575             case 1:
576 // on bad type: null or exception?
577                 $value = reset($this->me);
578                 $type = key($this->me);
579                 return $type == $offset ? $value : null;
580             default:
581 // return null or exception?
582                 throw new \Exception("XML-RPC Value is of type 'undef' and can not be accessed using array index");
583         }
584     }
585 }