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
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 // $msg 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
433 * @param Request $req
434 * @param string $server
436 * @param int $timeout
437 * @param string $username
438 * @param string $password
439 * @param int $authType
440 * @param string $proxyHost
441 * @param int $proxyPort
442 * @param string $proxyUsername
443 * @param string $proxyPassword
444 * @param int $proxyAuthType
447 protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
448 $username = '', $password = '', $authType = 1, $proxyHost = '',
449 $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
455 // Only create the payload if it was not created previously
456 if (empty($req->payload)) {
457 $req->createPayload($this->request_charset_encoding);
460 $payload = $req->payload;
461 // Deflate request body and set appropriate request headers
462 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
463 if ($this->request_compression == 'gzip') {
464 $a = @gzencode($payload);
467 $encodingHdr = "Content-Encoding: gzip\r\n";
470 $a = @gzcompress($payload);
473 $encodingHdr = "Content-Encoding: deflate\r\n";
480 // thanks to Grant Rauscher <grant7@firstworld.net> for this
482 if ($username != '') {
483 $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
484 if ($authType != 1) {
485 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
489 $acceptedEncoding = '';
490 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
491 $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
494 $proxyCredentials = '';
496 if ($proxyPort == 0) {
499 $connectServer = $proxyHost;
500 $connectPort = $proxyPort;
501 $uri = 'http://' . $server . ':' . $port . $this->path;
502 if ($proxyUsername != '') {
503 if ($proxyAuthType != 1) {
504 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
506 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
509 $connectServer = $server;
510 $connectPort = $port;
514 // Cookie generation, as per rfc2965 (version 1 cookies) or
515 // netscape's rules (version 0 cookies)
517 if (count($this->cookies)) {
519 foreach ($this->cookies as $name => $cookie) {
520 if ($cookie['version']) {
521 $version = ' $Version="' . $cookie['version'] . '";';
522 $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
523 if ($cookie['path']) {
524 $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
526 if ($cookie['domain']) {
527 $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
529 if ($cookie['port']) {
530 $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
533 $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
536 $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
540 $port = ($port == 80) ? '' : (':' . $port);
542 $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
543 'User-Agent: ' . $this->user_agent . "\r\n" .
544 'Host: ' . $server . $port . "\r\n" .
549 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
551 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
552 strlen($payload) . "\r\n\r\n" .
555 if ($this->debug > 1) {
556 Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
560 $fp = @fsockopen($connectServer, $connectPort, $this->errno, $this->errstr, $timeout);
562 $fp = @fsockopen($connectServer, $connectPort, $this->errno, $this->errstr);
565 if ($timeout > 0 && function_exists('stream_set_timeout')) {
566 stream_set_timeout($fp, $timeout);
569 $this->errstr = 'Connect error: ' . $this->errstr;
570 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
575 if (!fputs($fp, $op, strlen($op))) {
577 $this->errstr = 'Write error';
578 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
582 // reset errno and errstr on successful socket connection
585 // G. Giunta 2005/10/24: close socket before parsing.
586 // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
589 // shall we check for $data === FALSE?
590 // as per the manual, it signals an error
591 $ipd .= fread($fp, 32768);
592 } while (!feof($fp));
594 $r = $req->parseResponse($ipd, false, $this->return_type);
600 * @param Request $req
601 * @param string $server
603 * @param int $timeout
604 * @param string $username
605 * @param string $password
606 * @param int $authType
607 * @param string $cert
608 * @param string $certPass
609 * @param string $caCert
610 * @param string $caCertDir
611 * @param string $proxyHost
612 * @param int $proxyPort
613 * @param string $proxyUsername
614 * @param string $proxyPassword
615 * @param int $proxyAuthType
616 * @param bool $keepAlive
618 * @param string $keyPass
619 * @param int $sslVersion
622 protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '',
623 $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
624 $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
625 $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
627 return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
628 $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
629 $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
633 * Contributed by Justin Miller <justin@voxel.net>
634 * Requires curl to be built into PHP
635 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
637 * @param Request $msg
638 * @param string $server
640 * @param int $timeout
641 * @param string $username
642 * @param string $password
643 * @param int $authType
644 * @param string $cert
645 * @param string $certPass
646 * @param string $caCert
647 * @param string $caCertDir
648 * @param string $proxyHost
649 * @param int $proxyPort
650 * @param string $proxyUsername
651 * @param string $proxyPassword
652 * @param int $proxyAuthType
653 * @param string $method
654 * @param bool $keepAlive
656 * @param string $keyPass
657 * @param int $sslVersion
660 protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = '',
661 $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
662 $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https',
663 $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
665 if (!function_exists('curl_init')) {
666 $this->errstr = 'CURL unavailable on this install';
667 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
669 if ($method == 'https') {
670 if (($info = curl_version()) &&
671 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
673 $this->errstr = 'SSL unavailable on this install';
674 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
679 if ($method == 'http') {
686 // Only create the payload if it was not created previously
687 if (empty($msg->payload)) {
688 $msg->createPayload($this->request_charset_encoding);
691 // Deflate request body and set appropriate request headers
692 $payload = $msg->payload;
693 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
694 if ($this->request_compression == 'gzip') {
695 $a = @gzencode($payload);
698 $encodingHdr = 'Content-Encoding: gzip';
701 $a = @gzcompress($payload);
704 $encodingHdr = 'Content-Encoding: deflate';
711 if ($this->debug > 1) {
712 Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
715 if (!$keepAlive || !$this->xmlrpc_curl_handle) {
716 $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
718 $this->xmlrpc_curl_handle = $curl;
721 $curl = $this->xmlrpc_curl_handle;
724 // results into variable
725 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
727 if ($this->debug > 1) {
728 curl_setopt($curl, CURLOPT_VERBOSE, true);
729 /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
731 curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
732 // required for XMLRPC: post the data
733 curl_setopt($curl, CURLOPT_POST, 1);
735 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
737 // return the header too
738 curl_setopt($curl, CURLOPT_HEADER, 1);
740 // NB: if we set an empty string, CURL will add http header indicating
741 // ALL methods it is supporting. This is possibly a better option than
742 // letting the user tell what curl can / cannot do...
743 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
744 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
745 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
746 if (count($this->accepted_compression) == 1) {
747 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
749 curl_setopt($curl, CURLOPT_ENCODING, '');
753 $headers = array('Content-Type: ' . $msg->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
754 // if no keepalive is wanted, let the server know it in advance
756 $headers[] = 'Connection: close';
758 // request compression header
760 $headers[] = $encodingHdr;
763 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
766 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
769 if ($username && $password) {
770 curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
771 if (defined('CURLOPT_HTTPAUTH')) {
772 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
773 } elseif ($authType != 1) {
774 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
778 if ($method == 'https') {
781 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
785 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
787 // whether to verify remote host's cert
788 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
789 // set ca certificates file/dir
791 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
794 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
796 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
798 curl_setopt($curl, CURLOPT_SSLKEY, $key);
800 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
802 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
804 // 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
805 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
806 // allow usage of different SSL versions
807 curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
812 if ($proxyPort == 0) {
813 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
815 curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
816 if ($proxyUsername) {
817 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
818 if (defined('CURLOPT_PROXYAUTH')) {
819 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
820 } elseif ($proxyAuthType != 1) {
821 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
826 // NB: should we build cookie http headers by hand rather than let CURL do it?
827 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
828 // set to client obj the the user...
829 if (count($this->cookies)) {
831 foreach ($this->cookies as $name => $cookie) {
832 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
834 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
837 foreach ($this->extracurlopts as $opt => $val) {
838 curl_setopt($curl, $opt, $val);
841 $result = curl_exec($curl);
843 if ($this->debug > 1) {
844 $message = "---CURL INFO---\n";
845 foreach (curl_getinfo($curl) as $name => $val) {
846 if (is_array($val)) {
847 $val = implode("\n", $val);
849 $message .= $name . ': ' . $val . "\n";
851 $message .= "---END---";
852 Logger::instance()->debugMessage($message);
856 /// @todo we should use a better check here - what if we get back '' or '0'?
858 $this->errstr = 'no response';
859 $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
862 $this->xmlrpc_curl_handle = null;
868 $resp = $msg->parseResponse($result, true, $this->return_type);
869 // if we got back a 302, we can not reuse the curl handle for later calls
870 if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
872 $this->xmlrpc_curl_handle = null;
880 * Send an array of requests and return an array of responses.
881 * Unless $this->no_multicall has been set to true, it will try first
882 * to use one single xmlrpc call to server method system.multicall, and
883 * revert to sending many successive calls in case of failure.
884 * This failure is also stored in $this->no_multicall for subsequent calls.
885 * Unfortunately, there is no server error code universally used to denote
886 * the fact that multicall is unsupported, so there is no way to reliably
887 * distinguish between that and a temporary failure.
888 * If you are sure that server supports multicall and do not want to
889 * fallback to using many single calls, set the fourth parameter to FALSE.
891 * NB: trying to shoehorn extra functionality into existing syntax has resulted
892 * in pretty much convoluted code...
894 * @param Request[] $reqs an array of Request objects
895 * @param integer $timeout connection timeout (in seconds)
896 * @param string $method the http protocol variant to be used
897 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted
901 public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
904 $method = $this->method;
906 if (!$this->no_multicall) {
907 $results = $this->_try_multicall($reqs, $timeout, $method);
908 if (is_array($results)) {
909 // System.multicall succeeded
912 // either system.multicall is unsupported by server,
913 // or call failed for some other reason.
915 // Don't try it next time...
916 $this->no_multicall = true;
918 if (is_a($results, '\PhpXmlRpc\Response')) {
921 $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
926 // override fallback, in case careless user tries to do two
927 // opposite things at the same time
933 // system.multicall is (probably) unsupported by server:
934 // emulate multicall via multiple requests
935 foreach ($reqs as $req) {
936 $results[] = $this->send($req, $timeout, $method);
939 // user does NOT want to fallback on many single calls:
940 // since we should always return an array of responses,
941 // return an array with the same error repeated n times
942 foreach ($reqs as $req) {
943 $results[] = $result;
951 * Attempt to boxcar $reqs via system.multicall.
952 * Returns either an array of xmlrpc reponses, an xmlrpc error response
953 * or false (when received response does not respect valid multicall syntax).
955 * @param Request[] $reqs
956 * @param int $timeout
957 * @param string $method
958 * @return array|bool|mixed|Response
960 private function _try_multicall($reqs, $timeout, $method)
962 // Construct multicall request
964 foreach ($reqs as $req) {
965 $call['methodName'] = new Value($req->method(), 'string');
966 $numParams = $req->getNumParams();
968 for ($i = 0; $i < $numParams; $i++) {
969 $params[$i] = $req->getParam($i);
971 $call['params'] = new Value($params, 'array');
972 $calls[] = new Value($call, 'struct');
974 $multiCall = new Request('system.multicall');
975 $multiCall->addParam(new Value($calls, 'array'));
978 $result = $this->send($multiCall, $timeout, $method);
980 if ($result->faultCode() != 0) {
981 // call to system.multicall failed
986 $rets = $result->value();
988 if ($this->return_type == 'xml') {
990 } elseif ($this->return_type == 'phpvals') {
991 /// @todo test this code branch...
992 $rets = $result->value();
993 if (!is_array($rets)) {
994 return false; // bad return type from system.multicall
996 $numRets = count($rets);
997 if ($numRets != count($reqs)) {
998 return false; // wrong number of return values.
1001 $response = array();
1002 for ($i = 0; $i < $numRets; $i++) {
1004 if (!is_array($val)) {
1007 switch (count($val)) {
1009 if (!isset($val[0])) {
1010 return false; // Bad value
1012 // Normal return value
1013 $response[$i] = new Response($val[0], 0, '', 'phpvals');
1016 /// @todo remove usage of @: it is apparently quite slow
1017 $code = @$val['faultCode'];
1018 if (!is_int($code)) {
1021 $str = @$val['faultString'];
1022 if (!is_string($str)) {
1025 $response[$i] = new Response(0, $code, $str);
1034 // return type == 'xmlrpcvals'
1036 $rets = $result->value();
1037 if ($rets->kindOf() != 'array') {
1038 return false; // bad return type from system.multicall
1040 $numRets = $rets->arraysize();
1041 if ($numRets != count($reqs)) {
1042 return false; // wrong number of return values.
1045 $response = array();
1046 for ($i = 0; $i < $numRets; $i++) {
1047 $val = $rets->arraymem($i);
1048 switch ($val->kindOf()) {
1050 if ($val->arraysize() != 1) {
1051 return false; // Bad value
1053 // Normal return value
1054 $response[$i] = new Response($val->arraymem(0));
1057 $code = $val->structmem('faultCode');
1058 if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1061 $str = $val->structmem('faultString');
1062 if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1065 $response[$i] = new Response(0, $code->scalarval(), $str->scalarval());