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>';
47 * Kept the old name even if class was renamed, for compatibility.
51 private function kindOf()
56 public function createPayload($charset_encoding = '')
58 if ($charset_encoding != '') {
59 $this->content_type = 'text/xml; charset=' . $charset_encoding;
61 $this->content_type = 'text/xml';
63 $this->payload = $this->xml_header($charset_encoding);
64 $this->payload .= '<methodName>' . $this->methodname . "</methodName>\n";
65 $this->payload .= "<params>\n";
66 foreach ($this->params as $p) {
67 $this->payload .= "<param>\n" . $p->serialize($charset_encoding) .
70 $this->payload .= "</params>\n";
71 $this->payload .= $this->xml_footer();
75 * Gets/sets the xmlrpc method to be invoked.
77 * @param string $methodName the method to be set (leave empty not to set it)
79 * @return string the method that will be invoked
81 public function method($methodName = '')
83 if ($methodName != '') {
84 $this->methodname = $methodName;
87 return $this->methodname;
91 * Returns xml representation of the message. XML prologue included.
93 * @param string $charset_encoding
95 * @return string the xml representation of the message, xml prologue included
97 public function serialize($charset_encoding = '')
99 $this->createPayload($charset_encoding);
101 return $this->payload;
105 * Add a parameter to the list of parameters to be used upon method invocation.
107 * @param Value $param
109 * @return boolean false on failure
111 public function addParam($param)
113 // add check: do not add to self params which are not xmlrpcvals
114 if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
115 $this->params[] = $param;
124 * Returns the nth parameter in the request. The index zero-based.
126 * @param integer $i the index of the parameter to fetch (zero based)
128 * @return Value the i-th parameter
130 public function getParam($i)
132 return $this->params[$i];
136 * Returns the number of parameters in the message.
138 * @return integer the number of parameters currently set
140 public function getNumParams()
142 return count($this->params);
146 * Given an open file handle, read all data available and parse it as an xmlrpc response.
147 * NB: the file handle is not closed by this function.
148 * NNB: might have trouble in rare cases to work on network streams, as we
149 * check for a read of 0 bytes instead of feof($fp).
150 * But since checking for feof(null) returns false, we would risk an
151 * infinite loop in that case, because we cannot trust the caller
152 * to give us a valid pointer to an open file...
154 * @param resource $fp stream pointer
158 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
160 public function parseResponseFile($fp)
163 while ($data = fread($fp, 32768)) {
167 return $this->parseResponse($ipd);
171 * Parses HTTP headers and separates them from data.
173 * @return null|Response null on success, or a Response on error
175 private function parseResponseHeaders(&$data, $headers_processed = false)
177 $this->httpResponse['headers'] = array();
178 $this->httpResponse['cookies'] = array();
180 // Support "web-proxy-tunelling" connections for https through proxies
181 if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
182 // Look for CR/LF or simple LF as line separator,
183 // (even though it is not valid http)
184 $pos = strpos($data, "\r\n\r\n");
185 if ($pos || is_int($pos)) {
188 $pos = strpos($data, "\n\n");
189 if ($pos || is_int($pos)) {
192 // No separation between response headers and body: fault?
197 // this filters out all http headers from proxy.
198 // maybe we could take them into account, too?
199 $data = substr($data, $bd);
201 error_log('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
202 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)');
208 // Strip HTTP 1.1 100 Continue header if present
209 while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
210 $pos = strpos($data, 'HTTP', 12);
211 // server sent a Continue header without any (valid) content following...
212 // give the client a chance to know it
213 if (!$pos && !is_int($pos)) {
214 // works fine in php 3, 4 and 5
218 $data = substr($data, $pos);
220 if (!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) {
221 $errstr = substr($data, 0, strpos($data, "\n") - 1);
222 error_log('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
223 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')');
228 // be tolerant to usage of \n instead of \r\n to separate headers and data
229 // (even though it is not valid http)
230 $pos = strpos($data, "\r\n\r\n");
231 if ($pos || is_int($pos)) {
234 $pos = strpos($data, "\n\n");
235 if ($pos || is_int($pos)) {
238 // No separation between response headers and body: fault?
239 // we could take some action here instead of going on...
243 // be tolerant to line endings, and extra empty lines
244 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
245 while (list(, $line) = @each($ar)) {
246 // take care of multi-line headers and cookies
247 $arr = explode(':', $line, 2);
248 if (count($arr) > 1) {
249 $header_name = strtolower(trim($arr[0]));
250 /// @todo some other headers (the ones that allow a CSV list of values)
251 /// do allow many values to be passed using multiple header lines.
252 /// We should add content to $xmlrpc->_xh['headers'][$header_name]
253 /// instead of replacing it for those...
254 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') {
255 if ($header_name == 'set-cookie2') {
256 // version 2 cookies:
257 // there could be many cookies on one line, comma separated
258 $cookies = explode(',', $arr[1]);
260 $cookies = array($arr[1]);
262 foreach ($cookies as $cookie) {
263 // glue together all received cookies, using a comma to separate them
264 // (same as php does with getallheaders())
265 if (isset($this->httpResponse['headers'][$header_name])) {
266 $this->httpResponse['headers'][$header_name] .= ', ' . trim($cookie);
268 $this->httpResponse['headers'][$header_name] = trim($cookie);
270 // parse cookie attributes, in case user wants to correctly honour them
271 // feature creep: only allow rfc-compliant cookie attributes?
272 // @todo support for server sending multiple time cookie with same name, but using different PATHs
273 $cookie = explode(';', $cookie);
274 foreach ($cookie as $pos => $val) {
275 $val = explode('=', $val, 2);
276 $tag = trim($val[0]);
277 $val = trim(@$val[1]);
278 /// @todo with version 1 cookies, we should strip leading and trailing " chars
281 $this->httpResponse['cookies'][$tag] = array();
282 $this->httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
284 if ($tag != 'value') {
285 $this->httpResponse['cookies'][$cookiename][$tag] = $val;
291 $this->httpResponse['headers'][$header_name] = trim($arr[1]);
293 } elseif (isset($header_name)) {
294 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
295 $this->httpResponse['headers'][$header_name] .= ' ' . trim($line);
299 $data = substr($data, $bd);
301 if ($this->debug && count($this->httpResponse['headers'])) {
303 foreach ($this->httpResponse['headers'] as $header => $value) {
304 $msg .= "HEADER: $header: $value\n";
306 foreach ($this->httpResponse['cookies'] as $header => $value) {
307 $msg .= "COOKIE: $header={$value['value']}\n";
309 $this->debugMessage($msg);
312 // if CURL was used for the call, http headers have been processed,
313 // and dechunking + reinflating have been carried out
314 if (!$headers_processed) {
315 // Decode chunked encoding sent by http 1.1 servers
316 if (isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked') {
317 if (!$data = Http::decode_chunked($data)) {
318 error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
319 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']);
325 // Decode gzip-compressed stuff
326 // code shamelessly inspired from nusoap library by Dietrich Ayala
327 if (isset($this->httpResponse['headers']['content-encoding'])) {
328 $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']);
329 if ($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip') {
330 // if decoding works, use it. else assume data wasn't gzencoded
331 if (function_exists('gzinflate')) {
332 if ($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
335 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
337 } elseif ($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
340 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
343 error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
344 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']);
349 error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
350 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']);
356 } // end of 'if needed, de-chunk, re-inflate response'
362 * Parse the xmlrpc response contained in the string $data and return a Response object.
364 * @param string $data the xmlrpc response, eventually including http headers
365 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
366 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
370 public function parseResponse($data = '', $headers_processed = false, $return_type = 'xmlrpcvals')
373 // by maHo, replaced htmlspecialchars with htmlentities
374 $this->debugMessage("---GOT---\n$data\n---END---");
377 $this->httpResponse = array();
378 $this->httpResponse['raw_data'] = $data;
379 $this->httpResponse['headers'] = array();
380 $this->httpResponse['cookies'] = array();
383 error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.');
384 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
389 // parse the HTTP headers of the response, if present, and separate them from data
390 if (substr($data, 0, 4) == 'HTTP') {
391 $r = $this->parseResponseHeaders($data, $headers_processed);
393 // failed processing of HTTP response headers
394 // save into response obj the full payload received, for debugging
395 $r->raw_data = $data;
402 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
404 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
405 $end = strpos($data, '-->', $start);
406 $comments = substr($data, $start, $end - $start);
407 $this->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n</PRE>";
411 // be tolerant of extra whitespace in response body
414 /// @todo return an error msg if $data=='' ?
416 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
417 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
418 $pos = strrpos($data, '</methodResponse>');
419 if ($pos !== false) {
420 $data = substr($data, 0, $pos + 17);
423 // if user wants back raw xml, give it to him
424 if ($return_type == 'xml') {
425 $r = new Response($data, 0, '', 'xml');
426 $r->hdrs = $this->httpResponse['headers'];
427 $r->_cookies = $this->httpResponse['cookies'];
428 $r->raw_data = $this->httpResponse['raw_data'];
433 // try to 'guestimate' the character encoding of the received response
434 $resp_encoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data);
436 // if response charset encoding is not known / supported, try to use
437 // the default encoding and parse the xml anyway, but log a warning...
438 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
439 // the following code might be better for mb_string enabled installs, but
440 // makes the lib about 200% slower...
441 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
443 error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $resp_encoding);
444 $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding;
446 $parser = xml_parser_create($resp_encoding);
447 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
448 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
449 // the xml parser to give us back data in the expected charset.
450 // What if internal encoding is not in one of the 3 allowed?
451 // we use the broadest one, ie. utf8
452 // This allows to send data which is native in various charset,
453 // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
454 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
455 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
457 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
460 $xmlRpcParser = new XMLParser();
461 xml_set_object($parser, $xmlRpcParser);
463 if ($return_type == 'phpvals') {
464 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
466 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
469 xml_set_character_data_handler($parser, 'xmlrpc_cd');
470 xml_set_default_handler($parser, 'xmlrpc_dh');
472 // first error check: xml not well formed
473 if (!xml_parse($parser, $data, count($data))) {
474 // thanks to Peter Kocks <peter.kocks@baygate.com>
475 if ((xml_get_current_line_number($parser)) == 1) {
476 $errstr = 'XML error at line 1, check URL';
478 $errstr = sprintf('XML error: %s at line %d, column %d',
479 xml_error_string(xml_get_error_code($parser)),
480 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
483 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errstr . ')');
484 xml_parser_free($parser);
488 $r->hdrs = $this->httpResponse['headers'];
489 $r->_cookies = $this->httpResponse['cookies'];
490 $r->raw_data = $this->httpResponse['raw_data'];
494 xml_parser_free($parser);
495 // second error check: xml well formed but not xml-rpc compliant
496 if ($xmlRpcParser->_xh['isf'] > 1) {
498 /// @todo echo something for user?
501 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
502 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
504 // third error check: parsing of the response has somehow gone boink.
505 // NB: shall we omit this check, since we trust the parsing code?
506 elseif ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
507 // something odd has happened
508 // and it's time to generate a client side error
509 // indicating something odd went on
510 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
511 PhpXmlRpc::$xmlrpcstr['invalid_return']);
515 "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---", false
519 // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
520 $v = &$xmlRpcParser->_xh['value'];
522 if ($xmlRpcParser->_xh['isf']) {
523 /// @todo we should test here if server sent an int and a string,
524 /// and/or coerce them into such...
525 if ($return_type == 'xmlrpcvals') {
526 $errno_v = $v->structmem('faultCode');
527 $errstr_v = $v->structmem('faultString');
528 $errno = $errno_v->scalarval();
529 $errstr = $errstr_v->scalarval();
531 $errno = $v['faultCode'];
532 $errstr = $v['faultString'];
536 // FAULT returned, errno needs to reflect that
540 $r = new Response(0, $errno, $errstr);
542 $r = new Response($v, 0, '', $return_type);
546 $r->hdrs = $this->httpResponse['headers'];
547 $r->_cookies = $this->httpResponse['cookies'];
548 $r->raw_data = $this->httpResponse['raw_data'];
554 * Echoes a debug message, taking care of escaping it when not in console mode
556 * @param string $message
558 protected function debugMessage($message, $encodeEntities = true)
560 if (PHP_SAPI != 'cli') {
562 print "<PRE>\n".htmlentities($message)."\n</PRE>";
564 print "<PRE>\n".htmlspecialchars($message)."\n</PRE>";
567 print "\n$message\n";