4 /// @todo: does these need to be public?
7 public $params=array();
9 public $content_type = 'text/xml';
12 * @param string $meth the name of the method to invoke
13 * @param array $pars array of parameters to be passed to the method (xmlrpcval objects)
15 function __construct($meth, $pars=0)
17 $this->methodname=$meth;
18 if(is_array($pars) && count($pars)>0)
20 for($i=0; $i<count($pars); $i++)
22 $this->addParam($pars[$i]);
27 private function xml_header($charset_encoding='')
29 if ($charset_encoding != '')
31 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
35 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
39 private function xml_footer()
41 return '</methodCall>';
44 private function kindOf()
49 public function createPayload($charset_encoding='')
51 if ($charset_encoding != '')
52 $this->content_type = 'text/xml; charset=' . $charset_encoding;
54 $this->content_type = 'text/xml';
55 $this->payload=$this->xml_header($charset_encoding);
56 $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";
57 $this->payload.="<params>\n";
58 for($i=0; $i<count($this->params); $i++)
61 $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
64 $this->payload.="</params>\n";
65 $this->payload.=$this->xml_footer();
69 * Gets/sets the xmlrpc method to be invoked
70 * @param string $meth the method to be set (leave empty not to set it)
71 * @return string the method that will be invoked
73 public function method($meth='')
77 $this->methodname=$meth;
79 return $this->methodname;
83 * Returns xml representation of the message. XML prologue included
84 * @param string $charset_encoding
85 * @return string the xml representation of the message, xml prologue included
87 public function serialize($charset_encoding='')
89 $this->createPayload($charset_encoding);
90 return $this->payload;
94 * Add a parameter to the list of parameters to be used upon method invocation
95 * @param xmlrpcval $par
96 * @return boolean false on failure
98 public function addParam($par)
100 // add check: do not add to self params which are not xmlrpcvals
101 if(is_object($par) && is_a($par, 'xmlrpcval'))
103 $this->params[]=$par;
113 * Returns the nth parameter in the message. The index zero-based.
114 * @param integer $i the index of the parameter to fetch (zero based)
115 * @return xmlrpcval the i-th parameter
117 public function getParam($i) { return $this->params[$i]; }
120 * Returns the number of parameters in the messge.
121 * @return integer the number of parameters currently set
123 public function getNumParams() { return count($this->params); }
126 * Given an open file handle, read all data available and parse it as axmlrpc response.
127 * NB: the file handle is not closed by this function.
128 * NNB: might have trouble in rare cases to work on network streams, as we
129 * check for a read of 0 bytes instead of feof($fp).
130 * But since checking for feof(null) returns false, we would risk an
131 * infinite loop in that case, because we cannot trust the caller
132 * to give us a valid pointer to an open file...
133 * @param resource $fp stream pointer
135 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
137 public function &parseResponseFile($fp)
140 while($data=fread($fp, 32768))
145 $r =& $this->parseResponse($ipd);
150 * Parses HTTP headers and separates them from data.
152 private function &parseResponseHeaders(&$data, $headers_processed=false)
154 $xmlrpc = Phpxmlrpc::instance();
155 // Support "web-proxy-tunelling" connections for https through proxies
156 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
158 // Look for CR/LF or simple LF as line separator,
159 // (even though it is not valid http)
160 $pos = strpos($data,"\r\n\r\n");
161 if($pos || is_int($pos))
167 $pos = strpos($data,"\n\n");
168 if($pos || is_int($pos))
174 // No separation between response headers and body: fault?
180 // this filters out all http headers from proxy.
181 // maybe we could take them into account, too?
182 $data = substr($data, $bd);
186 error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');
187 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
192 // Strip HTTP 1.1 100 Continue header if present
193 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
195 $pos = strpos($data, 'HTTP', 12);
196 // server sent a Continue header without any (valid) content following...
197 // give the client a chance to know it
198 if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
202 $data = substr($data, $pos);
204 if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
206 $errstr= substr($data, 0, strpos($data, "\n")-1);
207 error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);
208 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (' . $errstr . ')');
212 $xmlrpc->_xh['headers'] = array();
213 $xmlrpc->_xh['cookies'] = array();
215 // be tolerant to usage of \n instead of \r\n to separate headers and data
216 // (even though it is not valid http)
217 $pos = strpos($data,"\r\n\r\n");
218 if($pos || is_int($pos))
224 $pos = strpos($data,"\n\n");
225 if($pos || is_int($pos))
231 // No separation between response headers and body: fault?
232 // we could take some action here instead of going on...
236 // be tolerant to line endings, and extra empty lines
237 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
238 while(list(,$line) = @each($ar))
240 // take care of multi-line headers and cookies
241 $arr = explode(':',$line,2);
244 $header_name = strtolower(trim($arr[0]));
245 /// @todo some other headers (the ones that allow a CSV list of values)
246 /// do allow many values to be passed using multiple header lines.
247 /// We should add content to $xmlrpc->_xh['headers'][$header_name]
248 /// instead of replacing it for those...
249 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
251 if ($header_name == 'set-cookie2')
253 // version 2 cookies:
254 // there could be many cookies on one line, comma separated
255 $cookies = explode(',', $arr[1]);
259 $cookies = array($arr[1]);
261 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($xmlrpc->_xh['headers'][$header_name]))
266 $xmlrpc->_xh['headers'][$header_name] .= ', ' . trim($cookie);
268 $xmlrpc->_xh['headers'][$header_name] = trim($cookie);
269 // parse cookie attributes, in case user wants to correctly honour them
270 // feature creep: only allow rfc-compliant cookie attributes?
271 // @todo support for server sending multiple time cookie with same name, but using different PATHs
272 $cookie = explode(';', $cookie);
273 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
282 $xmlrpc->_xh['cookies'][$tag] = array();
283 $xmlrpc->_xh['cookies'][$cookiename]['value'] = urldecode($val);
289 $xmlrpc->_xh['cookies'][$cookiename][$tag] = $val;
297 $xmlrpc->_xh['headers'][$header_name] = trim($arr[1]);
300 elseif(isset($header_name))
302 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
303 $xmlrpc->_xh['headers'][$header_name] .= ' ' . trim($line);
307 $data = substr($data, $bd);
309 if($this->debug && count($xmlrpc->_xh['headers']))
312 foreach($xmlrpc->_xh['headers'] as $header => $value)
314 print htmlentities("HEADER: $header: $value\n");
316 foreach($xmlrpc->_xh['cookies'] as $header => $value)
318 print htmlentities("COOKIE: $header={$value['value']}\n");
323 // if CURL was used for the call, http headers have been processed,
324 // and dechunking + reinflating have been carried out
325 if(!$headers_processed)
327 // Decode chunked encoding sent by http 1.1 servers
328 if(isset($xmlrpc->_xh['headers']['transfer-encoding']) && $xmlrpc->_xh['headers']['transfer-encoding'] == 'chunked')
330 if(!$data = decode_chunked($data))
332 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');
333 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['dechunk_fail'], $xmlrpc->xmlrpcstr['dechunk_fail']);
338 // Decode gzip-compressed stuff
339 // code shamelessly inspired from nusoap library by Dietrich Ayala
340 if(isset($xmlrpc->_xh['headers']['content-encoding']))
342 $xmlrpc->_xh['headers']['content-encoding'] = str_replace('x-', '', $xmlrpc->_xh['headers']['content-encoding']);
343 if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' || $xmlrpc->_xh['headers']['content-encoding'] == 'gzip')
345 // if decoding works, use it. else assume data wasn't gzencoded
346 if(function_exists('gzinflate'))
348 if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
352 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
354 elseif($xmlrpc->_xh['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
358 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
362 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');
363 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['decompress_fail'], $xmlrpc->xmlrpcstr['decompress_fail']);
369 error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
370 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['cannot_decompress'], $xmlrpc->xmlrpcstr['cannot_decompress']);
375 } // end of 'if needed, de-chunk, re-inflate response'
377 // real stupid hack to avoid PHP complaining about returning NULL by ref
384 * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object.
385 * @param string $data the xmlrpc response, eventually including http headers
386 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
387 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
390 public function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')
392 $xmlrpc = Phpxmlrpc::instance();
396 //by maHo, replaced htmlspecialchars with htmlentities
397 print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";
402 error_log('XML-RPC: '.__METHOD__.': no response received from server.');
403 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_data'], $xmlrpc->xmlrpcstr['no_data']);
407 $xmlrpc->_xh=array();
410 // parse the HTTP headers of the response, if present, and separate them from data
411 if(substr($data, 0, 4) == 'HTTP')
413 $r =& $this->parseResponseHeaders($data, $headers_processed);
416 // failed processing of HTTP response headers
417 // save into response obj the full payload received, for debugging
418 $r->raw_data = $data;
424 $xmlrpc->_xh['headers'] = array();
425 $xmlrpc->_xh['cookies'] = array();
430 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
433 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
434 $end = strpos($data, '-->', $start);
435 $comments = substr($data, $start, $end-$start);
436 print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";
440 // be tolerant of extra whitespace in response body
443 /// @todo return an error msg if $data=='' ?
445 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
446 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
447 $pos = strrpos($data, '</methodResponse>');
450 $data = substr($data, 0, $pos+17);
453 // if user wants back raw xml, give it to him
454 if ($return_type == 'xml')
456 $r = new xmlrpcresp($data, 0, '', 'xml');
457 $r->hdrs = $xmlrpc->_xh['headers'];
458 $r->_cookies = $xmlrpc->_xh['cookies'];
459 $r->raw_data = $raw_data;
463 // try to 'guestimate' the character encoding of the received response
464 $resp_encoding = guess_encoding(@$xmlrpc->_xh['headers']['content-type'], $data);
466 $xmlrpc->_xh['ac']='';
467 //$xmlrpc->_xh['qt']=''; //unused...
468 $xmlrpc->_xh['stack'] = array();
469 $xmlrpc->_xh['valuestack'] = array();
470 $xmlrpc->_xh['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc
471 $xmlrpc->_xh['isf_reason']='';
472 $xmlrpc->_xh['rt']=''; // 'methodcall or 'methodresponse'
474 // if response charset encoding is not known / supported, try to use
475 // the default encoding and parse the xml anyway, but log a warning...
476 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
477 // the following code might be better for mb_string enabled installs, but
478 // makes the lib about 200% slower...
479 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
481 error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding);
482 $resp_encoding = $xmlrpc->xmlrpc_defencoding;
484 $parser = xml_parser_create($resp_encoding);
485 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
486 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
487 // the xml parser to give us back data in the expected charset.
488 // What if internal encoding is not in one of the 3 allowed?
489 // we use the broadest one, ie. utf8
490 // This allows to send data which is native in various charset,
491 // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding
492 if (!in_array($xmlrpc->xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
494 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
498 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $xmlrpc->xmlrpc_internalencoding);
501 if ($return_type == 'phpvals')
503 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
507 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
510 xml_set_character_data_handler($parser, 'xmlrpc_cd');
511 xml_set_default_handler($parser, 'xmlrpc_dh');
513 // first error check: xml not well formed
514 if(!xml_parse($parser, $data, count($data)))
516 // thanks to Peter Kocks <peter.kocks@baygate.com>
517 if((xml_get_current_line_number($parser)) == 1)
519 $errstr = 'XML error at line 1, check URL';
523 $errstr = sprintf('XML error: %s at line %d, column %d',
524 xml_error_string(xml_get_error_code($parser)),
525 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
528 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], $xmlrpc->xmlrpcstr['invalid_return'].' ('.$errstr.')');
529 xml_parser_free($parser);
534 $r->hdrs = $xmlrpc->_xh['headers'];
535 $r->_cookies = $xmlrpc->_xh['cookies'];
536 $r->raw_data = $raw_data;
539 xml_parser_free($parser);
540 // second error check: xml well formed but not xml-rpc compliant
541 if ($xmlrpc->_xh['isf'] > 1)
545 /// @todo echo something for user?
548 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'],
549 $xmlrpc->xmlrpcstr['invalid_return'] . ' ' . $xmlrpc->_xh['isf_reason']);
551 // third error check: parsing of the response has somehow gone boink.
552 // NB: shall we omit this check, since we trust the parsing code?
553 elseif ($return_type == 'xmlrpcvals' && !is_object($xmlrpc->_xh['value']))
555 // something odd has happened
556 // and it's time to generate a client side error
557 // indicating something odd went on
558 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'],
559 $xmlrpc->xmlrpcstr['invalid_return']);
565 print "<PRE>---PARSED---\n";
566 // somehow htmlentities chokes on var_export, and some full html string...
567 //print htmlentitites(var_export($xmlrpc->_xh['value'], true));
568 print htmlspecialchars(var_export($xmlrpc->_xh['value'], true));
569 print "\n---END---</PRE>";
572 // note that using =& will raise an error if $xmlrpc->_xh['st'] does not generate an object.
573 $v =& $xmlrpc->_xh['value'];
575 if($xmlrpc->_xh['isf'])
577 /// @todo we should test here if server sent an int and a string,
578 /// and/or coerce them into such...
579 if ($return_type == 'xmlrpcvals')
581 $errno_v = $v->structmem('faultCode');
582 $errstr_v = $v->structmem('faultString');
583 $errno = $errno_v->scalarval();
584 $errstr = $errstr_v->scalarval();
588 $errno = $v['faultCode'];
589 $errstr = $v['faultString'];
594 // FAULT returned, errno needs to reflect that
598 $r = new xmlrpcresp(0, $errno, $errstr);
602 $r=new xmlrpcresp($v, 0, '', $return_type);
606 $r->hdrs = $xmlrpc->_xh['headers'];
607 $r->_cookies = $xmlrpc->_xh['cookies'];
608 $r->raw_data = $raw_data;