Implement interface ArrayAccess in the Value class
[plcapi.git] / src / Encoder.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\XMLParser;
6
7 class Encoder
8 {
9     /**
10      * Takes an xmlrpc value in object format and translates it into native PHP types.
11      *
12      * Works with xmlrpc requests objects as input, too.
13      *
14      * Given proper options parameter, can rebuild generic php object instances
15      * (provided those have been encoded to xmlrpc format using a corresponding
16      * option in php_xmlrpc_encode())
17      * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
18      * This means that the remote communication end can decide which php code will
19      * get executed on your server, leaving the door possibly open to 'php-injection'
20      * style of attacks (provided you have some classes defined on your server that
21      * might wreak havoc if instances are built outside an appropriate context).
22      * Make sure you trust the remote server/client before eanbling this!
23      *
24      * @author Dan Libby (dan@libby.com)
25      *
26      * @param Value|Request $xmlrpcVal
27      * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects; if 'dates_as_objects' is set xmlrpc datetimes are decoded as php DateTime objects (standard is
28      *
29      * @return mixed
30      */
31     public function decode($xmlrpcVal, $options = array())
32     {
33         switch ($xmlrpcVal->kindOf()) {
34             case 'scalar':
35                 if (in_array('extension_api', $options)) {
36                     reset($xmlrpcVal->me);
37                     list($typ, $val) = each($xmlrpcVal->me);
38                     switch ($typ) {
39                         case 'dateTime.iso8601':
40                             $xmlrpcVal->scalar = $val;
41                             $xmlrpcVal->type = 'datetime';
42                             $xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601Decode($val);
43
44                             return $xmlrpcVal;
45                         case 'base64':
46                             $xmlrpcVal->scalar = $val;
47                             $xmlrpcVal->type = $typ;
48
49                             return $xmlrpcVal;
50                         default:
51                             return $xmlrpcVal->scalarval();
52                     }
53                 }
54                 if (in_array('dates_as_objects', $options) && $xmlrpcVal->scalartyp() == 'dateTime.iso8601') {
55                     // we return a Datetime object instead of a string
56                     // since now the constructor of xmlrpc value accepts safely strings, ints and datetimes,
57                     // we cater to all 3 cases here
58                     $out = $xmlrpcVal->scalarval();
59                     if (is_string($out)) {
60                         $out = strtotime($out);
61                     }
62                     if (is_int($out)) {
63                         $result = new \Datetime();
64                         $result->setTimestamp($out);
65
66                         return $result;
67                     } elseif (is_a($out, 'Datetime')) {
68                         return $out;
69                     }
70                 }
71
72                 return $xmlrpcVal->scalarval();
73             case 'array':
74                 //$size = $xmlrpcVal->count();
75                 $arr = array();
76                 //for ($i = 0; $i < $size; $i++) {
77                 foreach($xmlrpcVal as $value) {
78                     //$arr[] = $this->decode($xmlrpcVal->arraymem($i), $options);
79                     $arr[] = $this->decode($value, $options);
80                 }
81
82                 return $arr;
83             case 'struct':
84                 // If user said so, try to rebuild php objects for specific struct vals.
85                 /// @todo should we raise a warning for class not found?
86                 // shall we check for proper subclass of xmlrpc value instead of
87                 // presence of _php_class to detect what we can do?
88                 if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
89                     && class_exists($xmlrpcVal->_php_class)
90                 ) {
91                     $obj = @new $xmlrpcVal->_php_class();
92                     foreach ($xmlrpcVal as $key => $value) {
93                         $obj->$key = $this->decode($value, $options);
94                     }
95
96                     return $obj;
97                 } else {
98                     $arr = array();
99                     foreach ($xmlrpcVal as $key => $value) {
100                         $arr[$key] = $this->decode($value, $options);
101                     }
102
103                     return $arr;
104                 }
105             case 'msg':
106                 $paramCount = $xmlrpcVal->getNumParams();
107                 $arr = array();
108                 for ($i = 0; $i < $paramCount; $i++) {
109                     $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
110                 }
111
112                 return $arr;
113         }
114     }
115
116     /**
117      * Takes native php types and encodes them into xmlrpc PHP object format.
118      * It will not re-encode xmlrpc value objects.
119      *
120      * Feature creep -- could support more types via optional type argument
121      * (string => datetime support has been added, ??? => base64 not yet)
122      *
123      * If given a proper options parameter, php object instances will be encoded
124      * into 'special' xmlrpc values, that can later be decoded into php objects
125      * by calling php_xmlrpc_decode() with a corresponding option
126      *
127      * @author Dan Libby (dan@libby.com)
128      *
129      * @param mixed $phpVal the value to be converted into an xmlrpc value object
130      * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
131      *
132      * @return \PhpXmlrpc\Value
133      */
134     public function encode($phpVal, $options = array())
135     {
136         $type = gettype($phpVal);
137         switch ($type) {
138             case 'string':
139                 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) {
140                     $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
141                 } else {
142                     $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
143                 }
144                 break;
145             case 'integer':
146                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
147                 break;
148             case 'double':
149                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
150                 break;
151             // <G_Giunta_2001-02-29>
152             // Add support for encoding/decoding of booleans, since they are supported in PHP
153             case 'boolean':
154                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
155                 break;
156             // </G_Giunta_2001-02-29>
157             case 'array':
158                 // PHP arrays can be encoded to either xmlrpc structs or arrays,
159                 // depending on wheter they are hashes or plain 0..n integer indexed
160                 // A shorter one-liner would be
161                 // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
162                 // but execution time skyrockets!
163                 $j = 0;
164                 $arr = array();
165                 $ko = false;
166                 foreach ($phpVal as $key => $val) {
167                     $arr[$key] = $this->encode($val, $options);
168                     if (!$ko && $key !== $j) {
169                         $ko = true;
170                     }
171                     $j++;
172                 }
173                 if ($ko) {
174                     $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
175                 } else {
176                     $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
177                 }
178                 break;
179             case 'object':
180                 if (is_a($phpVal, 'PhpXmlRpc\Value')) {
181                     $xmlrpcVal = $phpVal;
182                 } elseif (is_a($phpVal, 'DateTime')) {
183                     $xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcStruct);
184                 } else {
185                     $arr = array();
186                     reset($phpVal);
187                     while (list($k, $v) = each($phpVal)) {
188                         $arr[$k] = $this->encode($v, $options);
189                     }
190                     $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
191                     if (in_array('encode_php_objs', $options)) {
192                         // let's save original class name into xmlrpc value:
193                         // might be useful later on...
194                         $xmlrpcVal->_php_class = get_class($phpVal);
195                     }
196                 }
197                 break;
198             case 'NULL':
199                 if (in_array('extension_api', $options)) {
200                     $xmlrpcVal = new Value('', Value::$xmlrpcString);
201                 } elseif (in_array('null_extension', $options)) {
202                     $xmlrpcVal = new Value('', Value::$xmlrpcNull);
203                 } else {
204                     $xmlrpcVal = new Value();
205                 }
206                 break;
207             case 'resource':
208                 if (in_array('extension_api', $options)) {
209                     $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
210                 } else {
211                     $xmlrpcVal = new Value();
212                 }
213             // catch "user function", "unknown type"
214             default:
215                 // giancarlo pinerolo <ping@alt.it>
216                 // it has to return
217                 // an empty object in case, not a boolean.
218                 $xmlrpcVal = new Value();
219                 break;
220         }
221
222         return $xmlrpcVal;
223     }
224
225     /**
226      * Convert the xml representation of a method response, method request or single
227      * xmlrpc value into the appropriate object (a.k.a. deserialize).
228      *
229      * @param string $xmlVal
230      * @param array $options
231      *
232      * @return mixed false on error, or an instance of either Value, Request or Response
233      */
234     public function decodeXml($xmlVal, $options = array())
235     {
236         // 'guestimate' encoding
237         $valEncoding = XMLParser::guessEncoding('', $xmlVal);
238         if ($valEncoding != '') {
239
240             // Since parsing will fail if charset is not specified in the xml prologue,
241             // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
242             // The following code might be better for mb_string enabled installs, but
243             // makes the lib about 200% slower...
244             //if (!is_valid_charset($valEncoding, array('UTF-8'))
245             if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) {
246                 if ($valEncoding == 'ISO-8859-1') {
247                     $xmlVal = utf8_encode($xmlVal);
248                 } else {
249                     if (extension_loaded('mbstring')) {
250                         $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
251                     } else {
252                         error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
253                     }
254                 }
255             }
256         }
257
258         $parser = xml_parser_create();
259         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
260         // What if internal encoding is not in one of the 3 allowed?
261         // we use the broadest one, ie. utf8!
262         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
263             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
264         } else {
265             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
266         }
267
268         $xmlRpcParser = new XMLParser();
269         xml_set_object($parser, $xmlRpcParser);
270
271         xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
272         xml_set_character_data_handler($parser, 'xmlrpc_cd');
273         xml_set_default_handler($parser, 'xmlrpc_dh');
274         if (!xml_parse($parser, $xmlVal, 1)) {
275             $errstr = sprintf('XML error: %s at line %d, column %d',
276                 xml_error_string(xml_get_error_code($parser)),
277                 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
278             error_log($errstr);
279             xml_parser_free($parser);
280
281             return false;
282         }
283         xml_parser_free($parser);
284         if ($xmlRpcParser->_xh['isf'] > 1) {
285             // test that $xmlrpc->_xh['value'] is an obj, too???
286
287             error_log($xmlRpcParser->_xh['isf_reason']);
288
289             return false;
290         }
291         switch ($xmlRpcParser->_xh['rt']) {
292             case 'methodresponse':
293                 $v = &$xmlRpcParser->_xh['value'];
294                 if ($xmlRpcParser->_xh['isf'] == 1) {
295                     //$vc = $v->structmem('faultCode');
296                     //$vs = $v->structmem('faultString');
297                     $vc = $v['faultCode'];
298                     $vs = $v['faultString'];
299                     $r = new Response(0, $vc->scalarval(), $vs->scalarval());
300                 } else {
301                     $r = new Response($v);
302                 }
303
304                 return $r;
305             case 'methodcall':
306                 $req = new Request($xmlRpcParser->_xh['method']);
307                 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
308                     $req->addParam($xmlRpcParser->_xh['params'][$i]);
309                 }
310
311                 return $req;
312             case 'value':
313                 return $xmlRpcParser->_xh['value'];
314             default:
315                 return false;
316         }
317     }
318
319 }