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