5 use PhpXmlRpc\Helper\Logger;
9 /// @todo: do these need to be public?
10 public $method = 'http';
19 public $username = '';
20 public $password = '';
24 public $certpass = '';
26 public $cacertdir = '';
29 public $verifypeer = true;
30 public $verifyhost = 2;
31 public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
34 public $proxyport = 0;
35 public $proxy_user = '';
36 public $proxy_pass = '';
37 public $proxy_authtype = 1;
39 public $cookies = array();
40 public $extracurlopts = array();
42 public $no_multicall = false;
45 * List of http compression methods accepted by the client for responses.
46 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib.
48 * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
49 * in those cases it will be up to CURL to decide the compression methods
50 * it supports. You might check for the presence of 'zlib' in the output of
51 * curl_version() to determine wheter compression is supported or not
53 public $accepted_compression = array();
55 * Name of compression scheme to be used for sending requests.
56 * Either null, gzip or deflate.
58 public $request_compression = '';
60 * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
61 * http://curl.haxx.se/docs/faq.html#7.3).
63 public $xmlrpc_curl_handle = null;
64 /// Whether to use persistent connections for http 1.1 and https
65 public $keepalive = false;
66 /// Charset encodings that can be decoded without problems by the client
67 public $accepted_charset_encodings = array();
68 /// Charset encoding to be used in serializing request. NULL = use ASCII
69 public $request_charset_encoding = '';
71 * Decides the content of Response objects returned by calls to send()
72 * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'.
74 public $return_type = 'xmlrpcvals';
76 * Sent to servers in http headers.
81 * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php
82 * @param string $server the server name / ip address
83 * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used
84 * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed
86 public function __construct($path, $server = '', $port = '', $method = '')
88 // allow user to specify all params in $path
89 if ($server == '' and $port == '' and $method == '') {
90 $parts = parse_url($path);
91 $server = $parts['host'];
92 $path = isset($parts['path']) ? $parts['path'] : '';
93 if (isset($parts['query'])) {
94 $path .= '?' . $parts['query'];
96 if (isset($parts['fragment'])) {
97 $path .= '#' . $parts['fragment'];
99 if (isset($parts['port'])) {
100 $port = $parts['port'];
102 if (isset($parts['scheme'])) {
103 $method = $parts['scheme'];
105 if (isset($parts['user'])) {
106 $this->username = $parts['user'];
108 if (isset($parts['pass'])) {
109 $this->password = $parts['pass'];
112 if ($path == '' || $path[0] != '/') {
113 $this->path = '/' . $path;
117 $this->server = $server;
122 $this->method = $method;
125 // if ZLIB is enabled, let the client by default accept compressed responses
126 if (function_exists('gzinflate') || (
127 function_exists('curl_init') && (($info = curl_version()) &&
128 ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
131 $this->accepted_compression = array('gzip', 'deflate');
134 // keepalives: enabled by default
135 $this->keepalive = true;
137 // by default the xml parser can support these 3 charset encodings
138 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
140 // initialize user_agent string
141 $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
145 * Enables/disables the echoing to screen of the xmlrpc responses received.
147 * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
149 public function setDebug($in)
155 * Add some http BASIC AUTH credentials, used by the client to authenticate.
157 * @param string $u username
158 * @param string $p password
159 * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)
161 public function setCredentials($u, $p, $t = 1)
163 $this->username = $u;
164 $this->password = $p;
165 $this->authtype = $t;
169 * Add a client-side https certificate.
171 * @param string $cert
172 * @param string $certPass
174 public function setCertificate($cert, $certPass)
177 $this->certpass = $certPass;
181 * Add a CA certificate to verify server with (see man page about
182 * CURLOPT_CAINFO for more details).
184 * @param string $caCert certificate file name (or dir holding certificates)
185 * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
187 public function setCaCertificate($caCert, $isDir = false)
190 $this->cacertdir = $caCert;
192 $this->cacert = $caCert;
197 * Set attributes for SSL communication: private SSL key
198 * NB: does not work in older php/curl installs
199 * Thanks to Daniel Convissor.
201 * @param string $key The name of a file containing a private SSL key
202 * @param string $keyPass The secret password needed to use the private SSL key
204 public function setKey($key, $keyPass)
207 $this->keypass = $keyPass;
211 * Set attributes for SSL communication: verify server certificate.
213 * @param bool $i enable/disable verification of peer certificate
215 public function setSSLVerifyPeer($i)
217 $this->verifypeer = $i;
221 * Set attributes for SSL communication: verify match of server cert w. hostname.
225 public function setSSLVerifyHost($i)
227 $this->verifyhost = $i;
231 * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide
235 public function setSSLVersion($i)
237 $this->sslversion = $i;
243 * @param string $proxyHost
244 * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
245 * @param string $proxyUsername Leave blank if proxy has public access
246 * @param string $proxyPassword Leave blank if proxy has public access
247 * @param int $proxyAuthType set to constant CURLAUTH_NTLM to use NTLM auth with proxy
249 public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
251 $this->proxy = $proxyHost;
252 $this->proxyport = $proxyPort;
253 $this->proxy_user = $proxyUsername;
254 $this->proxy_pass = $proxyPassword;
255 $this->proxy_authtype = $proxyAuthType;
259 * Enables/disables reception of compressed xmlrpc responses.
260 * Note that enabling reception of compressed responses merely adds some standard
261 * http headers to xmlrpc requests. It is up to the xmlrpc server to return
262 * compressed responses when receiving such requests.
264 * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
266 public function setAcceptedCompression($compMethod)
268 if ($compMethod == 'any') {
269 $this->accepted_compression = array('gzip', 'deflate');
270 } elseif ($compMethod == false) {
271 $this->accepted_compression = array();
273 $this->accepted_compression = array($compMethod);
278 * Enables/disables http compression of xmlrpc request.
279 * Take care when sending compressed requests: servers might not support them
280 * (and automatic fallback to uncompressed requests is not yet implemented).
282 * @param string $compMethod either 'gzip', 'deflate' or ''
284 public function setRequestCompression($compMethod)
286 $this->request_compression = $compMethod;
290 * Adds a cookie to list of cookies that will be sent to server.
291 * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:
292 * do not do it unless you know what you are doing.
294 * @param string $name
295 * @param string $value
296 * @param string $path
297 * @param string $domain
300 * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)
302 public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
304 $this->cookies[$name]['value'] = urlencode($value);
305 if ($path || $domain || $port) {
306 $this->cookies[$name]['path'] = $path;
307 $this->cookies[$name]['domain'] = $domain;
308 $this->cookies[$name]['port'] = $port;
309 $this->cookies[$name]['version'] = 1;
311 $this->cookies[$name]['version'] = 0;
316 * Directly set cURL options, for extra flexibility
317 * It allows eg. to bind client to a specific IP interface / address.
319 * @param array $options
321 public function SetCurlOptions($options)
323 $this->extracurlopts = $options;
327 * Set user-agent string that will be used by this client instance
328 * in http headers sent to the server.
330 * @param string $agentString
332 public function SetUserAgent($agentString)
334 $this->user_agent = $agentString;
338 * Send an xmlrpc request.
340 * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the complete xml representation of a request
341 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply
342 * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used
344 * @return Response|Response[]
346 public function send($req, $timeout = 0, $method = '')
348 // if user does not specify http protocol, use native method of this client
349 // (i.e. method set during call to constructor)
351 $method = $this->method;
354 if (is_array($req)) {
355 // $req is an array of Requests
356 $r = $this->multicall($req, $timeout, $method);
359 } elseif (is_string($req)) {
360 $n = new Request('');
365 // where req is a Request
366 $req->setDebug($this->debug);
368 if ($method == 'https') {
369 $r = $this->sendPayloadHTTPS(
385 $this->proxy_authtype,
391 } elseif ($method == 'http11') {
392 $r = $this->sendPayloadCURL(
408 $this->proxy_authtype,
413 $r = $this->sendPayloadHTTP10(
425 $this->proxy_authtype,
434 * @param Request $req
435 * @param string $server
437 * @param int $timeout
438 * @param string $username
439 * @param string $password
440 * @param int $authType
441 * @param string $proxyHost
442 * @param int $proxyPort
443 * @param string $proxyUsername
444 * @param string $proxyPassword
445 * @param int $proxyAuthType
446 * @param string $method
449 protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
450 $username = '', $password = '', $authType = 1, $proxyHost = '',
451 $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
455 $port = ( $method === "https" ) ? 443 : 80;
458 // Only create the payload if it was not created previously
459 if (empty($req->payload)) {
460 $req->createPayload($this->request_charset_encoding);
463 $payload = $req->payload;
464 // Deflate request body and set appropriate request headers
465 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
466 if ($this->request_compression == 'gzip') {
467 $a = @gzencode($payload);
470 $encodingHdr = "Content-Encoding: gzip\r\n";
473 $a = @gzcompress($payload);
476 $encodingHdr = "Content-Encoding: deflate\r\n";
483 // thanks to Grant Rauscher <grant7@firstworld.net> for this
485 if ($username != '') {
486 $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
487 if ($authType != 1) {
488 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
492 $acceptedEncoding = '';
493 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
494 $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
497 $proxyCredentials = '';
499 if ($proxyPort == 0) {
502 $connectServer = $proxyHost;
503 $connectPort = $proxyPort;
505 $uri = 'http://' . $server . ':' . $port . $this->path;
506 if ($proxyUsername != '') {
507 if ($proxyAuthType != 1) {
508 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
510 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
513 $connectServer = $server;
514 $connectPort = $port;
515 /// @todo if supporting https, we should support all its current options as well: peer name verification etc...
516 $transport = ( $method === "https" ) ? "tls" : "tcp";
520 // Cookie generation, as per rfc2965 (version 1 cookies) or
521 // netscape's rules (version 0 cookies)
523 if (count($this->cookies)) {
525 foreach ($this->cookies as $name => $cookie) {
526 if ($cookie['version']) {
527 $version = ' $Version="' . $cookie['version'] . '";';
528 $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
529 if ($cookie['path']) {
530 $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
532 if ($cookie['domain']) {
533 $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
535 if ($cookie['port']) {
536 $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
539 $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
542 $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
546 $port = ($port == 80) ? '' : (':' . $port);
548 $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
549 'User-Agent: ' . $this->user_agent . "\r\n" .
550 'Host: ' . $server . $port . "\r\n" .
555 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
557 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
558 strlen($payload) . "\r\n\r\n" .
561 if ($this->debug > 1) {
562 Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
566 $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $timeout);
568 $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr);
572 stream_set_timeout($fp, $timeout);
575 $this->errstr = 'Connect error: ' . $this->errstr;
576 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
581 if (!fputs($fp, $op, strlen($op))) {
583 $this->errstr = 'Write error';
584 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
588 // reset errno and errstr on successful socket connection
591 // G. Giunta 2005/10/24: close socket before parsing.
592 // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
595 // shall we check for $data === FALSE?
596 // as per the manual, it signals an error
597 $ipd .= fread($fp, 32768);
598 } while (!feof($fp));
600 $r = $req->parseResponse($ipd, false, $this->return_type);
606 * @param Request $req
607 * @param string $server
609 * @param int $timeout
610 * @param string $username
611 * @param string $password
612 * @param int $authType
613 * @param string $cert
614 * @param string $certPass
615 * @param string $caCert
616 * @param string $caCertDir
617 * @param string $proxyHost
618 * @param int $proxyPort
619 * @param string $proxyUsername
620 * @param string $proxyPassword
621 * @param int $proxyAuthType
622 * @param bool $keepAlive
624 * @param string $keyPass
625 * @param int $sslVersion
628 protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '',
629 $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
630 $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
631 $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
633 return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
634 $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
635 $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
639 * Contributed by Justin Miller <justin@voxel.net>
640 * Requires curl to be built into PHP
641 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
643 * @param Request $req
644 * @param string $server
646 * @param int $timeout
647 * @param string $username
648 * @param string $password
649 * @param int $authType
650 * @param string $cert
651 * @param string $certPass
652 * @param string $caCert
653 * @param string $caCertDir
654 * @param string $proxyHost
655 * @param int $proxyPort
656 * @param string $proxyUsername
657 * @param string $proxyPassword
658 * @param int $proxyAuthType
659 * @param string $method
660 * @param bool $keepAlive
662 * @param string $keyPass
663 * @param int $sslVersion
666 protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '',
667 $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
668 $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https',
669 $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
671 if (!function_exists('curl_init')) {
672 $this->errstr = 'CURL unavailable on this install';
673 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
675 if ($method == 'https') {
676 if (($info = curl_version()) &&
677 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
679 $this->errstr = 'SSL unavailable on this install';
680 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
685 if ($method == 'http') {
692 // Only create the payload if it was not created previously
693 if (empty($req->payload)) {
694 $req->createPayload($this->request_charset_encoding);
697 // Deflate request body and set appropriate request headers
698 $payload = $req->payload;
699 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
700 if ($this->request_compression == 'gzip') {
701 $a = @gzencode($payload);
704 $encodingHdr = 'Content-Encoding: gzip';
707 $a = @gzcompress($payload);
710 $encodingHdr = 'Content-Encoding: deflate';
717 if ($this->debug > 1) {
718 Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
721 if (!$keepAlive || !$this->xmlrpc_curl_handle) {
722 $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
724 $this->xmlrpc_curl_handle = $curl;
727 $curl = $this->xmlrpc_curl_handle;
730 // results into variable
731 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
733 if ($this->debug > 1) {
734 curl_setopt($curl, CURLOPT_VERBOSE, true);
735 /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
737 curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
738 // required for XMLRPC: post the data
739 curl_setopt($curl, CURLOPT_POST, 1);
741 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
743 // return the header too
744 curl_setopt($curl, CURLOPT_HEADER, 1);
746 // NB: if we set an empty string, CURL will add http header indicating
747 // ALL methods it is supporting. This is possibly a better option than
748 // letting the user tell what curl can / cannot do...
749 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
750 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
751 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
752 if (count($this->accepted_compression) == 1) {
753 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
755 curl_setopt($curl, CURLOPT_ENCODING, '');
759 $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
760 // if no keepalive is wanted, let the server know it in advance
762 $headers[] = 'Connection: close';
764 // request compression header
766 $headers[] = $encodingHdr;
769 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
772 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
775 if ($username && $password) {
776 curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
777 if (defined('CURLOPT_HTTPAUTH')) {
778 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
779 } elseif ($authType != 1) {
780 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
784 if ($method == 'https') {
787 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
791 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
793 // whether to verify remote host's cert
794 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
795 // set ca certificates file/dir
797 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
800 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
802 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
804 curl_setopt($curl, CURLOPT_SSLKEY, $key);
806 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
808 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
810 // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used
811 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
812 // allow usage of different SSL versions
813 curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
818 if ($proxyPort == 0) {
819 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
821 curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
822 if ($proxyUsername) {
823 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
824 if (defined('CURLOPT_PROXYAUTH')) {
825 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
826 } elseif ($proxyAuthType != 1) {
827 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
832 // NB: should we build cookie http headers by hand rather than let CURL do it?
833 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
834 // set to client obj the the user...
835 if (count($this->cookies)) {
837 foreach ($this->cookies as $name => $cookie) {
838 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
840 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
843 foreach ($this->extracurlopts as $opt => $val) {
844 curl_setopt($curl, $opt, $val);
847 $result = curl_exec($curl);
849 if ($this->debug > 1) {
850 $message = "---CURL INFO---\n";
851 foreach (curl_getinfo($curl) as $name => $val) {
852 if (is_array($val)) {
853 $val = implode("\n", $val);
855 $message .= $name . ': ' . $val . "\n";
857 $message .= "---END---";
858 Logger::instance()->debugMessage($message);
862 /// @todo we should use a better check here - what if we get back '' or '0'?
864 $this->errstr = 'no response';
865 $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
868 $this->xmlrpc_curl_handle = null;
874 $resp = $req->parseResponse($result, true, $this->return_type);
875 // if we got back a 302, we can not reuse the curl handle for later calls
876 if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
878 $this->xmlrpc_curl_handle = null;
886 * Send an array of requests and return an array of responses.
887 * Unless $this->no_multicall has been set to true, it will try first
888 * to use one single xmlrpc call to server method system.multicall, and
889 * revert to sending many successive calls in case of failure.
890 * This failure is also stored in $this->no_multicall for subsequent calls.
891 * Unfortunately, there is no server error code universally used to denote
892 * the fact that multicall is unsupported, so there is no way to reliably
893 * distinguish between that and a temporary failure.
894 * If you are sure that server supports multicall and do not want to
895 * fallback to using many single calls, set the fourth parameter to FALSE.
897 * NB: trying to shoehorn extra functionality into existing syntax has resulted
898 * in pretty much convoluted code...
900 * @param Request[] $reqs an array of Request objects
901 * @param integer $timeout connection timeout (in seconds)
902 * @param string $method the http protocol variant to be used
903 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted
907 public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
910 $method = $this->method;
912 if (!$this->no_multicall) {
913 $results = $this->_try_multicall($reqs, $timeout, $method);
914 if (is_array($results)) {
915 // System.multicall succeeded
918 // either system.multicall is unsupported by server,
919 // or call failed for some other reason.
921 // Don't try it next time...
922 $this->no_multicall = true;
924 if (is_a($results, '\PhpXmlRpc\Response')) {
927 $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
932 // override fallback, in case careless user tries to do two
933 // opposite things at the same time
939 // system.multicall is (probably) unsupported by server:
940 // emulate multicall via multiple requests
941 foreach ($reqs as $req) {
942 $results[] = $this->send($req, $timeout, $method);
945 // user does NOT want to fallback on many single calls:
946 // since we should always return an array of responses,
947 // return an array with the same error repeated n times
948 foreach ($reqs as $req) {
949 $results[] = $result;
957 * Attempt to boxcar $reqs via system.multicall.
958 * Returns either an array of xmlrpc reponses, an xmlrpc error response
959 * or false (when received response does not respect valid multicall syntax).
961 * @param Request[] $reqs
962 * @param int $timeout
963 * @param string $method
964 * @return array|bool|mixed|Response
966 private function _try_multicall($reqs, $timeout, $method)
968 // Construct multicall request
970 foreach ($reqs as $req) {
971 $call['methodName'] = new Value($req->method(), 'string');
972 $numParams = $req->getNumParams();
974 for ($i = 0; $i < $numParams; $i++) {
975 $params[$i] = $req->getParam($i);
977 $call['params'] = new Value($params, 'array');
978 $calls[] = new Value($call, 'struct');
980 $multiCall = new Request('system.multicall');
981 $multiCall->addParam(new Value($calls, 'array'));
984 $result = $this->send($multiCall, $timeout, $method);
986 if ($result->faultCode() != 0) {
987 // call to system.multicall failed
992 $rets = $result->value();
994 if ($this->return_type == 'xml') {
996 } elseif ($this->return_type == 'phpvals') {
997 /// @todo test this code branch...
998 $rets = $result->value();
999 if (!is_array($rets)) {
1000 return false; // bad return type from system.multicall
1002 $numRets = count($rets);
1003 if ($numRets != count($reqs)) {
1004 return false; // wrong number of return values.
1007 $response = array();
1008 for ($i = 0; $i < $numRets; $i++) {
1010 if (!is_array($val)) {
1013 switch (count($val)) {
1015 if (!isset($val[0])) {
1016 return false; // Bad value
1018 // Normal return value
1019 $response[$i] = new Response($val[0], 0, '', 'phpvals');
1022 /// @todo remove usage of @: it is apparently quite slow
1023 $code = @$val['faultCode'];
1024 if (!is_int($code)) {
1027 $str = @$val['faultString'];
1028 if (!is_string($str)) {
1031 $response[$i] = new Response(0, $code, $str);
1040 // return type == 'xmlrpcvals'
1042 $rets = $result->value();
1043 if ($rets->kindOf() != 'array') {
1044 return false; // bad return type from system.multicall
1046 $numRets = $rets->count();
1047 if ($numRets != count($reqs)) {
1048 return false; // wrong number of return values.
1051 $response = array();
1052 //for ($i = 0; $i < $numRets; $i++) {
1053 foreach($rets as $val) {
1054 //$val = $rets->arraymem($i);
1055 switch ($val->kindOf()) {
1057 if ($val->count() != 1) {
1058 return false; // Bad value
1060 // Normal return value
1061 //$response[] = new Response($val->arraymem(0));
1062 $response[] = new Response($val[0]);
1065 //$code = $val->structmem('faultCode');
1066 $code = $val['faultCode'];
1067 if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1070 //$str = $val->structmem('faultString');
1071 $str = $val['faultString'];
1072 if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1075 $response[] = new Response(0, $code->scalarval(), $str->scalarval());