9 var $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 xmlrpcmsg($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]);
30 function xml_header($charset_encoding='')
32 if ($charset_encoding != '')
34 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
38 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
47 return '</methodCall>';
61 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 for($i=0; $i<count($this->params); $i++)
73 $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
76 $this->payload.="</params>\n";
77 $this->payload.=$this->xml_footer();
81 * Gets/sets the xmlrpc method to be invoked
82 * @param string $meth the method to be set (leave empty not to set it)
83 * @return string the method that will be invoked
86 function method($meth='')
90 $this->methodname=$meth;
92 return $this->methodname;
96 * Returns xml representation of the message. XML prologue included
97 * @param string $charset_encoding
98 * @return string the xml representation of the message, xml prologue included
101 function serialize($charset_encoding='')
103 $this->createPayload($charset_encoding);
104 return $this->payload;
108 * Add a parameter to the list of parameters to be used upon method invocation
109 * @param xmlrpcval $par
110 * @return boolean false on failure
113 function addParam($par)
115 // add check: do not add to self params which are not xmlrpcvals
116 if(is_object($par) && is_a($par, 'xmlrpcval'))
118 $this->params[]=$par;
128 * Returns the nth parameter in the message. The index zero-based.
129 * @param integer $i the index of the parameter to fetch (zero based)
130 * @return xmlrpcval the i-th parameter
133 function getParam($i) { return $this->params[$i]; }
136 * Returns the number of parameters in the messge.
137 * @return integer the number of parameters currently set
140 function getNumParams() { return count($this->params); }
143 * Given an open file handle, read all data available and parse it as axmlrpc response.
144 * NB: the file handle is not closed by this function.
145 * NNB: might have trouble in rare cases to work on network streams, as we
146 * check for a read of 0 bytes instead of feof($fp).
147 * But since checking for feof(null) returns false, we would risk an
148 * infinite loop in that case, because we cannot trust the caller
149 * to give us a valid pointer to an open file...
151 * @param resource $fp stream pointer
153 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
155 function &parseResponseFile($fp)
158 while($data=fread($fp, 32768))
163 $r =& $this->parseResponse($ipd);
168 * Parses HTTP headers and separates them from data.
171 function &parseResponseHeaders(&$data, $headers_processed=false)
173 $xmlrpc = Phpxmlrpc::instance();
174 // Support "web-proxy-tunelling" connections for https through proxies
175 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
177 // Look for CR/LF or simple LF as line separator,
178 // (even though it is not valid http)
179 $pos = strpos($data,"\r\n\r\n");
180 if($pos || is_int($pos))
186 $pos = strpos($data,"\n\n");
187 if($pos || is_int($pos))
193 // No separation between response headers and body: fault?
199 // this filters out all http headers from proxy.
200 // maybe we could take them into account, too?
201 $data = substr($data, $bd);
205 error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');
206 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
211 // Strip HTTP 1.1 100 Continue header if present
212 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
214 $pos = strpos($data, 'HTTP', 12);
215 // server sent a Continue header without any (valid) content following...
216 // give the client a chance to know it
217 if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
221 $data = substr($data, $pos);
223 if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
225 $errstr= substr($data, 0, strpos($data, "\n")-1);
226 error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);
227 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (' . $errstr . ')');
231 $xmlrpc->_xh['headers'] = array();
232 $xmlrpc->_xh['cookies'] = array();
234 // be tolerant to usage of \n instead of \r\n to separate headers and data
235 // (even though it is not valid http)
236 $pos = strpos($data,"\r\n\r\n");
237 if($pos || is_int($pos))
243 $pos = strpos($data,"\n\n");
244 if($pos || is_int($pos))
250 // No separation between response headers and body: fault?
251 // we could take some action here instead of going on...
255 // be tolerant to line endings, and extra empty lines
256 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
257 while(list(,$line) = @each($ar))
259 // take care of multi-line headers and cookies
260 $arr = explode(':',$line,2);
263 $header_name = strtolower(trim($arr[0]));
264 /// @todo some other headers (the ones that allow a CSV list of values)
265 /// do allow many values to be passed using multiple header lines.
266 /// We should add content to $xmlrpc->_xh['headers'][$header_name]
267 /// instead of replacing it for those...
268 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
270 if ($header_name == 'set-cookie2')
272 // version 2 cookies:
273 // there could be many cookies on one line, comma separated
274 $cookies = explode(',', $arr[1]);
278 $cookies = array($arr[1]);
280 foreach ($cookies as $cookie)
282 // glue together all received cookies, using a comma to separate them
283 // (same as php does with getallheaders())
284 if (isset($xmlrpc->_xh['headers'][$header_name]))
285 $xmlrpc->_xh['headers'][$header_name] .= ', ' . trim($cookie);
287 $xmlrpc->_xh['headers'][$header_name] = trim($cookie);
288 // parse cookie attributes, in case user wants to correctly honour them
289 // feature creep: only allow rfc-compliant cookie attributes?
290 // @todo support for server sending multiple time cookie with same name, but using different PATHs
291 $cookie = explode(';', $cookie);
292 foreach ($cookie as $pos => $val)
294 $val = explode('=', $val, 2);
295 $tag = trim($val[0]);
296 $val = trim(@$val[1]);
297 /// @todo with version 1 cookies, we should strip leading and trailing " chars
301 $xmlrpc->_xh['cookies'][$tag] = array();
302 $xmlrpc->_xh['cookies'][$cookiename]['value'] = urldecode($val);
308 $xmlrpc->_xh['cookies'][$cookiename][$tag] = $val;
316 $xmlrpc->_xh['headers'][$header_name] = trim($arr[1]);
319 elseif(isset($header_name))
321 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
322 $xmlrpc->_xh['headers'][$header_name] .= ' ' . trim($line);
326 $data = substr($data, $bd);
328 if($this->debug && count($xmlrpc->_xh['headers']))
331 foreach($xmlrpc->_xh['headers'] as $header => $value)
333 print htmlentities("HEADER: $header: $value\n");
335 foreach($xmlrpc->_xh['cookies'] as $header => $value)
337 print htmlentities("COOKIE: $header={$value['value']}\n");
342 // if CURL was used for the call, http headers have been processed,
343 // and dechunking + reinflating have been carried out
344 if(!$headers_processed)
346 // Decode chunked encoding sent by http 1.1 servers
347 if(isset($xmlrpc->_xh['headers']['transfer-encoding']) && $xmlrpc->_xh['headers']['transfer-encoding'] == 'chunked')
349 if(!$data = decode_chunked($data))
351 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');
352 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['dechunk_fail'], $xmlrpc->xmlrpcstr['dechunk_fail']);
357 // Decode gzip-compressed stuff
358 // code shamelessly inspired from nusoap library by Dietrich Ayala
359 if(isset($xmlrpc->_xh['headers']['content-encoding']))
361 $xmlrpc->_xh['headers']['content-encoding'] = str_replace('x-', '', $xmlrpc->_xh['headers']['content-encoding']);
362 if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' || $xmlrpc->_xh['headers']['content-encoding'] == 'gzip')
364 // if decoding works, use it. else assume data wasn't gzencoded
365 if(function_exists('gzinflate'))
367 if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
371 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
373 elseif($xmlrpc->_xh['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
377 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
381 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');
382 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['decompress_fail'], $xmlrpc->xmlrpcstr['decompress_fail']);
388 error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
389 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['cannot_decompress'], $xmlrpc->xmlrpcstr['cannot_decompress']);
394 } // end of 'if needed, de-chunk, re-inflate response'
396 // real stupid hack to avoid PHP complaining about returning NULL by ref
403 * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object.
404 * @param string $data the xmlrpc response, eventually including http headers
405 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
406 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
410 function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')
412 $xmlrpc = Phpxmlrpc::instance();
416 //by maHo, replaced htmlspecialchars with htmlentities
417 print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";
422 error_log('XML-RPC: '.__METHOD__.': no response received from server.');
423 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_data'], $xmlrpc->xmlrpcstr['no_data']);
427 $xmlrpc->_xh=array();
430 // parse the HTTP headers of the response, if present, and separate them from data
431 if(substr($data, 0, 4) == 'HTTP')
433 $r =& $this->parseResponseHeaders($data, $headers_processed);
436 // failed processing of HTTP response headers
437 // save into response obj the full payload received, for debugging
438 $r->raw_data = $data;
444 $xmlrpc->_xh['headers'] = array();
445 $xmlrpc->_xh['cookies'] = array();
450 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
453 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
454 $end = strpos($data, '-->', $start);
455 $comments = substr($data, $start, $end-$start);
456 print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";
460 // be tolerant of extra whitespace in response body
463 /// @todo return an error msg if $data=='' ?
465 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
466 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
467 $pos = strrpos($data, '</methodResponse>');
470 $data = substr($data, 0, $pos+17);
473 // if user wants back raw xml, give it to him
474 if ($return_type == 'xml')
476 $r = new xmlrpcresp($data, 0, '', 'xml');
477 $r->hdrs = $xmlrpc->_xh['headers'];
478 $r->_cookies = $xmlrpc->_xh['cookies'];
479 $r->raw_data = $raw_data;
483 // try to 'guestimate' the character encoding of the received response
484 $resp_encoding = guess_encoding(@$xmlrpc->_xh['headers']['content-type'], $data);
486 $xmlrpc->_xh['ac']='';
487 //$xmlrpc->_xh['qt']=''; //unused...
488 $xmlrpc->_xh['stack'] = array();
489 $xmlrpc->_xh['valuestack'] = array();
490 $xmlrpc->_xh['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc
491 $xmlrpc->_xh['isf_reason']='';
492 $xmlrpc->_xh['rt']=''; // 'methodcall or 'methodresponse'
494 // if response charset encoding is not known / supported, try to use
495 // the default encoding and parse the xml anyway, but log a warning...
496 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
497 // the following code might be better for mb_string enabled installs, but
498 // makes the lib about 200% slower...
499 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
501 error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding);
502 $resp_encoding = $xmlrpc->xmlrpc_defencoding;
504 $parser = xml_parser_create($resp_encoding);
505 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
506 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
507 // the xml parser to give us back data in the expected charset.
508 // What if internal encoding is not in one of the 3 allowed?
509 // we use the broadest one, ie. utf8
510 // This allows to send data which is native in various charset,
511 // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding
512 if (!in_array($xmlrpc->xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
514 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
518 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $xmlrpc->xmlrpc_internalencoding);
521 if ($return_type == 'phpvals')
523 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
527 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
530 xml_set_character_data_handler($parser, 'xmlrpc_cd');
531 xml_set_default_handler($parser, 'xmlrpc_dh');
533 // first error check: xml not well formed
534 if(!xml_parse($parser, $data, count($data)))
536 // thanks to Peter Kocks <peter.kocks@baygate.com>
537 if((xml_get_current_line_number($parser)) == 1)
539 $errstr = 'XML error at line 1, check URL';
543 $errstr = sprintf('XML error: %s at line %d, column %d',
544 xml_error_string(xml_get_error_code($parser)),
545 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
548 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], $xmlrpc->xmlrpcstr['invalid_return'].' ('.$errstr.')');
549 xml_parser_free($parser);
554 $r->hdrs = $xmlrpc->_xh['headers'];
555 $r->_cookies = $xmlrpc->_xh['cookies'];
556 $r->raw_data = $raw_data;
559 xml_parser_free($parser);
560 // second error check: xml well formed but not xml-rpc compliant
561 if ($xmlrpc->_xh['isf'] > 1)
565 /// @todo echo something for user?
568 $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'],
569 $xmlrpc->xmlrpcstr['invalid_return'] . ' ' . $xmlrpc->_xh['isf_reason']);
571 // third error check: parsing of the response has somehow gone boink.
572 // NB: shall we omit this check, since we trust the parsing code?
573 elseif ($return_type == 'xmlrpcvals' && !is_object($xmlrpc->_xh['value']))
575 // something odd has happened
576 // and it's time to generate a client side error
577 // indicating something odd went on
578 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'],
579 $xmlrpc->xmlrpcstr['invalid_return']);
585 print "<PRE>---PARSED---\n";
586 // somehow htmlentities chokes on var_export, and some full html string...
587 //print htmlentitites(var_export($xmlrpc->_xh['value'], true));
588 print htmlspecialchars(var_export($xmlrpc->_xh['value'], true));
589 print "\n---END---</PRE>";
592 // note that using =& will raise an error if $xmlrpc->_xh['st'] does not generate an object.
593 $v =& $xmlrpc->_xh['value'];
595 if($xmlrpc->_xh['isf'])
597 /// @todo we should test here if server sent an int and a string,
598 /// and/or coerce them into such...
599 if ($return_type == 'xmlrpcvals')
601 $errno_v = $v->structmem('faultCode');
602 $errstr_v = $v->structmem('faultString');
603 $errno = $errno_v->scalarval();
604 $errstr = $errstr_v->scalarval();
608 $errno = $v['faultCode'];
609 $errstr = $v['faultString'];
614 // FAULT returned, errno needs to reflect that
618 $r = new xmlrpcresp(0, $errno, $errstr);
622 $r=new xmlrpcresp($v, 0, '', $return_type);
626 $r->hdrs = $xmlrpc->_xh['headers'];
627 $r->_cookies = $xmlrpc->_xh['cookies'];
628 $r->raw_data = $raw_data;