5 use PhpXmlRpc\Helper\Http;
6 use PhpXmlRpc\Helper\XMLParser;
7 use PhpXmlRpc\Helper\Logger;
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 Value[] $params array of parameters to be passed to the method (Value objects)
25 public function __construct($methodName, $params = array())
27 $this->methodname = $methodName;
28 foreach ($params as $param) {
29 $this->addParam($param);
33 public function xml_header($charsetEncoding = '')
35 if ($charsetEncoding != '') {
36 return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\" ?" . ">\n<methodCall>\n";
38 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
42 public function xml_footer()
44 return '</methodCall>';
47 public function createPayload($charsetEncoding = '')
49 if ($charsetEncoding != '') {
50 $this->content_type = 'text/xml; charset=' . $charsetEncoding;
52 $this->content_type = 'text/xml';
54 $this->payload = $this->xml_header($charsetEncoding);
55 $this->payload .= '<methodName>' . $this->methodname . "</methodName>\n";
56 $this->payload .= "<params>\n";
57 foreach ($this->params as $p) {
58 $this->payload .= "<param>\n" . $p->serialize($charsetEncoding) .
61 $this->payload .= "</params>\n";
62 $this->payload .= $this->xml_footer();
66 * Gets/sets the xmlrpc method to be invoked.
68 * @param string $methodName the method to be set (leave empty not to set it)
70 * @return string the method that will be invoked
72 public function method($methodName = '')
74 if ($methodName != '') {
75 $this->methodname = $methodName;
78 return $this->methodname;
82 * Returns xml representation of the message. XML prologue included.
84 * @param string $charsetEncoding
86 * @return string the xml representation of the message, xml prologue included
88 public function serialize($charsetEncoding = '')
90 $this->createPayload($charsetEncoding);
92 return $this->payload;
96 * Add a parameter to the list of parameters to be used upon method invocation.
100 * @return boolean false on failure
102 public function addParam($param)
104 // add check: do not add to self params which are not xmlrpc values
105 if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
106 $this->params[] = $param;
115 * Returns the nth parameter in the request. The index zero-based.
117 * @param integer $i the index of the parameter to fetch (zero based)
119 * @return Value the i-th parameter
121 public function getParam($i)
123 return $this->params[$i];
127 * Returns the number of parameters in the message.
129 * @return integer the number of parameters currently set
131 public function getNumParams()
133 return count($this->params);
137 * Given an open file handle, read all data available and parse it as an xmlrpc 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...
145 * @param resource $fp stream pointer
149 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
151 public function parseResponseFile($fp)
154 while ($data = fread($fp, 32768)) {
157 return $this->parseResponse($ipd);
161 * Parse the xmlrpc response contained in the string $data and return a Response object.
163 * @param string $data the xmlrpc response, eventually including http headers
164 * @param bool $headersProcessed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
165 * @param string $returnType decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
169 public function parseResponse($data = '', $headersProcessed = false, $returnType = 'xmlrpcvals')
172 Logger::instance()->debugMessage("---GOT---\n$data\n---END---");
175 $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array());
178 error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.');
179 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
182 // parse the HTTP headers of the response, if present, and separate them from data
183 if (substr($data, 0, 4) == 'HTTP') {
184 $httpParser = new Http();
186 $this->httpResponse = $httpParser->parseResponseHeaders($data, $headersProcessed, $this->debug);
187 } catch(\Exception $e) {
188 $r = new Response(0, $e->getCode(), $e->getMessage());
189 // failed processing of HTTP response headers
190 // save into response obj the full payload received, for debugging
191 $r->raw_data = $data;
197 // be tolerant of extra whitespace in response body
200 /// @todo return an error msg if $data=='' ?
202 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
203 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
204 $pos = strrpos($data, '</methodResponse>');
205 if ($pos !== false) {
206 $data = substr($data, 0, $pos + 17);
209 // try to 'guestimate' the character encoding of the received response
210 $respEncoding = XMLParser::guessEncoding(@$this->httpResponse['headers']['content-type'], $data);
213 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
215 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
216 $end = strpos($data, '-->', $start);
217 $comments = substr($data, $start, $end - $start);
218 Logger::instance()->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" .
219 str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", $respEncoding);
223 // if user wants back raw xml, give it to him
224 if ($returnType == 'xml') {
225 $r = new Response($data, 0, '', 'xml');
226 $r->hdrs = $this->httpResponse['headers'];
227 $r->_cookies = $this->httpResponse['cookies'];
228 $r->raw_data = $this->httpResponse['raw_data'];
233 if ($respEncoding != '') {
235 // Since parsing will fail if charset is not specified in the xml prologue,
236 // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
237 // The following code might be better for mb_string enabled installs, but
238 // makes the lib about 200% slower...
239 //if (!is_valid_charset($respEncoding, array('UTF-8')))
240 if (!in_array($respEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
241 if ($respEncoding == 'ISO-8859-1') {
242 $data = utf8_encode($data);
244 if (extension_loaded('mbstring')) {
245 $data = mb_convert_encoding($data, 'UTF-8', $respEncoding);
247 error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $respEncoding);
253 $parser = xml_parser_create();
254 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
255 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
256 // the xml parser to give us back data in the expected charset.
257 // What if internal encoding is not in one of the 3 allowed?
258 // we use the broadest one, ie. utf8
259 // This allows to send data which is native in various charset,
260 // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
261 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
262 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
264 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
267 $xmlRpcParser = new XMLParser();
268 xml_set_object($parser, $xmlRpcParser);
270 if ($returnType == 'phpvals') {
271 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
273 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
276 xml_set_character_data_handler($parser, 'xmlrpc_cd');
277 xml_set_default_handler($parser, 'xmlrpc_dh');
279 // first error check: xml not well formed
280 if (!xml_parse($parser, $data, count($data))) {
281 // thanks to Peter Kocks <peter.kocks@baygate.com>
282 if ((xml_get_current_line_number($parser)) == 1) {
283 $errStr = 'XML error at line 1, check URL';
285 $errStr = sprintf('XML error: %s at line %d, column %d',
286 xml_error_string(xml_get_error_code($parser)),
287 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
290 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errStr . ')');
291 xml_parser_free($parser);
295 $r->hdrs = $this->httpResponse['headers'];
296 $r->_cookies = $this->httpResponse['cookies'];
297 $r->raw_data = $this->httpResponse['raw_data'];
301 xml_parser_free($parser);
302 // second error check: xml well formed but not xml-rpc compliant
303 if ($xmlRpcParser->_xh['isf'] > 1) {
305 /// @todo echo something for user?
308 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
309 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
311 // third error check: parsing of the response has somehow gone boink.
312 // NB: shall we omit this check, since we trust the parsing code?
313 elseif ($returnType == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
314 // something odd has happened
315 // and it's time to generate a client side error
316 // indicating something odd went on
317 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
318 PhpXmlRpc::$xmlrpcstr['invalid_return']);
320 if ($this->debug > 1) {
321 Logger::instance()->debugMessage(
322 "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---"
326 // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
327 $v = &$xmlRpcParser->_xh['value'];
329 if ($xmlRpcParser->_xh['isf']) {
330 /// @todo we should test here if server sent an int and a string, and/or coerce them into such...
331 if ($returnType == 'xmlrpcvals') {
332 $errNo_v = $v->structmem('faultCode');
333 $errStr_v = $v->structmem('faultString');
334 $errNo = $errNo_v->scalarval();
335 $errStr = $errStr_v->scalarval();
337 $errNo = $v['faultCode'];
338 $errStr = $v['faultString'];
342 // FAULT returned, errno needs to reflect that
346 $r = new Response(0, $errNo, $errStr);
348 $r = new Response($v, 0, '', $returnType);
352 $r->hdrs = $this->httpResponse['headers'];
353 $r->_cookies = $this->httpResponse['cookies'];
354 $r->raw_data = $this->httpResponse['raw_data'];
360 * Enables/disables the echoing to screen of the xmlrpc responses received.
362 * @param integer $in values 0, 1, 2 are supported
364 public function setDebug($in)