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.
451 * @return Response|Response[] Note that the client will always return a Response object, even if the call fails
453 public function send($req, $timeout = 0, $method = '')
455 // if user does not specify http protocol, use native method of this client
456 // (i.e. method set during call to constructor)
458 $method = $this->method;
461 if (is_array($req)) {
462 // $req is an array of Requests
463 $r = $this->multicall($req, $timeout, $method);
466 } elseif (is_string($req)) {
467 $n = new Request('');
472 // where req is a Request
473 $req->setDebug($this->debug);
475 /// @todo we could be smarter about this and force usage of curl in scenarios where it is both available and
476 /// needed, such as digest or ntlm auth
477 $useCurl = ($method == 'https' || $method == 'http11');
480 $r = $this->sendPayloadCURL(
496 $this->proxy_authtype,
498 $method == 'http11' ? 'http' : $method,
505 // plain 'http 1.0': default to using socket
506 $r = $this->sendPayloadSocket(
522 $this->proxy_authtype,
536 * @param Request $req
537 * @param string $server
539 * @param int $timeout
540 * @param string $username
541 * @param string $password
542 * @param int $authType
543 * @param string $proxyHost
544 * @param int $proxyPort
545 * @param string $proxyUsername
546 * @param string $proxyPassword
547 * @param int $proxyAuthType
548 * @param string $method
551 protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '',
552 $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
555 return $this->sendPayloadSocket($req, $server, $port, $timeout, $username, $password, $authType, null, null,
556 null, null, $proxyHost, $proxyPort, $proxyUsername, $proxyPassword, $proxyAuthType);
561 * @param Request $req
562 * @param string $server
564 * @param int $timeout
565 * @param string $username
566 * @param string $password
567 * @param int $authType
568 * @param string $cert
569 * @param string $certPass
570 * @param string $caCert
571 * @param string $caCertDir
572 * @param string $proxyHost
573 * @param int $proxyPort
574 * @param string $proxyUsername
575 * @param string $proxyPassword
576 * @param int $proxyAuthType
577 * @param bool $keepAlive
579 * @param string $keyPass
580 * @param int $sslVersion
583 protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '', $password = '',
584 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
585 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $keepAlive = false, $key = '', $keyPass = '',
588 return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
589 $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
590 $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
594 * @param Request $req
595 * @param string $server
597 * @param int $timeout
598 * @param string $username
599 * @param string $password
600 * @param int $authType only value supported is 1
601 * @param string $cert
602 * @param string $certPass
603 * @param string $caCert
604 * @param string $caCertDir
605 * @param string $proxyHost
606 * @param int $proxyPort
607 * @param string $proxyUsername
608 * @param string $proxyPassword
609 * @param int $proxyAuthType only value supported is 1
610 * @param string $method 'http' (synonym for 'http10'), 'http10' or 'https'
612 * @param string $keyPass @todo not implemented yet.
613 * @param int $sslVersion @todo not implemented yet. See http://php.net/manual/en/migration56.openssl.php
616 protected function sendPayloadSocket($req, $server, $port, $timeout = 0, $username = '', $password = '',
617 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
618 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method='http', $key = '', $keyPass = '',
622 $port = ( $method === 'https' ) ? 443 : 80;
625 // Only create the payload if it was not created previously
626 if (empty($req->payload)) {
627 $req->createPayload($this->request_charset_encoding);
630 $payload = $req->payload;
631 // Deflate request body and set appropriate request headers
632 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
633 if ($this->request_compression == 'gzip') {
634 $a = @gzencode($payload);
637 $encodingHdr = "Content-Encoding: gzip\r\n";
640 $a = @gzcompress($payload);
643 $encodingHdr = "Content-Encoding: deflate\r\n";
650 // thanks to Grant Rauscher <grant7@firstworld.net> for this
652 if ($username != '') {
653 $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
654 if ($authType != 1) {
655 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
659 $acceptedEncoding = '';
660 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
661 $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
664 $proxyCredentials = '';
666 if ($proxyPort == 0) {
669 $connectServer = $proxyHost;
670 $connectPort = $proxyPort;
672 $uri = 'http://' . $server . ':' . $port . $this->path;
673 if ($proxyUsername != '') {
674 if ($proxyAuthType != 1) {
675 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
677 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
680 $connectServer = $server;
681 $connectPort = $port;
682 /// @todo if supporting https, we should support all its current options as well: peer name verification etc...
683 $transport = ( $method === 'https' ) ? 'tls' : 'tcp';
687 // Cookie generation, as per rfc2965 (version 1 cookies) or
688 // netscape's rules (version 0 cookies)
690 if (count($this->cookies)) {
692 foreach ($this->cookies as $name => $cookie) {
693 if ($cookie['version']) {
694 $version = ' $Version="' . $cookie['version'] . '";';
695 $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
696 if ($cookie['path']) {
697 $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
699 if ($cookie['domain']) {
700 $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
702 if ($cookie['port']) {
703 $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
706 $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
709 $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
712 // omit port if default
713 if (($port == 80 && in_array($method, array('http', 'http10'))) || ($port == 443 && $method == 'https')) {
719 $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
720 'User-Agent: ' . $this->user_agent . "\r\n" .
721 'Host: ' . $server . $port . "\r\n" .
726 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
728 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
729 strlen($payload) . "\r\n\r\n" .
732 if ($this->debug > 1) {
733 Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
736 $contextOptions = array();
737 if ($method == 'https') {
739 $contextOptions['ssl']['local_cert'] = $cert;
740 if ($certPass != '') {
741 $contextOptions['ssl']['passphrase'] = $certPass;
745 $contextOptions['ssl']['cafile'] = $caCert;
747 if ($caCertDir != '') {
748 $contextOptions['ssl']['capath'] = $caCertDir;
751 $contextOptions['ssl']['local_pk'] = $key;
753 $contextOptions['ssl']['verify_peer'] = $this->verifypeer;
756 $context = stream_context_create($contextOptions);
759 $connectTimeout = ini_get('default_socket_timeout');
761 $connectTimeout = $timeout;
764 $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $connectTimeout,
765 STREAM_CLIENT_CONNECT, $context);
768 stream_set_timeout($fp, $timeout);
771 $this->errstr = 'Connect error: ' . $this->errstr;
772 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
777 if (!fputs($fp, $op, strlen($op))) {
779 $this->errstr = 'Write error';
780 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
784 // reset errno and errstr on successful socket connection
787 // G. Giunta 2005/10/24: close socket before parsing.
788 // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
791 // shall we check for $data === FALSE?
792 // as per the manual, it signals an error
793 $ipd .= fread($fp, 32768);
794 } while (!feof($fp));
796 $r = $req->parseResponse($ipd, false, $this->return_type);
802 * Contributed by Justin Miller <justin@voxel.net>
803 * Requires curl to be built into PHP
804 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
806 * @param Request $req
807 * @param string $server
809 * @param int $timeout
810 * @param string $username
811 * @param string $password
812 * @param int $authType
813 * @param string $cert
814 * @param string $certPass
815 * @param string $caCert
816 * @param string $caCertDir
817 * @param string $proxyHost
818 * @param int $proxyPort
819 * @param string $proxyUsername
820 * @param string $proxyPassword
821 * @param int $proxyAuthType
822 * @param string $method 'http' (let curl decide), 'http10', 'http11' or 'https'
823 * @param bool $keepAlive
825 * @param string $keyPass
826 * @param int $sslVersion
829 protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
830 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
831 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
832 $keyPass = '', $sslVersion = 0)
834 if (!function_exists('curl_init')) {
835 $this->errstr = 'CURL unavailable on this install';
836 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
838 if ($method == 'https') {
839 if (($info = curl_version()) &&
840 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
842 $this->errstr = 'SSL unavailable on this install';
843 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
848 if (in_array($method, array('http', 'http10', 'http11'))) {
855 // Only create the payload if it was not created previously
856 if (empty($req->payload)) {
857 $req->createPayload($this->request_charset_encoding);
860 // Deflate request body and set appropriate request headers
861 $payload = $req->payload;
862 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
863 if ($this->request_compression == 'gzip') {
864 $a = @gzencode($payload);
867 $encodingHdr = 'Content-Encoding: gzip';
870 $a = @gzcompress($payload);
873 $encodingHdr = 'Content-Encoding: deflate';
880 if ($this->debug > 1) {
881 Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
884 if (!$keepAlive || !$this->xmlrpc_curl_handle) {
885 if ($method == 'http11' || $method == 'http10') {
890 $curl = curl_init($protocol . '://' . $server . ':' . $port . $this->path);
892 $this->xmlrpc_curl_handle = $curl;
895 $curl = $this->xmlrpc_curl_handle;
898 // results into variable
899 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
901 if ($this->debug > 1) {
902 curl_setopt($curl, CURLOPT_VERBOSE, true);
903 /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
905 curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
906 // required for XMLRPC: post the data
907 curl_setopt($curl, CURLOPT_POST, 1);
909 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
911 // return the header too
912 curl_setopt($curl, CURLOPT_HEADER, 1);
914 // NB: if we set an empty string, CURL will add http header indicating
915 // ALL methods it is supporting. This is possibly a better option than
916 // letting the user tell what curl can / cannot do...
917 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
918 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
919 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
920 if (count($this->accepted_compression) == 1) {
921 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
923 curl_setopt($curl, CURLOPT_ENCODING, '');
927 $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
928 // if no keepalive is wanted, let the server know it in advance
930 $headers[] = 'Connection: close';
932 // request compression header
934 $headers[] = $encodingHdr;
937 // Fix the HTTP/1.1 417 Expectation Failed Bug (curl by default adds a 'Expect: 100-continue' header when POST
938 // size exceeds 1025 bytes, apparently)
939 $headers[] = 'Expect:';
941 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
944 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
947 if ($method == 'http10') {
948 curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
949 } elseif ($method == 'http11') {
950 curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
953 if ($username && $password) {
954 curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
955 if (defined('CURLOPT_HTTPAUTH')) {
956 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
957 } elseif ($authType != 1) {
958 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
962 if ($method == 'https') {
965 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
969 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
971 // whether to verify remote host's cert
972 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
973 // set ca certificates file/dir
975 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
978 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
980 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
982 curl_setopt($curl, CURLOPT_SSLKEY, $key);
984 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
986 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
988 // 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
989 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
990 // allow usage of different SSL versions
991 curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
996 if ($proxyPort == 0) {
997 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
999 curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
1000 if ($proxyUsername) {
1001 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
1002 if (defined('CURLOPT_PROXYAUTH')) {
1003 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
1004 } elseif ($proxyAuthType != 1) {
1005 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1010 // NB: should we build cookie http headers by hand rather than let CURL do it?
1011 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
1012 // set to client obj the the user...
1013 if (count($this->cookies)) {
1015 foreach ($this->cookies as $name => $cookie) {
1016 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
1018 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
1021 foreach ($this->extracurlopts as $opt => $val) {
1022 curl_setopt($curl, $opt, $val);
1025 $result = curl_exec($curl);
1027 if ($this->debug > 1) {
1028 $message = "---CURL INFO---\n";
1029 foreach (curl_getinfo($curl) as $name => $val) {
1030 if (is_array($val)) {
1031 $val = implode("\n", $val);
1033 $message .= $name . ': ' . $val . "\n";
1035 $message .= '---END---';
1036 Logger::instance()->debugMessage($message);
1040 /// @todo we should use a better check here - what if we get back '' or '0'?
1042 $this->errstr = 'no response';
1043 $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
1046 $this->xmlrpc_curl_handle = null;
1052 $resp = $req->parseResponse($result, true, $this->return_type);
1053 // if we got back a 302, we can not reuse the curl handle for later calls
1054 if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
1056 $this->xmlrpc_curl_handle = null;
1064 * Send an array of requests and return an array of responses.
1066 * Unless $this->no_multicall has been set to true, it will try first to use one single xmlrpc call to server method
1067 * system.multicall, and revert to sending many successive calls in case of failure.
1068 * This failure is also stored in $this->no_multicall for subsequent calls.
1069 * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported,
1070 * so there is no way to reliably distinguish between that and a temporary failure.
1071 * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the
1072 * fourth parameter to FALSE.
1074 * NB: trying to shoehorn extra functionality into existing syntax has resulted
1075 * in pretty much convoluted code...
1077 * @param Request[] $reqs an array of Request objects
1078 * @param integer $timeout connection timeout (in seconds). See the details in the docs for the send() method
1079 * @param string $method the http protocol variant to be used. See the details in the docs for the send() method
1080 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be
1083 * @return Response[]
1085 public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
1087 if ($method == '') {
1088 $method = $this->method;
1090 if (!$this->no_multicall) {
1091 $results = $this->_try_multicall($reqs, $timeout, $method);
1092 if (is_array($results)) {
1093 // System.multicall succeeded
1096 // either system.multicall is unsupported by server,
1097 // or call failed for some other reason.
1099 // Don't try it next time...
1100 $this->no_multicall = true;
1102 if (is_a($results, '\PhpXmlRpc\Response')) {
1105 $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
1110 // override fallback, in case careless user tries to do two
1111 // opposite things at the same time
1117 // system.multicall is (probably) unsupported by server:
1118 // emulate multicall via multiple requests
1119 foreach ($reqs as $req) {
1120 $results[] = $this->send($req, $timeout, $method);
1123 // user does NOT want to fallback on many single calls:
1124 // since we should always return an array of responses,
1125 // return an array with the same error repeated n times
1126 foreach ($reqs as $req) {
1127 $results[] = $result;
1135 * Attempt to boxcar $reqs via system.multicall.
1137 * Returns either an array of Response, a single error Response or false (when received response does not respect
1138 * valid multicall syntax).
1140 * @param Request[] $reqs
1141 * @param int $timeout
1142 * @param string $method
1143 * @return Response[]|bool|mixed|Response
1145 private function _try_multicall($reqs, $timeout, $method)
1147 // Construct multicall request
1149 foreach ($reqs as $req) {
1150 $call['methodName'] = new Value($req->method(), 'string');
1151 $numParams = $req->getNumParams();
1153 for ($i = 0; $i < $numParams; $i++) {
1154 $params[$i] = $req->getParam($i);
1156 $call['params'] = new Value($params, 'array');
1157 $calls[] = new Value($call, 'struct');
1159 $multiCall = new Request('system.multicall');
1160 $multiCall->addParam(new Value($calls, 'array'));
1163 $result = $this->send($multiCall, $timeout, $method);
1165 if ($result->faultCode() != 0) {
1166 // call to system.multicall failed
1170 // Unpack responses.
1171 $rets = $result->value();
1173 if ($this->return_type == 'xml') {
1175 } elseif ($this->return_type == 'phpvals') {
1176 /// @todo test this code branch...
1177 $rets = $result->value();
1178 if (!is_array($rets)) {
1179 return false; // bad return type from system.multicall
1181 $numRets = count($rets);
1182 if ($numRets != count($reqs)) {
1183 return false; // wrong number of return values.
1186 $response = array();
1187 for ($i = 0; $i < $numRets; $i++) {
1189 if (!is_array($val)) {
1192 switch (count($val)) {
1194 if (!isset($val[0])) {
1195 return false; // Bad value
1197 // Normal return value
1198 $response[$i] = new Response($val[0], 0, '', 'phpvals');
1201 /// @todo remove usage of @: it is apparently quite slow
1202 $code = @$val['faultCode'];
1203 if (!is_int($code)) {
1206 $str = @$val['faultString'];
1207 if (!is_string($str)) {
1210 $response[$i] = new Response(0, $code, $str);
1219 // return type == 'xmlrpcvals'
1221 $rets = $result->value();
1222 if ($rets->kindOf() != 'array') {
1223 return false; // bad return type from system.multicall
1225 $numRets = $rets->count();
1226 if ($numRets != count($reqs)) {
1227 return false; // wrong number of return values.
1230 $response = array();
1231 foreach($rets as $val) {
1232 switch ($val->kindOf()) {
1234 if ($val->count() != 1) {
1235 return false; // Bad value
1237 // Normal return value
1238 $response[] = new Response($val[0]);
1241 $code = $val['faultCode'];
1242 if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1245 $str = $val['faultString'];
1246 if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1249 $response[] = new Response(0, $code->scalarval(), $str->scalarval());