Move deprecated methods into the compatibility classes, out of the main library classes
[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 Value[] $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 Value[] $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     protected 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     /**
343      * Checks whether a struct member with a given name is present.
344      * Works only on xmlrpcvals of type struct.
345      *
346      * @param string $m the name of the struct member to be looked up
347      *
348      * @return boolean
349      */
350     public function structmemexists($m)
351     {
352         return array_key_exists($m, $this->me['struct']);
353     }
354
355     /**
356      * Returns the value of a given struct member (an xmlrpcval object in itself).
357      * Will raise a php warning if struct member of given name does not exist.
358      *
359      * @param string $m the name of the struct member to be looked up
360      *
361      * @return Value
362      */
363     public function structmem($m)
364     {
365         return $this->me['struct'][$m];
366     }
367
368     /**
369      * Reset internal pointer for xmlrpcvals of type struct.
370      */
371     public function structreset()
372     {
373         reset($this->me['struct']);
374     }
375
376     /**
377      * Return next member element for xmlrpcvals of type struct.
378      *
379      * @return xmlrpcval
380      */
381     public function structeach()
382     {
383         return each($this->me['struct']);
384     }
385
386     /**
387      * Returns the value of a scalar xmlrpcval.
388      *
389      * @return mixed
390      */
391     public function scalarval()
392     {
393         reset($this->me);
394         list(, $b) = each($this->me);
395
396         return $b;
397     }
398
399     /**
400      * Returns the type of the xmlrpcval.
401      * For integers, 'int' is always returned in place of 'i4'.
402      *
403      * @return string
404      */
405     public function scalartyp()
406     {
407         reset($this->me);
408         list($a,) = each($this->me);
409         if ($a == static::$xmlrpcI4) {
410             $a = static::$xmlrpcInt;
411         }
412
413         return $a;
414     }
415
416     /**
417      * Returns the m-th member of an xmlrpcval of struct type.
418      *
419      * @param integer $m the index of the value to be retrieved (zero based)
420      *
421      * @return Value
422      */
423     public function arraymem($m)
424     {
425         return $this->me['array'][$m];
426     }
427
428     /**
429      * Returns the number of members in an xmlrpcval of array type.
430      *
431      * @return integer
432      */
433     public function arraysize()
434     {
435         return count($this->me['array']);
436     }
437
438     /**
439      * Returns the number of members in an xmlrpcval of struct type.
440      *
441      * @return integer
442      */
443     public function structsize()
444     {
445         return count($this->me['struct']);
446     }
447 }