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 // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
141 // in http://www.iana.org/assignments/character-sets/character-sets.xhtml
142 // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
143 /*if (function_exists('mb_list_encodings')) {
145 $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
146 'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
147 $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
150 // initialize user_agent string
151 $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
155 * Enables/disables the echoing to screen of the xmlrpc responses received.
157 * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
159 public function setDebug($in)
165 * Add some http BASIC AUTH credentials, used by the client to authenticate.
167 * @param string $u username
168 * @param string $p password
169 * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)
171 public function setCredentials($u, $p, $t = 1)
173 $this->username = $u;
174 $this->password = $p;
175 $this->authtype = $t;
179 * Add a client-side https certificate.
181 * @param string $cert
182 * @param string $certPass
184 public function setCertificate($cert, $certPass)
187 $this->certpass = $certPass;
191 * Add a CA certificate to verify server with (see man page about
192 * CURLOPT_CAINFO for more details).
194 * @param string $caCert certificate file name (or dir holding certificates)
195 * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
197 public function setCaCertificate($caCert, $isDir = false)
200 $this->cacertdir = $caCert;
202 $this->cacert = $caCert;
207 * Set attributes for SSL communication: private SSL key
208 * NB: does not work in older php/curl installs
209 * Thanks to Daniel Convissor.
211 * @param string $key The name of a file containing a private SSL key
212 * @param string $keyPass The secret password needed to use the private SSL key
214 public function setKey($key, $keyPass)
217 $this->keypass = $keyPass;
221 * Set attributes for SSL communication: verify server certificate.
223 * @param bool $i enable/disable verification of peer certificate
225 public function setSSLVerifyPeer($i)
227 $this->verifypeer = $i;
231 * Set attributes for SSL communication: verify match of server cert w. hostname.
235 public function setSSLVerifyHost($i)
237 $this->verifyhost = $i;
241 * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide
245 public function setSSLVersion($i)
247 $this->sslversion = $i;
253 * @param string $proxyHost
254 * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
255 * @param string $proxyUsername Leave blank if proxy has public access
256 * @param string $proxyPassword Leave blank if proxy has public access
257 * @param int $proxyAuthType set to constant CURLAUTH_NTLM to use NTLM auth with proxy
259 public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
261 $this->proxy = $proxyHost;
262 $this->proxyport = $proxyPort;
263 $this->proxy_user = $proxyUsername;
264 $this->proxy_pass = $proxyPassword;
265 $this->proxy_authtype = $proxyAuthType;
269 * Enables/disables reception of compressed xmlrpc responses.
270 * Note that enabling reception of compressed responses merely adds some standard
271 * http headers to xmlrpc requests. It is up to the xmlrpc server to return
272 * compressed responses when receiving such requests.
274 * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
276 public function setAcceptedCompression($compMethod)
278 if ($compMethod == 'any') {
279 $this->accepted_compression = array('gzip', 'deflate');
280 } elseif ($compMethod == false) {
281 $this->accepted_compression = array();
283 $this->accepted_compression = array($compMethod);
288 * Enables/disables http compression of xmlrpc request.
289 * Take care when sending compressed requests: servers might not support them
290 * (and automatic fallback to uncompressed requests is not yet implemented).
292 * @param string $compMethod either 'gzip', 'deflate' or ''
294 public function setRequestCompression($compMethod)
296 $this->request_compression = $compMethod;
300 * Adds a cookie to list of cookies that will be sent to server.
301 * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:
302 * do not do it unless you know what you are doing.
304 * @param string $name
305 * @param string $value
306 * @param string $path
307 * @param string $domain
310 * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)
312 public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
314 $this->cookies[$name]['value'] = urlencode($value);
315 if ($path || $domain || $port) {
316 $this->cookies[$name]['path'] = $path;
317 $this->cookies[$name]['domain'] = $domain;
318 $this->cookies[$name]['port'] = $port;
319 $this->cookies[$name]['version'] = 1;
321 $this->cookies[$name]['version'] = 0;
326 * Directly set cURL options, for extra flexibility
327 * It allows eg. to bind client to a specific IP interface / address.
329 * @param array $options
331 public function SetCurlOptions($options)
333 $this->extracurlopts = $options;
337 * Set user-agent string that will be used by this client instance
338 * in http headers sent to the server.
340 * @param string $agentString
342 public function SetUserAgent($agentString)
344 $this->user_agent = $agentString;
348 * Send an xmlrpc request.
350 * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the complete xml representation of a request
351 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply
352 * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used
354 * @return Response|Response[]
356 public function send($req, $timeout = 0, $method = '')
358 // if user does not specify http protocol, use native method of this client
359 // (i.e. method set during call to constructor)
361 $method = $this->method;
364 if (is_array($req)) {
365 // $req is an array of Requests
366 $r = $this->multicall($req, $timeout, $method);
369 } elseif (is_string($req)) {
370 $n = new Request('');
375 // where req is a Request
376 $req->setDebug($this->debug);
378 if ($method == 'https') {
379 $r = $this->sendPayloadHTTPS(
395 $this->proxy_authtype,
401 } elseif ($method == 'http11') {
402 $r = $this->sendPayloadCURL(
418 $this->proxy_authtype,
423 $r = $this->sendPayloadHTTP10(
435 $this->proxy_authtype,
444 * @param Request $req
445 * @param string $server
447 * @param int $timeout
448 * @param string $username
449 * @param string $password
450 * @param int $authType
451 * @param string $proxyHost
452 * @param int $proxyPort
453 * @param string $proxyUsername
454 * @param string $proxyPassword
455 * @param int $proxyAuthType
456 * @param string $method
459 protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
460 $username = '', $password = '', $authType = 1, $proxyHost = '',
461 $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
465 $port = ( $method === "https" ) ? 443 : 80;
468 // Only create the payload if it was not created previously
469 if (empty($req->payload)) {
470 $req->createPayload($this->request_charset_encoding);
473 $payload = $req->payload;
474 // Deflate request body and set appropriate request headers
475 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
476 if ($this->request_compression == 'gzip') {
477 $a = @gzencode($payload);
480 $encodingHdr = "Content-Encoding: gzip\r\n";
483 $a = @gzcompress($payload);
486 $encodingHdr = "Content-Encoding: deflate\r\n";
493 // thanks to Grant Rauscher <grant7@firstworld.net> for this
495 if ($username != '') {
496 $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
497 if ($authType != 1) {
498 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
502 $acceptedEncoding = '';
503 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
504 $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
507 $proxyCredentials = '';
509 if ($proxyPort == 0) {
512 $connectServer = $proxyHost;
513 $connectPort = $proxyPort;
515 $uri = 'http://' . $server . ':' . $port . $this->path;
516 if ($proxyUsername != '') {
517 if ($proxyAuthType != 1) {
518 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
520 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
523 $connectServer = $server;
524 $connectPort = $port;
525 /// @todo if supporting https, we should support all its current options as well: peer name verification etc...
526 $transport = ( $method === "https" ) ? "tls" : "tcp";
530 // Cookie generation, as per rfc2965 (version 1 cookies) or
531 // netscape's rules (version 0 cookies)
533 if (count($this->cookies)) {
535 foreach ($this->cookies as $name => $cookie) {
536 if ($cookie['version']) {
537 $version = ' $Version="' . $cookie['version'] . '";';
538 $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
539 if ($cookie['path']) {
540 $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
542 if ($cookie['domain']) {
543 $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
545 if ($cookie['port']) {
546 $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
549 $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
552 $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
556 $port = ($port == 80) ? '' : (':' . $port);
558 $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
559 'User-Agent: ' . $this->user_agent . "\r\n" .
560 'Host: ' . $server . $port . "\r\n" .
565 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
567 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
568 strlen($payload) . "\r\n\r\n" .
571 if ($this->debug > 1) {
572 Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
576 $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $timeout);
578 $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr);
582 stream_set_timeout($fp, $timeout);
585 $this->errstr = 'Connect error: ' . $this->errstr;
586 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
591 if (!fputs($fp, $op, strlen($op))) {
593 $this->errstr = 'Write error';
594 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
598 // reset errno and errstr on successful socket connection
601 // G. Giunta 2005/10/24: close socket before parsing.
602 // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
605 // shall we check for $data === FALSE?
606 // as per the manual, it signals an error
607 $ipd .= fread($fp, 32768);
608 } while (!feof($fp));
610 $r = $req->parseResponse($ipd, false, $this->return_type);
616 * @param Request $req
617 * @param string $server
619 * @param int $timeout
620 * @param string $username
621 * @param string $password
622 * @param int $authType
623 * @param string $cert
624 * @param string $certPass
625 * @param string $caCert
626 * @param string $caCertDir
627 * @param string $proxyHost
628 * @param int $proxyPort
629 * @param string $proxyUsername
630 * @param string $proxyPassword
631 * @param int $proxyAuthType
632 * @param bool $keepAlive
634 * @param string $keyPass
635 * @param int $sslVersion
638 protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '',
639 $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
640 $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
641 $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
643 return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
644 $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
645 $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
649 * Contributed by Justin Miller <justin@voxel.net>
650 * Requires curl to be built into PHP
651 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
653 * @param Request $req
654 * @param string $server
656 * @param int $timeout
657 * @param string $username
658 * @param string $password
659 * @param int $authType
660 * @param string $cert
661 * @param string $certPass
662 * @param string $caCert
663 * @param string $caCertDir
664 * @param string $proxyHost
665 * @param int $proxyPort
666 * @param string $proxyUsername
667 * @param string $proxyPassword
668 * @param int $proxyAuthType
669 * @param string $method
670 * @param bool $keepAlive
672 * @param string $keyPass
673 * @param int $sslVersion
676 protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '',
677 $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
678 $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https',
679 $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
681 if (!function_exists('curl_init')) {
682 $this->errstr = 'CURL unavailable on this install';
683 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
685 if ($method == 'https') {
686 if (($info = curl_version()) &&
687 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
689 $this->errstr = 'SSL unavailable on this install';
690 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
695 if ($method == 'http') {
702 // Only create the payload if it was not created previously
703 if (empty($req->payload)) {
704 $req->createPayload($this->request_charset_encoding);
707 // Deflate request body and set appropriate request headers
708 $payload = $req->payload;
709 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
710 if ($this->request_compression == 'gzip') {
711 $a = @gzencode($payload);
714 $encodingHdr = 'Content-Encoding: gzip';
717 $a = @gzcompress($payload);
720 $encodingHdr = 'Content-Encoding: deflate';
727 if ($this->debug > 1) {
728 Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
731 if (!$keepAlive || !$this->xmlrpc_curl_handle) {
732 $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
734 $this->xmlrpc_curl_handle = $curl;
737 $curl = $this->xmlrpc_curl_handle;
740 // results into variable
741 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
743 if ($this->debug > 1) {
744 curl_setopt($curl, CURLOPT_VERBOSE, true);
745 /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
747 curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
748 // required for XMLRPC: post the data
749 curl_setopt($curl, CURLOPT_POST, 1);
751 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
753 // return the header too
754 curl_setopt($curl, CURLOPT_HEADER, 1);
756 // NB: if we set an empty string, CURL will add http header indicating
757 // ALL methods it is supporting. This is possibly a better option than
758 // letting the user tell what curl can / cannot do...
759 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
760 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
761 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
762 if (count($this->accepted_compression) == 1) {
763 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
765 curl_setopt($curl, CURLOPT_ENCODING, '');
769 $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
770 // if no keepalive is wanted, let the server know it in advance
772 $headers[] = 'Connection: close';
774 // request compression header
776 $headers[] = $encodingHdr;
779 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
782 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
785 if ($username && $password) {
786 curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
787 if (defined('CURLOPT_HTTPAUTH')) {
788 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
789 } elseif ($authType != 1) {
790 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
794 if ($method == 'https') {
797 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
801 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
803 // whether to verify remote host's cert
804 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
805 // set ca certificates file/dir
807 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
810 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
812 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
814 curl_setopt($curl, CURLOPT_SSLKEY, $key);
816 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
818 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
820 // 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
821 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
822 // allow usage of different SSL versions
823 curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
828 if ($proxyPort == 0) {
829 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
831 curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
832 if ($proxyUsername) {
833 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
834 if (defined('CURLOPT_PROXYAUTH')) {
835 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
836 } elseif ($proxyAuthType != 1) {
837 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
842 // NB: should we build cookie http headers by hand rather than let CURL do it?
843 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
844 // set to client obj the the user...
845 if (count($this->cookies)) {
847 foreach ($this->cookies as $name => $cookie) {
848 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
850 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
853 foreach ($this->extracurlopts as $opt => $val) {
854 curl_setopt($curl, $opt, $val);
857 $result = curl_exec($curl);
859 if ($this->debug > 1) {
860 $message = "---CURL INFO---\n";
861 foreach (curl_getinfo($curl) as $name => $val) {
862 if (is_array($val)) {
863 $val = implode("\n", $val);
865 $message .= $name . ': ' . $val . "\n";
867 $message .= "---END---";
868 Logger::instance()->debugMessage($message);
872 /// @todo we should use a better check here - what if we get back '' or '0'?
874 $this->errstr = 'no response';
875 $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
878 $this->xmlrpc_curl_handle = null;
884 $resp = $req->parseResponse($result, true, $this->return_type);
885 // if we got back a 302, we can not reuse the curl handle for later calls
886 if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
888 $this->xmlrpc_curl_handle = null;
896 * Send an array of requests and return an array of responses.
897 * Unless $this->no_multicall has been set to true, it will try first
898 * to use one single xmlrpc call to server method system.multicall, and
899 * revert to sending many successive calls in case of failure.
900 * This failure is also stored in $this->no_multicall for subsequent calls.
901 * Unfortunately, there is no server error code universally used to denote
902 * the fact that multicall is unsupported, so there is no way to reliably
903 * distinguish between that and a temporary failure.
904 * If you are sure that server supports multicall and do not want to
905 * fallback to using many single calls, set the fourth parameter to FALSE.
907 * NB: trying to shoehorn extra functionality into existing syntax has resulted
908 * in pretty much convoluted code...
910 * @param Request[] $reqs an array of Request objects
911 * @param integer $timeout connection timeout (in seconds)
912 * @param string $method the http protocol variant to be used
913 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted
917 public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
920 $method = $this->method;
922 if (!$this->no_multicall) {
923 $results = $this->_try_multicall($reqs, $timeout, $method);
924 if (is_array($results)) {
925 // System.multicall succeeded
928 // either system.multicall is unsupported by server,
929 // or call failed for some other reason.
931 // Don't try it next time...
932 $this->no_multicall = true;
934 if (is_a($results, '\PhpXmlRpc\Response')) {
937 $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
942 // override fallback, in case careless user tries to do two
943 // opposite things at the same time
949 // system.multicall is (probably) unsupported by server:
950 // emulate multicall via multiple requests
951 foreach ($reqs as $req) {
952 $results[] = $this->send($req, $timeout, $method);
955 // user does NOT want to fallback on many single calls:
956 // since we should always return an array of responses,
957 // return an array with the same error repeated n times
958 foreach ($reqs as $req) {
959 $results[] = $result;
967 * Attempt to boxcar $reqs via system.multicall.
968 * Returns either an array of xmlrpc reponses, an xmlrpc error response
969 * or false (when received response does not respect valid multicall syntax).
971 * @param Request[] $reqs
972 * @param int $timeout
973 * @param string $method
974 * @return array|bool|mixed|Response
976 private function _try_multicall($reqs, $timeout, $method)
978 // Construct multicall request
980 foreach ($reqs as $req) {
981 $call['methodName'] = new Value($req->method(), 'string');
982 $numParams = $req->getNumParams();
984 for ($i = 0; $i < $numParams; $i++) {
985 $params[$i] = $req->getParam($i);
987 $call['params'] = new Value($params, 'array');
988 $calls[] = new Value($call, 'struct');
990 $multiCall = new Request('system.multicall');
991 $multiCall->addParam(new Value($calls, 'array'));
994 $result = $this->send($multiCall, $timeout, $method);
996 if ($result->faultCode() != 0) {
997 // call to system.multicall failed
1001 // Unpack responses.
1002 $rets = $result->value();
1004 if ($this->return_type == 'xml') {
1006 } elseif ($this->return_type == 'phpvals') {
1007 /// @todo test this code branch...
1008 $rets = $result->value();
1009 if (!is_array($rets)) {
1010 return false; // bad return type from system.multicall
1012 $numRets = count($rets);
1013 if ($numRets != count($reqs)) {
1014 return false; // wrong number of return values.
1017 $response = array();
1018 for ($i = 0; $i < $numRets; $i++) {
1020 if (!is_array($val)) {
1023 switch (count($val)) {
1025 if (!isset($val[0])) {
1026 return false; // Bad value
1028 // Normal return value
1029 $response[$i] = new Response($val[0], 0, '', 'phpvals');
1032 /// @todo remove usage of @: it is apparently quite slow
1033 $code = @$val['faultCode'];
1034 if (!is_int($code)) {
1037 $str = @$val['faultString'];
1038 if (!is_string($str)) {
1041 $response[$i] = new Response(0, $code, $str);
1050 // return type == 'xmlrpcvals'
1052 $rets = $result->value();
1053 if ($rets->kindOf() != 'array') {
1054 return false; // bad return type from system.multicall
1056 $numRets = $rets->count();
1057 if ($numRets != count($reqs)) {
1058 return false; // wrong number of return values.
1061 $response = array();
1062 foreach($rets as $val) {
1063 switch ($val->kindOf()) {
1065 if ($val->count() != 1) {
1066 return false; // Bad value
1068 // Normal return value
1069 $response[] = new Response($val[0]);
1072 $code = $val['faultCode'];
1073 if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1076 $str = $val['faultString'];
1077 if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1080 $response[] = new Response(0, $code->scalarval(), $str->scalarval());