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 return $xmlrpcVal->scalarval();
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);
69 $result = new \DateTime();
70 $result->setTimestamp($out);
73 } elseif (is_a($out, 'DateTimeInterface')) {
78 return $xmlrpcVal->scalarval();
81 foreach($xmlrpcVal as $value) {
82 $arr[] = $this->decode($value, $options);
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
91 if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
92 && class_exists($xmlrpcVal->_php_class)
94 $obj = @new $xmlrpcVal->_php_class();
95 foreach ($xmlrpcVal as $key => $value) {
96 $obj->$key = $this->decode($value, $options);
102 foreach ($xmlrpcVal as $key => $value) {
103 $arr[$key] = $this->decode($value, $options);
109 $paramCount = $xmlrpcVal->getNumParams();
111 for ($i = 0; $i < $paramCount; $i++) {
112 $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
120 * Takes native php types and encodes them into xmlrpc PHP object format.
121 * It will not re-encode xmlrpc value objects.
123 * Feature creep -- could support more types via optional type argument
124 * (string => datetime support has been added, ??? => base64 not yet)
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
129 * @author Dan Libby (dan@libby.com)
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'
134 * @return \PhpXmlrpc\Value
136 public function encode($phpVal, $options = array())
138 $type = gettype($phpVal);
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);
145 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
149 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
152 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
154 // Add support for encoding/decoding of booleans, since they are supported in PHP
156 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
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!
167 foreach ($phpVal as $key => $val) {
168 $arr[$key] = $this->encode($val, $options);
169 if (!$ko && $key !== $j) {
175 $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
177 $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
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) {
190 $xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcBase64);
193 $xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcDateTime);
196 $xmlrpcVal = new Value();
199 $xmlrpcVal = new Value();
204 foreach($phpVal as $k => $v) {
205 $arr[$k] = $this->encode($v, $options);
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);
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);
221 $xmlrpcVal = new Value();
225 if (in_array('extension_api', $options)) {
226 $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
228 $xmlrpcVal = new Value();
231 // catch "user function", "unknown type"
233 // giancarlo pinerolo <ping@alt.it>
234 // it has to return an empty object in case, not a boolean.
235 $xmlrpcVal = new Value();
243 * Convert the xml representation of a method response, method request or single
244 * xmlrpc value into the appropriate object (a.k.a. deserialize).
246 * Q: is this a good name for this method? It does something quite different from 'decode' after all
247 * (returning objects vs returns plain php values)...
249 * @param string $xmlVal
250 * @param array $options
252 * @return mixed false on error, or an instance of either Value, Request or Response
254 public function decodeXml($xmlVal, $options = array())
256 // 'guestimate' encoding
257 $valEncoding = XMLParser::guessEncoding('', $xmlVal);
258 if ($valEncoding != '') {
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);
271 if (extension_loaded('mbstring')) {
272 $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
274 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
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');
284 $parserOptions = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
287 $xmlRpcParser = new XMLParser($parserOptions);
288 $xmlRpcParser->parse($xmlVal, XMLParser::RETURN_XMLRPCVALS, XMLParser::ACCEPT_REQUEST | XMLParser::ACCEPT_RESPONSE | XMLParser::ACCEPT_VALUE | XMLParser::ACCEPT_FAULT);
290 if ($xmlRpcParser->_xh['isf'] > 1) {
291 // test that $xmlrpc->_xh['value'] is an obj, too???
293 Logger::instance()->errorLog($xmlRpcParser->_xh['isf_reason']);
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());
308 $r = new Response($v);
313 $req = new Request($xmlRpcParser->_xh['method']);
314 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
315 $req->addParam($xmlRpcParser->_xh['params'][$i]);
320 return $xmlRpcParser->_xh['value'];
323 $v = $xmlRpcParser->_xh['value'];
324 // use a known error code
325 /** @var Value $vc */
326 $vc = isset($v['faultCode']) ? $v['faultCode']->scalarval() : PhpXmlRpc::$xmlrpcerr['invalid_return'];
327 /** @var Value $vs */
328 $vs = isset($v['faultString']) ? $v['faultString']->scalarval() : '';
329 if (!is_int($vc) || $vc == 0) {
330 $vc = PhpXmlRpc::$xmlrpcerr['invalid_return'];
332 return new Response(0, $vc, $vs);