c391897a0195de61e15d7a64e6776456ec1d4f48
[plcapi.git] / src / Encoder.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\XMLParser;
6
7 /**
8  * A helper class to easily convert between Value objects and php native values
9  * @todo implement an interface
10  */
11 class Encoder
12 {
13     /**
14      * Takes an xmlrpc value in object format and translates it into native PHP types.
15      *
16      * Works with xmlrpc requests objects as input, too.
17      *
18      * Given proper options parameter, can rebuild generic php object instances
19      * (provided those have been encoded to xmlrpc format using a corresponding
20      * option in php_xmlrpc_encode())
21      * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
22      * This means that the remote communication end can decide which php code will
23      * get executed on your server, leaving the door possibly open to 'php-injection'
24      * style of attacks (provided you have some classes defined on your server that
25      * might wreak havoc if instances are built outside an appropriate context).
26      * Make sure you trust the remote server/client before eanbling 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 objects; if 'dates_as_objects' is set xmlrpc datetimes are decoded as php DateTime objects (standard is
32      *
33      * @return mixed
34      */
35     public function decode($xmlrpcVal, $options = array())
36     {
37         switch ($xmlrpcVal->kindOf()) {
38             case 'scalar':
39                 if (in_array('extension_api', $options)) {
40                     $val = reset($xmlrpcVal->me);
41                     $typ = key($xmlrpcVal->me);
42                     switch ($typ) {
43                         case 'dateTime.iso8601':
44                             $xmlrpcVal->scalar = $val;
45                             $xmlrpcVal->type = 'datetime';
46                             $xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601Decode($val);
47
48                             return $xmlrpcVal;
49                         case 'base64':
50                             $xmlrpcVal->scalar = $val;
51                             $xmlrpcVal->type = $typ;
52
53                             return $xmlrpcVal;
54                         default:
55                             return $xmlrpcVal->scalarval();
56                     }
57                 }
58                 if (in_array('dates_as_objects', $options) && $xmlrpcVal->scalartyp() == 'dateTime.iso8601') {
59                     // we return a Datetime object instead of a string
60                     // since now the constructor of xmlrpc value accepts safely strings, ints and datetimes,
61                     // we cater to all 3 cases here
62                     $out = $xmlrpcVal->scalarval();
63                     if (is_string($out)) {
64                         $out = strtotime($out);
65                     }
66                     if (is_int($out)) {
67                         $result = new \DateTime();
68                         $result->setTimestamp($out);
69
70                         return $result;
71                     } elseif (is_a($out, 'DateTimeInterface')) {
72                         return $out;
73                     }
74                 }
75
76                 return $xmlrpcVal->scalarval();
77             case 'array':
78                 $arr = array();
79                 foreach($xmlrpcVal as $value) {
80                     $arr[] = $this->decode($value, $options);
81                 }
82
83                 return $arr;
84             case 'struct':
85                 // If user said so, try to rebuild php objects for specific struct vals.
86                 /// @todo should we raise a warning for class not found?
87                 // shall we check for proper subclass of xmlrpc value instead of
88                 // presence of _php_class to detect what we can do?
89                 if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
90                     && class_exists($xmlrpcVal->_php_class)
91                 ) {
92                     $obj = @new $xmlrpcVal->_php_class();
93                     foreach ($xmlrpcVal as $key => $value) {
94                         $obj->$key = $this->decode($value, $options);
95                     }
96
97                     return $obj;
98                 } else {
99                     $arr = array();
100                     foreach ($xmlrpcVal as $key => $value) {
101                         $arr[$key] = $this->decode($value, $options);
102                     }
103
104                     return $arr;
105                 }
106             case 'msg':
107                 $paramCount = $xmlrpcVal->getNumParams();
108                 $arr = array();
109                 for ($i = 0; $i < $paramCount; $i++) {
110                     $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
111                 }
112
113                 return $arr;
114         }
115     }
116
117     /**
118      * Takes native php types and encodes them into xmlrpc PHP object format.
119      * It will not re-encode xmlrpc value objects.
120      *
121      * Feature creep -- could support more types via optional type argument
122      * (string => datetime support has been added, ??? => base64 not yet)
123      *
124      * If given a proper options parameter, php object instances will be encoded
125      * into 'special' xmlrpc values, that can later be decoded into php objects
126      * by calling php_xmlrpc_decode() with a corresponding option
127      *
128      * @author Dan Libby (dan@libby.com)
129      *
130      * @param mixed $phpVal the value to be converted into an xmlrpc value object
131      * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
132      *
133      * @return \PhpXmlrpc\Value
134      */
135     public function encode($phpVal, $options = array())
136     {
137         $type = gettype($phpVal);
138         switch ($type) {
139             case 'string':
140                 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) {
141                     $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
142                 } else {
143                     $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
144                 }
145                 break;
146             case 'integer':
147                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
148                 break;
149             case 'double':
150                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
151                 break;
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             case 'array':
157                 // PHP arrays can be encoded to either xmlrpc structs or arrays,
158                 // depending on whether they are hashes or plain 0..n integer indexed
159                 // A shorter one-liner would be
160                 // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
161                 // but execution time skyrockets!
162                 $j = 0;
163                 $arr = array();
164                 $ko = false;
165                 foreach ($phpVal as $key => $val) {
166                     $arr[$key] = $this->encode($val, $options);
167                     if (!$ko && $key !== $j) {
168                         $ko = true;
169                     }
170                     $j++;
171                 }
172                 if ($ko) {
173                     $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
174                 } else {
175                     $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
176                 }
177                 break;
178             case 'object':
179                 if (is_a($phpVal, 'PhpXmlRpc\Value')) {
180                     $xmlrpcVal = $phpVal;
181                 } elseif (is_a($phpVal, 'DateTimeInterface')) {
182                     $xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcStruct);
183                 } else {
184                     $arr = array();
185                     foreach($phpVal as $k => $v) {
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                 break;
212             // catch "user function", "unknown type"
213             default:
214                 // giancarlo pinerolo <ping@alt.it>
215                 // it has to return 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      * Q: is this a good name for this method? It does something quite different from 'decode' after all (returning objects vs returns plain php values)...
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         // What if internal encoding is not in one of the 3 allowed? We use the broadest one, ie. utf8!
259         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
260             $options = array(XML_OPTION_TARGET_ENCODING => 'UTF-8');
261         } else {
262             $options = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
263         }
264
265         $xmlRpcParser = new XMLParser($options);
266         $xmlRpcParser->parse($xmlVal, XMLParser::RETURN_XMLRPCVALS, XMLParser::ACCEPT_REQUEST | XMLParser::ACCEPT_RESPONSE | XMLParser::ACCEPT_VALUE);
267
268         if ($xmlRpcParser->_xh['isf'] > 1) {
269             // test that $xmlrpc->_xh['value'] is an obj, too???
270
271             error_log($xmlRpcParser->_xh['isf_reason']);
272
273             return false;
274         }
275
276         switch ($xmlRpcParser->_xh['rt']) {
277             case 'methodresponse':
278                 $v = $xmlRpcParser->_xh['value'];
279                 if ($xmlRpcParser->_xh['isf'] == 1) {
280                     /** @var Value $vc */
281                     $vc = $v['faultCode'];
282                     /** @var Value $vs */
283                     $vs = $v['faultString'];
284                     $r = new Response(0, $vc->scalarval(), $vs->scalarval());
285                 } else {
286                     $r = new Response($v);
287                 }
288
289                 return $r;
290             case 'methodcall':
291                 $req = new Request($xmlRpcParser->_xh['method']);
292                 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
293                     $req->addParam($xmlRpcParser->_xh['params'][$i]);
294                 }
295
296                 return $req;
297             case 'value':
298                 return $xmlRpcParser->_xh['value'];
299             default:
300                 return false;
301         }
302     }
303
304 }