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