5 use PhpXmlRpc\Helper\XMLParser;
8 * A helper class to easily convert between Value objects and php native values
9 * @todo implement an interface
14 * Takes an xmlrpc value in object format and translates it into native PHP types.
16 * Works with xmlrpc requests objects as input, too.
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!
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 objects; if 'dates_as_objects' is set xmlrpc datetimes are decoded as php DateTime objects (standard is
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
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);
67 $result = new \DateTime();
68 $result->setTimestamp($out);
71 } elseif (is_a($out, 'DateTimeInterface')) {
76 return $xmlrpcVal->scalarval();
79 foreach($xmlrpcVal as $value) {
80 $arr[] = $this->decode($value, $options);
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)
92 $obj = @new $xmlrpcVal->_php_class();
93 foreach ($xmlrpcVal as $key => $value) {
94 $obj->$key = $this->decode($value, $options);
100 foreach ($xmlrpcVal as $key => $value) {
101 $arr[$key] = $this->decode($value, $options);
107 $paramCount = $xmlrpcVal->getNumParams();
109 for ($i = 0; $i < $paramCount; $i++) {
110 $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
118 * Takes native php types and encodes them into xmlrpc PHP object format.
119 * It will not re-encode xmlrpc value objects.
121 * Feature creep -- could support more types via optional type argument
122 * (string => datetime support has been added, ??? => base64 not yet)
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
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 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);
143 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
147 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
150 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
152 // <G_Giunta_2001-02-29>
153 // Add support for encoding/decoding of booleans, since they are supported in PHP
155 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
157 // </G_Giunta_2001-02-29>
159 // PHP arrays can be encoded to either xmlrpc structs or arrays,
160 // depending on whether they are hashes 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::$xmlrpcStruct);
187 foreach($phpVal as $k => $v) {
188 $arr[$k] = $this->encode($v, $options);
190 $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
191 if (in_array('encode_php_objs', $options)) {
192 // let's save original class name into xmlrpc value:
193 // might be useful later on...
194 $xmlrpcVal->_php_class = get_class($phpVal);
199 if (in_array('extension_api', $options)) {
200 $xmlrpcVal = new Value('', Value::$xmlrpcString);
201 } elseif (in_array('null_extension', $options)) {
202 $xmlrpcVal = new Value('', Value::$xmlrpcNull);
204 $xmlrpcVal = new Value();
208 if (in_array('extension_api', $options)) {
209 $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
211 $xmlrpcVal = new Value();
214 // catch "user function", "unknown type"
216 // giancarlo pinerolo <ping@alt.it>
218 // an empty object in case, not a boolean.
219 $xmlrpcVal = new Value();
227 * Convert the xml representation of a method response, method request or single
228 * xmlrpc value into the appropriate object (a.k.a. deserialize).
230 * @param string $xmlVal
231 * @param array $options
233 * @return mixed false on error, or an instance of either Value, Request or Response
235 public function decodeXml($xmlVal, $options = array())
237 // 'guestimate' encoding
238 $valEncoding = XMLParser::guessEncoding('', $xmlVal);
239 if ($valEncoding != '') {
241 // Since parsing will fail if charset is not specified in the xml prologue,
242 // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
243 // The following code might be better for mb_string enabled installs, but
244 // 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 error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
259 $parser = xml_parser_create();
260 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
261 // What if internal encoding is not in one of the 3 allowed?
262 // we use the broadest one, ie. utf8!
263 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
264 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
266 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
269 $xmlRpcParser = new XMLParser();
270 xml_set_object($parser, $xmlRpcParser);
272 xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
273 xml_set_character_data_handler($parser, 'xmlrpc_cd');
274 xml_set_default_handler($parser, 'xmlrpc_dh');
275 if (!xml_parse($parser, $xmlVal, 1)) {
276 $errstr = sprintf('XML error: %s at line %d, column %d',
277 xml_error_string(xml_get_error_code($parser)),
278 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
280 xml_parser_free($parser);
284 xml_parser_free($parser);
285 if ($xmlRpcParser->_xh['isf'] > 1) {
286 // test that $xmlrpc->_xh['value'] is an obj, too???
288 error_log($xmlRpcParser->_xh['isf_reason']);
292 switch ($xmlRpcParser->_xh['rt']) {
293 case 'methodresponse':
294 $v = &$xmlRpcParser->_xh['value'];
295 if ($xmlRpcParser->_xh['isf'] == 1) {
296 /** @var Value $vc */
297 $vc = $v['faultCode'];
298 /** @var Value $vs */
299 $vs = $v['faultString'];
300 $r = new Response(0, $vc->scalarval(), $vs->scalarval());
302 $r = new Response($v);
307 $req = new Request($xmlRpcParser->_xh['method']);
308 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
309 $req->addParam($xmlRpcParser->_xh['params'][$i]);
314 return $xmlRpcParser->_xh['value'];