Reformat source code: the library
[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         /// @todo: 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             /*if($type=='')
77             {
78                 $type='string';
79             }
80             if(static::$xmlrpcTypes[$type]==1)
81             {
82                 $this->addScalar($val,$type);
83             }
84             elseif(static::$xmlrpcTypes[$type]==2)
85             {
86                 $this->addArray($val);
87             }
88             elseif(static::$xmlrpcTypes[$type]==3)
89             {
90                 $this->addStruct($val);
91             }*/
92         }
93     }
94
95     /**
96      * Add a single php value to an (unitialized) xmlrpcval.
97      *
98      * @param mixed $val
99      * @param string $type
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
113             return 0;
114         }
115
116         // coerce booleans into correct values
117         // NB: we should either do it for datetimes, integers and doubles, too,
118         // or just plain remove this check, implemented on booleans only...
119         if ($type == static::$xmlrpcBoolean) {
120             if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
121                 $val = true;
122             } else {
123                 $val = false;
124             }
125         }
126
127         switch ($this->mytype) {
128             case 1:
129                 error_log('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
130
131                 return 0;
132             case 3:
133                 error_log('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
134
135                 return 0;
136             case 2:
137                 // we're adding a scalar value to an array here
138                 //$ar=$this->me['array'];
139                 //$ar[]=new Value($val, $type);
140                 //$this->me['array']=$ar;
141                 // Faster (?) avoid all the costly array-copy-by-val done 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 xmlrpcval objects to an xmlrpcval.
156      *
157      * @param array $vals
158      *
159      * @return int 1 or 0 on failure
160      *
161      * @todo add some checking for $vals to be an array of xmlrpcvals?
162      */
163     public function addArray($vals)
164     {
165         if ($this->mytype == 0) {
166             $this->mytype = static::$xmlrpcTypes['array'];
167             $this->me['array'] = $vals;
168
169             return 1;
170         } elseif ($this->mytype == 2) {
171             // we're adding to an array here
172             $this->me['array'] = array_merge($this->me['array'], $vals);
173
174             return 1;
175         } else {
176             error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
177
178             return 0;
179         }
180     }
181
182     /**
183      * Add an array of named xmlrpcval objects to an xmlrpcval.
184      *
185      * @param array $vals
186      *
187      * @return int 1 or 0 on failure
188      *
189      * @todo add some checking for $vals to be an array?
190      */
191     public function addStruct($vals)
192     {
193         if ($this->mytype == 0) {
194             $this->mytype = static::$xmlrpcTypes['struct'];
195             $this->me['struct'] = $vals;
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'], $vals);
201
202             return 1;
203         } else {
204             error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
205
206             return 0;
207         }
208     }
209
210     /**
211      * Returns a string containing "struct", "array" or "scalar" describing the base type of the value.
212      *
213      * @return string
214      */
215     public function kindOf()
216     {
217         switch ($this->mytype) {
218             case 3:
219                 return 'struct';
220                 break;
221             case 2:
222                 return 'array';
223                 break;
224             case 1:
225                 return 'scalar';
226                 break;
227             default:
228                 return 'undef';
229         }
230     }
231
232     private function serializedata($typ, $val, $charset_encoding = '')
233     {
234         $rs = '';
235
236         if (!isset(static::$xmlrpcTypes[$typ])) {
237             return $rs;
238         }
239
240         switch (static::$xmlrpcTypes[$typ]) {
241             case 1:
242                 switch ($typ) {
243                     case static::$xmlrpcBase64:
244                         $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
245                         break;
246                     case static::$xmlrpcBoolean:
247                         $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
248                         break;
249                     case static::$xmlrpcString:
250                         // G. Giunta 2005/2/13: do NOT use htmlentities, since
251                         // it will produce named html entities, which are invalid xml
252                         $rs .= "<${typ}>" . Charset::instance()->encode_entities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "</${typ}>";
253                         break;
254                     case static::$xmlrpcInt:
255                     case static::$xmlrpcI4:
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 xmlrpcvals 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->encode_entities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "</name>\n";
301                     //$rs.=$this->serializeval($val2);
302                     $rs .= $val2->serialize($charset_encoding);
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($charset_encoding);
313                 }
314                 $rs .= "</data>\n</array>";
315                 break;
316             default:
317                 break;
318         }
319
320         return $rs;
321     }
322
323     /**
324      * Returns xml representation of the value. XML prologue not included.
325      *
326      * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
327      *
328      * @return string
329      */
330     public function serialize($charset_encoding = '')
331     {
332         // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
333         //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
334         //{
335         reset($this->me);
336         list($typ, $val) = each($this->me);
337
338         return '<value>' . $this->serializedata($typ, $val, $charset_encoding) . "</value>\n";
339         //}
340     }
341
342     // DEPRECATED
343     public function serializeval($o)
344     {
345         // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
346         //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
347         //{
348         $ar = $o->me;
349         reset($ar);
350         list($typ, $val) = each($ar);
351
352         return '<value>' . $this->serializedata($typ, $val) . "</value>\n";
353         //}
354     }
355
356     /**
357      * Checks whether a struct member with a given name is present.
358      * Works only on xmlrpcvals of type struct.
359      *
360      * @param string $m the name of the struct member to be looked up
361      *
362      * @return boolean
363      */
364     public function structmemexists($m)
365     {
366         return array_key_exists($m, $this->me['struct']);
367     }
368
369     /**
370      * Returns the value of a given struct member (an xmlrpcval object in itself).
371      * Will raise a php warning if struct member of given name does not exist.
372      *
373      * @param string $m the name of the struct member to be looked up
374      *
375      * @return xmlrpcval
376      */
377     public function structmem($m)
378     {
379         return $this->me['struct'][$m];
380     }
381
382     /**
383      * Reset internal pointer for xmlrpcvals of type struct.
384      */
385     public function structreset()
386     {
387         reset($this->me['struct']);
388     }
389
390     /**
391      * Return next member element for xmlrpcvals of type struct.
392      *
393      * @return xmlrpcval
394      */
395     public function structeach()
396     {
397         return each($this->me['struct']);
398     }
399
400     // DEPRECATED! this code looks like it is very fragile and has not been fixed
401     // for a long long time. Shall we remove it for 2.0?
402     public function getval()
403     {
404         // UNSTABLE
405         reset($this->me);
406         list($a, $b) = each($this->me);
407         // contributed by I Sofer, 2001-03-24
408         // add support for nested arrays to scalarval
409         // i've created a new method here, so as to
410         // preserve back compatibility
411
412         if (is_array($b)) {
413             @reset($b);
414             while (list($id, $cont) = @each($b)) {
415                 $b[$id] = $cont->scalarval();
416             }
417         }
418
419         // add support for structures directly encoding php objects
420         if (is_object($b)) {
421             $t = get_object_vars($b);
422             @reset($t);
423             while (list($id, $cont) = @each($t)) {
424                 $t[$id] = $cont->scalarval();
425             }
426             @reset($t);
427             while (list($id, $cont) = @each($t)) {
428                 @$b->$id = $cont;
429             }
430         }
431         // end contrib
432         return $b;
433     }
434
435     /**
436      * Returns the value of a scalar xmlrpcval.
437      *
438      * @return mixed
439      */
440     public function scalarval()
441     {
442         reset($this->me);
443         list(, $b) = each($this->me);
444
445         return $b;
446     }
447
448     /**
449      * Returns the type of the xmlrpcval.
450      * For integers, 'int' is always returned in place of 'i4'.
451      *
452      * @return string
453      */
454     public function scalartyp()
455     {
456         reset($this->me);
457         list($a,) = each($this->me);
458         if ($a == static::$xmlrpcI4) {
459             $a = static::$xmlrpcInt;
460         }
461
462         return $a;
463     }
464
465     /**
466      * Returns the m-th member of an xmlrpcval of struct type.
467      *
468      * @param integer $m the index of the value to be retrieved (zero based)
469      *
470      * @return xmlrpcval
471      */
472     public function arraymem($m)
473     {
474         return $this->me['array'][$m];
475     }
476
477     /**
478      * Returns the number of members in an xmlrpcval of array type.
479      *
480      * @return integer
481      */
482     public function arraysize()
483     {
484         return count($this->me['array']);
485     }
486
487     /**
488      * Returns the number of members in an xmlrpcval of struct type.
489      *
490      * @return integer
491      */
492     public function structsize()
493     {
494         return count($this->me['struct']);
495     }
496 }