5 use PhpXmlRpc\Helper\Http;
6 use PhpXmlRpc\Helper\XMLParser;
11 /// @todo: do these need to be public?
14 public $params=array();
16 public $content_type = 'text/xml';
18 // holds data while parsing the response. NB: Not a full Response object
19 protected $httpResponse = array();
22 * @param string $methodName the name of the method to invoke
23 * @param array $params array of parameters to be passed to the method (xmlrpcval objects)
25 function __construct($methodName, $params=array())
27 $this->methodname = $methodName;
28 foreach($params as $param)
30 $this->addParam($param);
34 private function xml_header($charset_encoding='')
36 if ($charset_encoding != '')
38 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
42 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
46 private function xml_footer()
48 return '</methodCall>';
52 * Kept the old name even if class was renamed, for compatibility
55 private function kindOf()
60 public function createPayload($charset_encoding='')
62 if ($charset_encoding != '')
63 $this->content_type = 'text/xml; charset=' . $charset_encoding;
65 $this->content_type = 'text/xml';
66 $this->payload=$this->xml_header($charset_encoding);
67 $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";
68 $this->payload.="<params>\n";
69 foreach($this->params as $p)
71 $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
74 $this->payload.="</params>\n";
75 $this->payload.=$this->xml_footer();
79 * Gets/sets the xmlrpc method to be invoked
80 * @param string $meth the method to be set (leave empty not to set it)
81 * @return string the method that will be invoked
83 public function method($methodName='')
87 $this->methodname=$methodName;
89 return $this->methodname;
93 * Returns xml representation of the message. XML prologue included
94 * @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);
100 return $this->payload;
104 * Add a parameter to the list of parameters to be used upon method invocation
106 * @return boolean false on failure
108 public function addParam($param)
110 // add check: do not add to self params which are not xmlrpcvals
111 if(is_object($param) && is_a($param, 'PhpXmlRpc\Value'))
113 $this->params[]=$param;
123 * Returns the nth parameter in the request. The index zero-based.
124 * @param integer $i the index of the parameter to fetch (zero based)
125 * @return Value the i-th parameter
127 public function getParam($i) { return $this->params[$i]; }
130 * Returns the number of parameters in the messge.
131 * @return integer the number of parameters currently set
133 public function getNumParams() { return count($this->params); }
136 * Given an open file handle, read all data available and parse it as axmlrpc 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...
143 * @param resource $fp stream pointer
145 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
147 public function parseResponseFile($fp)
150 while($data=fread($fp, 32768))
155 return $this->parseResponse($ipd);
159 * Parses HTTP headers and separates them from data.
160 * @return null|Response null on success, or a Response on error
162 private function parseResponseHeaders(&$data, $headers_processed=false)
164 $this->httpResponse['headers'] = array();
165 $this->httpResponse['cookies'] = array();
167 // Support "web-proxy-tunelling" connections for https through proxies
168 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
170 // Look for CR/LF or simple LF as line separator,
171 // (even though it is not valid http)
172 $pos = strpos($data,"\r\n\r\n");
173 if($pos || is_int($pos))
179 $pos = strpos($data,"\n\n");
180 if($pos || is_int($pos))
186 // No separation between response headers and body: fault?
192 // this filters out all http headers from proxy.
193 // maybe we could take them into account, too?
194 $data = substr($data, $bd);
198 error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');
199 $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
204 // Strip HTTP 1.1 100 Continue header if present
205 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
207 $pos = strpos($data, 'HTTP', 12);
208 // server sent a Continue header without any (valid) content following...
209 // give the client a chance to know it
210 if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
214 $data = substr($data, $pos);
216 if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
218 $errstr= substr($data, 0, strpos($data, "\n")-1);
219 error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);
220 $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error']. ' (' . $errstr . ')');
224 // be tolerant to usage of \n instead of \r\n to separate headers and data
225 // (even though it is not valid http)
226 $pos = strpos($data,"\r\n\r\n");
227 if($pos || is_int($pos))
233 $pos = strpos($data,"\n\n");
234 if($pos || is_int($pos))
240 // No separation between response headers and body: fault?
241 // we could take some action here instead of going on...
245 // be tolerant to line endings, and extra empty lines
246 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
247 while(list(,$line) = @each($ar))
249 // take care of multi-line headers and cookies
250 $arr = explode(':',$line,2);
253 $header_name = strtolower(trim($arr[0]));
254 /// @todo some other headers (the ones that allow a CSV list of values)
255 /// do allow many values to be passed using multiple header lines.
256 /// We should add content to $xmlrpc->_xh['headers'][$header_name]
257 /// instead of replacing it for those...
258 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
260 if ($header_name == 'set-cookie2')
262 // version 2 cookies:
263 // there could be many cookies on one line, comma separated
264 $cookies = explode(',', $arr[1]);
268 $cookies = array($arr[1]);
270 foreach ($cookies as $cookie)
272 // glue together all received cookies, using a comma to separate them
273 // (same as php does with getallheaders())
274 if (isset($this->httpResponse['headers'][$header_name]))
275 $this->httpResponse['headers'][$header_name] .= ', ' . trim($cookie);
277 $this->httpResponse['headers'][$header_name] = trim($cookie);
278 // parse cookie attributes, in case user wants to correctly honour them
279 // feature creep: only allow rfc-compliant cookie attributes?
280 // @todo support for server sending multiple time cookie with same name, but using different PATHs
281 $cookie = explode(';', $cookie);
282 foreach ($cookie as $pos => $val)
284 $val = explode('=', $val, 2);
285 $tag = trim($val[0]);
286 $val = trim(@$val[1]);
287 /// @todo with version 1 cookies, we should strip leading and trailing " chars
291 $this->httpResponse['cookies'][$tag] = array();
292 $this->httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
298 $this->httpResponse['cookies'][$cookiename][$tag] = $val;
306 $this->httpResponse['headers'][$header_name] = trim($arr[1]);
309 elseif(isset($header_name))
311 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
312 $this->httpResponse['headers'][$header_name] .= ' ' . trim($line);
316 $data = substr($data, $bd);
318 /// @todo when in CLI mode, do not html-encode the output
319 if($this->debug && count($this->httpResponse['headers']))
322 foreach($this->httpResponse['headers'] as $header => $value)
324 print htmlentities("HEADER: $header: $value\n");
326 foreach($this->httpResponse['cookies'] as $header => $value)
328 print htmlentities("COOKIE: $header={$value['value']}\n");
333 // if CURL was used for the call, http headers have been processed,
334 // and dechunking + reinflating have been carried out
335 if(!$headers_processed)
337 // Decode chunked encoding sent by http 1.1 servers
338 if(isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked')
340 if(!$data = Http::decode_chunked($data))
342 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');
343 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']);
348 // Decode gzip-compressed stuff
349 // code shamelessly inspired from nusoap library by Dietrich Ayala
350 if(isset($this->httpResponse['headers']['content-encoding']))
352 $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']);
353 if($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip')
355 // if decoding works, use it. else assume data wasn't gzencoded
356 if(function_exists('gzinflate'))
358 if($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
362 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
364 elseif($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
368 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
372 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');
373 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']);
379 error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
380 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']);
385 } // end of 'if needed, de-chunk, re-inflate response'
391 * Parse the xmlrpc response contained in the string $data and return a Response object.
392 * @param string $data the xmlrpc response, eventually including http headers
393 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
394 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
397 public function parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')
401 // by maHo, replaced htmlspecialchars with htmlentities
402 print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";
405 $this->httpResponse = array();
406 $this->httpResponse['raw_data'] = $data;
407 $this->httpResponse['headers'] = array();
408 $this->httpResponse['cookies'] = array();
412 error_log('XML-RPC: '.__METHOD__.': no response received from server.');
413 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
417 // parse the HTTP headers of the response, if present, and separate them from data
418 if(substr($data, 0, 4) == 'HTTP')
420 $r = $this->parseResponseHeaders($data, $headers_processed);
423 // failed processing of HTTP response headers
424 // save into response obj the full payload received, for debugging
425 $r->raw_data = $data;
432 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
435 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
436 $end = strpos($data, '-->', $start);
437 $comments = substr($data, $start, $end-$start);
438 print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";
442 // be tolerant of extra whitespace in response body
445 /// @todo return an error msg if $data=='' ?
447 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
448 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
449 $pos = strrpos($data, '</methodResponse>');
452 $data = substr($data, 0, $pos+17);
455 // if user wants back raw xml, give it to him
456 if ($return_type == 'xml')
458 $r = new Response($data, 0, '', 'xml');
459 $r->hdrs = $this->httpResponse['headers'];
460 $r->_cookies = $this->httpResponse['cookies'];
461 $r->raw_data = $this->httpResponse['raw_data'];
465 // try to 'guestimate' the character encoding of the received response
466 $resp_encoding = guess_encoding(@$this->httpResponse['headers']['content-type'], $data);
468 // if response charset encoding is not known / supported, try to use
469 // the default encoding and parse the xml anyway, but log a warning...
470 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
471 // the following code might be better for mb_string enabled installs, but
472 // makes the lib about 200% slower...
473 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
475 error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding);
476 $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding;
478 $parser = xml_parser_create($resp_encoding);
479 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
480 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
481 // the xml parser to give us back data in the expected charset.
482 // What if internal encoding is not in one of the 3 allowed?
483 // we use the broadest one, ie. utf8
484 // This allows to send data which is native in various charset,
485 // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
486 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
488 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
492 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
495 $xmlRpcParser = new XMLParser();
496 xml_set_object($parser, $xmlRpcParser);
498 if ($return_type == 'phpvals')
500 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
504 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
507 xml_set_character_data_handler($parser, 'xmlrpc_cd');
508 xml_set_default_handler($parser, 'xmlrpc_dh');
510 // first error check: xml not well formed
511 if(!xml_parse($parser, $data, count($data)))
513 // thanks to Peter Kocks <peter.kocks@baygate.com>
514 if((xml_get_current_line_number($parser)) == 1)
516 $errstr = 'XML error at line 1, check URL';
520 $errstr = sprintf('XML error: %s at line %d, column %d',
521 xml_error_string(xml_get_error_code($parser)),
522 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
525 $r=new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'].' ('.$errstr.')');
526 xml_parser_free($parser);
531 $r->hdrs = $this->httpResponse['headers'];
532 $r->_cookies = $this->httpResponse['cookies'];
533 $r->raw_data = $this->httpResponse['raw_data'];
536 xml_parser_free($parser);
537 // second error check: xml well formed but not xml-rpc compliant
538 if ($xmlRpcParser->_xh['isf'] > 1)
542 /// @todo echo something for user?
545 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
546 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
548 // third error check: parsing of the response has somehow gone boink.
549 // NB: shall we omit this check, since we trust the parsing code?
550 elseif ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value']))
552 // something odd has happened
553 // and it's time to generate a client side error
554 // indicating something odd went on
555 $r=new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
556 PhpXmlRpc::$xmlrpcstr['invalid_return']);
562 print "<PRE>---PARSED---\n";
563 // somehow htmlentities chokes on var_export, and some full html string...
564 //print htmlentitites(var_export($xmlRpcParser->_xh['value'], true));
565 print htmlspecialchars(var_export($xmlRpcParser->_xh['value'], true));
566 print "\n---END---</PRE>";
569 // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
570 $v =& $xmlRpcParser->_xh['value'];
572 if($xmlRpcParser->_xh['isf'])
574 /// @todo we should test here if server sent an int and a string,
575 /// and/or coerce them into such...
576 if ($return_type == 'xmlrpcvals')
578 $errno_v = $v->structmem('faultCode');
579 $errstr_v = $v->structmem('faultString');
580 $errno = $errno_v->scalarval();
581 $errstr = $errstr_v->scalarval();
585 $errno = $v['faultCode'];
586 $errstr = $v['faultString'];
591 // FAULT returned, errno needs to reflect that
595 $r = new Response(0, $errno, $errstr);
599 $r=new Response($v, 0, '', $return_type);
603 $r->hdrs = $this->httpResponse['headers'];
604 $r->_cookies = $this->httpResponse['cookies'];
605 $r->raw_data = $this->httpResponse['raw_data'];;