f544fa588745a0b75638b225afff9f86a87c470e
[plcapi.git] / src / Value.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\Charset;
6
7 class Value
8 {
9     public static $xmlrpcI4 = "i4";
10     public static $xmlrpcInt = "int";
11     public static $xmlrpcBoolean = "boolean";
12     public static $xmlrpcDouble = "double";
13     public static $xmlrpcString = "string";
14     public static $xmlrpcDateTime = "dateTime.iso8601";
15     public static $xmlrpcBase64 = "base64";
16     public static $xmlrpcArray = "array";
17     public static $xmlrpcStruct = "struct";
18     public static $xmlrpcValue = "undefined";
19     public static $xmlrpcNull = "null";
20
21     public static $xmlrpcTypes = array(
22         "i4" => 1,
23         "int" => 1,
24         "boolean" => 1,
25         "double" => 1,
26         "string" => 1,
27         "dateTime.iso8601" => 1,
28         "base64" => 1,
29         "array" => 2,
30         "struct" => 3,
31         "null" => 1,
32     );
33
34     /// @todo: do these need to be public?
35     public $me = array();
36     public $mytype = 0;
37     public $_php_class = null;
38
39     /**
40      * Build an xmlrpc value
41      *
42      * @param mixed $val
43      * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
44      */
45     public function __construct($val = -1, $type = '')
46     {
47         // optimization creep - do not call addXX, do it all inline.
48         // downside: booleans will not be coerced anymore
49         if ($val !== -1 || $type != '') {
50             // optimization creep: inlined all work done by constructor
51             switch ($type) {
52                 case '':
53                     $this->mytype = 1;
54                     $this->me['string'] = $val;
55                     break;
56                 case 'i4':
57                 case 'int':
58                 case 'double':
59                 case 'string':
60                 case 'boolean':
61                 case 'dateTime.iso8601':
62                 case 'base64':
63                 case 'null':
64                     $this->mytype = 1;
65                     $this->me[$type] = $val;
66                     break;
67                 case 'array':
68                     $this->mytype = 2;
69                     $this->me['array'] = $val;
70                     break;
71                 case 'struct':
72                     $this->mytype = 3;
73                     $this->me['struct'] = $val;
74                     break;
75                 default:
76                     error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
77             }
78             /* was:
79             if($type=='')
80             {
81                 $type='string';
82             }
83             if(static::$xmlrpcTypes[$type]==1)
84             {
85                 $this->addScalar($val,$type);
86             }
87             elseif(static::$xmlrpcTypes[$type]==2)
88             {
89                 $this->addArray($val);
90             }
91             elseif(static::$xmlrpcTypes[$type]==3)
92             {
93                 $this->addStruct($val);
94             }*/
95         }
96     }
97
98     /**
99      * Add a single php value to an (unitialized) xmlrpc value.
100      *
101      * @param mixed $val
102      * @param string $type
103      *
104      * @return int 1 or 0 on failure
105      */
106     public function addScalar($val, $type = 'string')
107     {
108         $typeOf = null;
109         if (isset(static::$xmlrpcTypes[$type])) {
110             $typeOf = static::$xmlrpcTypes[$type];
111         }
112
113         if ($typeOf !== 1) {
114             error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
115
116             return 0;
117         }
118
119         // coerce booleans into correct values
120         // NB: we should either do it for datetimes, integers 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'))) {
124                 $val = true;
125             } else {
126                 $val = false;
127             }
128         }
129
130         switch ($this->mytype) {
131             case 1:
132                 error_log('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
133
134                 return 0;
135             case 3:
136                 error_log('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
137
138                 return 0;
139             case 2:
140                 // we're adding a scalar value to an array here
141                 $this->me['array'][] = new Value($val, $type);
142
143                 return 1;
144             default:
145                 // a scalar, so set the value and remember we're scalar
146                 $this->me[$type] = $val;
147                 $this->mytype = $typeOf;
148
149                 return 1;
150         }
151     }
152
153     /**
154      * Add an array of xmlrpc values objects to an xmlrpc value.
155      *
156      * @param Value[] $values
157      *
158      * @return int 1 or 0 on failure
159      *
160      * @todo add some checking for $values to be an array of xmlrpc values?
161      */
162     public function addArray($values)
163     {
164         if ($this->mytype == 0) {
165             $this->mytype = static::$xmlrpcTypes['array'];
166             $this->me['array'] = $values;
167
168             return 1;
169         } elseif ($this->mytype == 2) {
170             // we're adding to an array here
171             $this->me['array'] = array_merge($this->me['array'], $values);
172
173             return 1;
174         } else {
175             error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
176
177             return 0;
178         }
179     }
180
181     /**
182      * Add an array of named xmlrpc value objects to an xmlrpc value.
183      *
184      * @param Value[] $values
185      *
186      * @return int 1 or 0 on failure
187      *
188      * @todo add some checking for $values to be an array?
189      */
190     public function addStruct($values)
191     {
192         if ($this->mytype == 0) {
193             $this->mytype = static::$xmlrpcTypes['struct'];
194             $this->me['struct'] = $values;
195
196             return 1;
197         } elseif ($this->mytype == 3) {
198             // we're adding to a struct here
199             $this->me['struct'] = array_merge($this->me['struct'], $values);
200
201             return 1;
202         } else {
203             error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
204
205             return 0;
206         }
207     }
208
209     /**
210      * Returns a string containing "struct", "array" or "scalar" 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                         $rs .= "<${typ}>" . (int)$val . "</${typ}>";
256                         break;
257                     case static::$xmlrpcDouble:
258                         // avoid using standard conversion of float to string because it is locale-dependent,
259                         // and also because the xmlrpc spec forbids exponential notation.
260                         // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
261                         // The code below tries its best at keeping max precision while avoiding exp notation,
262                         // but there is of course no limit in the number of decimal places to be used...
263                         $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, 128, '.', '')) . "</${typ}>";
264                         break;
265                     case static::$xmlrpcDateTime:
266                         if (is_string($val)) {
267                             $rs .= "<${typ}>${val}</${typ}>";
268                         } elseif (is_a($val, 'DateTime')) {
269                             $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "</${typ}>";
270                         } elseif (is_int($val)) {
271                             $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "</${typ}>";
272                         } else {
273                             // not really a good idea here: but what shall we output anyway? left for backward compat...
274                             $rs .= "<${typ}>${val}</${typ}>";
275                         }
276                         break;
277                     case static::$xmlrpcNull:
278                         if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
279                             $rs .= "<ex:nil/>";
280                         } else {
281                             $rs .= "<nil/>";
282                         }
283                         break;
284                     default:
285                         // no standard type value should arrive here, but provide a possibility
286                         // for xmlrpc values of unknown type...
287                         $rs .= "<${typ}>${val}</${typ}>";
288                 }
289                 break;
290             case 3:
291                 // struct
292                 if ($this->_php_class) {
293                     $rs .= '<struct php_class="' . $this->_php_class . "\">\n";
294                 } else {
295                     $rs .= "<struct>\n";
296                 }
297                 $charsetEncoder = Charset::instance();
298                 foreach ($val as $key2 => $val2) {
299                     $rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
300                     //$rs.=$this->serializeval($val2);
301                     $rs .= $val2->serialize($charsetEncoding);
302                     $rs .= "</member>\n";
303                 }
304                 $rs .= '</struct>';
305                 break;
306             case 2:
307                 // array
308                 $rs .= "<array>\n<data>\n";
309                 foreach ($val as $element) {
310                     //$rs.=$this->serializeval($val[$i]);
311                     $rs .= $element->serialize($charsetEncoding);
312                 }
313                 $rs .= "</data>\n</array>";
314                 break;
315             default:
316                 break;
317         }
318
319         return $rs;
320     }
321
322     /**
323      * Returns xml representation of the value. XML prologue not included.
324      *
325      * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
326      *
327      * @return string
328      */
329     public function serialize($charsetEncoding = '')
330     {
331         // add check? slower, but helps to avoid recursion in serializing broken xmlrpc values...
332         //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
333         //{
334         reset($this->me);
335         list($typ, $val) = each($this->me);
336
337         return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
338         //}
339     }
340
341     /**
342      * Checks whether a struct member with a given name is present.
343      * Works only on xmlrpc values of type struct.
344      *
345      * @param string $key the name of the struct member to be looked up
346      *
347      * @return boolean
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     public function structmem($key)
363     {
364         return $this->me['struct'][$key];
365     }
366
367     /**
368      * Reset internal pointer for xmlrpc values of type struct.
369      */
370     public function structreset()
371     {
372         reset($this->me['struct']);
373     }
374
375     /**
376      * Return next member element for xmlrpc values of type struct.
377      *
378      * @return Value
379      */
380     public function structeach()
381     {
382         return each($this->me['struct']);
383     }
384
385     /**
386      * Returns the value of a scalar xmlrpc value.
387      *
388      * @return mixed
389      */
390     public function scalarval()
391     {
392         reset($this->me);
393         list(, $b) = each($this->me);
394
395         return $b;
396     }
397
398     /**
399      * Returns the type of the xmlrpc value.
400      * For integers, 'int' is always returned in place of 'i4'.
401      *
402      * @return string
403      */
404     public function scalartyp()
405     {
406         reset($this->me);
407         list($a,) = each($this->me);
408         if ($a == static::$xmlrpcI4) {
409             $a = static::$xmlrpcInt;
410         }
411
412         return $a;
413     }
414
415     /**
416      * Returns the m-th member of an xmlrpc value of struct type.
417      *
418      * @param integer $key the index of the value to be retrieved (zero based)
419      *
420      * @return Value
421      */
422     public function arraymem($key)
423     {
424         return $this->me['array'][$key];
425     }
426
427     /**
428      * Returns the number of members in an xmlrpc value of array type.
429      *
430      * @return integer
431      */
432     public function arraysize()
433     {
434         return count($this->me['array']);
435     }
436
437     /**
438      * Returns the number of members in an xmlrpc value of struct type.
439      *
440      * @return integer
441      */
442     public function structsize()
443     {
444         return count($this->me['struct']);
445     }
446 }