5 use PhpXmlRpc\Helper\Http;
6 use PhpXmlRpc\Helper\XMLParser;
7 use PhpXmlRpc\Helper\Encoder;
12 /// @todo: do these need to be public?
15 public $params=array();
17 public $content_type = 'text/xml';
19 // holds data while parsing the response. NB: Not a full Response object
20 protected $httpResponse = array();
23 * @param string $methodName the name of the method to invoke
24 * @param array $params array of parameters to be passed to the method (xmlrpcval objects)
26 function __construct($methodName, $params=array())
28 $this->methodname = $methodName;
29 foreach($params as $param)
31 $this->addParam($param);
35 private function xml_header($charset_encoding='')
37 if ($charset_encoding != '')
39 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
43 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
47 private function xml_footer()
49 return '</methodCall>';
53 * Kept the old name even if class was renamed, for compatibility
56 private function kindOf()
61 public function createPayload($charset_encoding='')
63 if ($charset_encoding != '')
64 $this->content_type = 'text/xml; charset=' . $charset_encoding;
66 $this->content_type = 'text/xml';
67 $this->payload=$this->xml_header($charset_encoding);
68 $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";
69 $this->payload.="<params>\n";
70 foreach($this->params as $p)
72 $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
75 $this->payload.="</params>\n";
76 $this->payload.=$this->xml_footer();
80 * Gets/sets the xmlrpc method to be invoked
81 * @param string $meth the method to be set (leave empty not to set it)
82 * @return string the method that will be invoked
84 public function method($methodName='')
88 $this->methodname=$methodName;
90 return $this->methodname;
94 * Returns xml representation of the message. XML prologue included
95 * @param string $charset_encoding
96 * @return string the xml representation of the message, xml prologue included
98 public function serialize($charset_encoding='')
100 $this->createPayload($charset_encoding);
101 return $this->payload;
105 * Add a parameter to the list of parameters to be used upon method invocation
107 * @return boolean false on failure
109 public function addParam($param)
111 // add check: do not add to self params which are not xmlrpcvals
112 if(is_object($param) && is_a($param, 'PhpXmlRpc\Value'))
114 $this->params[]=$param;
124 * Returns the nth parameter in the request. The index zero-based.
125 * @param integer $i the index of the parameter to fetch (zero based)
126 * @return Value the i-th parameter
128 public function getParam($i) { return $this->params[$i]; }
131 * Returns the number of parameters in the messge.
132 * @return integer the number of parameters currently set
134 public function getNumParams() { return count($this->params); }
137 * Given an open file handle, read all data available and parse it as axmlrpc response.
138 * NB: the file handle is not closed by this function.
139 * NNB: might have trouble in rare cases to work on network streams, as we
140 * check for a read of 0 bytes instead of feof($fp).
141 * But since checking for feof(null) returns false, we would risk an
142 * infinite loop in that case, because we cannot trust the caller
143 * to give us a valid pointer to an open file...
144 * @param resource $fp stream pointer
146 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
148 public function parseResponseFile($fp)
151 while($data=fread($fp, 32768))
156 return $this->parseResponse($ipd);
160 * Parses HTTP headers and separates them from data.
161 * @return null|Response null on success, or a Response on error
163 private function parseResponseHeaders(&$data, $headers_processed=false)
165 $this->httpResponse['headers'] = array();
166 $this->httpResponse['cookies'] = array();
168 // Support "web-proxy-tunelling" connections for https through proxies
169 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
171 // Look for CR/LF or simple LF as line separator,
172 // (even though it is not valid http)
173 $pos = strpos($data,"\r\n\r\n");
174 if($pos || is_int($pos))
180 $pos = strpos($data,"\n\n");
181 if($pos || is_int($pos))
187 // No separation between response headers and body: fault?
193 // this filters out all http headers from proxy.
194 // maybe we could take them into account, too?
195 $data = substr($data, $bd);
199 error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');
200 $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
205 // Strip HTTP 1.1 100 Continue header if present
206 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
208 $pos = strpos($data, 'HTTP', 12);
209 // server sent a Continue header without any (valid) content following...
210 // give the client a chance to know it
211 if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
215 $data = substr($data, $pos);
217 if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
219 $errstr= substr($data, 0, strpos($data, "\n")-1);
220 error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);
221 $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error']. ' (' . $errstr . ')');
225 // be tolerant to usage of \n instead of \r\n to separate headers and data
226 // (even though it is not valid http)
227 $pos = strpos($data,"\r\n\r\n");
228 if($pos || is_int($pos))
234 $pos = strpos($data,"\n\n");
235 if($pos || is_int($pos))
241 // No separation between response headers and body: fault?
242 // we could take some action here instead of going on...
246 // be tolerant to line endings, and extra empty lines
247 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
248 while(list(,$line) = @each($ar))
250 // take care of multi-line headers and cookies
251 $arr = explode(':',$line,2);
254 $header_name = strtolower(trim($arr[0]));
255 /// @todo some other headers (the ones that allow a CSV list of values)
256 /// do allow many values to be passed using multiple header lines.
257 /// We should add content to $xmlrpc->_xh['headers'][$header_name]
258 /// instead of replacing it for those...
259 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
261 if ($header_name == 'set-cookie2')
263 // version 2 cookies:
264 // there could be many cookies on one line, comma separated
265 $cookies = explode(',', $arr[1]);
269 $cookies = array($arr[1]);
271 foreach ($cookies as $cookie)
273 // glue together all received cookies, using a comma to separate them
274 // (same as php does with getallheaders())
275 if (isset($this->httpResponse['headers'][$header_name]))
276 $this->httpResponse['headers'][$header_name] .= ', ' . trim($cookie);
278 $this->httpResponse['headers'][$header_name] = trim($cookie);
279 // parse cookie attributes, in case user wants to correctly honour them
280 // feature creep: only allow rfc-compliant cookie attributes?
281 // @todo support for server sending multiple time cookie with same name, but using different PATHs
282 $cookie = explode(';', $cookie);
283 foreach ($cookie as $pos => $val)
285 $val = explode('=', $val, 2);
286 $tag = trim($val[0]);
287 $val = trim(@$val[1]);
288 /// @todo with version 1 cookies, we should strip leading and trailing " chars
292 $this->httpResponse['cookies'][$tag] = array();
293 $this->httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
299 $this->httpResponse['cookies'][$cookiename][$tag] = $val;
307 $this->httpResponse['headers'][$header_name] = trim($arr[1]);
310 elseif(isset($header_name))
312 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
313 $this->httpResponse['headers'][$header_name] .= ' ' . trim($line);
317 $data = substr($data, $bd);
319 /// @todo when in CLI mode, do not html-encode the output
320 if($this->debug && count($this->httpResponse['headers']))
323 foreach($this->httpResponse['headers'] as $header => $value)
325 print htmlentities("HEADER: $header: $value\n");
327 foreach($this->httpResponse['cookies'] as $header => $value)
329 print htmlentities("COOKIE: $header={$value['value']}\n");
334 // if CURL was used for the call, http headers have been processed,
335 // and dechunking + reinflating have been carried out
336 if(!$headers_processed)
338 // Decode chunked encoding sent by http 1.1 servers
339 if(isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked')
341 if(!$data = Http::decode_chunked($data))
343 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');
344 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']);
349 // Decode gzip-compressed stuff
350 // code shamelessly inspired from nusoap library by Dietrich Ayala
351 if(isset($this->httpResponse['headers']['content-encoding']))
353 $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']);
354 if($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip')
356 // if decoding works, use it. else assume data wasn't gzencoded
357 if(function_exists('gzinflate'))
359 if($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
363 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
365 elseif($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
369 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
373 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');
374 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']);
380 error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
381 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']);
386 } // end of 'if needed, de-chunk, re-inflate response'
392 * Parse the xmlrpc response contained in the string $data and return a Response object.
393 * @param string $data the xmlrpc response, eventually including http headers
394 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
395 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
398 public function parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')
402 // by maHo, replaced htmlspecialchars with htmlentities
403 print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";
406 $this->httpResponse = array();
407 $this->httpResponse['raw_data'] = $data;
408 $this->httpResponse['headers'] = array();
409 $this->httpResponse['cookies'] = array();
413 error_log('XML-RPC: '.__METHOD__.': no response received from server.');
414 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
418 // parse the HTTP headers of the response, if present, and separate them from data
419 if(substr($data, 0, 4) == 'HTTP')
421 $r = $this->parseResponseHeaders($data, $headers_processed);
424 // failed processing of HTTP response headers
425 // save into response obj the full payload received, for debugging
426 $r->raw_data = $data;
433 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
436 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
437 $end = strpos($data, '-->', $start);
438 $comments = substr($data, $start, $end-$start);
439 print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";
443 // be tolerant of extra whitespace in response body
446 /// @todo return an error msg if $data=='' ?
448 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
449 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
450 $pos = strrpos($data, '</methodResponse>');
453 $data = substr($data, 0, $pos+17);
456 // if user wants back raw xml, give it to him
457 if ($return_type == 'xml')
459 $r = new Response($data, 0, '', 'xml');
460 $r->hdrs = $this->httpResponse['headers'];
461 $r->_cookies = $this->httpResponse['cookies'];
462 $r->raw_data = $this->httpResponse['raw_data'];
466 // try to 'guestimate' the character encoding of the received response
467 $resp_encoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data);
469 // if response charset encoding is not known / supported, try to use
470 // the default encoding and parse the xml anyway, but log a warning...
471 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
472 // the following code might be better for mb_string enabled installs, but
473 // makes the lib about 200% slower...
474 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
476 error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding);
477 $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding;
479 $parser = xml_parser_create($resp_encoding);
480 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
481 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
482 // the xml parser to give us back data in the expected charset.
483 // What if internal encoding is not in one of the 3 allowed?
484 // we use the broadest one, ie. utf8
485 // This allows to send data which is native in various charset,
486 // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
487 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
489 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
493 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
496 $xmlRpcParser = new XMLParser();
497 xml_set_object($parser, $xmlRpcParser);
499 if ($return_type == 'phpvals')
501 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
505 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
508 xml_set_character_data_handler($parser, 'xmlrpc_cd');
509 xml_set_default_handler($parser, 'xmlrpc_dh');
511 // first error check: xml not well formed
512 if(!xml_parse($parser, $data, count($data)))
514 // thanks to Peter Kocks <peter.kocks@baygate.com>
515 if((xml_get_current_line_number($parser)) == 1)
517 $errstr = 'XML error at line 1, check URL';
521 $errstr = sprintf('XML error: %s at line %d, column %d',
522 xml_error_string(xml_get_error_code($parser)),
523 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
526 $r=new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'].' ('.$errstr.')');
527 xml_parser_free($parser);
532 $r->hdrs = $this->httpResponse['headers'];
533 $r->_cookies = $this->httpResponse['cookies'];
534 $r->raw_data = $this->httpResponse['raw_data'];
537 xml_parser_free($parser);
538 // second error check: xml well formed but not xml-rpc compliant
539 if ($xmlRpcParser->_xh['isf'] > 1)
543 /// @todo echo something for user?
546 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
547 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
549 // third error check: parsing of the response has somehow gone boink.
550 // NB: shall we omit this check, since we trust the parsing code?
551 elseif ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value']))
553 // something odd has happened
554 // and it's time to generate a client side error
555 // indicating something odd went on
556 $r=new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
557 PhpXmlRpc::$xmlrpcstr['invalid_return']);
563 print "<PRE>---PARSED---\n";
564 // somehow htmlentities chokes on var_export, and some full html string...
565 //print htmlentitites(var_export($xmlRpcParser->_xh['value'], true));
566 print htmlspecialchars(var_export($xmlRpcParser->_xh['value'], true));
567 print "\n---END---</PRE>";
570 // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
571 $v =& $xmlRpcParser->_xh['value'];
573 if($xmlRpcParser->_xh['isf'])
575 /// @todo we should test here if server sent an int and a string,
576 /// and/or coerce them into such...
577 if ($return_type == 'xmlrpcvals')
579 $errno_v = $v->structmem('faultCode');
580 $errstr_v = $v->structmem('faultString');
581 $errno = $errno_v->scalarval();
582 $errstr = $errstr_v->scalarval();
586 $errno = $v['faultCode'];
587 $errstr = $v['faultString'];
592 // FAULT returned, errno needs to reflect that
596 $r = new Response(0, $errno, $errstr);
600 $r=new Response($v, 0, '', $return_type);
604 $r->hdrs = $this->httpResponse['headers'];
605 $r->_cookies = $this->httpResponse['cookies'];
606 $r->raw_data = $this->httpResponse['raw_data'];;