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':
44 $xmlrpcVal->scalar = $val;
45 $xmlrpcVal->type = 'datetime';
46 $xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601Decode($val);
50 $xmlrpcVal->scalar = $val;
51 $xmlrpcVal->type = $typ;
55 return $xmlrpcVal->scalarval();
58 if (in_array('dates_as_objects', $options) && $xmlrpcVal->scalartyp() == 'dateTime.iso8601') {
59 // we return a Datetime object instead of a string since now the constructor of xmlrpc value accepts
60 // safely strings, ints and datetimes, we cater to all 3 cases here
61 $out = $xmlrpcVal->scalarval();
62 if (is_string($out)) {
63 $out = strtotime($out);
66 $result = new \DateTime();
67 $result->setTimestamp($out);
70 } elseif (is_a($out, 'DateTimeInterface')) {
75 return $xmlrpcVal->scalarval();
78 foreach($xmlrpcVal as $value) {
79 $arr[] = $this->decode($value, $options);
84 // If user said so, try to rebuild php objects for specific struct vals.
85 /// @todo should we raise a warning for class not found?
86 // shall we check for proper subclass of xmlrpc value instead of presence of _php_class to detect
88 if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
89 && class_exists($xmlrpcVal->_php_class)
91 $obj = @new $xmlrpcVal->_php_class();
92 foreach ($xmlrpcVal as $key => $value) {
93 $obj->$key = $this->decode($value, $options);
99 foreach ($xmlrpcVal as $key => $value) {
100 $arr[$key] = $this->decode($value, $options);
106 $paramCount = $xmlrpcVal->getNumParams();
108 for ($i = 0; $i < $paramCount; $i++) {
109 $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
117 * Takes native php types and encodes them into xmlrpc PHP object format.
118 * It will not re-encode xmlrpc value objects.
120 * Feature creep -- could support more types via optional type argument
121 * (string => datetime support has been added, ??? => base64 not yet)
123 * If given a proper options parameter, php object instances will be encoded into 'special' xmlrpc values, that can
124 * later be decoded into php objects by calling php_xmlrpc_decode() with a corresponding option
126 * @author Dan Libby (dan@libby.com)
128 * @param mixed $phpVal the value to be converted into an xmlrpc value object
129 * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
131 * @return \PhpXmlrpc\Value
133 public function encode($phpVal, $options = array())
135 $type = gettype($phpVal);
138 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) {
139 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
141 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
145 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
148 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
150 // Add support for encoding/decoding of booleans, since they are supported in PHP
152 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
155 // PHP arrays can be encoded to either xmlrpc structs or arrays, depending on whether they are hashes
156 // or plain 0..n integer indexed
157 // A shorter one-liner would be
158 // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
159 // but execution time skyrockets!
163 foreach ($phpVal as $key => $val) {
164 $arr[$key] = $this->encode($val, $options);
165 if (!$ko && $key !== $j) {
171 $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
173 $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
177 if (is_a($phpVal, 'PhpXmlRpc\Value')) {
178 $xmlrpcVal = $phpVal;
179 } elseif (is_a($phpVal, 'DateTimeInterface')) {
180 $xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcStruct);
183 foreach($phpVal as $k => $v) {
184 $arr[$k] = $this->encode($v, $options);
186 $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
187 if (in_array('encode_php_objs', $options)) {
188 // let's save original class name into xmlrpc value:
189 // might be useful later on...
190 $xmlrpcVal->_php_class = get_class($phpVal);
195 if (in_array('extension_api', $options)) {
196 $xmlrpcVal = new Value('', Value::$xmlrpcString);
197 } elseif (in_array('null_extension', $options)) {
198 $xmlrpcVal = new Value('', Value::$xmlrpcNull);
200 $xmlrpcVal = new Value();
204 if (in_array('extension_api', $options)) {
205 $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
207 $xmlrpcVal = new Value();
210 // catch "user function", "unknown type"
212 // giancarlo pinerolo <ping@alt.it>
213 // it has to return an empty object in case, not a boolean.
214 $xmlrpcVal = new Value();
222 * Convert the xml representation of a method response, method request or single
223 * xmlrpc value into the appropriate object (a.k.a. deserialize).
225 * Q: is this a good name for this method? It does something quite different from 'decode' after all
226 * (returning objects vs returns plain php values)...
228 * @param string $xmlVal
229 * @param array $options
231 * @return mixed false on error, or an instance of either Value, Request or Response
233 public function decodeXml($xmlVal, $options = array())
235 // 'guestimate' encoding
236 $valEncoding = XMLParser::guessEncoding('', $xmlVal);
237 if ($valEncoding != '') {
239 // Since parsing will fail if
240 // - charset is not specified in the xml prologue,
241 // - the encoding is not UTF8 and
242 // - there are non-ascii chars in the text,
243 // we try to work round that...
244 // The following code might be better for mb_string enabled installs, but makes the lib about 200% slower...
245 //if (!is_valid_charset($valEncoding, array('UTF-8'))
246 if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) {
247 if ($valEncoding == 'ISO-8859-1') {
248 $xmlVal = utf8_encode($xmlVal);
250 if (extension_loaded('mbstring')) {
251 $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
253 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
259 // What if internal encoding is not in one of the 3 allowed? We use the broadest one, ie. utf8!
260 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
261 $options = array(XML_OPTION_TARGET_ENCODING => 'UTF-8');
263 $options = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
266 $xmlRpcParser = new XMLParser($options);
267 $xmlRpcParser->parse($xmlVal, XMLParser::RETURN_XMLRPCVALS, XMLParser::ACCEPT_REQUEST | XMLParser::ACCEPT_RESPONSE | XMLParser::ACCEPT_VALUE);
269 if ($xmlRpcParser->_xh['isf'] > 1) {
270 // test that $xmlrpc->_xh['value'] is an obj, too???
272 Logger::instance()->errorLog($xmlRpcParser->_xh['isf_reason']);
277 switch ($xmlRpcParser->_xh['rt']) {
278 case 'methodresponse':
279 $v = $xmlRpcParser->_xh['value'];
280 if ($xmlRpcParser->_xh['isf'] == 1) {
281 /** @var Value $vc */
282 $vc = $v['faultCode'];
283 /** @var Value $vs */
284 $vs = $v['faultString'];
285 $r = new Response(0, $vc->scalarval(), $vs->scalarval());
287 $r = new Response($v);
292 $req = new Request($xmlRpcParser->_xh['method']);
293 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
294 $req->addParam($xmlRpcParser->_xh['params'][$i]);
299 return $xmlRpcParser->_xh['value'];