5 use PhpXmlRpc\Helper\Charset;
6 use PhpXmlRpc\Helper\Http;
7 use PhpXmlRpc\Helper\Logger;
8 use PhpXmlRpc\Helper\XMLParser;
11 * This class provides the representation of a request to an XML-RPC server.
12 * A client sends a PhpXmlrpc\Request to a server, and receives back an PhpXmlrpc\Response.
16 /// @todo: do these need to be public?
21 public $params = array();
23 public $content_type = 'text/xml';
25 // holds data while parsing the response. NB: Not a full Response object
26 protected $httpResponse = array();
29 * @param string $methodName the name of the method to invoke
30 * @param Value[] $params array of parameters to be passed to the method (NB: Value objects, not plain php values)
32 public function __construct($methodName, $params = array())
34 $this->methodname = $methodName;
35 foreach ($params as $param) {
36 $this->addParam($param);
41 * @internal this function will become protected in the future
42 * @param string $charsetEncoding
45 public function xml_header($charsetEncoding = '')
47 if ($charsetEncoding != '') {
48 return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\" ?" . ">\n<methodCall>\n";
50 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
55 * @internal this function will become protected in the future
58 public function xml_footer()
60 return '</methodCall>';
64 * @internal this function will become protected in the future
65 * @param string $charsetEncoding
67 public function createPayload($charsetEncoding = '')
69 if ($charsetEncoding != '') {
70 $this->content_type = 'text/xml; charset=' . $charsetEncoding;
72 $this->content_type = 'text/xml';
74 $this->payload = $this->xml_header($charsetEncoding);
75 $this->payload .= '<methodName>' . Charset::instance()->encodeEntities(
76 $this->methodname, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</methodName>\n";
77 $this->payload .= "<params>\n";
78 foreach ($this->params as $p) {
79 $this->payload .= "<param>\n" . $p->serialize($charsetEncoding) .
82 $this->payload .= "</params>\n";
83 $this->payload .= $this->xml_footer();
87 * Gets/sets the xmlrpc method to be invoked.
89 * @param string $methodName the method to be set (leave empty not to set it)
91 * @return string the method that will be invoked
93 public function method($methodName = '')
95 if ($methodName != '') {
96 $this->methodname = $methodName;
99 return $this->methodname;
103 * Returns xml representation of the message. XML prologue included.
105 * @param string $charsetEncoding
107 * @return string the xml representation of the message, xml prologue included
109 public function serialize($charsetEncoding = '')
111 $this->createPayload($charsetEncoding);
113 return $this->payload;
117 * Add a parameter to the list of parameters to be used upon method invocation.
119 * Checks that $params is actually a Value object and not a plain php value.
121 * @param Value $param
123 * @return boolean false on failure
125 public function addParam($param)
127 // check: do not add to self params which are not xmlrpc values
128 if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
129 $this->params[] = $param;
138 * Returns the nth parameter in the request. The index zero-based.
140 * @param integer $i the index of the parameter to fetch (zero based)
142 * @return Value the i-th parameter
144 public function getParam($i)
146 return $this->params[$i];
150 * Returns the number of parameters in the message.
152 * @return integer the number of parameters currently set
154 public function getNumParams()
156 return count($this->params);
160 * Given an open file handle, read all data available and parse it as an xmlrpc response.
162 * NB: the file handle is not closed by this function.
163 * NNB: might have trouble in rare cases to work on network streams, as we check for a read of 0 bytes instead of
164 * feof($fp). But since checking for feof(null) returns false, we would risk an infinite loop in that case,
165 * because we cannot trust the caller to give us a valid pointer to an open file...
167 * @param resource $fp stream pointer
168 * @param bool $headersProcessed
169 * @param string $returnType
173 public function parseResponseFile($fp, $headersProcessed = false, $returnType = 'xmlrpcvals')
176 while ($data = fread($fp, 32768)) {
179 return $this->parseResponse($ipd, $headersProcessed, $returnType);
183 * Parse the xmlrpc response contained in the string $data and return a Response object.
185 * When $this->debug has been set to a value greater than 0, will echo debug messages to screen while decoding.
187 * @param string $data the xmlrpc response, possibly including http headers
188 * @param bool $headersProcessed when true prevents parsing HTTP headers for interpretation of content-encoding and
189 * consequent decoding
190 * @param string $returnType decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or
195 * @todo parsing Responses is not really the responsibility of the Request class. Maybe of the Client...
197 public function parseResponse($data = '', $headersProcessed = false, $returnType = 'xmlrpcvals')
200 Logger::instance()->debugMessage("---GOT---\n$data\n---END---");
203 $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array());
206 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': no response received from server.');
207 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
210 // parse the HTTP headers of the response, if present, and separate them from data
211 if (substr($data, 0, 4) == 'HTTP') {
212 $httpParser = new Http();
214 $this->httpResponse = $httpParser->parseResponseHeaders($data, $headersProcessed, $this->debug);
215 } catch(\Exception $e) {
216 $r = new Response(0, $e->getCode(), $e->getMessage());
217 // failed processing of HTTP response headers
218 // save into response obj the full payload received, for debugging
219 $r->raw_data = $data;
225 // be tolerant of extra whitespace in response body
228 /// @todo return an error msg if $data == '' ?
230 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
231 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
232 $pos = strrpos($data, '</methodResponse>');
233 if ($pos !== false) {
234 $data = substr($data, 0, $pos + 17);
237 // try to 'guestimate' the character encoding of the received response
238 $respEncoding = XMLParser::guessEncoding(@$this->httpResponse['headers']['content-type'], $data);
241 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
243 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
244 $end = strpos($data, '-->', $start);
245 $comments = substr($data, $start, $end - $start);
246 Logger::instance()->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" .
247 str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", $respEncoding);
251 // if user wants back raw xml, give it to her
252 if ($returnType == 'xml') {
253 $r = new Response($data, 0, '', 'xml');
254 $r->hdrs = $this->httpResponse['headers'];
255 $r->_cookies = $this->httpResponse['cookies'];
256 $r->raw_data = $this->httpResponse['raw_data'];
261 if ($respEncoding != '') {
263 // Since parsing will fail if charset is not specified in the xml prologue,
264 // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
265 // The following code might be better for mb_string enabled installs, but makes the lib about 200% slower...
266 //if (!is_valid_charset($respEncoding, array('UTF-8')))
267 if (!in_array($respEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
268 if ($respEncoding == 'ISO-8859-1') {
269 $data = utf8_encode($data);
271 if (extension_loaded('mbstring')) {
272 $data = mb_convert_encoding($data, 'UTF-8', $respEncoding);
274 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $respEncoding);
280 // PHP internally might use ISO-8859-1, so we have to tell the xml parser to give us back data in the expected charset.
281 // What if internal encoding is not in one of the 3 allowed? We use the broadest one, ie. utf8
282 // This allows to send data which is native in various charset, by extending xmlrpc_encode_entities() and
283 // setting xmlrpc_internalencoding
284 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
285 $options = array(XML_OPTION_TARGET_ENCODING => 'UTF-8');
287 $options = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
290 $xmlRpcParser = new XMLParser($options);
291 $xmlRpcParser->parse($data, $returnType, XMLParser::ACCEPT_RESPONSE);
293 // first error check: xml not well formed
294 if ($xmlRpcParser->_xh['isf'] > 2) {
296 // BC break: in the past for some cases we used the error message: 'XML error at line 1, check URL'
298 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
299 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
302 print $xmlRpcParser->_xh['isf_reason'];
305 // second error check: xml well formed but not xml-rpc compliant
306 elseif ($xmlRpcParser->_xh['isf'] == 2) {
308 /// @todo echo something for user?
311 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
312 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
314 // third error check: parsing of the response has somehow gone boink.
315 // NB: shall we omit this check, since we trust the parsing code?
316 elseif ($returnType == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
317 // something odd has happened
318 // and it's time to generate a client side error
319 // indicating something odd went on
320 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
321 PhpXmlRpc::$xmlrpcstr['invalid_return']);
323 if ($this->debug > 1) {
324 Logger::instance()->debugMessage(
325 "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---"
329 $v = $xmlRpcParser->_xh['value'];
331 if ($xmlRpcParser->_xh['isf']) {
332 /// @todo we should test here if server sent an int and a string, and/or coerce them into such...
333 if ($returnType == 'xmlrpcvals') {
334 $errNo_v = $v['faultCode'];
335 $errStr_v = $v['faultString'];
336 $errNo = $errNo_v->scalarval();
337 $errStr = $errStr_v->scalarval();
339 $errNo = $v['faultCode'];
340 $errStr = $v['faultString'];
344 // FAULT returned, errno needs to reflect that
348 $r = new Response(0, $errNo, $errStr);
350 $r = new Response($v, 0, '', $returnType);
354 $r->hdrs = $this->httpResponse['headers'];
355 $r->_cookies = $this->httpResponse['cookies'];
356 $r->raw_data = $this->httpResponse['raw_data'];
362 * Kept the old name even if Request class was renamed, for compatibility.
366 public function kindOf()
372 * Enables/disables the echoing to screen of the xmlrpc responses received.
374 * @param integer $level values 0, 1, 2 are supported
376 public function setDebug($level)
378 $this->debug = $level;