7 /// @todo: do these need to be public?
8 public $method = 'http';
17 public $username = '';
18 public $password = '';
22 public $certpass = '';
24 public $cacertdir = '';
27 public $verifypeer = true;
28 public $verifyhost = 2;
29 public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
32 public $proxyport = 0;
33 public $proxy_user = '';
34 public $proxy_pass = '';
35 public $proxy_authtype = 1;
37 public $cookies = array();
38 public $extracurlopts = array();
40 public $no_multicall = false;
43 * List of http compression methods accepted by the client for responses.
44 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib.
46 * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
47 * in those cases it will be up to CURL to decide the compression methods
48 * it supports. You might check for the presence of 'zlib' in the output of
49 * curl_version() to determine wheter compression is supported or not
51 public $accepted_compression = array();
53 * Name of compression scheme to be used for sending requests.
54 * Either null, gzip or deflate.
56 public $request_compression = '';
58 * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
59 * http://curl.haxx.se/docs/faq.html#7.3).
61 public $xmlrpc_curl_handle = null;
62 /// Whether to use persistent connections for http 1.1 and https
63 public $keepalive = false;
64 /// Charset encodings that can be decoded without problems by the client
65 public $accepted_charset_encodings = array();
66 /// Charset encoding to be used in serializing request. NULL = use ASCII
67 public $request_charset_encoding = '';
69 * Decides the content of Response objects returned by calls to send()
70 * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'.
72 public $return_type = 'xmlrpcvals';
74 * Sent to servers in http headers.
79 * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php
80 * @param string $server the server name / ip address
81 * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used
82 * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed
84 public function __construct($path, $server = '', $port = '', $method = '')
86 // allow user to specify all params in $path
87 if ($server == '' and $port == '' and $method == '') {
88 $parts = parse_url($path);
89 $server = $parts['host'];
90 $path = isset($parts['path']) ? $parts['path'] : '';
91 if (isset($parts['query'])) {
92 $path .= '?' . $parts['query'];
94 if (isset($parts['fragment'])) {
95 $path .= '#' . $parts['fragment'];
97 if (isset($parts['port'])) {
98 $port = $parts['port'];
100 if (isset($parts['scheme'])) {
101 $method = $parts['scheme'];
103 if (isset($parts['user'])) {
104 $this->username = $parts['user'];
106 if (isset($parts['pass'])) {
107 $this->password = $parts['pass'];
110 if ($path == '' || $path[0] != '/') {
111 $this->path = '/' . $path;
115 $this->server = $server;
120 $this->method = $method;
123 // if ZLIB is enabled, let the client by default accept compressed responses
124 if (function_exists('gzinflate') || (
125 function_exists('curl_init') && (($info = curl_version()) &&
126 ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
129 $this->accepted_compression = array('gzip', 'deflate');
132 // keepalives: enabled by default
133 $this->keepalive = true;
135 // by default the xml parser can support these 3 charset encodings
136 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
138 // initialize user_agent string
139 $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
143 * Enables/disables the echoing to screen of the xmlrpc responses received.
145 * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
147 public function setDebug($in)
153 * Add some http BASIC AUTH credentials, used by the client to authenticate.
155 * @param string $u username
156 * @param string $p password
157 * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)
159 public function setCredentials($u, $p, $t = 1)
161 $this->username = $u;
162 $this->password = $p;
163 $this->authtype = $t;
167 * Add a client-side https certificate.
169 * @param string $cert
170 * @param string $certPass
172 public function setCertificate($cert, $certPass)
175 $this->certpass = $certPass;
179 * Add a CA certificate to verify server with (see man page about
180 * CURLOPT_CAINFO for more details).
182 * @param string $caCert certificate file name (or dir holding certificates)
183 * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
185 public function setCaCertificate($caCert, $isDir = false)
188 $this->cacertdir = $caCert;
190 $this->cacert = $caCert;
195 * Set attributes for SSL communication: private SSL key
196 * NB: does not work in older php/curl installs
197 * Thanks to Daniel Convissor.
199 * @param string $key The name of a file containing a private SSL key
200 * @param string $keyPass The secret password needed to use the private SSL key
202 public function setKey($key, $keyPass)
205 $this->keypass = $keyPass;
209 * Set attributes for SSL communication: verify server certificate.
211 * @param bool $i enable/disable verification of peer certificate
213 public function setSSLVerifyPeer($i)
215 $this->verifypeer = $i;
219 * Set attributes for SSL communication: verify match of server cert w. hostname.
223 public function setSSLVerifyHost($i)
225 $this->verifyhost = $i;
229 * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide
233 public function setSSLVersion($i)
235 $this->sslversion = $i;
241 * @param string $proxyHost
242 * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
243 * @param string $proxyUsername Leave blank if proxy has public access
244 * @param string $proxyPassword Leave blank if proxy has public access
245 * @param int $proxyAuthType set to constant CURLAUTH_NTLM to use NTLM auth with proxy
247 public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
249 $this->proxy = $proxyHost;
250 $this->proxyport = $proxyPort;
251 $this->proxy_user = $proxyUsername;
252 $this->proxy_pass = $proxyPassword;
253 $this->proxy_authtype = $proxyAuthType;
257 * Enables/disables reception of compressed xmlrpc responses.
258 * Note that enabling reception of compressed responses merely adds some standard
259 * http headers to xmlrpc requests. It is up to the xmlrpc server to return
260 * compressed responses when receiving such requests.
262 * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
264 public function setAcceptedCompression($compMethod)
266 if ($compMethod == 'any') {
267 $this->accepted_compression = array('gzip', 'deflate');
268 } elseif ($compMethod == false) {
269 $this->accepted_compression = array();
271 $this->accepted_compression = array($compMethod);
276 * Enables/disables http compression of xmlrpc request.
277 * Take care when sending compressed requests: servers might not support them
278 * (and automatic fallback to uncompressed requests is not yet implemented).
280 * @param string $compMethod either 'gzip', 'deflate' or ''
282 public function setRequestCompression($compMethod)
284 $this->request_compression = $compMethod;
288 * Adds a cookie to list of cookies that will be sent to server.
289 * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:
290 * do not do it unless you know what you are doing.
292 * @param string $name
293 * @param string $value
294 * @param string $path
295 * @param string $domain
298 * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)
300 public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
302 $this->cookies[$name]['value'] = urlencode($value);
303 if ($path || $domain || $port) {
304 $this->cookies[$name]['path'] = $path;
305 $this->cookies[$name]['domain'] = $domain;
306 $this->cookies[$name]['port'] = $port;
307 $this->cookies[$name]['version'] = 1;
309 $this->cookies[$name]['version'] = 0;
314 * Directly set cURL options, for extra flexibility
315 * It allows eg. to bind client to a specific IP interface / address.
317 * @param array $options
319 public function SetCurlOptions($options)
321 $this->extracurlopts = $options;
325 * Set user-agent string that will be used by this client instance
326 * in http headers sent to the server.
328 * @param string $agentString
330 public function SetUserAgent($agentString)
332 $this->user_agent = $agentString;
336 * Send an xmlrpc request.
338 * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the complete xml representation of a request
339 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply
340 * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used
344 public function send($req, $timeout = 0, $method = '')
346 // if user does not specify http protocol, use native method of this client
347 // (i.e. method set during call to constructor)
349 $method = $this->method;
352 if (is_array($req)) {
353 // $msg is an array of Requests
354 $r = $this->multicall($req, $timeout, $method);
357 } elseif (is_string($req)) {
358 $n = new Request('');
363 // where msg is a Request
364 $req->debug = $this->debug;
366 if ($method == 'https') {
367 $r = $this->sendPayloadHTTPS(
383 $this->proxy_authtype,
389 } elseif ($method == 'http11') {
390 $r = $this->sendPayloadCURL(
406 $this->proxy_authtype,
411 $r = $this->sendPayloadHTTP10(
423 $this->proxy_authtype
431 * @param Request $req
432 * @param string $server
434 * @param int $timeout
435 * @param string $username
436 * @param string $password
437 * @param int $authType
438 * @param string $proxyHost
439 * @param int $proxyPort
440 * @param string $proxyUsername
441 * @param string $proxyPassword
442 * @param int $proxyAuthType
445 protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
446 $username = '', $password = '', $authType = 1, $proxyHost = '',
447 $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
453 // Only create the payload if it was not created previously
454 if (empty($req->payload)) {
455 $req->createPayload($this->request_charset_encoding);
458 $payload = $req->payload;
459 // Deflate request body and set appropriate request headers
460 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
461 if ($this->request_compression == 'gzip') {
462 $a = @gzencode($payload);
465 $encodingHdr = "Content-Encoding: gzip\r\n";
468 $a = @gzcompress($payload);
471 $encodingHdr = "Content-Encoding: deflate\r\n";
478 // thanks to Grant Rauscher <grant7@firstworld.net> for this
480 if ($username != '') {
481 $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
482 if ($authType != 1) {
483 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
487 $acceptedEncoding = '';
488 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
489 $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
492 $proxyCredentials = '';
494 if ($proxyPort == 0) {
497 $connectServer = $proxyHost;
498 $connectPort = $proxyPort;
499 $uri = 'http://' . $server . ':' . $port . $this->path;
500 if ($proxyUsername != '') {
501 if ($proxyAuthType != 1) {
502 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
504 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
507 $connectServer = $server;
508 $connectPort = $port;
512 // Cookie generation, as per rfc2965 (version 1 cookies) or
513 // netscape's rules (version 0 cookies)
515 if (count($this->cookies)) {
517 foreach ($this->cookies as $name => $cookie) {
518 if ($cookie['version']) {
519 $version = ' $Version="' . $cookie['version'] . '";';
520 $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
521 if ($cookie['path']) {
522 $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
524 if ($cookie['domain']) {
525 $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
527 if ($cookie['port']) {
528 $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
531 $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
534 $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
538 $port = ($port == 80) ? '' : (':' . $port);
540 $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
541 'User-Agent: ' . $this->user_agent . "\r\n" .
542 'Host: ' . $server . $port . "\r\n" .
547 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
549 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
550 strlen($payload) . "\r\n\r\n" .
553 if ($this->debug > 1) {
554 $this->debugMessage("---SENDING---\n$op\n---END---");
558 $fp = @fsockopen($connectServer, $connectPort, $this->errno, $this->errstr, $timeout);
560 $fp = @fsockopen($connectServer, $connectPort, $this->errno, $this->errstr);
563 if ($timeout > 0 && function_exists('stream_set_timeout')) {
564 stream_set_timeout($fp, $timeout);
567 $this->errstr = 'Connect error: ' . $this->errstr;
568 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
573 if (!fputs($fp, $op, strlen($op))) {
575 $this->errstr = 'Write error';
576 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
580 // reset errno and errstr on successful socket connection
583 // G. Giunta 2005/10/24: close socket before parsing.
584 // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
587 // shall we check for $data === FALSE?
588 // as per the manual, it signals an error
589 $ipd .= fread($fp, 32768);
590 } while (!feof($fp));
592 $r = $req->parseResponse($ipd, false, $this->return_type);
598 * @param Request $req
599 * @param string $server
601 * @param int $timeout
602 * @param string $username
603 * @param string $password
604 * @param int $authType
605 * @param string $cert
606 * @param string $certPass
607 * @param string $caCert
608 * @param string $caCertDir
609 * @param string $proxyHost
610 * @param int $proxyPort
611 * @param string $proxyUsername
612 * @param string $proxyPassword
613 * @param int $proxyAuthType
614 * @param bool $keepAlive
616 * @param string $keyPass
617 * @param int $sslVersion
620 protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '',
621 $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
622 $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
623 $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
625 return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
626 $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
627 $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
631 * Contributed by Justin Miller <justin@voxel.net>
632 * Requires curl to be built into PHP
633 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
635 * @param Request $msg
636 * @param string $server
638 * @param int $timeout
639 * @param string $username
640 * @param string $password
641 * @param int $authType
642 * @param string $cert
643 * @param string $certPass
644 * @param string $caCert
645 * @param string $caCertDir
646 * @param string $proxyHost
647 * @param int $proxyPort
648 * @param string $proxyUsername
649 * @param string $proxyPassword
650 * @param int $proxyAuthType
651 * @param string $method
652 * @param bool $keepAlive
654 * @param string $keyPass
655 * @param int $sslVersion
658 protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = '',
659 $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
660 $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https',
661 $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
663 if (!function_exists('curl_init')) {
664 $this->errstr = 'CURL unavailable on this install';
665 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
667 if ($method == 'https') {
668 if (($info = curl_version()) &&
669 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
671 $this->errstr = 'SSL unavailable on this install';
672 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
677 if ($method == 'http') {
684 // Only create the payload if it was not created previously
685 if (empty($msg->payload)) {
686 $msg->createPayload($this->request_charset_encoding);
689 // Deflate request body and set appropriate request headers
690 $payload = $msg->payload;
691 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
692 if ($this->request_compression == 'gzip') {
693 $a = @gzencode($payload);
696 $encodingHdr = 'Content-Encoding: gzip';
699 $a = @gzcompress($payload);
702 $encodingHdr = 'Content-Encoding: deflate';
709 if ($this->debug > 1) {
710 $this->debugMessage("---SENDING---\n$payload\n---END---");
711 // let the client see this now in case http times out...
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, 1);
728 curl_setopt($curl, CURLOPT_VERBOSE, 1);
730 curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
731 // required for XMLRPC: post the data
732 curl_setopt($curl, CURLOPT_POST, 1);
734 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
736 // return the header too
737 curl_setopt($curl, CURLOPT_HEADER, 1);
739 // NB: if we set an empty string, CURL will add http header indicating
740 // ALL methods it is supporting. This is possibly a better option than
741 // letting the user tell what curl can / cannot do...
742 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
743 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
744 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
745 if (count($this->accepted_compression) == 1) {
746 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
748 curl_setopt($curl, CURLOPT_ENCODING, '');
752 $headers = array('Content-Type: ' . $msg->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
753 // if no keepalive is wanted, let the server know it in advance
755 $headers[] = 'Connection: close';
757 // request compression header
759 $headers[] = $encodingHdr;
762 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
765 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
768 if ($username && $password) {
769 curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
770 if (defined('CURLOPT_HTTPAUTH')) {
771 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
772 } elseif ($authType != 1) {
773 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
777 if ($method == 'https') {
780 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
784 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
786 // whether to verify remote host's cert
787 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
788 // set ca certificates file/dir
790 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
793 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
795 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
797 curl_setopt($curl, CURLOPT_SSLKEY, $key);
799 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
801 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
803 // 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
804 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
805 // allow usage of different SSL versions
806 curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
811 if ($proxyPort == 0) {
812 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
814 curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
815 if ($proxyUsername) {
816 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
817 if (defined('CURLOPT_PROXYAUTH')) {
818 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
819 } elseif ($proxyAuthType != 1) {
820 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
825 // NB: should we build cookie http headers by hand rather than let CURL do it?
826 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
827 // set to client obj the the user...
828 if (count($this->cookies)) {
830 foreach ($this->cookies as $name => $cookie) {
831 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
833 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
836 foreach ($this->extracurlopts as $opt => $val) {
837 curl_setopt($curl, $opt, $val);
840 $result = curl_exec($curl);
842 if ($this->debug > 1) {
843 $message = "---CURL INFO---\n";
844 foreach (curl_getinfo($curl) as $name => $val) {
845 if (is_array($val)) {
846 $val = implode("\n", $val);
848 $message .= $name . ': ' . $val . "\n";
850 $message .= "---END---";
851 $this->debugMessage($message);
855 /// @todo we should use a better check here - what if we get back '' or '0'?
857 $this->errstr = 'no response';
858 $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
861 $this->xmlrpc_curl_handle = null;
867 $resp = $msg->parseResponse($result, true, $this->return_type);
868 // if we got back a 302, we can not reuse the curl handle for later calls
869 if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
871 $this->xmlrpc_curl_handle = null;
879 * Send an array of requests and return an array of responses.
880 * Unless $this->no_multicall has been set to true, it will try first
881 * to use one single xmlrpc call to server method system.multicall, and
882 * revert to sending many successive calls in case of failure.
883 * This failure is also stored in $this->no_multicall for subsequent calls.
884 * Unfortunately, there is no server error code universally used to denote
885 * the fact that multicall is unsupported, so there is no way to reliably
886 * distinguish between that and a temporary failure.
887 * If you are sure that server supports multicall and do not want to
888 * fallback to using many single calls, set the fourth parameter to FALSE.
890 * NB: trying to shoehorn extra functionality into existing syntax has resulted
891 * in pretty much convoluted code...
893 * @param Request[] $reqs an array of Request objects
894 * @param integer $timeout connection timeout (in seconds)
895 * @param string $method the http protocol variant to be used
896 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted
900 public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
903 $method = $this->method;
905 if (!$this->no_multicall) {
906 $results = $this->_try_multicall($reqs, $timeout, $method);
907 if (is_array($results)) {
908 // System.multicall succeeded
911 // either system.multicall is unsupported by server,
912 // or call failed for some other reason.
914 // Don't try it next time...
915 $this->no_multicall = true;
917 if (is_a($results, '\PhpXmlRpc\Response')) {
920 $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
925 // override fallback, in case careless user tries to do two
926 // opposite things at the same time
932 // system.multicall is (probably) unsupported by server:
933 // emulate multicall via multiple requests
934 foreach ($reqs as $req) {
935 $results[] = $this->send($req, $timeout, $method);
938 // user does NOT want to fallback on many single calls:
939 // since we should always return an array of responses,
940 // return an array with the same error repeated n times
941 foreach ($reqs as $req) {
942 $results[] = $result;
950 * Attempt to boxcar $reqs via system.multicall.
951 * Returns either an array of xmlrpc reponses, an xmlrpc error response
952 * or false (when received response does not respect valid multicall syntax).
954 * @param Request[] $reqs
955 * @param int $timeout
956 * @param string $method
957 * @return array|bool|mixed|Response
959 private function _try_multicall($reqs, $timeout, $method)
961 // Construct multicall request
963 foreach ($reqs as $req) {
964 $call['methodName'] = new Value($req->method(), 'string');
965 $numParams = $req->getNumParams();
967 for ($i = 0; $i < $numParams; $i++) {
968 $params[$i] = $req->getParam($i);
970 $call['params'] = new Value($params, 'array');
971 $calls[] = new Value($call, 'struct');
973 $multiCall = new Request('system.multicall');
974 $multiCall->addParam(new Value($calls, 'array'));
977 $result = $this->send($multiCall, $timeout, $method);
979 if ($result->faultCode() != 0) {
980 // call to system.multicall failed
985 $rets = $result->value();
987 if ($this->return_type == 'xml') {
989 } elseif ($this->return_type == 'phpvals') {
990 ///@todo test this code branch...
991 $rets = $result->value();
992 if (!is_array($rets)) {
993 return false; // bad return type from system.multicall
995 $numRets = count($rets);
996 if ($numRets != count($reqs)) {
997 return false; // wrong number of return values.
1000 $response = array();
1001 for ($i = 0; $i < $numRets; $i++) {
1003 if (!is_array($val)) {
1006 switch (count($val)) {
1008 if (!isset($val[0])) {
1009 return false; // Bad value
1011 // Normal return value
1012 $response[$i] = new Response($val[0], 0, '', 'phpvals');
1015 /// @todo remove usage of @: it is apparently quite slow
1016 $code = @$val['faultCode'];
1017 if (!is_int($code)) {
1020 $str = @$val['faultString'];
1021 if (!is_string($str)) {
1024 $response[$i] = new Response(0, $code, $str);
1033 // return type == 'xmlrpcvals'
1035 $rets = $result->value();
1036 if ($rets->kindOf() != 'array') {
1037 return false; // bad return type from system.multicall
1039 $numRets = $rets->arraysize();
1040 if ($numRets != count($reqs)) {
1041 return false; // wrong number of return values.
1044 $response = array();
1045 for ($i = 0; $i < $numRets; $i++) {
1046 $val = $rets->arraymem($i);
1047 switch ($val->kindOf()) {
1049 if ($val->arraysize() != 1) {
1050 return false; // Bad value
1052 // Normal return value
1053 $response[$i] = new Response($val->arraymem(0));
1056 $code = $val->structmem('faultCode');
1057 if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1060 $str = $val->structmem('faultString');
1061 if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1064 $response[$i] = new Response(0, $code->scalarval(), $str->scalarval());
1076 * Echoes a debug message, taking care of escaping it when not in console mode
1078 * @param string $message
1080 protected function debugMessage($message)
1082 if (PHP_SAPI != 'cli') {
1083 print "<PRE>\n".htmlentities($message)."\n</PRE>";
1086 print "\n$message\n";
1088 // let the client see this now in case http times out...