5 use PhpXmlRpc\Helper\Http;
6 use PhpXmlRpc\Helper\XMLParser;
10 /// @todo: do these need to be public?
13 public $params = array();
15 public $content_type = 'text/xml';
17 // holds data while parsing the response. NB: Not a full Response object
18 protected $httpResponse = array();
21 * @param string $methodName the name of the method to invoke
22 * @param Value[] $params array of parameters to be passed to the method (Value objects)
24 public function __construct($methodName, $params = array())
26 $this->methodname = $methodName;
27 foreach ($params as $param) {
28 $this->addParam($param);
32 public function xml_header($charset_encoding = '')
34 if ($charset_encoding != '') {
35 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
37 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
41 public function xml_footer()
43 return '</methodCall>';
46 public function createPayload($charset_encoding = '')
48 if ($charset_encoding != '') {
49 $this->content_type = 'text/xml; charset=' . $charset_encoding;
51 $this->content_type = 'text/xml';
53 $this->payload = $this->xml_header($charset_encoding);
54 $this->payload .= '<methodName>' . $this->methodname . "</methodName>\n";
55 $this->payload .= "<params>\n";
56 foreach ($this->params as $p) {
57 $this->payload .= "<param>\n" . $p->serialize($charset_encoding) .
60 $this->payload .= "</params>\n";
61 $this->payload .= $this->xml_footer();
65 * Gets/sets the xmlrpc method to be invoked.
67 * @param string $methodName the method to be set (leave empty not to set it)
69 * @return string the method that will be invoked
71 public function method($methodName = '')
73 if ($methodName != '') {
74 $this->methodname = $methodName;
77 return $this->methodname;
81 * Returns xml representation of the message. XML prologue included.
83 * @param string $charset_encoding
85 * @return string the xml representation of the message, xml prologue included
87 public function serialize($charset_encoding = '')
89 $this->createPayload($charset_encoding);
91 return $this->payload;
95 * Add a parameter to the list of parameters to be used upon method invocation.
99 * @return boolean false on failure
101 public function addParam($param)
103 // add check: do not add to self params which are not xmlrpcvals
104 if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
105 $this->params[] = $param;
114 * Returns the nth parameter in the request. The index zero-based.
116 * @param integer $i the index of the parameter to fetch (zero based)
118 * @return Value the i-th parameter
120 public function getParam($i)
122 return $this->params[$i];
126 * Returns the number of parameters in the message.
128 * @return integer the number of parameters currently set
130 public function getNumParams()
132 return count($this->params);
136 * Given an open file handle, read all data available and parse it as an xmlrpc response.
137 * NB: the file handle is not closed by this function.
138 * NNB: might have trouble in rare cases to work on network streams, as we
139 * check for a read of 0 bytes instead of feof($fp).
140 * But since checking for feof(null) returns false, we would risk an
141 * infinite loop in that case, because we cannot trust the caller
142 * to give us a valid pointer to an open file...
144 * @param resource $fp stream pointer
148 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
150 public function parseResponseFile($fp)
153 while ($data = fread($fp, 32768)) {
157 return $this->parseResponse($ipd);
161 * Parses HTTP headers and separates them from data.
163 * @return null|Response null on success, or a Response on error
165 private function parseResponseHeaders(&$data, $headers_processed = false)
167 $this->httpResponse['headers'] = array();
168 $this->httpResponse['cookies'] = array();
170 // Support "web-proxy-tunelling" connections for https through proxies
171 if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
172 // Look for CR/LF or simple LF as line separator,
173 // (even though it is not valid http)
174 $pos = strpos($data, "\r\n\r\n");
175 if ($pos || is_int($pos)) {
178 $pos = strpos($data, "\n\n");
179 if ($pos || is_int($pos)) {
182 // No separation between response headers and body: fault?
187 // this filters out all http headers from proxy.
188 // maybe we could take them into account, too?
189 $data = substr($data, $bd);
191 error_log('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
192 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)');
198 // Strip HTTP 1.1 100 Continue header if present
199 while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
200 $pos = strpos($data, 'HTTP', 12);
201 // server sent a Continue header without any (valid) content following...
202 // give the client a chance to know it
203 if (!$pos && !is_int($pos)) {
204 // works fine in php 3, 4 and 5
208 $data = substr($data, $pos);
210 if (!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) {
211 $errstr = substr($data, 0, strpos($data, "\n") - 1);
212 error_log('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
213 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')');
218 // be tolerant to usage of \n instead of \r\n to separate headers and data
219 // (even though it is not valid http)
220 $pos = strpos($data, "\r\n\r\n");
221 if ($pos || is_int($pos)) {
224 $pos = strpos($data, "\n\n");
225 if ($pos || is_int($pos)) {
228 // No separation between response headers and body: fault?
229 // we could take some action here instead of going on...
233 // be tolerant to line endings, and extra empty lines
234 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
235 while (list(, $line) = @each($ar)) {
236 // take care of multi-line headers and cookies
237 $arr = explode(':', $line, 2);
238 if (count($arr) > 1) {
239 $header_name = strtolower(trim($arr[0]));
240 /// @todo some other headers (the ones that allow a CSV list of values)
241 /// do allow many values to be passed using multiple header lines.
242 /// We should add content to $xmlrpc->_xh['headers'][$header_name]
243 /// instead of replacing it for those...
244 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') {
245 if ($header_name == 'set-cookie2') {
246 // version 2 cookies:
247 // there could be many cookies on one line, comma separated
248 $cookies = explode(',', $arr[1]);
250 $cookies = array($arr[1]);
252 foreach ($cookies as $cookie) {
253 // glue together all received cookies, using a comma to separate them
254 // (same as php does with getallheaders())
255 if (isset($this->httpResponse['headers'][$header_name])) {
256 $this->httpResponse['headers'][$header_name] .= ', ' . trim($cookie);
258 $this->httpResponse['headers'][$header_name] = trim($cookie);
260 // parse cookie attributes, in case user wants to correctly honour them
261 // feature creep: only allow rfc-compliant cookie attributes?
262 // @todo support for server sending multiple time cookie with same name, but using different PATHs
263 $cookie = explode(';', $cookie);
264 foreach ($cookie as $pos => $val) {
265 $val = explode('=', $val, 2);
266 $tag = trim($val[0]);
267 $val = trim(@$val[1]);
268 /// @todo with version 1 cookies, we should strip leading and trailing " chars
271 $this->httpResponse['cookies'][$tag] = array();
272 $this->httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
274 if ($tag != 'value') {
275 $this->httpResponse['cookies'][$cookiename][$tag] = $val;
281 $this->httpResponse['headers'][$header_name] = trim($arr[1]);
283 } elseif (isset($header_name)) {
284 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
285 $this->httpResponse['headers'][$header_name] .= ' ' . trim($line);
289 $data = substr($data, $bd);
291 if ($this->debug && count($this->httpResponse['headers'])) {
293 foreach ($this->httpResponse['headers'] as $header => $value) {
294 $msg .= "HEADER: $header: $value\n";
296 foreach ($this->httpResponse['cookies'] as $header => $value) {
297 $msg .= "COOKIE: $header={$value['value']}\n";
299 $this->debugMessage($msg);
302 // if CURL was used for the call, http headers have been processed,
303 // and dechunking + reinflating have been carried out
304 if (!$headers_processed) {
305 // Decode chunked encoding sent by http 1.1 servers
306 if (isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked') {
307 if (!$data = Http::decode_chunked($data)) {
308 error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
309 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']);
315 // Decode gzip-compressed stuff
316 // code shamelessly inspired from nusoap library by Dietrich Ayala
317 if (isset($this->httpResponse['headers']['content-encoding'])) {
318 $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']);
319 if ($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip') {
320 // if decoding works, use it. else assume data wasn't gzencoded
321 if (function_exists('gzinflate')) {
322 if ($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
325 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
327 } elseif ($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
330 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
333 error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
334 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']);
339 error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
340 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']);
346 } // end of 'if needed, de-chunk, re-inflate response'
352 * Parse the xmlrpc response contained in the string $data and return a Response object.
354 * @param string $data the xmlrpc response, eventually including http headers
355 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
356 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
360 public function parseResponse($data = '', $headers_processed = false, $return_type = 'xmlrpcvals')
363 // by maHo, replaced htmlspecialchars with htmlentities
364 $this->debugMessage("---GOT---\n$data\n---END---");
367 $this->httpResponse = array();
368 $this->httpResponse['raw_data'] = $data;
369 $this->httpResponse['headers'] = array();
370 $this->httpResponse['cookies'] = array();
373 error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.');
374 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
379 // parse the HTTP headers of the response, if present, and separate them from data
380 if (substr($data, 0, 4) == 'HTTP') {
381 $r = $this->parseResponseHeaders($data, $headers_processed);
383 // failed processing of HTTP response headers
384 // save into response obj the full payload received, for debugging
385 $r->raw_data = $data;
392 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
394 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
395 $end = strpos($data, '-->', $start);
396 $comments = substr($data, $start, $end - $start);
397 $this->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n</PRE>";
401 // be tolerant of extra whitespace in response body
404 /// @todo return an error msg if $data=='' ?
406 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
407 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
408 $pos = strrpos($data, '</methodResponse>');
409 if ($pos !== false) {
410 $data = substr($data, 0, $pos + 17);
413 // if user wants back raw xml, give it to him
414 if ($return_type == 'xml') {
415 $r = new Response($data, 0, '', 'xml');
416 $r->hdrs = $this->httpResponse['headers'];
417 $r->_cookies = $this->httpResponse['cookies'];
418 $r->raw_data = $this->httpResponse['raw_data'];
423 // try to 'guestimate' the character encoding of the received response
424 $resp_encoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data);
426 // if response charset encoding is not known / supported, try to use
427 // the default encoding and parse the xml anyway, but log a warning...
428 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
429 // the following code might be better for mb_string enabled installs, but
430 // makes the lib about 200% slower...
431 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
433 error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $resp_encoding);
434 $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding;
436 $parser = xml_parser_create($resp_encoding);
437 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
438 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
439 // the xml parser to give us back data in the expected charset.
440 // What if internal encoding is not in one of the 3 allowed?
441 // we use the broadest one, ie. utf8
442 // This allows to send data which is native in various charset,
443 // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
444 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
445 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
447 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
450 $xmlRpcParser = new XMLParser();
451 xml_set_object($parser, $xmlRpcParser);
453 if ($return_type == 'phpvals') {
454 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
456 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
459 xml_set_character_data_handler($parser, 'xmlrpc_cd');
460 xml_set_default_handler($parser, 'xmlrpc_dh');
462 // first error check: xml not well formed
463 if (!xml_parse($parser, $data, count($data))) {
464 // thanks to Peter Kocks <peter.kocks@baygate.com>
465 if ((xml_get_current_line_number($parser)) == 1) {
466 $errstr = 'XML error at line 1, check URL';
468 $errstr = sprintf('XML error: %s at line %d, column %d',
469 xml_error_string(xml_get_error_code($parser)),
470 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
473 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errstr . ')');
474 xml_parser_free($parser);
478 $r->hdrs = $this->httpResponse['headers'];
479 $r->_cookies = $this->httpResponse['cookies'];
480 $r->raw_data = $this->httpResponse['raw_data'];
484 xml_parser_free($parser);
485 // second error check: xml well formed but not xml-rpc compliant
486 if ($xmlRpcParser->_xh['isf'] > 1) {
488 /// @todo echo something for user?
491 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
492 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
494 // third error check: parsing of the response has somehow gone boink.
495 // NB: shall we omit this check, since we trust the parsing code?
496 elseif ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
497 // something odd has happened
498 // and it's time to generate a client side error
499 // indicating something odd went on
500 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
501 PhpXmlRpc::$xmlrpcstr['invalid_return']);
505 "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---", false
509 // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
510 $v = &$xmlRpcParser->_xh['value'];
512 if ($xmlRpcParser->_xh['isf']) {
513 /// @todo we should test here if server sent an int and a string,
514 /// and/or coerce them into such...
515 if ($return_type == 'xmlrpcvals') {
516 $errno_v = $v->structmem('faultCode');
517 $errstr_v = $v->structmem('faultString');
518 $errno = $errno_v->scalarval();
519 $errstr = $errstr_v->scalarval();
521 $errno = $v['faultCode'];
522 $errstr = $v['faultString'];
526 // FAULT returned, errno needs to reflect that
530 $r = new Response(0, $errno, $errstr);
532 $r = new Response($v, 0, '', $return_type);
536 $r->hdrs = $this->httpResponse['headers'];
537 $r->_cookies = $this->httpResponse['cookies'];
538 $r->raw_data = $this->httpResponse['raw_data'];
544 * Echoes a debug message, taking care of escaping it when not in console mode
546 * @param string $message
548 protected function debugMessage($message, $encodeEntities = true)
550 if (PHP_SAPI != 'cli') {
552 print "<PRE>\n".htmlentities($message)."\n</PRE>";
554 print "<PRE>\n".htmlspecialchars($message)."\n</PRE>";
557 print "\n$message\n";