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 /// @todo: do these need to be public?
17 public $method = 'http';
26 public $username = '';
27 public $password = '';
31 public $certpass = '';
33 public $cacertdir = '';
36 public $verifypeer = true;
37 public $verifyhost = 2;
38 public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
41 public $proxyport = 0;
42 public $proxy_user = '';
43 public $proxy_pass = '';
44 public $proxy_authtype = 1;
46 public $cookies = array();
47 public $extracurlopts = array();
48 public $use_curl = self::USE_CURL_AUTO;
53 * This determines whether the multicall() method will try to take advantage of the system.multicall xmlrpc method
54 * to dispatch to the server an array of requests in a single http roundtrip or simply execute many consecutive http
55 * calls. Defaults to FALSE, but it will be enabled automatically on the first failure of execution of
58 public $no_multicall = false;
61 * List of http compression methods accepted by the client for responses.
62 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib.
64 * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
65 * in those cases it will be up to CURL to decide the compression methods
66 * it supports. You might check for the presence of 'zlib' in the output of
67 * curl_version() to determine whether compression is supported or not
69 public $accepted_compression = array();
72 * Name of compression scheme to be used for sending requests.
73 * 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).
82 public $xmlrpc_curl_handle = null;
84 /// Whether to use persistent connections for http 1.1 and https
85 public $keepalive = false;
87 /// Charset encodings that can be decoded without problems by the client
88 public $accepted_charset_encodings = array();
91 * The charset encoding that will be used for serializing request sent by the client.
92 * It defaults to NULL, which means using US-ASCII and encoding all characters outside of the ASCII range using
93 * their xml character entity representation (this has the benefit that line end characters will not be mangled in
94 * the transfer, a CR-LF will be preserved as well as a singe LF).
95 * Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1'
97 public $request_charset_encoding = '';
100 * Decides the content of Response objects returned by calls to send() and multicall().
101 * Valid values are 'xmlrpcvals', 'phpvals' or 'xml'.
103 * Determines whether the value returned inside an Response object as results of calls to the send() and multicall()
104 * methods will be a Value object, a plain php value or a raw xml string.
105 * Allowed values are 'xmlrpcvals' (the default), 'phpvals' and 'xml'.
106 * To allow the user to differentiate between a correct and a faulty response, fault responses will be returned as
107 * Response objects in any case.
108 * Note that the 'phpvals' setting will yield faster execution times, but some of the information from the original
109 * response will be lost. It will be e.g. impossible to tell whether a particular php string value was sent by the
110 * server as an xmlrpc string or base64 value.
112 public $return_type = 'xmlrpcvals';
115 * Sent to servers in http headers.
120 * @param string $path either the PATH part of the xmlrpc server URL, or complete server URL (in which case you
121 * should use and empty string for all other parameters)
122 * e.g. /xmlrpc/server.php
123 * e.g. http://phpxmlrpc.sourceforge.net/server.php
124 * e.g. https://james:bond@secret.service.com:443/xmlrpcserver?agent=007
125 * @param string $server the server name / ip address
126 * @param integer $port the port the server is listening on, when omitted defaults to 80 or 443 depending on
128 * @param string $method the http protocol variant: defaults to 'http'; 'https' and 'http11' can be used if CURL is
129 * installed. The value set here can be overridden in any call to $this->send().
131 public function __construct($path, $server = '', $port = '', $method = '')
133 // allow user to specify all params in $path
134 if ($server == '' && $port == '' && $method == '') {
135 $parts = parse_url($path);
136 $server = $parts['host'];
137 $path = isset($parts['path']) ? $parts['path'] : '';
138 if (isset($parts['query'])) {
139 $path .= '?' . $parts['query'];
141 if (isset($parts['fragment'])) {
142 $path .= '#' . $parts['fragment'];
144 if (isset($parts['port'])) {
145 $port = $parts['port'];
147 if (isset($parts['scheme'])) {
148 $method = $parts['scheme'];
150 if (isset($parts['user'])) {
151 $this->username = $parts['user'];
153 if (isset($parts['pass'])) {
154 $this->password = $parts['pass'];
157 if ($path == '' || $path[0] != '/') {
158 $this->path = '/' . $path;
162 $this->server = $server;
167 $this->method = $method;
170 // if ZLIB is enabled, let the client by default accept compressed responses
171 if (function_exists('gzinflate') || (
172 function_exists('curl_init') && (($info = curl_version()) &&
173 ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
176 $this->accepted_compression = array('gzip', 'deflate');
179 // keepalives: enabled by default
180 $this->keepalive = true;
182 // by default the xml parser can support these 3 charset encodings
183 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
185 // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
186 // http://www.iana.org/assignments/character-sets/character-sets.xhtml
187 // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
188 /*if (function_exists('mb_list_encodings')) {
190 $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
191 'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
192 $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
195 // initialize user_agent string
196 $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
200 * Enable/disable the echoing to screen of the xmlrpc responses received. The default is not no output anything.
202 * The debugging information at level 1 includes the raw data returned from the XML-RPC server it was querying
203 * (including bot HTTP headers and the full XML payload), and the PHP value the client attempts to create to
204 * represent the value returned by the server
205 * At level2, the complete payload of the xmlrpc request is also printed, before being sent t the server.
207 * This option can be very useful when debugging servers as it allows you to see exactly what the client sends and
208 * the server returns.
210 * @param integer $level values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
212 public function setDebug($level)
214 $this->debug = $level;
218 * Sets the username and password for authorizing the client to the server.
220 * With the default (HTTP) transport, this information is used for HTTP Basic authorization.
221 * Note that username and password can also be set using the class constructor.
222 * With HTTP 1.1 and HTTPS transport, NTLM and Digest authentication protocols are also supported. To enable them use
223 * the constants CURLAUTH_DIGEST and CURLAUTH_NTLM as values for the auth type parameter.
225 * @param string $user username
226 * @param string $password password
227 * @param integer $authType auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC
228 * (basic auth). Note that auth types NTLM and Digest will only work if the Curl php
229 * extension is enabled.
231 public function setCredentials($user, $password, $authType = 1)
233 $this->username = $user;
234 $this->password = $password;
235 $this->authtype = $authType;
239 * Set the optional certificate and passphrase used in SSL-enabled communication with a remote server.
241 * Note: to retrieve information about the client certificate on the server side, you will need to look into the
242 * environment variables which are set up by the webserver. Different webservers will typically set up different
245 * @param string $cert the name of a file containing a PEM formatted certificate
246 * @param string $certPass the password required to use it
248 public function setCertificate($cert, $certPass = '')
251 $this->certpass = $certPass;
255 * Add a CA certificate to verify server with in SSL-enabled communication when SetSSLVerifypeer has been set to TRUE.
257 * See the php manual page about CURLOPT_CAINFO for more details.
259 * @param string $caCert certificate file name (or dir holding certificates)
260 * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
262 public function setCaCertificate($caCert, $isDir = false)
265 $this->cacertdir = $caCert;
267 $this->cacert = $caCert;
272 * Set attributes for SSL communication: private SSL key.
274 * NB: does not work in older php/curl installs.
275 * Thanks to Daniel Convissor.
277 * @param string $key The name of a file containing a private SSL key
278 * @param string $keyPass The secret password needed to use the private SSL key
280 public function setKey($key, $keyPass)
283 $this->keypass = $keyPass;
287 * Set attributes for SSL communication: verify the remote host's SSL certificate, and cause the connection to fail
288 * if the cert verification fails.
290 * By default, verification is enabled.
291 * To specify custom SSL certificates to validate the server with, use the setCaCertificate method.
293 * @param bool $i enable/disable verification of peer certificate
295 public function setSSLVerifyPeer($i)
297 $this->verifypeer = $i;
301 * Set attributes for SSL communication: verify the remote host's SSL certificate's common name (CN).
303 * Note that support for value 1 has been removed in cURL 7.28.1
305 * @param int $i Set to 1 to only the existence of a CN, not that it matches
307 public function setSSLVerifyHost($i)
309 $this->verifyhost = $i;
313 * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide
317 public function setSSLVersion($i)
319 $this->sslversion = $i;
325 * NB: CURL versions before 7.11.10 cannot use a proxy to communicate with https servers.
327 * @param string $proxyHost
328 * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
329 * @param string $proxyUsername Leave blank if proxy has public access
330 * @param string $proxyPassword Leave blank if proxy has public access
331 * @param int $proxyAuthType defaults to CURLAUTH_BASIC (Basic authentication protocol); set to constant CURLAUTH_NTLM
332 * to use NTLM auth with proxy (has effect only when the client uses the HTTP 1.1 protocol)
334 public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
336 $this->proxy = $proxyHost;
337 $this->proxyport = $proxyPort;
338 $this->proxy_user = $proxyUsername;
339 $this->proxy_pass = $proxyPassword;
340 $this->proxy_authtype = $proxyAuthType;
344 * Enables/disables reception of compressed xmlrpc responses.
346 * This requires the "zlib" extension to be enabled in your php install. If it is, by default xmlrpc_client
347 * instances will enable reception of compressed content.
348 * Note that enabling reception of compressed responses merely adds some standard http headers to xmlrpc requests.
349 * It is up to the xmlrpc server to return compressed responses when receiving such requests.
351 * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
353 public function setAcceptedCompression($compMethod)
355 if ($compMethod == 'any') {
356 $this->accepted_compression = array('gzip', 'deflate');
357 } elseif ($compMethod == false) {
358 $this->accepted_compression = array();
360 $this->accepted_compression = array($compMethod);
365 * Enables/disables http compression of xmlrpc request.
367 * This requires the "zlib" extension to be enabled in your php install.
368 * Take care when sending compressed requests: servers might not support them (and automatic fallback to
369 * uncompressed requests is not yet implemented).
371 * @param string $compMethod either 'gzip', 'deflate' or ''
373 public function setRequestCompression($compMethod)
375 $this->request_compression = $compMethod;
379 * Adds a cookie to list of cookies that will be sent to server with every further request (useful e.g. for keeping
380 * session info outside of the xml-rpc payload).
382 * NB: By default cookies are sent using the 'original/netscape' format, which is also the same as the RFC 2965;
383 * setting any param but name and value will turn the cookie into a 'version 1' cookie (i.e. RFC 2109 cookie) that
384 * might not be fully supported by the server. Note that RFC 2109 has currently 'historic' status...
386 * @param string $name nb: will not be escaped in the request's http headers. Take care not to use CTL chars or
388 * @param string $value
389 * @param string $path leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
390 * @param string $domain leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
391 * @param int $port leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
393 * @todo check correctness of urlencoding cookie value (copied from php way of doing it, but php is generally sending
394 * response not requests. We do the opposite...)
395 * @todo strip invalid chars from cookie name? As per RFC6265, we should follow RFC2616, Section 2.2
397 public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
399 $this->cookies[$name]['value'] = urlencode($value);
400 if ($path || $domain || $port) {
401 $this->cookies[$name]['path'] = $path;
402 $this->cookies[$name]['domain'] = $domain;
403 $this->cookies[$name]['port'] = $port;
404 $this->cookies[$name]['version'] = 1;
406 $this->cookies[$name]['version'] = 0;
411 * Directly set cURL options, for extra flexibility (when in cURL mode).
413 * It allows eg. to bind client to a specific IP interface / address.
415 * @param array $options
417 public function setCurlOptions($options)
419 $this->extracurlopts = $options;
423 * @param int $useCurlMode self::USE_CURL_ALWAYS, self::USE_CURL_AUTO or self::USE_CURL_NEVER
425 public function setUseCurl($useCurlMode)
427 $this->use_curl = $useCurlMode;
432 * Set user-agent string that will be used by this client instance in http headers sent to the server.
434 * The default user agent string includes the name of this library and the version number.
436 * @param string $agentString
438 public function setUserAgent($agentString)
440 $this->user_agent = $agentString;
444 * Send an xmlrpc request to the server.
446 * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the
447 * complete xml representation of a request.
448 * When sending an array of Request objects, the client will try to make use of
449 * a single 'system.multicall' xml-rpc method call to forward to the server all
450 * the requests in a single HTTP round trip, unless $this->no_multicall has
451 * been previously set to TRUE (see the multicall method below), in which case
452 * many consecutive xmlrpc requests will be sent. The method will return an
453 * array of Response objects in both cases.
454 * The third variant allows to build by hand (or any other means) a complete
455 * xmlrpc request message, and send it to the server. $req should be a string
456 * containing the complete xml representation of the request. It is e.g. useful
457 * when, for maximal speed of execution, the request is serialized into a
458 * string using the native php xmlrpc functions (see http://www.php.net/xmlrpc)
459 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply.
460 * This timeout value is passed to fsockopen(). It is also used for detecting server
461 * timeouts during communication (i.e. if the server does not send anything to the client
462 * for $timeout seconds, the connection will be closed).
463 * @param string $method valid values are 'http', 'http11' and 'https'. If left unspecified, the http protocol
464 * chosen during creation of the object will be used.
466 * @return Response|Response[] Note that the client will always return a Response object, even if the call fails
468 public function send($req, $timeout = 0, $method = '')
470 // if user does not specify http protocol, use native method of this client
471 // (i.e. method set during call to constructor)
473 $method = $this->method;
476 if (is_array($req)) {
477 // $req is an array of Requests
478 $r = $this->multicall($req, $timeout, $method);
481 } elseif (is_string($req)) {
482 $n = new Request('');
487 // where req is a Request
488 $req->setDebug($this->debug);
490 /// @todo we could be smarter about this and force usage of curl in scenarios where it is both available and
491 /// needed, such as digest or ntlm auth. Do not attempt to use it for https if not present
492 $useCurl = ($this->use_curl == self::USE_CURL_ALWAYS) || ($this->use_curl == self::USE_CURL_AUTO &&
493 ($method == 'https' || $method == 'http11'));
496 $r = $this->sendPayloadCURL(
512 $this->proxy_authtype,
514 $method == 'http11' ? 'http' : $method,
521 // plain 'http 1.0': default to using socket
522 $r = $this->sendPayloadSocket(
538 $this->proxy_authtype,
551 * @param Request $req
552 * @param string $server
554 * @param int $timeout
555 * @param string $username
556 * @param string $password
557 * @param int $authType
558 * @param string $proxyHost
559 * @param int $proxyPort
560 * @param string $proxyUsername
561 * @param string $proxyPassword
562 * @param int $proxyAuthType
563 * @param string $method
566 protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '',
567 $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
570 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
572 return $this->sendPayloadSocket($req, $server, $port, $timeout, $username, $password, $authType, null, null,
573 null, null, $proxyHost, $proxyPort, $proxyUsername, $proxyPassword, $proxyAuthType, $method);
578 * @param Request $req
579 * @param string $server
581 * @param int $timeout
582 * @param string $username
583 * @param string $password
584 * @param int $authType
585 * @param string $cert
586 * @param string $certPass
587 * @param string $caCert
588 * @param string $caCertDir
589 * @param string $proxyHost
590 * @param int $proxyPort
591 * @param string $proxyUsername
592 * @param string $proxyPassword
593 * @param int $proxyAuthType
594 * @param bool $keepAlive
596 * @param string $keyPass
597 * @param int $sslVersion
600 protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '', $password = '',
601 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
602 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $keepAlive = false, $key = '', $keyPass = '',
605 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
607 return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
608 $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
609 $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
613 * @param Request $req
614 * @param string $server
616 * @param int $timeout
617 * @param string $username
618 * @param string $password
619 * @param int $authType only value supported is 1
620 * @param string $cert
621 * @param string $certPass
622 * @param string $caCert
623 * @param string $caCertDir
624 * @param string $proxyHost
625 * @param int $proxyPort
626 * @param string $proxyUsername
627 * @param string $proxyPassword
628 * @param int $proxyAuthType only value supported is 1
629 * @param string $method 'http' (synonym for 'http10'), 'http10' or 'https'
631 * @param string $keyPass @todo not implemented yet.
632 * @param int $sslVersion @todo not implemented yet. See http://php.net/manual/en/migration56.openssl.php
635 protected function sendPayloadSocket($req, $server, $port, $timeout = 0, $username = '', $password = '',
636 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
637 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method='http', $key = '', $keyPass = '',
641 $port = ( $method === 'https' ) ? 443 : 80;
644 // Only create the payload if it was not created previously
645 if (empty($req->payload)) {
646 $req->createPayload($this->request_charset_encoding);
649 $payload = $req->payload;
650 // Deflate request body and set appropriate request headers
652 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
653 if ($this->request_compression == 'gzip') {
654 $a = @gzencode($payload);
657 $encodingHdr = "Content-Encoding: gzip\r\n";
660 $a = @gzcompress($payload);
663 $encodingHdr = "Content-Encoding: deflate\r\n";
668 // thanks to Grant Rauscher <grant7@firstworld.net> for this
670 if ($username != '') {
671 $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
672 if ($authType != 1) {
673 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
677 $acceptedEncoding = '';
678 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
679 $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
682 $proxyCredentials = '';
684 if ($proxyPort == 0) {
687 $connectServer = $proxyHost;
688 $connectPort = $proxyPort;
690 $uri = 'http://' . $server . ':' . $port . $this->path;
691 if ($proxyUsername != '') {
692 if ($proxyAuthType != 1) {
693 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
695 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
698 $connectServer = $server;
699 $connectPort = $port;
700 $transport = ( $method === 'https' ) ? 'tls' : 'tcp';
704 // Cookie generation, as per rfc2965 (version 1 cookies) or
705 // netscape's rules (version 0 cookies)
707 if (count($this->cookies)) {
709 foreach ($this->cookies as $name => $cookie) {
710 if ($cookie['version']) {
711 $version = ' $Version="' . $cookie['version'] . '";';
712 $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
713 if ($cookie['path']) {
714 $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
716 if ($cookie['domain']) {
717 $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
719 if ($cookie['port']) {
720 $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
723 $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
726 $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
729 // omit port if default
730 if (($port == 80 && in_array($method, array('http', 'http10'))) || ($port == 443 && $method == 'https')) {
736 $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
737 'User-Agent: ' . $this->user_agent . "\r\n" .
738 'Host: ' . $server . $port . "\r\n" .
743 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
745 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
746 strlen($payload) . "\r\n\r\n" .
749 if ($this->debug > 1) {
750 Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
753 $contextOptions = array();
754 if ($method == 'https') {
756 $contextOptions['ssl']['local_cert'] = $cert;
757 if ($certPass != '') {
758 $contextOptions['ssl']['passphrase'] = $certPass;
762 $contextOptions['ssl']['cafile'] = $caCert;
764 if ($caCertDir != '') {
765 $contextOptions['ssl']['capath'] = $caCertDir;
768 $contextOptions['ssl']['local_pk'] = $key;
770 $contextOptions['ssl']['verify_peer'] = $this->verifypeer;
771 $contextOptions['ssl']['verify_peer_name'] = $this->verifypeer;
773 $context = stream_context_create($contextOptions);
776 $connectTimeout = ini_get('default_socket_timeout');
778 $connectTimeout = $timeout;
784 $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $connectTimeout,
785 STREAM_CLIENT_CONNECT, $context);
788 stream_set_timeout($fp, $timeout);
791 if ($this->errstr == '') {
792 $err = error_get_last();
793 $this->errstr = $err['message'];
795 $this->errstr = 'Connect error: ' . $this->errstr;
796 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
801 if (!fputs($fp, $op, strlen($op))) {
803 $this->errstr = 'Write error';
804 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
809 // G. Giunta 2005/10/24: close socket before parsing.
810 // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
813 // shall we check for $data === FALSE?
814 // as per the manual, it signals an error
815 $ipd .= fread($fp, 32768);
816 } while (!feof($fp));
819 $r = $req->parseResponse($ipd, false, $this->return_type);
825 * Contributed by Justin Miller <justin@voxel.net>
826 * Requires curl to be built into PHP
827 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
829 * @param Request $req
830 * @param string $server
832 * @param int $timeout
833 * @param string $username
834 * @param string $password
835 * @param int $authType
836 * @param string $cert
837 * @param string $certPass
838 * @param string $caCert
839 * @param string $caCertDir
840 * @param string $proxyHost
841 * @param int $proxyPort
842 * @param string $proxyUsername
843 * @param string $proxyPassword
844 * @param int $proxyAuthType
845 * @param string $method 'http' (let curl decide), 'http10', 'http11' or 'https'
846 * @param bool $keepAlive
848 * @param string $keyPass
849 * @param int $sslVersion
852 protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
853 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
854 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
855 $keyPass = '', $sslVersion = 0)
857 if (!function_exists('curl_init')) {
858 $this->errstr = 'CURL unavailable on this install';
859 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
861 if ($method == 'https') {
862 if (($info = curl_version()) &&
863 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
865 $this->errstr = 'SSL unavailable on this install';
866 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
871 if (in_array($method, array('http', 'http10', 'http11'))) {
878 // Only create the payload if it was not created previously
879 if (empty($req->payload)) {
880 $req->createPayload($this->request_charset_encoding);
883 // Deflate request body and set appropriate request headers
884 $payload = $req->payload;
885 if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
886 if ($this->request_compression == 'gzip') {
887 $a = @gzencode($payload);
890 $encodingHdr = 'Content-Encoding: gzip';
893 $a = @gzcompress($payload);
896 $encodingHdr = 'Content-Encoding: deflate';
903 if ($this->debug > 1) {
904 Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
907 if (!$keepAlive || !$this->xmlrpc_curl_handle) {
908 if ($method == 'http11' || $method == 'http10') {
913 $curl = curl_init($protocol . '://' . $server . ':' . $port . $this->path);
915 $this->xmlrpc_curl_handle = $curl;
918 $curl = $this->xmlrpc_curl_handle;
921 // results into variable
922 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
924 if ($this->debug > 1) {
925 curl_setopt($curl, CURLOPT_VERBOSE, true);
926 /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
928 curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
929 // required for XMLRPC: post the data
930 curl_setopt($curl, CURLOPT_POST, 1);
932 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
934 // return the header too
935 curl_setopt($curl, CURLOPT_HEADER, 1);
937 // NB: if we set an empty string, CURL will add http header indicating
938 // ALL methods it is supporting. This is possibly a better option than
939 // letting the user tell what curl can / cannot do...
940 if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
941 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
942 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
943 if (count($this->accepted_compression) == 1) {
944 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
946 curl_setopt($curl, CURLOPT_ENCODING, '');
950 $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
951 // if no keepalive is wanted, let the server know it in advance
953 $headers[] = 'Connection: close';
955 // request compression header
957 $headers[] = $encodingHdr;
960 // Fix the HTTP/1.1 417 Expectation Failed Bug (curl by default adds a 'Expect: 100-continue' header when POST
961 // size exceeds 1025 bytes, apparently)
962 $headers[] = 'Expect:';
964 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
967 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
970 if ($method == 'http10') {
971 curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
972 } elseif ($method == 'http11') {
973 curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
976 if ($username && $password) {
977 curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
978 if (defined('CURLOPT_HTTPAUTH')) {
979 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
980 } elseif ($authType != 1) {
981 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
985 if ($method == 'https') {
988 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
992 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
994 // whether to verify remote host's cert
995 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
996 // set ca certificates file/dir
998 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
1001 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
1003 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1005 curl_setopt($curl, CURLOPT_SSLKEY, $key);
1007 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1009 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
1011 // 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
1012 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
1013 // allow usage of different SSL versions
1014 curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
1019 if ($proxyPort == 0) {
1020 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
1022 curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
1023 if ($proxyUsername) {
1024 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
1025 if (defined('CURLOPT_PROXYAUTH')) {
1026 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
1027 } elseif ($proxyAuthType != 1) {
1028 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1033 // NB: should we build cookie http headers by hand rather than let CURL do it?
1034 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
1035 // set to client obj the the user...
1036 if (count($this->cookies)) {
1038 foreach ($this->cookies as $name => $cookie) {
1039 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
1041 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
1044 foreach ($this->extracurlopts as $opt => $val) {
1045 curl_setopt($curl, $opt, $val);
1048 $result = curl_exec($curl);
1050 if ($this->debug > 1) {
1051 $message = "---CURL INFO---\n";
1052 foreach (curl_getinfo($curl) as $name => $val) {
1053 if (is_array($val)) {
1054 $val = implode("\n", $val);
1056 $message .= $name . ': ' . $val . "\n";
1058 $message .= '---END---';
1059 Logger::instance()->debugMessage($message);
1063 /// @todo we should use a better check here - what if we get back '' or '0'?
1065 $this->errstr = 'no response';
1066 $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
1069 $this->xmlrpc_curl_handle = null;
1075 $resp = $req->parseResponse($result, true, $this->return_type);
1076 // if we got back a 302, we can not reuse the curl handle for later calls
1077 if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
1079 $this->xmlrpc_curl_handle = null;
1087 * Send an array of requests and return an array of responses.
1089 * Unless $this->no_multicall has been set to true, it will try first to use one single xmlrpc call to server method
1090 * system.multicall, and revert to sending many successive calls in case of failure.
1091 * This failure is also stored in $this->no_multicall for subsequent calls.
1092 * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported,
1093 * so there is no way to reliably distinguish between that and a temporary failure.
1094 * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the
1095 * fourth parameter to FALSE.
1097 * NB: trying to shoehorn extra functionality into existing syntax has resulted
1098 * in pretty much convoluted code...
1100 * @param Request[] $reqs an array of Request objects
1101 * @param integer $timeout connection timeout (in seconds). See the details in the docs for the send() method
1102 * @param string $method the http protocol variant to be used. See the details in the docs for the send() method
1103 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be
1106 * @return Response[]
1108 public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
1110 if ($method == '') {
1111 $method = $this->method;
1113 if (!$this->no_multicall) {
1114 $results = $this->_try_multicall($reqs, $timeout, $method);
1115 if (is_array($results)) {
1116 // System.multicall succeeded
1119 // either system.multicall is unsupported by server,
1120 // or call failed for some other reason.
1122 // Don't try it next time...
1123 $this->no_multicall = true;
1125 if (is_a($results, '\PhpXmlRpc\Response')) {
1128 $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
1133 // override fallback, in case careless user tries to do two
1134 // opposite things at the same time
1140 // system.multicall is (probably) unsupported by server:
1141 // emulate multicall via multiple requests
1142 foreach ($reqs as $req) {
1143 $results[] = $this->send($req, $timeout, $method);
1146 // user does NOT want to fallback on many single calls:
1147 // since we should always return an array of responses,
1148 // return an array with the same error repeated n times
1149 foreach ($reqs as $req) {
1150 $results[] = $result;
1158 * Attempt to boxcar $reqs via system.multicall.
1160 * Returns either an array of Response, a single error Response or false (when received response does not respect
1161 * valid multicall syntax).
1163 * @param Request[] $reqs
1164 * @param int $timeout
1165 * @param string $method
1166 * @return Response[]|bool|mixed|Response
1168 private function _try_multicall($reqs, $timeout, $method)
1170 // Construct multicall request
1172 foreach ($reqs as $req) {
1173 $call['methodName'] = new Value($req->method(), 'string');
1174 $numParams = $req->getNumParams();
1176 for ($i = 0; $i < $numParams; $i++) {
1177 $params[$i] = $req->getParam($i);
1179 $call['params'] = new Value($params, 'array');
1180 $calls[] = new Value($call, 'struct');
1182 $multiCall = new Request('system.multicall');
1183 $multiCall->addParam(new Value($calls, 'array'));
1186 $result = $this->send($multiCall, $timeout, $method);
1188 if ($result->faultCode() != 0) {
1189 // call to system.multicall failed
1193 // Unpack responses.
1194 $rets = $result->value();
1196 if ($this->return_type == 'xml') {
1198 } elseif ($this->return_type == 'phpvals') {
1199 /// @todo test this code branch...
1200 $rets = $result->value();
1201 if (!is_array($rets)) {
1202 return false; // bad return type from system.multicall
1204 $numRets = count($rets);
1205 if ($numRets != count($reqs)) {
1206 return false; // wrong number of return values.
1209 $response = array();
1210 for ($i = 0; $i < $numRets; $i++) {
1212 if (!is_array($val)) {
1215 switch (count($val)) {
1217 if (!isset($val[0])) {
1218 return false; // Bad value
1220 // Normal return value
1221 $response[$i] = new Response($val[0], 0, '', 'phpvals');
1224 /// @todo remove usage of @: it is apparently quite slow
1225 $code = @$val['faultCode'];
1226 if (!is_int($code)) {
1229 $str = @$val['faultString'];
1230 if (!is_string($str)) {
1233 $response[$i] = new Response(0, $code, $str);
1242 // return type == 'xmlrpcvals'
1244 $rets = $result->value();
1245 if ($rets->kindOf() != 'array') {
1246 return false; // bad return type from system.multicall
1248 $numRets = $rets->count();
1249 if ($numRets != count($reqs)) {
1250 return false; // wrong number of return values.
1253 $response = array();
1254 foreach($rets as $val) {
1255 switch ($val->kindOf()) {
1257 if ($val->count() != 1) {
1258 return false; // Bad value
1260 // Normal return value
1261 $response[] = new Response($val[0]);
1264 $code = $val['faultCode'];
1265 /** @var Value $code */
1266 if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1269 $str = $val['faultString'];
1270 /** @var Value $str */
1271 if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1274 $response[] = new Response(0, $code->scalarval(), $str->scalarval());