6 /// @todo: do these need to be public?
9 public $params=array();
11 public $content_type = 'text/xml';
14 * @param string $meth the name of the method to invoke
15 * @param array $pars array of parameters to be passed to the method (xmlrpcval objects)
17 function __construct($meth, $pars=0)
19 $this->methodname=$meth;
20 if(is_array($pars) && count($pars)>0)
22 for($i=0; $i<count($pars); $i++)
24 $this->addParam($pars[$i]);
29 private function xml_header($charset_encoding='')
31 if ($charset_encoding != '')
33 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
37 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
41 private function xml_footer()
43 return '</methodCall>';
46 private function kindOf()
51 public function createPayload($charset_encoding='')
53 if ($charset_encoding != '')
54 $this->content_type = 'text/xml; charset=' . $charset_encoding;
56 $this->content_type = 'text/xml';
57 $this->payload=$this->xml_header($charset_encoding);
58 $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";
59 $this->payload.="<params>\n";
60 for($i=0; $i<count($this->params); $i++)
63 $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
66 $this->payload.="</params>\n";
67 $this->payload.=$this->xml_footer();
71 * Gets/sets the xmlrpc method to be invoked
72 * @param string $meth the method to be set (leave empty not to set it)
73 * @return string the method that will be invoked
75 public function method($meth='')
79 $this->methodname=$meth;
81 return $this->methodname;
85 * Returns xml representation of the message. XML prologue included
86 * @param string $charset_encoding
87 * @return string the xml representation of the message, xml prologue included
89 public function serialize($charset_encoding='')
91 $this->createPayload($charset_encoding);
92 return $this->payload;
96 * Add a parameter to the list of parameters to be used upon method invocation
97 * @param xmlrpcval $par
98 * @return boolean false on failure
100 public function addParam($par)
102 // add check: do not add to self params which are not xmlrpcvals
103 if(is_object($par) && is_a($par, 'xmlrpcval'))
105 $this->params[]=$par;
115 * Returns the nth parameter in the message. The index zero-based.
116 * @param integer $i the index of the parameter to fetch (zero based)
117 * @return xmlrpcval the i-th parameter
119 public function getParam($i) { return $this->params[$i]; }
122 * Returns the number of parameters in the messge.
123 * @return integer the number of parameters currently set
125 public function getNumParams() { return count($this->params); }
128 * Given an open file handle, read all data available and parse it as axmlrpc response.
129 * NB: the file handle is not closed by this function.
130 * NNB: might have trouble in rare cases to work on network streams, as we
131 * check for a read of 0 bytes instead of feof($fp).
132 * But since checking for feof(null) returns false, we would risk an
133 * infinite loop in that case, because we cannot trust the caller
134 * to give us a valid pointer to an open file...
135 * @param resource $fp stream pointer
137 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
139 public function &parseResponseFile($fp)
142 while($data=fread($fp, 32768))
147 $r =& $this->parseResponse($ipd);
152 * Parses HTTP headers and separates them from data.
154 private function &parseResponseHeaders(&$data, $headers_processed=false)
156 $xmlrpc = Phpxmlrpc::instance();
157 // Support "web-proxy-tunelling" connections for https through proxies
158 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
160 // Look for CR/LF or simple LF as line separator,
161 // (even though it is not valid http)
162 $pos = strpos($data,"\r\n\r\n");
163 if($pos || is_int($pos))
169 $pos = strpos($data,"\n\n");
170 if($pos || is_int($pos))
176 // No separation between response headers and body: fault?
182 // this filters out all http headers from proxy.
183 // maybe we could take them into account, too?
184 $data = substr($data, $bd);
188 error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');
189 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
194 // Strip HTTP 1.1 100 Continue header if present
195 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
197 $pos = strpos($data, 'HTTP', 12);
198 // server sent a Continue header without any (valid) content following...
199 // give the client a chance to know it
200 if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
204 $data = substr($data, $pos);
206 if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
208 $errstr= substr($data, 0, strpos($data, "\n")-1);
209 error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);
210 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (' . $errstr . ')');
214 $xmlrpc->_xh['headers'] = array();
215 $xmlrpc->_xh['cookies'] = array();
217 // be tolerant to usage of \n instead of \r\n to separate headers and data
218 // (even though it is not valid http)
219 $pos = strpos($data,"\r\n\r\n");
220 if($pos || is_int($pos))
226 $pos = strpos($data,"\n\n");
227 if($pos || is_int($pos))
233 // No separation between response headers and body: fault?
234 // we could take some action here instead of going on...
238 // be tolerant to line endings, and extra empty lines
239 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
240 while(list(,$line) = @each($ar))
242 // take care of multi-line headers and cookies
243 $arr = explode(':',$line,2);
246 $header_name = strtolower(trim($arr[0]));
247 /// @todo some other headers (the ones that allow a CSV list of values)
248 /// do allow many values to be passed using multiple header lines.
249 /// We should add content to $xmlrpc->_xh['headers'][$header_name]
250 /// instead of replacing it for those...
251 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
253 if ($header_name == 'set-cookie2')
255 // version 2 cookies:
256 // there could be many cookies on one line, comma separated
257 $cookies = explode(',', $arr[1]);
261 $cookies = array($arr[1]);
263 foreach ($cookies as $cookie)
265 // glue together all received cookies, using a comma to separate them
266 // (same as php does with getallheaders())
267 if (isset($xmlrpc->_xh['headers'][$header_name]))
268 $xmlrpc->_xh['headers'][$header_name] .= ', ' . trim($cookie);
270 $xmlrpc->_xh['headers'][$header_name] = trim($cookie);
271 // parse cookie attributes, in case user wants to correctly honour them
272 // feature creep: only allow rfc-compliant cookie attributes?
273 // @todo support for server sending multiple time cookie with same name, but using different PATHs
274 $cookie = explode(';', $cookie);
275 foreach ($cookie as $pos => $val)
277 $val = explode('=', $val, 2);
278 $tag = trim($val[0]);
279 $val = trim(@$val[1]);
280 /// @todo with version 1 cookies, we should strip leading and trailing " chars
284 $xmlrpc->_xh['cookies'][$tag] = array();
285 $xmlrpc->_xh['cookies'][$cookiename]['value'] = urldecode($val);
291 $xmlrpc->_xh['cookies'][$cookiename][$tag] = $val;
299 $xmlrpc->_xh['headers'][$header_name] = trim($arr[1]);
302 elseif(isset($header_name))
304 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
305 $xmlrpc->_xh['headers'][$header_name] .= ' ' . trim($line);
309 $data = substr($data, $bd);
311 if($this->debug && count($xmlrpc->_xh['headers']))
314 foreach($xmlrpc->_xh['headers'] as $header => $value)
316 print htmlentities("HEADER: $header: $value\n");
318 foreach($xmlrpc->_xh['cookies'] as $header => $value)
320 print htmlentities("COOKIE: $header={$value['value']}\n");
325 // if CURL was used for the call, http headers have been processed,
326 // and dechunking + reinflating have been carried out
327 if(!$headers_processed)
329 // Decode chunked encoding sent by http 1.1 servers
330 if(isset($xmlrpc->_xh['headers']['transfer-encoding']) && $xmlrpc->_xh['headers']['transfer-encoding'] == 'chunked')
332 if(!$data = decode_chunked($data))
334 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');
335 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['dechunk_fail'], $xmlrpc->xmlrpcstr['dechunk_fail']);
340 // Decode gzip-compressed stuff
341 // code shamelessly inspired from nusoap library by Dietrich Ayala
342 if(isset($xmlrpc->_xh['headers']['content-encoding']))
344 $xmlrpc->_xh['headers']['content-encoding'] = str_replace('x-', '', $xmlrpc->_xh['headers']['content-encoding']);
345 if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' || $xmlrpc->_xh['headers']['content-encoding'] == 'gzip')
347 // if decoding works, use it. else assume data wasn't gzencoded
348 if(function_exists('gzinflate'))
350 if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
354 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
356 elseif($xmlrpc->_xh['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
360 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
364 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');
365 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['decompress_fail'], $xmlrpc->xmlrpcstr['decompress_fail']);
371 error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
372 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['cannot_decompress'], $xmlrpc->xmlrpcstr['cannot_decompress']);
377 } // end of 'if needed, de-chunk, re-inflate response'
379 // real stupid hack to avoid PHP complaining about returning NULL by ref
386 * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object.
387 * @param string $data the xmlrpc response, eventually including http headers
388 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
389 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
392 public function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')
394 $xmlrpc = Phpxmlrpc::instance();
398 //by maHo, replaced htmlspecialchars with htmlentities
399 print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";
404 error_log('XML-RPC: '.__METHOD__.': no response received from server.');
405 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_data'], $xmlrpc->xmlrpcstr['no_data']);
409 $xmlrpc->_xh=array();
412 // parse the HTTP headers of the response, if present, and separate them from data
413 if(substr($data, 0, 4) == 'HTTP')
415 $r =& $this->parseResponseHeaders($data, $headers_processed);
418 // failed processing of HTTP response headers
419 // save into response obj the full payload received, for debugging
420 $r->raw_data = $data;
426 $xmlrpc->_xh['headers'] = array();
427 $xmlrpc->_xh['cookies'] = array();
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 xmlrpcresp($data, 0, '', 'xml');
459 $r->hdrs = $xmlrpc->_xh['headers'];
460 $r->_cookies = $xmlrpc->_xh['cookies'];
461 $r->raw_data = $raw_data;
465 // try to 'guestimate' the character encoding of the received response
466 $resp_encoding = guess_encoding(@$xmlrpc->_xh['headers']['content-type'], $data);
468 $xmlrpc->_xh['ac']='';
469 //$xmlrpc->_xh['qt']=''; //unused...
470 $xmlrpc->_xh['stack'] = array();
471 $xmlrpc->_xh['valuestack'] = array();
472 $xmlrpc->_xh['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc
473 $xmlrpc->_xh['isf_reason']='';
474 $xmlrpc->_xh['rt']=''; // 'methodcall or 'methodresponse'
476 // if response charset encoding is not known / supported, try to use
477 // the default encoding and parse the xml anyway, but log a warning...
478 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
479 // the following code might be better for mb_string enabled installs, but
480 // makes the lib about 200% slower...
481 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
483 error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding);
484 $resp_encoding = $xmlrpc->xmlrpc_defencoding;
486 $parser = xml_parser_create($resp_encoding);
487 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
488 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
489 // the xml parser to give us back data in the expected charset.
490 // What if internal encoding is not in one of the 3 allowed?
491 // we use the broadest one, ie. utf8
492 // This allows to send data which is native in various charset,
493 // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding
494 if (!in_array($xmlrpc->xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
496 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
500 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $xmlrpc->xmlrpc_internalencoding);
503 if ($return_type == 'phpvals')
505 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
509 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
512 xml_set_character_data_handler($parser, 'xmlrpc_cd');
513 xml_set_default_handler($parser, 'xmlrpc_dh');
515 // first error check: xml not well formed
516 if(!xml_parse($parser, $data, count($data)))
518 // thanks to Peter Kocks <peter.kocks@baygate.com>
519 if((xml_get_current_line_number($parser)) == 1)
521 $errstr = 'XML error at line 1, check URL';
525 $errstr = sprintf('XML error: %s at line %d, column %d',
526 xml_error_string(xml_get_error_code($parser)),
527 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
530 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], $xmlrpc->xmlrpcstr['invalid_return'].' ('.$errstr.')');
531 xml_parser_free($parser);
536 $r->hdrs = $xmlrpc->_xh['headers'];
537 $r->_cookies = $xmlrpc->_xh['cookies'];
538 $r->raw_data = $raw_data;
541 xml_parser_free($parser);
542 // second error check: xml well formed but not xml-rpc compliant
543 if ($xmlrpc->_xh['isf'] > 1)
547 /// @todo echo something for user?
550 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'],
551 $xmlrpc->xmlrpcstr['invalid_return'] . ' ' . $xmlrpc->_xh['isf_reason']);
553 // third error check: parsing of the response has somehow gone boink.
554 // NB: shall we omit this check, since we trust the parsing code?
555 elseif ($return_type == 'xmlrpcvals' && !is_object($xmlrpc->_xh['value']))
557 // something odd has happened
558 // and it's time to generate a client side error
559 // indicating something odd went on
560 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'],
561 $xmlrpc->xmlrpcstr['invalid_return']);
567 print "<PRE>---PARSED---\n";
568 // somehow htmlentities chokes on var_export, and some full html string...
569 //print htmlentitites(var_export($xmlrpc->_xh['value'], true));
570 print htmlspecialchars(var_export($xmlrpc->_xh['value'], true));
571 print "\n---END---</PRE>";
574 // note that using =& will raise an error if $xmlrpc->_xh['st'] does not generate an object.
575 $v =& $xmlrpc->_xh['value'];
577 if($xmlrpc->_xh['isf'])
579 /// @todo we should test here if server sent an int and a string,
580 /// and/or coerce them into such...
581 if ($return_type == 'xmlrpcvals')
583 $errno_v = $v->structmem('faultCode');
584 $errstr_v = $v->structmem('faultString');
585 $errno = $errno_v->scalarval();
586 $errstr = $errstr_v->scalarval();
590 $errno = $v['faultCode'];
591 $errstr = $v['faultString'];
596 // FAULT returned, errno needs to reflect that
600 $r = new xmlrpcresp(0, $errno, $errstr);
604 $r=new xmlrpcresp($v, 0, '', $return_type);
608 $r->hdrs = $xmlrpc->_xh['headers'];
609 $r->_cookies = $xmlrpc->_xh['cookies'];
610 $r->raw_data = $raw_data;