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