5 use PhpXmlRpc\Helper\Logger;
6 use PhpXmlRpc\Helper\XMLParser;
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
16 * Takes an xmlrpc value in object format and translates it into native PHP types.
18 * Works with xmlrpc requests objects as input, too.
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!
28 * @author Dan Libby (dan@libby.com)
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
36 public function decode($xmlrpcVal, $options = array())
38 switch ($xmlrpcVal->kindOf()) {
40 if (in_array('extension_api', $options)) {
41 $val = reset($xmlrpcVal->me);
42 $typ = key($xmlrpcVal->me);
44 case 'dateTime.iso8601':
46 'xmlrpc_type' => 'datetime',
48 'timestamp' => \PhpXmlRpc\Helper\Date::iso8601Decode($val)
50 return (object)$xmlrpcVal;
53 'xmlrpc_type' => 'base64',
56 return (object)$xmlrpcVal;
58 if (isset($options['extension_api_encoding'])) {
59 $dval = @iconv('UTF-8', $options['extension_api_encoding'], $val);
60 if ($dval !== false) {
65 // break through voluntarily
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);
78 $result = new \DateTime();
79 $result->setTimestamp($out);
82 } elseif (is_a($out, 'DateTimeInterface')) {
86 return $xmlrpcVal->scalarval();
90 foreach($xmlrpcVal as $value) {
91 $arr[] = $this->decode($value, $options);
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
100 if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
101 && class_exists($xmlrpcVal->_php_class)
103 $obj = @new $xmlrpcVal->_php_class();
104 foreach ($xmlrpcVal as $key => $value) {
105 $obj->$key = $this->decode($value, $options);
110 foreach ($xmlrpcVal as $key => $value) {
111 $arr[$key] = $this->decode($value, $options);
117 $paramCount = $xmlrpcVal->getNumParams();
119 for ($i = 0; $i < $paramCount; $i++) {
120 $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
124 /// @todo throw on unsupported type
129 * Takes native php types and encodes them into xmlrpc PHP object format.
130 * It will not re-encode xmlrpc value objects.
132 * Feature creep -- could support more types via optional type argument
133 * (string => datetime support has been added, ??? => base64 not yet)
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
138 * @author Dan Libby (dan@libby.com)
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'
145 public function encode($phpVal, $options = array())
147 $type = gettype($phpVal);
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);
154 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
158 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
161 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
163 // Add support for encoding/decoding of booleans, since they are supported in PHP
165 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
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!
176 foreach ($phpVal as $key => $val) {
177 $arr[$key] = $this->encode($val, $options);
178 if (!$ko && $key !== $j) {
184 $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
186 $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
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) {
199 $xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcBase64);
202 $xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcDateTime);
205 $xmlrpcVal = new Value();
208 $xmlrpcVal = new Value();
213 foreach($phpVal as $k => $v) {
214 $arr[$k] = $this->encode($v, $options);
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);
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);
230 $xmlrpcVal = new Value();
234 if (in_array('extension_api', $options)) {
235 $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
237 $xmlrpcVal = new Value();
240 // catch "user function", "unknown type"
242 // giancarlo pinerolo <ping@alt.it>
243 // it has to return an empty object in case, not a boolean.
244 $xmlrpcVal = new Value();
252 * Convert the xml representation of a method response, method request or single
253 * xmlrpc value into the appropriate object (a.k.a. deserialize).
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
258 * @param string $xmlVal
259 * @param array $options
261 * @return Value|Request|Response|false false on error, or an instance of either Value, Request or Response
263 public function decodeXml($xmlVal, $options = array())
265 // 'guestimate' encoding
266 $valEncoding = XMLParser::guessEncoding('', $xmlVal);
267 if ($valEncoding != '') {
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);
280 if (extension_loaded('mbstring')) {
281 $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
283 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
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');
294 $parserOptions = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
297 $xmlRpcParser = new XMLParser($parserOptions);
298 $xmlRpcParser->parse($xmlVal, XMLParser::RETURN_XMLRPCVALS, XMLParser::ACCEPT_REQUEST | XMLParser::ACCEPT_RESPONSE | XMLParser::ACCEPT_VALUE | XMLParser::ACCEPT_FAULT);
300 if ($xmlRpcParser->_xh['isf'] > 1) {
301 // test that $xmlrpc->_xh['value'] is an obj, too???
303 Logger::instance()->errorLog($xmlRpcParser->_xh['isf_reason']);
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());
318 $r = new Response($v);
323 $req = new Request($xmlRpcParser->_xh['method']);
324 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
325 $req->addParam($xmlRpcParser->_xh['params'][$i]);
330 return $xmlRpcParser->_xh['value'];
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'];
343 return new Response(0, $vc, $vs);