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 array $params array of parameters to be passed to the method (xmlrpcval 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 $meth 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.
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 messge.
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 axmlrpc 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 /// @todo when in CLI mode, do not html-encode the output
302 if ($this->debug && count($this->httpResponse['headers'])) {
304 foreach ($this->httpResponse['headers'] as $header => $value) {
305 print htmlentities("HEADER: $header: $value\n");
307 foreach ($this->httpResponse['cookies'] as $header => $value) {
308 print htmlentities("COOKIE: $header={$value['value']}\n");
313 // if CURL was used for the call, http headers have been processed,
314 // and dechunking + reinflating have been carried out
315 if (!$headers_processed) {
316 // Decode chunked encoding sent by http 1.1 servers
317 if (isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked') {
318 if (!$data = Http::decode_chunked($data)) {
319 error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
320 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']);
326 // Decode gzip-compressed stuff
327 // code shamelessly inspired from nusoap library by Dietrich Ayala
328 if (isset($this->httpResponse['headers']['content-encoding'])) {
329 $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']);
330 if ($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip') {
331 // if decoding works, use it. else assume data wasn't gzencoded
332 if (function_exists('gzinflate')) {
333 if ($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
336 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
338 } elseif ($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
341 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
344 error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
345 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']);
350 error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
351 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']);
357 } // end of 'if needed, de-chunk, re-inflate response'
363 * Parse the xmlrpc response contained in the string $data and return a Response object.
365 * @param string $data the xmlrpc response, eventually including http headers
366 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
367 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
371 public function parseResponse($data = '', $headers_processed = false, $return_type = 'xmlrpcvals')
374 // by maHo, replaced htmlspecialchars with htmlentities
375 $this->debugMessage("---GOT---\n$data\n---END---");
378 $this->httpResponse = array();
379 $this->httpResponse['raw_data'] = $data;
380 $this->httpResponse['headers'] = array();
381 $this->httpResponse['cookies'] = array();
384 error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.');
385 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
390 // parse the HTTP headers of the response, if present, and separate them from data
391 if (substr($data, 0, 4) == 'HTTP') {
392 $r = $this->parseResponseHeaders($data, $headers_processed);
394 // failed processing of HTTP response headers
395 // save into response obj the full payload received, for debugging
396 $r->raw_data = $data;
403 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
405 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
406 $end = strpos($data, '-->', $start);
407 $comments = substr($data, $start, $end - $start);
408 $this->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n</PRE>";
412 // be tolerant of extra whitespace in response body
415 /// @todo return an error msg if $data=='' ?
417 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
418 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
419 $pos = strrpos($data, '</methodResponse>');
420 if ($pos !== false) {
421 $data = substr($data, 0, $pos + 17);
424 // if user wants back raw xml, give it to him
425 if ($return_type == 'xml') {
426 $r = new Response($data, 0, '', 'xml');
427 $r->hdrs = $this->httpResponse['headers'];
428 $r->_cookies = $this->httpResponse['cookies'];
429 $r->raw_data = $this->httpResponse['raw_data'];
434 // try to 'guestimate' the character encoding of the received response
435 $resp_encoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data);
437 // if response charset encoding is not known / supported, try to use
438 // the default encoding and parse the xml anyway, but log a warning...
439 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
440 // the following code might be better for mb_string enabled installs, but
441 // makes the lib about 200% slower...
442 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
444 error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $resp_encoding);
445 $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding;
447 $parser = xml_parser_create($resp_encoding);
448 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
449 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
450 // the xml parser to give us back data in the expected charset.
451 // What if internal encoding is not in one of the 3 allowed?
452 // we use the broadest one, ie. utf8
453 // This allows to send data which is native in various charset,
454 // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
455 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
456 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
458 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
461 $xmlRpcParser = new XMLParser();
462 xml_set_object($parser, $xmlRpcParser);
464 if ($return_type == 'phpvals') {
465 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
467 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
470 xml_set_character_data_handler($parser, 'xmlrpc_cd');
471 xml_set_default_handler($parser, 'xmlrpc_dh');
473 // first error check: xml not well formed
474 if (!xml_parse($parser, $data, count($data))) {
475 // thanks to Peter Kocks <peter.kocks@baygate.com>
476 if ((xml_get_current_line_number($parser)) == 1) {
477 $errstr = 'XML error at line 1, check URL';
479 $errstr = sprintf('XML error: %s at line %d, column %d',
480 xml_error_string(xml_get_error_code($parser)),
481 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
484 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errstr . ')');
485 xml_parser_free($parser);
489 $r->hdrs = $this->httpResponse['headers'];
490 $r->_cookies = $this->httpResponse['cookies'];
491 $r->raw_data = $this->httpResponse['raw_data'];
495 xml_parser_free($parser);
496 // second error check: xml well formed but not xml-rpc compliant
497 if ($xmlRpcParser->_xh['isf'] > 1) {
499 /// @todo echo something for user?
502 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
503 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
505 // third error check: parsing of the response has somehow gone boink.
506 // NB: shall we omit this check, since we trust the parsing code?
507 elseif ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
508 // something odd has happened
509 // and it's time to generate a client side error
510 // indicating something odd went on
511 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
512 PhpXmlRpc::$xmlrpcstr['invalid_return']);
516 "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---", false
520 // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
521 $v = &$xmlRpcParser->_xh['value'];
523 if ($xmlRpcParser->_xh['isf']) {
524 /// @todo we should test here if server sent an int and a string,
525 /// and/or coerce them into such...
526 if ($return_type == 'xmlrpcvals') {
527 $errno_v = $v->structmem('faultCode');
528 $errstr_v = $v->structmem('faultString');
529 $errno = $errno_v->scalarval();
530 $errstr = $errstr_v->scalarval();
532 $errno = $v['faultCode'];
533 $errstr = $v['faultString'];
537 // FAULT returned, errno needs to reflect that
541 $r = new Response(0, $errno, $errstr);
543 $r = new Response($v, 0, '', $return_type);
547 $r->hdrs = $this->httpResponse['headers'];
548 $r->_cookies = $this->httpResponse['cookies'];
549 $r->raw_data = $this->httpResponse['raw_data'];
555 * Echoes a debug message, taking care of escaping it when not in console mode
557 * @param string $message
559 protected function debugMessage($message, $encodeEntities = true)
561 if (PHP_SAPI != 'cli') {
563 print "<PRE>\n".htmlentities($message)."\n</PRE>";
565 print "<PRE>\n".htmlspecialchars($message)."\n</PRE>";
568 print "\n$message\n";
570 // let the client see this now in case http times out...