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
15 * Takes an xmlrpc value in object format and translates it into native PHP types.
17 * Works with xmlrpc requests objects as input, too.
19 * Given proper options parameter, can rebuild generic php object instances (provided those have been encoded to
20 * xmlrpc format using a corresponding 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 get executed on your server, leaving
23 * the door possibly open to 'php-injection' style of attacks (provided you have some classes defined on your server
24 * that might wreak havoc if instances are built outside an appropriate context).
25 * Make sure you trust the remote server/client before eanbling this!
27 * @author Dan Libby (dan@libby.com)
29 * @param Value|Request $xmlrpcVal
30 * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php
31 * objects; if 'dates_as_objects' is set xmlrpc datetimes are decoded as php DateTime objects
35 public function decode($xmlrpcVal, $options = array())
37 switch ($xmlrpcVal->kindOf()) {
39 if (in_array('extension_api', $options)) {
40 $val = reset($xmlrpcVal->me);
41 $typ = key($xmlrpcVal->me);
43 case 'dateTime.iso8601':
45 'xmlrpc_type' => 'datetime',
47 'timestamp' => \PhpXmlRpc\Helper\Date::iso8601Decode($val)
49 return (object)$xmlrpcVal;
52 'xmlrpc_type' => 'base64',
55 return (object)$xmlrpcVal;
57 return $xmlrpcVal->scalarval();
60 if (in_array('dates_as_objects', $options) && $xmlrpcVal->scalartyp() == 'dateTime.iso8601') {
61 // we return a Datetime object instead of a string since now the constructor of xmlrpc value accepts
62 // safely strings, ints and datetimes, we cater to all 3 cases here
63 $out = $xmlrpcVal->scalarval();
64 if (is_string($out)) {
65 $out = strtotime($out);
68 $result = new \DateTime();
69 $result->setTimestamp($out);
72 } elseif (is_a($out, 'DateTimeInterface')) {
77 return $xmlrpcVal->scalarval();
80 foreach($xmlrpcVal as $value) {
81 $arr[] = $this->decode($value, $options);
86 // If user said so, try to rebuild php objects for specific struct vals.
87 /// @todo should we raise a warning for class not found?
88 // shall we check for proper subclass of xmlrpc value instead of presence of _php_class to detect
90 if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
91 && class_exists($xmlrpcVal->_php_class)
93 $obj = @new $xmlrpcVal->_php_class();
94 foreach ($xmlrpcVal as $key => $value) {
95 $obj->$key = $this->decode($value, $options);
101 foreach ($xmlrpcVal as $key => $value) {
102 $arr[$key] = $this->decode($value, $options);
108 $paramCount = $xmlrpcVal->getNumParams();
110 for ($i = 0; $i < $paramCount; $i++) {
111 $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
119 * Takes native php types and encodes them into xmlrpc PHP object format.
120 * It will not re-encode xmlrpc value objects.
122 * Feature creep -- could support more types via optional type argument
123 * (string => datetime support has been added, ??? => base64 not yet)
125 * If given a proper options parameter, php object instances will be encoded into 'special' xmlrpc values, that can
126 * later be decoded into php objects by calling php_xmlrpc_decode() with a corresponding option
128 * @author Dan Libby (dan@libby.com)
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'
133 * @return \PhpXmlrpc\Value
135 public function encode($phpVal, $options = array())
137 $type = gettype($phpVal);
140 /// @todo should we be stricter in the accepted dates (ie. reject more of invalid days & times)?
141 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) {
142 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
144 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
148 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
151 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
153 // Add support for encoding/decoding of booleans, since they are supported in PHP
155 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
158 // PHP arrays can be encoded to either xmlrpc structs or arrays, depending on whether they are hashes
159 // or plain 0..n integer indexed
160 // A shorter one-liner would be
161 // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
162 // but execution time skyrockets!
166 foreach ($phpVal as $key => $val) {
167 $arr[$key] = $this->encode($val, $options);
168 if (!$ko && $key !== $j) {
174 $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
176 $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
180 if (is_a($phpVal, 'PhpXmlRpc\Value')) {
181 $xmlrpcVal = $phpVal;
182 } elseif (is_a($phpVal, 'DateTimeInterface')) {
183 $xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcStruct);
184 } elseif (in_array('extension_api', $options) && $phpVal instanceof \stdClass && isset($phpVal->xmlrpc_type)) {
185 // Handle the 'pre-converted' base64 and datetime values
186 if (isset($phpVal->scalar)) {
187 switch ($phpVal->xmlrpc_type) {
189 $xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcBase64);
192 $xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcDateTime);
195 $xmlrpcVal = new Value();
198 $xmlrpcVal = new Value();
203 foreach($phpVal as $k => $v) {
204 $arr[$k] = $this->encode($v, $options);
206 $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
207 if (in_array('encode_php_objs', $options)) {
208 // let's save original class name into xmlrpc value:
209 // might be useful later on...
210 $xmlrpcVal->_php_class = get_class($phpVal);
215 if (in_array('extension_api', $options)) {
216 $xmlrpcVal = new Value('', Value::$xmlrpcString);
217 } elseif (in_array('null_extension', $options)) {
218 $xmlrpcVal = new Value('', Value::$xmlrpcNull);
220 $xmlrpcVal = new Value();
224 if (in_array('extension_api', $options)) {
225 $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
227 $xmlrpcVal = new Value();
230 // catch "user function", "unknown type"
232 // giancarlo pinerolo <ping@alt.it>
233 // it has to return an empty object in case, not a boolean.
234 $xmlrpcVal = new Value();
242 * Convert the xml representation of a method response, method request or single
243 * xmlrpc value into the appropriate object (a.k.a. deserialize).
245 * Q: is this a good name for this method? It does something quite different from 'decode' after all
246 * (returning objects vs returns plain php values)...
248 * @param string $xmlVal
249 * @param array $options
251 * @return mixed false on error, or an instance of either Value, Request or Response
253 public function decodeXml($xmlVal, $options = array())
255 // 'guestimate' encoding
256 $valEncoding = XMLParser::guessEncoding('', $xmlVal);
257 if ($valEncoding != '') {
259 // Since parsing will fail if
260 // - charset is not specified in the xml prologue,
261 // - the encoding is not UTF8 and
262 // - there are non-ascii chars in the text,
263 // we try to work round that...
264 // The following code might be better for mb_string enabled installs, but makes the lib about 200% slower...
265 //if (!is_valid_charset($valEncoding, array('UTF-8'))
266 if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) {
267 if ($valEncoding == 'ISO-8859-1') {
268 $xmlVal = utf8_encode($xmlVal);
270 if (extension_loaded('mbstring')) {
271 $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
273 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
279 // What if internal encoding is not in one of the 3 allowed? We use the broadest one, ie. utf8!
280 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
281 $options = array(XML_OPTION_TARGET_ENCODING => 'UTF-8');
283 $options = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
286 $xmlRpcParser = new XMLParser($options);
287 $xmlRpcParser->parse($xmlVal, XMLParser::RETURN_XMLRPCVALS, XMLParser::ACCEPT_REQUEST | XMLParser::ACCEPT_RESPONSE | XMLParser::ACCEPT_VALUE | XMLParser::ACCEPT_FAULT);
289 if ($xmlRpcParser->_xh['isf'] > 1) {
290 // test that $xmlrpc->_xh['value'] is an obj, too???
292 Logger::instance()->errorLog($xmlRpcParser->_xh['isf_reason']);
297 switch ($xmlRpcParser->_xh['rt']) {
298 case 'methodresponse':
299 $v = $xmlRpcParser->_xh['value'];
300 if ($xmlRpcParser->_xh['isf'] == 1) {
301 /** @var Value $vc */
302 $vc = $v['faultCode'];
303 /** @var Value $vs */
304 $vs = $v['faultString'];
305 $r = new Response(0, $vc->scalarval(), $vs->scalarval());
307 $r = new Response($v);
312 $req = new Request($xmlRpcParser->_xh['method']);
313 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
314 $req->addParam($xmlRpcParser->_xh['params'][$i]);
319 return $xmlRpcParser->_xh['value'];
322 $v = $xmlRpcParser->_xh['value'];
323 // use a known error code
324 /** @var Value $vc */
325 $vc = isset($v['faultCode']) ? $v['faultCode']->scalarval() : PhpXmlRpc::$xmlrpcerr['invalid_return'];
326 /** @var Value $vs */
327 $vs = isset($v['faultString']) ? $v['faultString']->scalarval() : '';
328 if (!is_int($vc) || $vc == 0) {
329 $vc = PhpXmlRpc::$xmlrpcerr['invalid_return'];
331 return new Response(0, $vc, $vs);