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