5 use PhpXmlRpc\Helper\Logger;
8 * Used to represent a client of an XML-RPC server.
12 const USE_CURL_NEVER = 0;
13 const USE_CURL_ALWAYS = 1;
14 const USE_CURL_AUTO = 2;
16 protected static $logger;
18 /// @todo: do these need to be public?
19 public $method = 'http';
28 public $username = '';
29 public $password = '';
33 public $certpass = '';
35 public $cacertdir = '';
38 public $verifypeer = true;
39 public $verifyhost = 2;
40 public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
43 public $proxyport = 0;
44 public $proxy_user = '';
45 public $proxy_pass = '';
46 public $proxy_authtype = 1;
48 public $cookies = array();
49 public $extracurlopts = array();
50 public $use_curl = self::USE_CURL_AUTO;
55 * This determines whether the multicall() method will try to take advantage of the system.multicall xmlrpc method
56 * to dispatch to the server an array of requests in a single http roundtrip or simply execute many consecutive http
57 * calls. Defaults to FALSE, but it will be enabled automatically on the first failure of execution of
60 public $no_multicall = false;
63 * List of http compression methods accepted by the client for responses.
64 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib.
66 * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since in those cases it will be up to CURL to
67 * decide the compression methods it supports. You might check for the presence of 'zlib' in the output of
68 * curl_version() to determine whether compression is supported or not
70 public $accepted_compression = array();
73 * Name of compression scheme to be used for sending requests.
74 * Either null, gzip or deflate.
76 public $request_compression = '';
79 * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
80 * http://curl.haxx.se/docs/faq.html#7.3).
83 public $xmlrpc_curl_handle = null;
85 /// Whether to use persistent connections for http 1.1 and https
86 public $keepalive = false;
88 /// Charset encodings that can be decoded without problems by the client
89 public $accepted_charset_encodings = array();
92 * The charset encoding that will be used for serializing request sent by the client.
93 * It defaults to NULL, which means using US-ASCII and encoding all characters outside of the ASCII printable range
94 * using their xml character entity representation (this has the benefit that line end characters will not be mangled
95 * in the transfer, a CR-LF will be preserved as well as a singe LF).
96 * Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1'.
97 * For the fastest mode of operation, set your both your app internal encoding as well as this to UTF-8.
99 public $request_charset_encoding = '';
102 * Decides the content of Response objects returned by calls to send() and multicall().
103 * Valid values are 'xmlrpcvals', 'phpvals' or 'xml'.
105 * Determines whether the value returned inside an Response object as results of calls to the send() and multicall()
106 * methods will be a Value object, a plain php value or a raw xml string.
107 * Allowed values are 'xmlrpcvals' (the default), 'phpvals' and 'xml'.
108 * To allow the user to differentiate between a correct and a faulty response, fault responses will be returned as
109 * Response objects in any case.
110 * Note that the 'phpvals' setting will yield faster execution times, but some of the information from the original
111 * response will be lost. It will be e.g. impossible to tell whether a particular php string value was sent by the
112 * server as an xmlrpc string or base64 value.
114 public $return_type = 'xmlrpcvals';
117 * Sent to servers in http headers.
121 public function getLogger()
123 if (self::$logger === null) {
124 self::$logger = Logger::instance();
126 return self::$logger;
129 public static function setLogger($logger)
131 self::$logger = $logger;
135 * @param string $path either the PATH part of the xmlrpc server URL, or complete server URL (in which case you
136 * should use and empty string for all other parameters)
137 * e.g. /xmlrpc/server.php
138 * e.g. http://phpxmlrpc.sourceforge.net/server.php
139 * e.g. https://james:bond@secret.service.com:443/xmlrpcserver?agent=007
140 * @param string $server the server name / ip address
141 * @param integer $port the port the server is listening on, when omitted defaults to 80 or 443 depending on
143 * @param string $method the http protocol variant: defaults to 'http'; 'https' and 'http11' can be used if CURL is
144 * installed. The value set here can be overridden in any call to $this->send().
146 public function __construct($path, $server = '', $port = '', $method = '')
148 // allow user to specify all params in $path
149 if ($server == '' && $port == '' && $method == '') {
150 $parts = parse_url($path);
151 $server = $parts['host'];
152 $path = isset($parts['path']) ? $parts['path'] : '';
153 if (isset($parts['query'])) {
154 $path .= '?' . $parts['query'];
156 if (isset($parts['fragment'])) {
157 $path .= '#' . $parts['fragment'];
159 if (isset($parts['port'])) {
160 $port = $parts['port'];
162 if (isset($parts['scheme'])) {
163 $method = $parts['scheme'];
165 if (isset($parts['user'])) {
166 $this->username = $parts['user'];
168 if (isset($parts['pass'])) {
169 $this->password = $parts['pass'];
172 if ($path == '' || $path[0] != '/') {
173 $this->path = '/' . $path;
177 $this->server = $server;
182 $this->method = $method;
185 // if ZLIB is enabled, let the client by default accept compressed responses
186 if (function_exists('gzinflate') || (
187 function_exists('curl_version') && (($info = curl_version()) &&
188 ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
191 $this->accepted_compression = array('gzip', 'deflate');
194 // keepalives: enabled by default
195 $this->keepalive = true;
197 // by default the xml parser can support these 3 charset encodings
198 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
200 // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
201 // http://www.iana.org/assignments/character-sets/character-sets.xhtml
202 // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
203 /*if (function_exists('mb_list_encodings')) {
205 $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
206 'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
207 $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
210 // initialize user_agent string
211 $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
215 * Enable/disable the echoing to screen of the xmlrpc responses received. The default is not no output anything.
217 * The debugging information at level 1 includes the raw data returned from the XML-RPC server it was querying
218 * (including bot HTTP headers and the full XML payload), and the PHP value the client attempts to create to
219 * represent the value returned by the server
220 * At level2, the complete payload of the xmlrpc request is also printed, before being sent t the server.
222 * This option can be very useful when debugging servers as it allows you to see exactly what the client sends and
223 * the server returns.
225 * @param integer $level values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
227 public function setDebug($level)
229 $this->debug = $level;
233 * Sets the username and password for authorizing the client to the server.
235 * With the default (HTTP) transport, this information is used for HTTP Basic authorization.
236 * Note that username and password can also be set using the class constructor.
237 * With HTTP 1.1 and HTTPS transport, NTLM and Digest authentication protocols are also supported. To enable them use
238 * the constants CURLAUTH_DIGEST and CURLAUTH_NTLM as values for the auth type parameter.
240 * @param string $user username
241 * @param string $password password
242 * @param integer $authType auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC
243 * (basic auth). Note that auth types NTLM and Digest will only work if the Curl php
244 * extension is enabled.
246 public function setCredentials($user, $password, $authType = 1)
248 $this->username = $user;
249 $this->password = $password;
250 $this->authtype = $authType;
254 * Set the optional certificate and passphrase used in SSL-enabled communication with a remote server.
256 * Note: to retrieve information about the client certificate on the server side, you will need to look into the
257 * environment variables which are set up by the webserver. Different webservers will typically set up different
260 * @param string $cert the name of a file containing a PEM formatted certificate
261 * @param string $certPass the password required to use it
263 public function setCertificate($cert, $certPass = '')
266 $this->certpass = $certPass;
270 * Add a CA certificate to verify server with in SSL-enabled communication when SetSSLVerifypeer has been set to TRUE.
272 * See the php manual page about CURLOPT_CAINFO for more details.
274 * @param string $caCert certificate file name (or dir holding certificates)
275 * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
277 public function setCaCertificate($caCert, $isDir = false)
280 $this->cacertdir = $caCert;
282 $this->cacert = $caCert;
287 * Set attributes for SSL communication: private SSL key.
289 * NB: does not work in older php/curl installs.
290 * Thanks to Daniel Convissor.
292 * @param string $key The name of a file containing a private SSL key
293 * @param string $keyPass The secret password needed to use the private SSL key
295 public function setKey($key, $keyPass)
298 $this->keypass = $keyPass;
302 * Set attributes for SSL communication: verify the remote host's SSL certificate, and cause the connection to fail
303 * if the cert verification fails.
305 * By default, verification is enabled.
306 * To specify custom SSL certificates to validate the server with, use the setCaCertificate method.
308 * @param bool $i enable/disable verification of peer certificate
310 public function setSSLVerifyPeer($i)
312 $this->verifypeer = $i;
316 * Set attributes for SSL communication: verify the remote host's SSL certificate's common name (CN).
318 * Note that support for value 1 has been removed in cURL 7.28.1
320 * @param int $i Set to 1 to only the existence of a CN, not that it matches
322 public function setSSLVerifyHost($i)
324 $this->verifyhost = $i;
328 * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide
332 public function setSSLVersion($i)
334 $this->sslversion = $i;
340 * NB: CURL versions before 7.11.10 cannot use a proxy to communicate with https servers.
342 * @param string $proxyHost
343 * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
344 * @param string $proxyUsername Leave blank if proxy has public access
345 * @param string $proxyPassword Leave blank if proxy has public access
346 * @param int $proxyAuthType defaults to CURLAUTH_BASIC (Basic authentication protocol); set to constant CURLAUTH_NTLM
347 * to use NTLM auth with proxy (has effect only when the client uses the HTTP 1.1 protocol)
349 public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
351 $this->proxy = $proxyHost;
352 $this->proxyport = $proxyPort;
353 $this->proxy_user = $proxyUsername;
354 $this->proxy_pass = $proxyPassword;
355 $this->proxy_authtype = $proxyAuthType;
359 * Enables/disables reception of compressed xmlrpc responses.
361 * This requires the "zlib" extension to be enabled in your php install. If it is, by default xmlrpc_client
362 * instances will enable reception of compressed content.
363 * Note that enabling reception of compressed responses merely adds some standard http headers to xmlrpc requests.
364 * It is up to the xmlrpc server to return compressed responses when receiving such requests.
366 * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
368 public function setAcceptedCompression($compMethod)
370 if ($compMethod == 'any') {
371 $this->accepted_compression = array('gzip', 'deflate');
372 } elseif ($compMethod == false) {
373 $this->accepted_compression = array();
375 $this->accepted_compression = array($compMethod);
380 * Enables/disables http compression of xmlrpc request.
382 * This requires the "zlib" extension to be enabled in your php install.
383 * Take care when sending compressed requests: servers might not support them (and automatic fallback to
384 * uncompressed requests is not yet implemented).
386 * @param string $compMethod either 'gzip', 'deflate' or ''
388 public function setRequestCompression($compMethod)
390 $this->request_compression = $compMethod;
394 * Adds a cookie to list of cookies that will be sent to server with every further request (useful e.g. for keeping
395 * session info outside of the xml-rpc payload).
397 * NB: By default cookies are sent using the 'original/netscape' format, which is also the same as the RFC 2965;
398 * setting any param but name and value will turn the cookie into a 'version 1' cookie (i.e. RFC 2109 cookie) that
399 * might not be fully supported by the server. Note that RFC 2109 has currently 'historic' status...
401 * @param string $name nb: will not be escaped in the request's http headers. Take care not to use CTL chars or
403 * @param string $value
404 * @param string $path leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
405 * @param string $domain leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
406 * @param int $port leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
408 * @todo check correctness of urlencoding cookie value (copied from php way of doing it, but php is generally sending
409 * response not requests. We do the opposite...)
410 * @todo strip invalid chars from cookie name? As per RFC6265, we should follow RFC2616, Section 2.2
412 public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
414 $this->cookies[$name]['value'] = rawurlencode($value);
415 if ($path || $domain || $port) {
416 $this->cookies[$name]['path'] = $path;
417 $this->cookies[$name]['domain'] = $domain;
418 $this->cookies[$name]['port'] = $port;
419 $this->cookies[$name]['version'] = 1;
421 $this->cookies[$name]['version'] = 0;
426 * Directly set cURL options, for extra flexibility (when in cURL mode).
428 * It allows eg. to bind client to a specific IP interface / address.
430 * @param array $options
432 public function setCurlOptions($options)
434 $this->extracurlopts = $options;
438 * @param int $useCurlMode self::USE_CURL_ALWAYS, self::USE_CURL_AUTO or self::USE_CURL_NEVER
440 public function setUseCurl($useCurlMode)
442 $this->use_curl = $useCurlMode;
447 * Set user-agent string that will be used by this client instance in http headers sent to the server.
449 * The default user agent string includes the name of this library and the version number.
451 * @param string $agentString
453 public function setUserAgent($agentString)
455 $this->user_agent = $agentString;
459 * Send an xmlrpc request to the server.
461 * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the
462 * complete xml representation of a request.
463 * When sending an array of Request objects, the client will try to make use of
464 * a single 'system.multicall' xml-rpc method call to forward to the server all
465 * the requests in a single HTTP round trip, unless $this->no_multicall has
466 * been previously set to TRUE (see the multicall method below), in which case
467 * many consecutive xmlrpc requests will be sent. The method will return an
468 * array of Response objects in both cases.
469 * The third variant allows to build by hand (or any other means) a complete
470 * xmlrpc request message, and send it to the server. $req should be a string
471 * containing the complete xml representation of the request. It is e.g. useful
472 * when, for maximal speed of execution, the request is serialized into a
473 * string using the native php xmlrpc functions (see http://www.php.net/xmlrpc)
474 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply.
475 * This timeout value is passed to fsockopen(). It is also used for detecting server
476 * timeouts during communication (i.e. if the server does not send anything to the client
477 * for $timeout seconds, the connection will be closed).
478 * @param string $method valid values are 'http', 'http11' and 'https'. If left unspecified, the http protocol
479 * chosen during creation of the object will be used.
481 * @return Response|Response[] Note that the client will always return a Response object, even if the call fails
482 * @todo allow throwing exceptions instead of returning responses in case of failed calls and/or Fault responses
484 public function send($req, $timeout = 0, $method = '')
486 // if user does not specify http protocol, use native method of this client
487 // (i.e. method set during call to constructor)
489 $method = $this->method;
492 if (is_array($req)) {
493 // $req is an array of Requests
494 $r = $this->multicall($req, $timeout, $method);
497 } elseif (is_string($req)) {
498 $n = new Request('');
503 // where req is a Request
504 $req->setDebug($this->debug);
506 /// @todo we could be smarter about this and force usage of curl in scenarios where it is both available and
507 /// needed, such as digest or ntlm auth. Do not attempt to use it for https if not present
508 $useCurl = ($this->use_curl == self::USE_CURL_ALWAYS) || ($this->use_curl == self::USE_CURL_AUTO &&
509 ($method == 'https' || $method == 'http11'));
512 $r = $this->sendPayloadCURL(
528 $this->proxy_authtype,
530 $method == 'http11' ? 'http' : $method,
537 // plain 'http 1.0': default to using socket
538 $r = $this->sendPayloadSocket(
554 $this->proxy_authtype,
567 * @param Request $req
568 * @param string $server
570 * @param int $timeout
571 * @param string $username
572 * @param string $password
573 * @param int $authType
574 * @param string $proxyHost
575 * @param int $proxyPort
576 * @param string $proxyUsername
577 * @param string $proxyPassword
578 * @param int $proxyAuthType
579 * @param string $method
582 protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '',
583 $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
586 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
588 return $this->sendPayloadSocket($req, $server, $port, $timeout, $username, $password, $authType, null, null,
589 null, null, $proxyHost, $proxyPort, $proxyUsername, $proxyPassword, $proxyAuthType, $method);
594 * @param Request $req
595 * @param string $server
597 * @param int $timeout
598 * @param string $username
599 * @param string $password
600 * @param int $authType
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
610 * @param bool $keepAlive
612 * @param string $keyPass
613 * @param int $sslVersion
616 protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '', $password = '',
617 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
618 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $keepAlive = false, $key = '', $keyPass = '',
621 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
623 return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
624 $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
625 $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
629 * @param Request $req
630 * @param string $server
632 * @param int $timeout
633 * @param string $username
634 * @param string $password
635 * @param int $authType only value supported is 1
636 * @param string $cert
637 * @param string $certPass
638 * @param string $caCert
639 * @param string $caCertDir
640 * @param string $proxyHost
641 * @param int $proxyPort
642 * @param string $proxyUsername
643 * @param string $proxyPassword
644 * @param int $proxyAuthType only value supported is 1
645 * @param string $method 'http' (synonym for 'http10'), 'http10' or 'https'
647 * @param string $keyPass @todo not implemented yet.
648 * @param int $sslVersion @todo not implemented yet. See http://php.net/manual/en/migration56.openssl.php
651 protected function sendPayloadSocket($req, $server, $port, $timeout = 0, $username = '', $password = '',
652 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
653 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method='http', $key = '', $keyPass = '',
657 $port = ( $method === 'https' ) ? 443 : 80;
660 // Only create the payload if it was not created previously
661 if (empty($req->payload)) {
662 $req->createPayload($this->request_charset_encoding);
665 $payload = $req->payload;
666 // Deflate request body and set appropriate request headers
668 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
669 if ($this->request_compression == 'gzip') {
670 $a = @gzencode($payload);
673 $encodingHdr = "Content-Encoding: gzip\r\n";
676 $a = @gzcompress($payload);
679 $encodingHdr = "Content-Encoding: deflate\r\n";
684 // thanks to Grant Rauscher <grant7@firstworld.net> for this
686 if ($username != '') {
687 $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
688 if ($authType != 1) {
689 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
693 $acceptedEncoding = '';
694 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
695 $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
698 $proxyCredentials = '';
700 if ($proxyPort == 0) {
703 $connectServer = $proxyHost;
704 $connectPort = $proxyPort;
706 $uri = 'http://' . $server . ':' . $port . $this->path;
707 if ($proxyUsername != '') {
708 if ($proxyAuthType != 1) {
709 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
711 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
714 $connectServer = $server;
715 $connectPort = $port;
716 $transport = ( $method === 'https' ) ? 'tls' : 'tcp';
720 // Cookie generation, as per rfc2965 (version 1 cookies) or netscape's rules (version 0 cookies)
722 if (count($this->cookies)) {
724 foreach ($this->cookies as $name => $cookie) {
725 if ($cookie['version']) {
726 $version = ' $Version="' . $cookie['version'] . '";';
727 $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
728 if ($cookie['path']) {
729 $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
731 if ($cookie['domain']) {
732 $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
734 if ($cookie['port']) {
735 $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
738 $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
741 $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
744 // omit port if default
745 if (($port == 80 && in_array($method, array('http', 'http10'))) || ($port == 443 && $method == 'https')) {
751 $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
752 'User-Agent: ' . $this->user_agent . "\r\n" .
753 'Host: ' . $server . $port . "\r\n" .
758 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
760 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
761 strlen($payload) . "\r\n\r\n" .
764 if ($this->debug > 1) {
765 $this->getLogger()->debugMessage("---SENDING---\n$op\n---END---");
768 $contextOptions = array();
769 if ($method == 'https') {
771 $contextOptions['ssl']['local_cert'] = $cert;
772 if ($certPass != '') {
773 $contextOptions['ssl']['passphrase'] = $certPass;
777 $contextOptions['ssl']['cafile'] = $caCert;
779 if ($caCertDir != '') {
780 $contextOptions['ssl']['capath'] = $caCertDir;
783 $contextOptions['ssl']['local_pk'] = $key;
785 $contextOptions['ssl']['verify_peer'] = $this->verifypeer;
786 $contextOptions['ssl']['verify_peer_name'] = $this->verifypeer;
788 $context = stream_context_create($contextOptions);
791 $connectTimeout = ini_get('default_socket_timeout');
793 $connectTimeout = $timeout;
799 $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $connectTimeout,
800 STREAM_CLIENT_CONNECT, $context);
803 stream_set_timeout($fp, $timeout);
806 if ($this->errstr == '') {
807 $err = error_get_last();
808 $this->errstr = $err['message'];
810 $this->errstr = 'Connect error: ' . $this->errstr;
811 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
816 if (!fputs($fp, $op, strlen($op))) {
818 $this->errstr = 'Write error';
819 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
824 // Close socket before parsing.
825 // It should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
828 // shall we check for $data === FALSE?
829 // as per the manual, it signals an error
830 $ipd .= fread($fp, 32768);
831 } while (!feof($fp));
834 $r = $req->parseResponse($ipd, false, $this->return_type);
840 * Contributed by Justin Miller <justin@voxel.net>
841 * Requires curl to be built into PHP
842 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
844 * @param Request $req
845 * @param string $server
847 * @param int $timeout
848 * @param string $username
849 * @param string $password
850 * @param int $authType
851 * @param string $cert
852 * @param string $certPass
853 * @param string $caCert
854 * @param string $caCertDir
855 * @param string $proxyHost
856 * @param int $proxyPort
857 * @param string $proxyUsername
858 * @param string $proxyPassword
859 * @param int $proxyAuthType
860 * @param string $method 'http' (let curl decide), 'http10', 'http11' or 'https'
861 * @param bool $keepAlive
863 * @param string $keyPass
864 * @param int $sslVersion
867 protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
868 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
869 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
870 $keyPass = '', $sslVersion = 0)
872 if (!function_exists('curl_init')) {
873 $this->errstr = 'CURL unavailable on this install';
874 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
876 if ($method == 'https') {
877 if (($info = curl_version()) &&
878 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
880 $this->errstr = 'SSL unavailable on this install';
881 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
886 if (in_array($method, array('http', 'http10', 'http11'))) {
893 // Only create the payload if it was not created previously
894 if (empty($req->payload)) {
895 $req->createPayload($this->request_charset_encoding);
898 // Deflate request body and set appropriate request headers
899 $payload = $req->payload;
900 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
901 if ($this->request_compression == 'gzip') {
902 $a = @gzencode($payload);
905 $encodingHdr = 'Content-Encoding: gzip';
908 $a = @gzcompress($payload);
911 $encodingHdr = 'Content-Encoding: deflate';
918 if ($this->debug > 1) {
919 $this->getLogger()->debugMessage("---SENDING---\n$payload\n---END---");
922 if (!$keepAlive || !$this->xmlrpc_curl_handle) {
923 if ($method == 'http11' || $method == 'http10') {
928 $curl = curl_init($protocol . '://' . $server . ':' . $port . $this->path);
930 $this->xmlrpc_curl_handle = $curl;
933 $curl = $this->xmlrpc_curl_handle;
936 // results into variable
937 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
939 if ($this->debug > 1) {
940 curl_setopt($curl, CURLOPT_VERBOSE, true);
941 /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
943 curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
944 // required for XMLRPC: post the data
945 curl_setopt($curl, CURLOPT_POST, 1);
947 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
949 // return the header too
950 curl_setopt($curl, CURLOPT_HEADER, 1);
952 // NB: if we set an empty string, CURL will add http header indicating
953 // ALL methods it is supporting. This is possibly a better option than letting the user tell what curl can / cannot do...
954 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
955 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
956 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
957 if (count($this->accepted_compression) == 1) {
958 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
960 curl_setopt($curl, CURLOPT_ENCODING, '');
964 $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
965 // if no keepalive is wanted, let the server know it in advance
967 $headers[] = 'Connection: close';
969 // request compression header
971 $headers[] = $encodingHdr;
974 // Fix the HTTP/1.1 417 Expectation Failed Bug (curl by default adds a 'Expect: 100-continue' header when POST
975 // size exceeds 1025 bytes, apparently)
976 $headers[] = 'Expect:';
978 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
981 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
984 if ($method == 'http10') {
985 curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
986 } elseif ($method == 'http11') {
987 curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
990 if ($username && $password) {
991 curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
992 if (defined('CURLOPT_HTTPAUTH')) {
993 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
994 } elseif ($authType != 1) {
995 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
999 if ($method == 'https') {
1002 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
1004 // set cert password
1006 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
1008 // whether to verify remote host's cert
1009 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
1010 // set ca certificates file/dir
1012 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
1015 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
1017 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1019 curl_setopt($curl, CURLOPT_SSLKEY, $key);
1021 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1023 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
1025 // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that
1026 // it matches the hostname used
1027 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
1028 // allow usage of different SSL versions
1029 curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
1034 if ($proxyPort == 0) {
1035 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
1037 curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
1038 if ($proxyUsername) {
1039 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
1040 if (defined('CURLOPT_PROXYAUTH')) {
1041 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
1042 } elseif ($proxyAuthType != 1) {
1043 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1048 // NB: should we build cookie http headers by hand rather than let CURL do it?
1049 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes set to client obj the the user...
1050 if (count($this->cookies)) {
1052 foreach ($this->cookies as $name => $cookie) {
1053 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
1055 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
1058 foreach ($this->extracurlopts as $opt => $val) {
1059 curl_setopt($curl, $opt, $val);
1062 $result = curl_exec($curl);
1064 if ($this->debug > 1) {
1065 $message = "---CURL INFO---\n";
1066 foreach (curl_getinfo($curl) as $name => $val) {
1067 if (is_array($val)) {
1068 $val = implode("\n", $val);
1070 $message .= $name . ': ' . $val . "\n";
1072 $message .= '---END---';
1073 $this->getLogger()->debugMessage($message);
1077 /// @todo we should use a better check here - what if we get back '' or '0'?
1079 $this->errstr = 'no response';
1080 $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
1083 $this->xmlrpc_curl_handle = null;
1089 $resp = $req->parseResponse($result, true, $this->return_type);
1090 // if we got back a 302, we can not reuse the curl handle for later calls
1091 if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
1093 $this->xmlrpc_curl_handle = null;
1101 * Send an array of requests and return an array of responses.
1103 * Unless $this->no_multicall has been set to true, it will try first to use one single xmlrpc call to server method
1104 * system.multicall, and revert to sending many successive calls in case of failure.
1105 * This failure is also stored in $this->no_multicall for subsequent calls.
1106 * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported,
1107 * so there is no way to reliably distinguish between that and a temporary failure.
1108 * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the
1109 * fourth parameter to FALSE.
1111 * NB: trying to shoehorn extra functionality into existing syntax has resulted
1112 * in pretty much convoluted code...
1114 * @param Request[] $reqs an array of Request objects
1115 * @param integer $timeout connection timeout (in seconds). See the details in the docs for the send() method
1116 * @param string $method the http protocol variant to be used. See the details in the docs for the send() method
1117 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be
1120 * @return Response[]
1122 public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
1124 if ($method == '') {
1125 $method = $this->method;
1127 if (!$this->no_multicall) {
1128 $results = $this->_try_multicall($reqs, $timeout, $method);
1129 if (is_array($results)) {
1130 // System.multicall succeeded
1133 // either system.multicall is unsupported by server,
1134 // or call failed for some other reason.
1136 // Don't try it next time...
1137 $this->no_multicall = true;
1139 if (is_a($results, '\PhpXmlRpc\Response')) {
1142 $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
1147 // override fallback, in case careless user tries to do two
1148 // opposite things at the same time
1154 // system.multicall is (probably) unsupported by server:
1155 // emulate multicall via multiple requests
1156 foreach ($reqs as $req) {
1157 $results[] = $this->send($req, $timeout, $method);
1160 // user does NOT want to fallback on many single calls:
1161 // since we should always return an array of responses,
1162 // return an array with the same error repeated n times
1163 foreach ($reqs as $req) {
1164 $results[] = $result;
1172 * Attempt to boxcar $reqs via system.multicall.
1174 * Returns either an array of Response, a single error Response or false (when received response does not respect
1175 * valid multicall syntax).
1177 * @param Request[] $reqs
1178 * @param int $timeout
1179 * @param string $method
1180 * @return Response[]|bool|mixed|Response
1182 private function _try_multicall($reqs, $timeout, $method)
1184 // Construct multicall request
1186 foreach ($reqs as $req) {
1187 $call['methodName'] = new Value($req->method(), 'string');
1188 $numParams = $req->getNumParams();
1190 for ($i = 0; $i < $numParams; $i++) {
1191 $params[$i] = $req->getParam($i);
1193 $call['params'] = new Value($params, 'array');
1194 $calls[] = new Value($call, 'struct');
1196 $multiCall = new Request('system.multicall');
1197 $multiCall->addParam(new Value($calls, 'array'));
1200 $result = $this->send($multiCall, $timeout, $method);
1202 if ($result->faultCode() != 0) {
1203 // call to system.multicall failed
1207 // Unpack responses.
1208 $rets = $result->value();
1210 if ($this->return_type == 'xml') {
1212 } elseif ($this->return_type == 'phpvals') {
1213 /// @todo test this code branch...
1214 $rets = $result->value();
1215 if (!is_array($rets)) {
1216 return false; // bad return type from system.multicall
1218 $numRets = count($rets);
1219 if ($numRets != count($reqs)) {
1220 return false; // wrong number of return values.
1223 $response = array();
1224 for ($i = 0; $i < $numRets; $i++) {
1226 if (!is_array($val)) {
1229 switch (count($val)) {
1231 if (!isset($val[0])) {
1232 return false; // Bad value
1234 // Normal return value
1235 $response[$i] = new Response($val[0], 0, '', 'phpvals');
1238 /// @todo remove usage of @: it is apparently quite slow
1239 $code = @$val['faultCode'];
1240 if (!is_int($code)) {
1243 $str = @$val['faultString'];
1244 if (!is_string($str)) {
1247 $response[$i] = new Response(0, $code, $str);
1256 // return type == 'xmlrpcvals'
1258 $rets = $result->value();
1259 if ($rets->kindOf() != 'array') {
1260 return false; // bad return type from system.multicall
1262 $numRets = $rets->count();
1263 if ($numRets != count($reqs)) {
1264 return false; // wrong number of return values.
1267 $response = array();
1268 foreach($rets as $val) {
1269 switch ($val->kindOf()) {
1271 if ($val->count() != 1) {
1272 return false; // Bad value
1274 // Normal return value
1275 $response[] = new Response($val[0]);
1278 $code = $val['faultCode'];
1279 /** @var Value $code */
1280 if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1283 $str = $val['faultString'];
1284 /** @var Value $str */
1285 if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1288 $response[] = new Response(0, $code->scalarval(), $str->scalarval());