5 use PhpXmlRpc\Helper\Logger;
8 * Used to represent a client of an XML-RPC server.
12 /// @todo: do these need to be public?
13 public $method = 'http';
22 public $username = '';
23 public $password = '';
27 public $certpass = '';
29 public $cacertdir = '';
32 public $verifypeer = true;
33 public $verifyhost = 2;
34 public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
37 public $proxyport = 0;
38 public $proxy_user = '';
39 public $proxy_pass = '';
40 public $proxy_authtype = 1;
42 public $cookies = array();
43 public $extracurlopts = array();
48 * This determines whether the multicall() method will try to take advantage of the system.multicall xmlrpc method
49 * to dispatch to the server an array of requests in a single http roundtrip or simply execute many consecutive http
50 * calls. Defaults to FALSE, but it will be enabled automatically on the first failure of execution of
53 public $no_multicall = false;
56 * List of http compression methods accepted by the client for responses.
57 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib.
59 * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
60 * in those cases it will be up to CURL to decide the compression methods
61 * it supports. You might check for the presence of 'zlib' in the output of
62 * curl_version() to determine wheter compression is supported or not
64 public $accepted_compression = array();
67 * Name of compression scheme to be used for sending requests.
68 * Either null, gzip or deflate.
71 public $request_compression = '';
73 * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
74 * http://curl.haxx.se/docs/faq.html#7.3).
76 public $xmlrpc_curl_handle = null;
78 /// Whether to use persistent connections for http 1.1 and https
79 public $keepalive = false;
81 /// Charset encodings that can be decoded without problems by the client
82 public $accepted_charset_encodings = array();
85 * The charset encoding that will be used for serializing request sent by the client.
86 * It defaults to NULL, which means using US-ASCII and encoding all characters outside of the ASCII range using
87 * their xml character entity representation (this has the benefit that line end characters will not be mangled in
88 * the transfer, a CR-LF will be preserved as well as a singe LF).
89 * Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1'
91 public $request_charset_encoding = '';
94 * Decides the content of Response objects returned by calls to send() and multicall().
95 * Valid values are 'xmlrpcvals', 'phpvals' or 'xml'.
97 * Determines whether the value returned inside an Response object as results of calls to the send() and multicall()
98 * methods will be a Value object, a plain php value or a raw xml string.
99 * Allowed values are 'xmlrpcvals' (the default), 'phpvals' and 'xml'.
100 * To allow the user to differentiate between a correct and a faulty response, fault responses will be returned as
101 * Response objects in any case.
102 * Note that the 'phpvals' setting will yield faster execution times, but some of the information from the original
103 * response will be lost. It will be e.g. impossible to tell whether a particular php string value was sent by the
104 * server as an xmlrpc string or base64 value.
106 public $return_type = 'xmlrpcvals';
109 * Sent to servers in http headers.
114 * @param string $path either the PATH part of the xmlrpc server URL, or complete server URL (in which case you
115 * should use and empty string for all other parameters)
116 * e.g. /xmlrpc/server.php
117 * e.g. http://phpxmlrpc.sourceforge.net/server.php
118 * e.g. https://james:bond@secret.service.com:443/xmlrpcserver?agent=007
119 * @param string $server the server name / ip address
120 * @param integer $port the port the server is listening on, when omitted defaults to 80 or 443 depending on
122 * @param string $method the http protocol variant: defaults to 'http'; 'https' and 'http11' can be used if CURL is
123 * installed. The value set here can be overridden in any call to $this->send().
125 public function __construct($path, $server = '', $port = '', $method = '')
127 // allow user to specify all params in $path
128 if ($server == '' and $port == '' and $method == '') {
129 $parts = parse_url($path);
130 $server = $parts['host'];
131 $path = isset($parts['path']) ? $parts['path'] : '';
132 if (isset($parts['query'])) {
133 $path .= '?' . $parts['query'];
135 if (isset($parts['fragment'])) {
136 $path .= '#' . $parts['fragment'];
138 if (isset($parts['port'])) {
139 $port = $parts['port'];
141 if (isset($parts['scheme'])) {
142 $method = $parts['scheme'];
144 if (isset($parts['user'])) {
145 $this->username = $parts['user'];
147 if (isset($parts['pass'])) {
148 $this->password = $parts['pass'];
151 if ($path == '' || $path[0] != '/') {
152 $this->path = '/' . $path;
156 $this->server = $server;
161 $this->method = $method;
164 // if ZLIB is enabled, let the client by default accept compressed responses
165 if (function_exists('gzinflate') || (
166 function_exists('curl_init') && (($info = curl_version()) &&
167 ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
170 $this->accepted_compression = array('gzip', 'deflate');
173 // keepalives: enabled by default
174 $this->keepalive = true;
176 // by default the xml parser can support these 3 charset encodings
177 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
179 // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
180 // in http://www.iana.org/assignments/character-sets/character-sets.xhtml
181 // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
182 /*if (function_exists('mb_list_encodings')) {
184 $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
185 'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
186 $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
189 // initialize user_agent string
190 $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
194 * Enable/disable the echoing to screen of the xmlrpc responses received. The default is not no output anything.
196 * The debugging information at level 1 includes the raw data returned from the XML-RPC server it was querying
197 * (including bot HTTP headers and the full XML payload), and the PHP value the client attempts to create to
198 * represent the value returned by the server
199 * At level2, the complete payload of the xmlrpc request is also printed, before being sent t the server.
201 * This option can be very useful when debugging servers as it allows you to see exactly what the client sends and
202 * the server returns.
204 * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
206 public function setDebug($level)
208 $this->debug = $level;
212 * Sets the username and password for authorizing the client to the server.
214 * With the default (HTTP) transport, this information is used for HTTP Basic authorization.
215 * Note that username and password can also be set using the class constructor.
216 * With HTTP 1.1 and HTTPS transport, NTLM and Digest authentication protocols are also supported. To enable them use
217 * the constants CURLAUTH_DIGEST and CURLAUTH_NTLM as values for the auth type parameter.
219 * @param string $user username
220 * @param string $password password
221 * @param integer $authType auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC
222 * (basic auth). Note that auth types NTLM and Digest will only work if the Curl php
223 * extension is enabled.
225 public function setCredentials($user, $password, $authType = 1)
227 $this->username = $user;
228 $this->password = $password;
229 $this->authtype = $authType;
233 * Set the optional certificate and passphrase used in SSL-enabled communication with a remote server.
235 * Note: to retrieve information about the client certificate on the server side, you will need to look into the
236 * environment variables which are set up by the webserver. Different webservers will typically set up different
239 * @param string $cert the name of a file containing a PEM formatted certificate
240 * @param string $certPass the password required to use it
242 public function setCertificate($cert, $certPass = '')
245 $this->certpass = $certPass;
249 * Add a CA certificate to verify server with in SSL-enabled communication when SetSSLVerifypeer has been set to TRUE.
251 * See the php manual page about CURLOPT_CAINFO for more details.
253 * @param string $caCert certificate file name (or dir holding certificates)
254 * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
256 public function setCaCertificate($caCert, $isDir = false)
259 $this->cacertdir = $caCert;
261 $this->cacert = $caCert;
266 * Set attributes for SSL communication: private SSL key.
268 * NB: does not work in older php/curl installs.
269 * Thanks to Daniel Convissor.
271 * @param string $key The name of a file containing a private SSL key
272 * @param string $keyPass The secret password needed to use the private SSL key
274 public function setKey($key, $keyPass)
277 $this->keypass = $keyPass;
281 * Set attributes for SSL communication: verify the remote host's SSL certificate, and cause the connection to fail
282 * if the cert verification fails.
284 * By default, verification is enabled.
285 * To specify custom SSL certificates to validate the server with, use the setCaCertificate method.
287 * @param bool $i enable/disable verification of peer certificate
289 public function setSSLVerifyPeer($i)
291 $this->verifypeer = $i;
295 * Set attributes for SSL communication: verify the remote host's SSL certificate's common name (CN).
297 * Note that support for value 1 has been removed in cURL 7.28.1
299 * @param int $i Set to 1 to only the existence of a CN, not that it matches
301 public function setSSLVerifyHost($i)
303 $this->verifyhost = $i;
307 * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide
311 public function setSSLVersion($i)
313 $this->sslversion = $i;
319 * NB: CURL versions before 7.11.10 cannot use a proxy to communicate with https servers.
321 * @param string $proxyHost
322 * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
323 * @param string $proxyUsername Leave blank if proxy has public access
324 * @param string $proxyPassword Leave blank if proxy has public access
325 * @param int $proxyAuthType defaults to CURLAUTH_BASIC (Basic authentication protocol); set to constant CURLAUTH_NTLM
326 * to use NTLM auth with proxy (has effect only when the client uses the HTTP 1.1 protocol)
328 public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
330 $this->proxy = $proxyHost;
331 $this->proxyport = $proxyPort;
332 $this->proxy_user = $proxyUsername;
333 $this->proxy_pass = $proxyPassword;
334 $this->proxy_authtype = $proxyAuthType;
338 * Enables/disables reception of compressed xmlrpc responses.
340 * This requires the "zlib" extension to be enabled in your php install. If it is, by default xmlrpc_client
341 * instances will enable reception of compressed content.
342 * Note that enabling reception of compressed responses merely adds some standard http headers to xmlrpc requests.
343 * It is up to the xmlrpc server to return compressed responses when receiving such requests.
345 * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
347 public function setAcceptedCompression($compMethod)
349 if ($compMethod == 'any') {
350 $this->accepted_compression = array('gzip', 'deflate');
351 } elseif ($compMethod == false) {
352 $this->accepted_compression = array();
354 $this->accepted_compression = array($compMethod);
359 * Enables/disables http compression of xmlrpc request.
361 * This requires the "zlib" extension to be enabled in your php install.
362 * Take care when sending compressed requests: servers might not support them (and automatic fallback to
363 * uncompressed requests is not yet implemented).
365 * @param string $compMethod either 'gzip', 'deflate' or ''
367 public function setRequestCompression($compMethod)
369 $this->request_compression = $compMethod;
373 * Adds a cookie to list of cookies that will be sent to server with every further request (useful e.g. for keeping
374 * session info outside of the xml-rpc payload).
376 * NB: By default cookies are sent using the 'original/netscape' format, which is also the same as the RFC 2965;
377 * setting any param but name and value will turn the cookie into a 'version 1' cookie (i.e. RFC 2109 cookie) that
378 * might not be fully supported by the server. Note that RFC 2109 has currently 'historic' status...
380 * @param string $name nb: will not be escaped in the request's http headers. Take care not to use CTL chars or
382 * @param string $value
383 * @param string $path leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
384 * @param string $domain leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
385 * @param int $port leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
387 * @todo check correctness of urlencoding cookie value (copied from php way of doing it, but php is generally sending
388 * response not requests. We do the opposite...)
389 * @todo strip invalid chars from cookie name? As per RFC6265, we should follow RFC2616, Section 2.2
391 public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
393 $this->cookies[$name]['value'] = urlencode($value);
394 if ($path || $domain || $port) {
395 $this->cookies[$name]['path'] = $path;
396 $this->cookies[$name]['domain'] = $domain;
397 $this->cookies[$name]['port'] = $port;
398 $this->cookies[$name]['version'] = 1;
400 $this->cookies[$name]['version'] = 0;
405 * Directly set cURL options, for extra flexibility (when in cURL mode).
407 * It allows eg. to bind client to a specific IP interface / address.
409 * @param array $options
411 public function setCurlOptions($options)
413 $this->extracurlopts = $options;
417 * Set user-agent string that will be used by this client instance in http headers sent to the server.
419 * The default user agent string includes the name of this library and the version number.
421 * @param string $agentString
423 public function setUserAgent($agentString)
425 $this->user_agent = $agentString;
429 * Send an xmlrpc request to the server.
431 * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the
432 * complete xml representation of a request.
433 * When sending an array of Request objects, the client will try to make use of
434 * a single 'system.multicall' xml-rpc method call to forward to the server all
435 * the requests in a single HTTP round trip, unless $this->no_multicall has
436 * been previously set to TRUE (see the multicall method below), in which case
437 * many consecutive xmlrpc requests will be sent. The method will return an
438 * array of Response objects in both cases.
439 * The third variant allows to build by hand (or any other means) a complete
440 * xmlrpc request message, and send it to the server. $req should be a string
441 * containing the complete xml representation of the request. It is e.g. useful
442 * when, for maximal speed of execution, the request is serialized into a
443 * string using the native php xmlrpc functions (see http://www.php.net/xmlrpc)
444 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply.
445 * This timeout value is passed to fsockopen(). It is also used for detecting server
446 * timeouts during communication (i.e. if the server does not send anything to the client
447 * for $timeout seconds, the connection will be closed).
448 * @param string $method valid values are 'http', 'http11' and 'https'. If left unspecified, the http protocol
449 * chosen during creation of the object will be used.
452 * @return Response|Response[] Note that the client will always return a Response object, even if the call fails
454 public function send($req, $timeout = 0, $method = '')
456 // if user does not specify http protocol, use native method of this client
457 // (i.e. method set during call to constructor)
459 $method = $this->method;
462 if (is_array($req)) {
463 // $req is an array of Requests
464 $r = $this->multicall($req, $timeout, $method);
467 } elseif (is_string($req)) {
468 $n = new Request('');
473 // where req is a Request
474 $req->setDebug($this->debug);
476 if ($method == 'https') {
477 $r = $this->sendPayloadHTTPS(
493 $this->proxy_authtype,
499 } elseif ($method == 'http11') {
500 $r = $this->sendPayloadCURL(
516 $this->proxy_authtype,
521 $r = $this->sendPayloadHTTP10(
533 $this->proxy_authtype,
542 * @param Request $req
543 * @param string $server
545 * @param int $timeout
546 * @param string $username
547 * @param string $password
548 * @param int $authType
549 * @param string $proxyHost
550 * @param int $proxyPort
551 * @param string $proxyUsername
552 * @param string $proxyPassword
553 * @param int $proxyAuthType
554 * @param string $method
557 protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '',
558 $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
562 $port = ( $method === "https" ) ? 443 : 80;
565 // Only create the payload if it was not created previously
566 if (empty($req->payload)) {
567 $req->createPayload($this->request_charset_encoding);
570 $payload = $req->payload;
571 // Deflate request body and set appropriate request headers
572 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
573 if ($this->request_compression == 'gzip') {
574 $a = @gzencode($payload);
577 $encodingHdr = "Content-Encoding: gzip\r\n";
580 $a = @gzcompress($payload);
583 $encodingHdr = "Content-Encoding: deflate\r\n";
590 // thanks to Grant Rauscher <grant7@firstworld.net> for this
592 if ($username != '') {
593 $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
594 if ($authType != 1) {
595 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
599 $acceptedEncoding = '';
600 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
601 $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
604 $proxyCredentials = '';
606 if ($proxyPort == 0) {
609 $connectServer = $proxyHost;
610 $connectPort = $proxyPort;
612 $uri = 'http://' . $server . ':' . $port . $this->path;
613 if ($proxyUsername != '') {
614 if ($proxyAuthType != 1) {
615 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
617 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
620 $connectServer = $server;
621 $connectPort = $port;
622 /// @todo if supporting https, we should support all its current options as well: peer name verification etc...
623 $transport = ( $method === "https" ) ? "tls" : "tcp";
627 // Cookie generation, as per rfc2965 (version 1 cookies) or
628 // netscape's rules (version 0 cookies)
630 if (count($this->cookies)) {
632 foreach ($this->cookies as $name => $cookie) {
633 if ($cookie['version']) {
634 $version = ' $Version="' . $cookie['version'] . '";';
635 $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
636 if ($cookie['path']) {
637 $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
639 if ($cookie['domain']) {
640 $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
642 if ($cookie['port']) {
643 $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
646 $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
649 $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
653 $port = ($port == 80) ? '' : (':' . $port);
655 $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
656 'User-Agent: ' . $this->user_agent . "\r\n" .
657 'Host: ' . $server . $port . "\r\n" .
662 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
664 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
665 strlen($payload) . "\r\n\r\n" .
668 if ($this->debug > 1) {
669 Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
673 $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $timeout);
675 $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr);
679 stream_set_timeout($fp, $timeout);
682 $this->errstr = 'Connect error: ' . $this->errstr;
683 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
688 if (!fputs($fp, $op, strlen($op))) {
690 $this->errstr = 'Write error';
691 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
695 // reset errno and errstr on successful socket connection
698 // G. Giunta 2005/10/24: close socket before parsing.
699 // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
702 // shall we check for $data === FALSE?
703 // as per the manual, it signals an error
704 $ipd .= fread($fp, 32768);
705 } while (!feof($fp));
707 $r = $req->parseResponse($ipd, false, $this->return_type);
713 * @param Request $req
714 * @param string $server
716 * @param int $timeout
717 * @param string $username
718 * @param string $password
719 * @param int $authType
720 * @param string $cert
721 * @param string $certPass
722 * @param string $caCert
723 * @param string $caCertDir
724 * @param string $proxyHost
725 * @param int $proxyPort
726 * @param string $proxyUsername
727 * @param string $proxyPassword
728 * @param int $proxyAuthType
729 * @param bool $keepAlive
731 * @param string $keyPass
732 * @param int $sslVersion
735 protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '', $password = '',
736 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
737 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $keepAlive = false, $key = '', $keyPass = '',
740 return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
741 $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
742 $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
746 * Contributed by Justin Miller <justin@voxel.net>
747 * Requires curl to be built into PHP
748 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
750 * @param Request $req
751 * @param string $server
753 * @param int $timeout
754 * @param string $username
755 * @param string $password
756 * @param int $authType
757 * @param string $cert
758 * @param string $certPass
759 * @param string $caCert
760 * @param string $caCertDir
761 * @param string $proxyHost
762 * @param int $proxyPort
763 * @param string $proxyUsername
764 * @param string $proxyPassword
765 * @param int $proxyAuthType
766 * @param string $method
767 * @param bool $keepAlive
769 * @param string $keyPass
770 * @param int $sslVersion
773 protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
774 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
775 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
776 $keyPass = '', $sslVersion = 0)
778 if (!function_exists('curl_init')) {
779 $this->errstr = 'CURL unavailable on this install';
780 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
782 if ($method == 'https') {
783 if (($info = curl_version()) &&
784 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
786 $this->errstr = 'SSL unavailable on this install';
787 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
792 if ($method == 'http') {
799 // Only create the payload if it was not created previously
800 if (empty($req->payload)) {
801 $req->createPayload($this->request_charset_encoding);
804 // Deflate request body and set appropriate request headers
805 $payload = $req->payload;
806 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
807 if ($this->request_compression == 'gzip') {
808 $a = @gzencode($payload);
811 $encodingHdr = 'Content-Encoding: gzip';
814 $a = @gzcompress($payload);
817 $encodingHdr = 'Content-Encoding: deflate';
824 if ($this->debug > 1) {
825 Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
828 if (!$keepAlive || !$this->xmlrpc_curl_handle) {
829 $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
831 $this->xmlrpc_curl_handle = $curl;
834 $curl = $this->xmlrpc_curl_handle;
837 // results into variable
838 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
840 if ($this->debug > 1) {
841 curl_setopt($curl, CURLOPT_VERBOSE, true);
842 /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
844 curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
845 // required for XMLRPC: post the data
846 curl_setopt($curl, CURLOPT_POST, 1);
848 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
850 // return the header too
851 curl_setopt($curl, CURLOPT_HEADER, 1);
853 // NB: if we set an empty string, CURL will add http header indicating
854 // ALL methods it is supporting. This is possibly a better option than
855 // letting the user tell what curl can / cannot do...
856 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
857 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
858 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
859 if (count($this->accepted_compression) == 1) {
860 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
862 curl_setopt($curl, CURLOPT_ENCODING, '');
866 $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
867 // if no keepalive is wanted, let the server know it in advance
869 $headers[] = 'Connection: close';
871 // request compression header
873 $headers[] = $encodingHdr;
876 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
879 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
882 if ($username && $password) {
883 curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
884 if (defined('CURLOPT_HTTPAUTH')) {
885 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
886 } elseif ($authType != 1) {
887 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
891 if ($method == 'https') {
894 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
898 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
900 // whether to verify remote host's cert
901 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
902 // set ca certificates file/dir
904 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
907 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
909 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
911 curl_setopt($curl, CURLOPT_SSLKEY, $key);
913 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
915 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
917 // 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
918 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
919 // allow usage of different SSL versions
920 curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
925 if ($proxyPort == 0) {
926 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
928 curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
929 if ($proxyUsername) {
930 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
931 if (defined('CURLOPT_PROXYAUTH')) {
932 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
933 } elseif ($proxyAuthType != 1) {
934 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
939 // NB: should we build cookie http headers by hand rather than let CURL do it?
940 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
941 // set to client obj the the user...
942 if (count($this->cookies)) {
944 foreach ($this->cookies as $name => $cookie) {
945 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
947 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
950 foreach ($this->extracurlopts as $opt => $val) {
951 curl_setopt($curl, $opt, $val);
954 $result = curl_exec($curl);
956 if ($this->debug > 1) {
957 $message = "---CURL INFO---\n";
958 foreach (curl_getinfo($curl) as $name => $val) {
959 if (is_array($val)) {
960 $val = implode("\n", $val);
962 $message .= $name . ': ' . $val . "\n";
964 $message .= "---END---";
965 Logger::instance()->debugMessage($message);
969 /// @todo we should use a better check here - what if we get back '' or '0'?
971 $this->errstr = 'no response';
972 $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
975 $this->xmlrpc_curl_handle = null;
981 $resp = $req->parseResponse($result, true, $this->return_type);
982 // if we got back a 302, we can not reuse the curl handle for later calls
983 if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
985 $this->xmlrpc_curl_handle = null;
993 * Send an array of requests and return an array of responses.
995 * Unless $this->no_multicall has been set to true, it will try first to use one single xmlrpc call to server method
996 * system.multicall, and revert to sending many successive calls in case of failure.
997 * This failure is also stored in $this->no_multicall for subsequent calls.
998 * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported,
999 * so there is no way to reliably distinguish between that and a temporary failure.
1000 * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the
1001 * fourth parameter to FALSE.
1003 * NB: trying to shoehorn extra functionality into existing syntax has resulted
1004 * in pretty much convoluted code...
1006 * @param Request[] $reqs an array of Request objects
1007 * @param integer $timeout connection timeout (in seconds). See the details in the docs for the send() method
1008 * @param string $method the http protocol variant to be used. See the details in the docs for the send() method
1009 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be
1012 * @return Response[]
1014 public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
1016 if ($method == '') {
1017 $method = $this->method;
1019 if (!$this->no_multicall) {
1020 $results = $this->_try_multicall($reqs, $timeout, $method);
1021 if (is_array($results)) {
1022 // System.multicall succeeded
1025 // either system.multicall is unsupported by server,
1026 // or call failed for some other reason.
1028 // Don't try it next time...
1029 $this->no_multicall = true;
1031 if (is_a($results, '\PhpXmlRpc\Response')) {
1034 $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
1039 // override fallback, in case careless user tries to do two
1040 // opposite things at the same time
1046 // system.multicall is (probably) unsupported by server:
1047 // emulate multicall via multiple requests
1048 foreach ($reqs as $req) {
1049 $results[] = $this->send($req, $timeout, $method);
1052 // user does NOT want to fallback on many single calls:
1053 // since we should always return an array of responses,
1054 // return an array with the same error repeated n times
1055 foreach ($reqs as $req) {
1056 $results[] = $result;
1064 * Attempt to boxcar $reqs via system.multicall.
1066 * Returns either an array of Response, a single error Response or false (when received response does not respect
1067 * valid multicall syntax).
1069 * @param Request[] $reqs
1070 * @param int $timeout
1071 * @param string $method
1072 * @return Response[]|bool|mixed|Response
1074 private function _try_multicall($reqs, $timeout, $method)
1076 // Construct multicall request
1078 foreach ($reqs as $req) {
1079 $call['methodName'] = new Value($req->method(), 'string');
1080 $numParams = $req->getNumParams();
1082 for ($i = 0; $i < $numParams; $i++) {
1083 $params[$i] = $req->getParam($i);
1085 $call['params'] = new Value($params, 'array');
1086 $calls[] = new Value($call, 'struct');
1088 $multiCall = new Request('system.multicall');
1089 $multiCall->addParam(new Value($calls, 'array'));
1092 $result = $this->send($multiCall, $timeout, $method);
1094 if ($result->faultCode() != 0) {
1095 // call to system.multicall failed
1099 // Unpack responses.
1100 $rets = $result->value();
1102 if ($this->return_type == 'xml') {
1104 } elseif ($this->return_type == 'phpvals') {
1105 /// @todo test this code branch...
1106 $rets = $result->value();
1107 if (!is_array($rets)) {
1108 return false; // bad return type from system.multicall
1110 $numRets = count($rets);
1111 if ($numRets != count($reqs)) {
1112 return false; // wrong number of return values.
1115 $response = array();
1116 for ($i = 0; $i < $numRets; $i++) {
1118 if (!is_array($val)) {
1121 switch (count($val)) {
1123 if (!isset($val[0])) {
1124 return false; // Bad value
1126 // Normal return value
1127 $response[$i] = new Response($val[0], 0, '', 'phpvals');
1130 /// @todo remove usage of @: it is apparently quite slow
1131 $code = @$val['faultCode'];
1132 if (!is_int($code)) {
1135 $str = @$val['faultString'];
1136 if (!is_string($str)) {
1139 $response[$i] = new Response(0, $code, $str);
1148 // return type == 'xmlrpcvals'
1150 $rets = $result->value();
1151 if ($rets->kindOf() != 'array') {
1152 return false; // bad return type from system.multicall
1154 $numRets = $rets->count();
1155 if ($numRets != count($reqs)) {
1156 return false; // wrong number of return values.
1159 $response = array();
1160 foreach($rets as $val) {
1161 switch ($val->kindOf()) {
1163 if ($val->count() != 1) {
1164 return false; // Bad value
1166 // Normal return value
1167 $response[] = new Response($val[0]);
1170 $code = $val['faultCode'];
1171 if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1174 $str = $val['faultString'];
1175 if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1178 $response[] = new Response(0, $code->scalarval(), $str->scalarval());