Fix ArrayIterator interface implementation; remove usage of arraysize(), structsize...
[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                     $arr[] = $this->decode($xmlrpcVal->arraymem($i), $options);
78                 }
79
80                 return $arr;
81             case 'struct':
82                 // If user said so, try to rebuild php objects for specific struct vals.
83                 /// @todo should we raise a warning for class not found?
84                 // shall we check for proper subclass of xmlrpc value instead of
85                 // presence of _php_class to detect what we can do?
86                 if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
87                     && class_exists($xmlrpcVal->_php_class)
88                 ) {
89                     $obj = @new $xmlrpcVal->_php_class();
90                     foreach ($xmlrpcVal as $key => $value) {
91                         $obj->$key = $this->decode($value, $options);
92                     }
93
94                     return $obj;
95                 } else {
96                     $arr = array();
97                     foreach ($xmlrpcVal as $key => $value) {
98                         $arr[$key] = $this->decode($value, $options);
99                     }
100
101                     return $arr;
102                 }
103             case 'msg':
104                 $paramCount = $xmlrpcVal->getNumParams();
105                 $arr = array();
106                 for ($i = 0; $i < $paramCount; $i++) {
107                     $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
108                 }
109
110                 return $arr;
111         }
112     }
113
114     /**
115      * Takes native php types and encodes them into xmlrpc PHP object format.
116      * It will not re-encode xmlrpc value objects.
117      *
118      * Feature creep -- could support more types via optional type argument
119      * (string => datetime support has been added, ??? => base64 not yet)
120      *
121      * If given a proper options parameter, php object instances will be encoded
122      * into 'special' xmlrpc values, that can later be decoded into php objects
123      * by calling php_xmlrpc_decode() with a corresponding option
124      *
125      * @author Dan Libby (dan@libby.com)
126      *
127      * @param mixed $phpVal the value to be converted into an xmlrpc value object
128      * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
129      *
130      * @return \PhpXmlrpc\Value
131      */
132     public function encode($phpVal, $options = array())
133     {
134         $type = gettype($phpVal);
135         switch ($type) {
136             case 'string':
137                 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) {
138                     $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
139                 } else {
140                     $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
141                 }
142                 break;
143             case 'integer':
144                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
145                 break;
146             case 'double':
147                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
148                 break;
149             // <G_Giunta_2001-02-29>
150             // Add support for encoding/decoding of booleans, since they are supported in PHP
151             case 'boolean':
152                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
153                 break;
154             // </G_Giunta_2001-02-29>
155             case 'array':
156                 // PHP arrays can be encoded to either xmlrpc structs or arrays,
157                 // depending on wheter they are hashes or plain 0..n integer indexed
158                 // A shorter one-liner would be
159                 // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
160                 // but execution time skyrockets!
161                 $j = 0;
162                 $arr = array();
163                 $ko = false;
164                 foreach ($phpVal as $key => $val) {
165                     $arr[$key] = $this->encode($val, $options);
166                     if (!$ko && $key !== $j) {
167                         $ko = true;
168                     }
169                     $j++;
170                 }
171                 if ($ko) {
172                     $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
173                 } else {
174                     $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
175                 }
176                 break;
177             case 'object':
178                 if (is_a($phpVal, 'PhpXmlRpc\Value')) {
179                     $xmlrpcVal = $phpVal;
180                 } elseif (is_a($phpVal, 'DateTime')) {
181                     $xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcStruct);
182                 } else {
183                     $arr = array();
184                     reset($phpVal);
185                     while (list($k, $v) = each($phpVal)) {
186                         $arr[$k] = $this->encode($v, $options);
187                     }
188                     $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
189                     if (in_array('encode_php_objs', $options)) {
190                         // let's save original class name into xmlrpc value:
191                         // might be useful later on...
192                         $xmlrpcVal->_php_class = get_class($phpVal);
193                     }
194                 }
195                 break;
196             case 'NULL':
197                 if (in_array('extension_api', $options)) {
198                     $xmlrpcVal = new Value('', Value::$xmlrpcString);
199                 } elseif (in_array('null_extension', $options)) {
200                     $xmlrpcVal = new Value('', Value::$xmlrpcNull);
201                 } else {
202                     $xmlrpcVal = new Value();
203                 }
204                 break;
205             case 'resource':
206                 if (in_array('extension_api', $options)) {
207                     $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
208                 } else {
209                     $xmlrpcVal = new Value();
210                 }
211             // catch "user function", "unknown type"
212             default:
213                 // giancarlo pinerolo <ping@alt.it>
214                 // it has to return
215                 // an empty object in case, not a boolean.
216                 $xmlrpcVal = new Value();
217                 break;
218         }
219
220         return $xmlrpcVal;
221     }
222
223     /**
224      * Convert the xml representation of a method response, method request or single
225      * xmlrpc value into the appropriate object (a.k.a. deserialize).
226      *
227      * @param string $xmlVal
228      * @param array $options
229      *
230      * @return mixed false on error, or an instance of either Value, Request or Response
231      */
232     public function decodeXml($xmlVal, $options = array())
233     {
234         // 'guestimate' encoding
235         $valEncoding = XMLParser::guessEncoding('', $xmlVal);
236         if ($valEncoding != '') {
237
238             // Since parsing will fail if charset is not specified in the xml prologue,
239             // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
240             // The following code might be better for mb_string enabled installs, but
241             // makes the lib about 200% slower...
242             //if (!is_valid_charset($valEncoding, array('UTF-8'))
243             if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) {
244                 if ($valEncoding == 'ISO-8859-1') {
245                     $xmlVal = utf8_encode($xmlVal);
246                 } else {
247                     if (extension_loaded('mbstring')) {
248                         $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
249                     } else {
250                         error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
251                     }
252                 }
253             }
254         }
255
256         $parser = xml_parser_create();
257         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
258         // What if internal encoding is not in one of the 3 allowed?
259         // we use the broadest one, ie. utf8!
260         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
261             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
262         } else {
263             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
264         }
265
266         $xmlRpcParser = new XMLParser();
267         xml_set_object($parser, $xmlRpcParser);
268
269         xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
270         xml_set_character_data_handler($parser, 'xmlrpc_cd');
271         xml_set_default_handler($parser, 'xmlrpc_dh');
272         if (!xml_parse($parser, $xmlVal, 1)) {
273             $errstr = sprintf('XML error: %s at line %d, column %d',
274                 xml_error_string(xml_get_error_code($parser)),
275                 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
276             error_log($errstr);
277             xml_parser_free($parser);
278
279             return false;
280         }
281         xml_parser_free($parser);
282         if ($xmlRpcParser->_xh['isf'] > 1) {
283             // test that $xmlrpc->_xh['value'] is an obj, too???
284
285             error_log($xmlRpcParser->_xh['isf_reason']);
286
287             return false;
288         }
289         switch ($xmlRpcParser->_xh['rt']) {
290             case 'methodresponse':
291                 $v = &$xmlRpcParser->_xh['value'];
292                 if ($xmlRpcParser->_xh['isf'] == 1) {
293                     $vc = $v->structmem('faultCode');
294                     $vs = $v->structmem('faultString');
295                     $r = new Response(0, $vc->scalarval(), $vs->scalarval());
296                 } else {
297                     $r = new Response($v);
298                 }
299
300                 return $r;
301             case 'methodcall':
302                 $req = new Request($xmlRpcParser->_xh['method']);
303                 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
304                     $req->addParam($xmlRpcParser->_xh['params'][$i]);
305                 }
306
307                 return $req;
308             case 'value':
309                 return $xmlRpcParser->_xh['value'];
310             default:
311                 return false;
312         }
313     }
314
315 }