5 use PhpXmlRpc\Helper\Logger
;
6 use PhpXmlRpc\Helper\XMLParser
;
9 * Used to represent a client of an XML-RPC server.
13 const USE_CURL_NEVER
= 0;
14 const USE_CURL_ALWAYS
= 1;
15 const USE_CURL_AUTO
= 2;
17 protected static $logger;
19 /// @todo: do these need to be public?
20 public $method = 'http';
29 public $username = '';
30 public $password = '';
34 public $certpass = '';
36 public $cacertdir = '';
39 public $verifypeer = true;
40 public $verifyhost = 2;
41 public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
44 public $proxyport = 0;
45 public $proxy_user = '';
46 public $proxy_pass = '';
47 public $proxy_authtype = 1;
49 public $cookies = array();
50 public $extracurlopts = array();
51 public $use_curl = self
::USE_CURL_AUTO
;
56 * This determines whether the multicall() method will try to take advantage of the system.multicall xmlrpc method
57 * to dispatch to the server an array of requests in a single http roundtrip or simply execute many consecutive http
58 * calls. Defaults to FALSE, but it will be enabled automatically on the first failure of execution of
61 public $no_multicall = false;
64 * List of http compression methods accepted by the client for responses.
65 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib.
67 * 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
68 * decide the compression methods it supports. You might check for the presence of 'zlib' in the output of
69 * curl_version() to determine whether compression is supported or not
71 public $accepted_compression = array();
74 * Name of compression scheme to be used for sending requests.
75 * Either null, gzip or deflate.
77 public $request_compression = '';
80 * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
81 * http://curl.haxx.se/docs/faq.html#7.3).
84 public $xmlrpc_curl_handle = null;
86 /// Whether to use persistent connections for http 1.1 and https
87 public $keepalive = false;
89 /// Charset encodings that can be decoded without problems by the client
90 public $accepted_charset_encodings = array();
93 * The charset encoding that will be used for serializing request sent by the client.
94 * It defaults to NULL, which means using US-ASCII and encoding all characters outside of the ASCII printable range
95 * using their xml character entity representation (this has the benefit that line end characters will not be mangled
96 * in the transfer, a CR-LF will be preserved as well as a singe LF).
97 * Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1'.
98 * For the fastest mode of operation, set your both your app internal encoding as well as this to UTF-8.
100 public $request_charset_encoding = '';
103 * Decides the content of Response objects returned by calls to send() and multicall().
104 * Valid values are 'xmlrpcvals', 'phpvals' or 'xml'.
106 * Determines whether the value returned inside an Response object as results of calls to the send() and multicall()
107 * methods will be a Value object, a plain php value or a raw xml string.
108 * Allowed values are 'xmlrpcvals' (the default), 'phpvals' and 'xml'.
109 * To allow the user to differentiate between a correct and a faulty response, fault responses will be returned as
110 * Response objects in any case.
111 * Note that the 'phpvals' setting will yield faster execution times, but some of the information from the original
112 * response will be lost. It will be e.g. impossible to tell whether a particular php string value was sent by the
113 * server as an xmlrpc string or base64 value.
115 public $return_type = XMLParser
::RETURN_XMLRPCVALS
;
118 * Sent to servers in http headers.
122 public function getLogger()
124 if (self
::$logger === null) {
125 self
::$logger = Logger
::instance();
127 return self
::$logger;
130 public static function setLogger($logger)
132 self
::$logger = $logger;
136 * @param string $path either the PATH part of the xmlrpc server URL, or complete server URL (in which case you
137 * should use and empty string for all other parameters)
138 * e.g. /xmlrpc/server.php
139 * e.g. http://phpxmlrpc.sourceforge.net/server.php
140 * e.g. https://james:bond@secret.service.com:444/xmlrpcserver?agent=007
141 * e.g. h2://fast-and-secure-services.org/endpoint
142 * @param string $server the server name / ip address
143 * @param integer $port the port the server is listening on, when omitted defaults to 80 or 443 depending on
145 * @param string $method the http protocol variant: defaults to 'http'; 'https', 'http11', 'h2' and 'h2c' can
146 * be used if CURL is installed. The value set here can be overridden in any call to $this->send().
147 * Use 'h2' to make the lib attempt to use http/2 over a secure connection, and 'h2c'
148 * for http/2 without tls. Note that 'h2c' will not use the h2c 'upgrade' method, and be
149 * thus incompatible with any server/proxy not supporting http/2. This is because POST
150 * request are not compatible with h2c upgrade.
152 public function __construct($path, $server = '', $port = '', $method = '')
154 // allow user to specify all params in $path
155 if ($server == '' && $port == '' && $method == '') {
156 $parts = parse_url($path);
157 $server = $parts['host'];
158 $path = isset($parts['path']) ?
$parts['path'] : '';
159 if (isset($parts['query'])) {
160 $path .= '?' . $parts['query'];
162 if (isset($parts['fragment'])) {
163 $path .= '#' . $parts['fragment'];
165 if (isset($parts['port'])) {
166 $port = $parts['port'];
168 if (isset($parts['scheme'])) {
169 $method = $parts['scheme'];
171 if (isset($parts['user'])) {
172 $this->username
= $parts['user'];
174 if (isset($parts['pass'])) {
175 $this->password
= $parts['pass'];
178 if ($path == '' ||
$path[0] != '/') {
179 $this->path
= '/' . $path;
183 $this->server
= $server;
188 $this->method
= $method;
191 // if ZLIB is enabled, let the client by default accept compressed responses
192 if (function_exists('gzinflate') ||
(
193 function_exists('curl_version') && (($info = curl_version()) &&
194 ((is_string($info) && strpos($info, 'zlib') !== null) ||
isset($info['libz_version'])))
197 $this->accepted_compression
= array('gzip', 'deflate');
200 // keepalives: enabled by default
201 $this->keepalive
= true;
203 // by default the xml parser can support these 3 charset encodings
204 $this->accepted_charset_encodings
= array('UTF-8', 'ISO-8859-1', 'US-ASCII');
206 // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
207 // http://www.iana.org/assignments/character-sets/character-sets.xhtml
208 // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
209 /*if (function_exists('mb_list_encodings')) {
211 $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
212 'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
213 $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
216 // initialize user_agent string
217 $this->user_agent
= PhpXmlRpc
::$xmlrpcName . ' ' . PhpXmlRpc
::$xmlrpcVersion;
221 * Enable/disable the echoing to screen of the xmlrpc responses received. The default is not no output anything.
223 * The debugging information at level 1 includes the raw data returned from the XML-RPC server it was querying
224 * (including bot HTTP headers and the full XML payload), and the PHP value the client attempts to create to
225 * represent the value returned by the server
226 * At level2, the complete payload of the xmlrpc request is also printed, before being sent t the server.
228 * This option can be very useful when debugging servers as it allows you to see exactly what the client sends and
229 * the server returns.
231 * @param integer $level values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
233 public function setDebug($level)
235 $this->debug
= $level;
239 * Sets the username and password for authorizing the client to the server.
241 * With the default (HTTP) transport, this information is used for HTTP Basic authorization.
242 * Note that username and password can also be set using the class constructor.
243 * With HTTP 1.1 and HTTPS transport, NTLM and Digest authentication protocols are also supported. To enable them use
244 * the constants CURLAUTH_DIGEST and CURLAUTH_NTLM as values for the auth type parameter.
246 * @param string $user username
247 * @param string $password password
248 * @param integer $authType auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC
249 * (basic auth). Note that auth types NTLM and Digest will only work if the Curl php
250 * extension is enabled.
252 public function setCredentials($user, $password, $authType = 1)
254 $this->username
= $user;
255 $this->password
= $password;
256 $this->authtype
= $authType;
260 * Set the optional certificate and passphrase used in SSL-enabled communication with a remote server.
262 * Note: to retrieve information about the client certificate on the server side, you will need to look into the
263 * environment variables which are set up by the webserver. Different webservers will typically set up different
266 * @param string $cert the name of a file containing a PEM formatted certificate
267 * @param string $certPass the password required to use it
269 public function setCertificate($cert, $certPass = '')
272 $this->certpass
= $certPass;
276 * Add a CA certificate to verify server with in SSL-enabled communication when SetSSLVerifypeer has been set to TRUE.
278 * See the php manual page about CURLOPT_CAINFO for more details.
280 * @param string $caCert certificate file name (or dir holding certificates)
281 * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
283 public function setCaCertificate($caCert, $isDir = false)
286 $this->cacertdir
= $caCert;
288 $this->cacert
= $caCert;
293 * Set attributes for SSL communication: private SSL key.
295 * NB: does not work in older php/curl installs.
296 * Thanks to Daniel Convissor.
298 * @param string $key The name of a file containing a private SSL key
299 * @param string $keyPass The secret password needed to use the private SSL key
301 public function setKey($key, $keyPass)
304 $this->keypass
= $keyPass;
308 * Set attributes for SSL communication: verify the remote host's SSL certificate, and cause the connection to fail
309 * if the cert verification fails.
311 * By default, verification is enabled.
312 * To specify custom SSL certificates to validate the server with, use the setCaCertificate method.
314 * @param bool $i enable/disable verification of peer certificate
316 public function setSSLVerifyPeer($i)
318 $this->verifypeer
= $i;
322 * Set attributes for SSL communication: verify the remote host's SSL certificate's common name (CN).
324 * Note that support for value 1 has been removed in cURL 7.28.1
326 * @param int $i Set to 1 to only the existence of a CN, not that it matches
328 public function setSSLVerifyHost($i)
330 $this->verifyhost
= $i;
334 * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value): let cURL decide
338 public function setSSLVersion($i)
340 $this->sslversion
= $i;
346 * NB: CURL versions before 7.11.10 cannot use a proxy to communicate with https servers.
348 * @param string $proxyHost
349 * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
350 * @param string $proxyUsername Leave blank if proxy has public access
351 * @param string $proxyPassword Leave blank if proxy has public access
352 * @param int $proxyAuthType defaults to CURLAUTH_BASIC (Basic authentication protocol); set to constant CURLAUTH_NTLM
353 * to use NTLM auth with proxy (has effect only when the client uses the HTTP 1.1 protocol)
355 public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
357 $this->proxy
= $proxyHost;
358 $this->proxyport
= $proxyPort;
359 $this->proxy_user
= $proxyUsername;
360 $this->proxy_pass
= $proxyPassword;
361 $this->proxy_authtype
= $proxyAuthType;
365 * Enables/disables reception of compressed xmlrpc responses.
367 * This requires the "zlib" extension to be enabled in your php install. If it is, by default xmlrpc_client
368 * instances will enable reception of compressed content.
369 * Note that enabling reception of compressed responses merely adds some standard http headers to xmlrpc requests.
370 * It is up to the xmlrpc server to return compressed responses when receiving such requests.
372 * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
374 public function setAcceptedCompression($compMethod)
376 if ($compMethod == 'any') {
377 $this->accepted_compression
= array('gzip', 'deflate');
378 } elseif ($compMethod == false) {
379 $this->accepted_compression
= array();
381 $this->accepted_compression
= array($compMethod);
386 * Enables/disables http compression of xmlrpc request.
388 * This requires the "zlib" extension to be enabled in your php install.
389 * Take care when sending compressed requests: servers might not support them (and automatic fallback to
390 * uncompressed requests is not yet implemented).
392 * @param string $compMethod either 'gzip', 'deflate' or ''
394 public function setRequestCompression($compMethod)
396 $this->request_compression
= $compMethod;
400 * Adds a cookie to list of cookies that will be sent to server with every further request (useful e.g. for keeping
401 * session info outside of the xml-rpc payload).
403 * NB: By default cookies are sent using the 'original/netscape' format, which is also the same as the RFC 2965;
404 * setting any param but name and value will turn the cookie into a 'version 1' cookie (i.e. RFC 2109 cookie) that
405 * might not be fully supported by the server. Note that RFC 2109 has currently 'historic' status...
407 * @param string $name nb: will not be escaped in the request's http headers. Take care not to use CTL chars or
409 * @param string $value
410 * @param string $path leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
411 * @param string $domain leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
412 * @param int $port leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
414 * @todo check correctness of urlencoding cookie value (copied from php way of doing it, but php is generally sending
415 * response not requests. We do the opposite...)
416 * @todo strip invalid chars from cookie name? As per RFC6265, we should follow RFC2616, Section 2.2
418 public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
420 $this->cookies
[$name]['value'] = rawurlencode($value);
421 if ($path ||
$domain ||
$port) {
422 $this->cookies
[$name]['path'] = $path;
423 $this->cookies
[$name]['domain'] = $domain;
424 $this->cookies
[$name]['port'] = $port;
425 $this->cookies
[$name]['version'] = 1;
427 $this->cookies
[$name]['version'] = 0;
432 * Directly set cURL options, for extra flexibility (when in cURL mode).
434 * It allows eg. to bind client to a specific IP interface / address.
436 * @param array $options
438 public function setCurlOptions($options)
440 $this->extracurlopts
= $options;
444 * @param int $useCurlMode self::USE_CURL_ALWAYS, self::USE_CURL_AUTO or self::USE_CURL_NEVER
446 public function setUseCurl($useCurlMode)
448 $this->use_curl
= $useCurlMode;
453 * Set user-agent string that will be used by this client instance in http headers sent to the server.
455 * The default user agent string includes the name of this library and the version number.
457 * @param string $agentString
459 public function setUserAgent($agentString)
461 $this->user_agent
= $agentString;
465 * Send an xmlrpc request to the server.
467 * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the
468 * complete xml representation of a request.
469 * When sending an array of Request objects, the client will try to make use of
470 * a single 'system.multicall' xml-rpc method call to forward to the server all
471 * the requests in a single HTTP round trip, unless $this->no_multicall has
472 * been previously set to TRUE (see the multicall method below), in which case
473 * many consecutive xmlrpc requests will be sent. The method will return an
474 * array of Response objects in both cases.
475 * The third variant allows to build by hand (or any other means) a complete
476 * xmlrpc request message, and send it to the server. $req should be a string
477 * containing the complete xml representation of the request. It is e.g. useful
478 * when, for maximal speed of execution, the request is serialized into a
479 * string using the native php xmlrpc functions (see http://www.php.net/xmlrpc)
480 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply.
481 * This timeout value is passed to fsockopen(). It is also used for detecting server
482 * timeouts during communication (i.e. if the server does not send anything to the client
483 * for $timeout seconds, the connection will be closed).
484 * @param string $method valid values are 'http', 'http11', 'https', 'h2' and 'h2c'. If left unspecified,
485 * the http protocol chosen during creation of the object will be used.
486 * Use 'h2' to make the lib attempt to use http/2 over a secure connection, and 'h2c'
487 * for http/2 without tls. Note that 'h2c' will not use the h2c 'upgrade' method, and be
488 * thus incompatible with any server/proxy not supporting http/2. This is because POST
489 * request are not compatible with h2c upgrade.
491 * @return Response|Response[] Note that the client will always return a Response object, even if the call fails
492 * @todo allow throwing exceptions instead of returning responses in case of failed calls and/or Fault responses
493 * @todo refactor: we now support many options besides connection timeout and http version to use. Why only privilege those?
495 public function send($req, $timeout = 0, $method = '')
497 // if user does not specify http protocol, use native method of this client
498 // (i.e. method set during call to constructor)
500 $method = $this->method
;
503 if (is_array($req)) {
504 // $req is an array of Requests
505 $r = $this->multicall($req, $timeout, $method);
508 } elseif (is_string($req)) {
509 $n = new Request('');
514 // where req is a Request
515 $req->setDebug($this->debug
);
517 /// @todo we could be smarter about this and force usage of curl in scenarios where it is both available and
518 /// needed, such as digest or ntlm auth. Do not attempt to use it for https if not present
519 $useCurl = ($this->use_curl
== self
::USE_CURL_ALWAYS
) ||
($this->use_curl
== self
::USE_CURL_AUTO
&&
520 (in_array($method, array('https', 'http11', 'h2c', 'h2'))));
523 $r = $this->sendPayloadCURL(
539 $this->proxy_authtype
,
541 $method == 'http11' ?
'http' : $method,
548 // plain 'http 1.0': default to using socket
549 $r = $this->sendPayloadSocket(
565 $this->proxy_authtype
,
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 $proxyHost
586 * @param int $proxyPort
587 * @param string $proxyUsername
588 * @param string $proxyPassword
589 * @param int $proxyAuthType
590 * @param string $method
593 protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '',
594 $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
597 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
599 return $this->sendPayloadSocket($req, $server, $port, $timeout, $username, $password, $authType, null, null,
600 null, null, $proxyHost, $proxyPort, $proxyUsername, $proxyPassword, $proxyAuthType, $method);
605 * @param Request $req
606 * @param string $server
608 * @param int $timeout
609 * @param string $username
610 * @param string $password
611 * @param int $authType
612 * @param string $cert
613 * @param string $certPass
614 * @param string $caCert
615 * @param string $caCertDir
616 * @param string $proxyHost
617 * @param int $proxyPort
618 * @param string $proxyUsername
619 * @param string $proxyPassword
620 * @param int $proxyAuthType
621 * @param bool $keepAlive
623 * @param string $keyPass
624 * @param int $sslVersion
627 protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '', $password = '',
628 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
629 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $keepAlive = false, $key = '', $keyPass = '',
632 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
634 return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
635 $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
636 $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
640 * @param Request $req
641 * @param string $server
643 * @param int $timeout
644 * @param string $username
645 * @param string $password
646 * @param int $authType only value supported is 1
647 * @param string $cert
648 * @param string $certPass
649 * @param string $caCert
650 * @param string $caCertDir
651 * @param string $proxyHost
652 * @param int $proxyPort
653 * @param string $proxyUsername
654 * @param string $proxyPassword
655 * @param int $proxyAuthType only value supported is 1
656 * @param string $method 'http' (synonym for 'http10'), 'http10' or 'https'
658 * @param string $keyPass @todo not implemented yet.
659 * @param int $sslVersion @todo not implemented yet. See http://php.net/manual/en/migration56.openssl.php
662 * @todo refactor: we get many options for the call passed in, but some we use from $this. We should clean that up
664 protected function sendPayloadSocket($req, $server, $port, $timeout = 0, $username = '', $password = '',
665 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
666 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method='http', $key = '', $keyPass = '',
669 /// @todo log a warning if passed an unsupported method
672 $port = ( $method === 'https' ) ?
443 : 80;
675 // Only create the payload if it was not created previously
676 if (empty($req->payload
)) {
677 $req->serialize($this->request_charset_encoding
);
680 $payload = $req->payload
;
681 // Deflate request body and set appropriate request headers
683 if (function_exists('gzdeflate') && ($this->request_compression
== 'gzip' ||
$this->request_compression
== 'deflate')) {
684 if ($this->request_compression
== 'gzip') {
685 $a = @gzencode
($payload);
688 $encodingHdr = "Content-Encoding: gzip\r\n";
691 $a = @gzcompress
($payload);
694 $encodingHdr = "Content-Encoding: deflate\r\n";
699 // thanks to Grant Rauscher <grant7@firstworld.net> for this
701 if ($username != '') {
702 $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
703 if ($authType != 1) {
704 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__
. ': warning. Only Basic auth is supported with HTTP 1.0');
708 $acceptedEncoding = '';
709 if (is_array($this->accepted_compression
) && count($this->accepted_compression
)) {
710 $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression
) . "\r\n";
713 $proxyCredentials = '';
715 if ($proxyPort == 0) {
718 $connectServer = $proxyHost;
719 $connectPort = $proxyPort;
721 $uri = 'http://' . $server . ':' . $port . $this->path
;
722 if ($proxyUsername != '') {
723 if ($proxyAuthType != 1) {
724 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__
. ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
726 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
729 $connectServer = $server;
730 $connectPort = $port;
731 $transport = ( $method === 'https' ) ?
'tls' : 'tcp';
735 // Cookie generation, as per rfc2965 (version 1 cookies) or netscape's rules (version 0 cookies)
737 if (count($this->cookies
)) {
739 foreach ($this->cookies
as $name => $cookie) {
740 if ($cookie['version']) {
741 $version = ' $Version="' . $cookie['version'] . '";';
742 $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
743 if ($cookie['path']) {
744 $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
746 if ($cookie['domain']) {
747 $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
749 if ($cookie['port']) {
750 $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
753 $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
756 $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
759 // omit port if default
760 if (($port == 80 && in_array($method, array('http', 'http10'))) ||
($port == 443 && $method == 'https')) {
766 $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
767 'User-Agent: ' . $this->user_agent
. "\r\n" .
768 'Host: ' . $server . $port . "\r\n" .
773 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings
) . "\r\n" .
775 'Content-Type: ' . $req->content_type
. "\r\nContent-Length: " .
776 strlen($payload) . "\r\n\r\n" .
779 if ($this->debug
> 1) {
780 $this->getLogger()->debugMessage("---SENDING---\n$op\n---END---");
783 $contextOptions = array();
784 if ($method == 'https') {
786 $contextOptions['ssl']['local_cert'] = $cert;
787 if ($certPass != '') {
788 $contextOptions['ssl']['passphrase'] = $certPass;
792 $contextOptions['ssl']['cafile'] = $caCert;
794 if ($caCertDir != '') {
795 $contextOptions['ssl']['capath'] = $caCertDir;
798 $contextOptions['ssl']['local_pk'] = $key;
800 $contextOptions['ssl']['verify_peer'] = $this->verifypeer
;
801 $contextOptions['ssl']['verify_peer_name'] = $this->verifypeer
;
804 $context = stream_context_create($contextOptions);
807 $connectTimeout = ini_get('default_socket_timeout');
809 $connectTimeout = $timeout;
815 $fp = @stream_socket_client
("$transport://$connectServer:$connectPort", $this->errno
, $this->errstr
, $connectTimeout,
816 STREAM_CLIENT_CONNECT
, $context);
819 stream_set_timeout($fp, $timeout);
822 if ($this->errstr
== '') {
823 $err = error_get_last();
824 $this->errstr
= $err['message'];
827 $this->errstr
= 'Connect error: ' . $this->errstr
;
828 $r = new Response(0, PhpXmlRpc
::$xmlrpcerr['http_error'], $this->errstr
. ' (' . $this->errno
. ')');
833 if (!fputs($fp, $op, strlen($op))) {
835 $this->errstr
= 'Write error';
836 $r = new Response(0, PhpXmlRpc
::$xmlrpcerr['http_error'], $this->errstr
);
841 // Close socket before parsing.
842 // It should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
845 // shall we check for $data === FALSE?
846 // as per the manual, it signals an error
847 $ipd .= fread($fp, 32768);
848 } while (!feof($fp));
851 $r = $req->parseResponse($ipd, false, $this->return_type
);
857 * Contributed by Justin Miller <justin@voxel.net>
858 * Requires curl to be built into PHP
859 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
861 * @param Request $req
862 * @param string $server
864 * @param int $timeout
865 * @param string $username
866 * @param string $password
867 * @param int $authType
868 * @param string $cert
869 * @param string $certPass
870 * @param string $caCert
871 * @param string $caCertDir
872 * @param string $proxyHost
873 * @param int $proxyPort
874 * @param string $proxyUsername
875 * @param string $proxyPassword
876 * @param int $proxyAuthType
877 * @param string $method 'http' (let curl decide), 'http10', 'http11', 'https', 'h2c' or 'h2'
878 * @param bool $keepAlive
880 * @param string $keyPass
881 * @param int $sslVersion
884 * @todo refactor: we get many options for the call passed in, but some we use from $this. We should clean that up
886 protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
887 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
888 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
889 $keyPass = '', $sslVersion = 0)
891 if (!function_exists('curl_init')) {
892 $this->errstr
= 'CURL unavailable on this install';
893 return new Response(0, PhpXmlRpc
::$xmlrpcerr['no_curl'], PhpXmlRpc
::$xmlrpcstr['no_curl']);
895 if ($method == 'https' ||
$method == 'h2') {
896 // q: what about installs where we get back a string, but curl is linked to other ssl libs than openssl?
897 if (($info = curl_version()) &&
898 ((is_string($info) && strpos($info, 'OpenSSL') === null) ||
(is_array($info) && !isset($info['ssl_version'])))
900 $this->errstr
= 'SSL unavailable on this install';
901 return new Response(0, PhpXmlRpc
::$xmlrpcerr['no_ssl'], PhpXmlRpc
::$xmlrpcstr['no_ssl']);
904 if (($method == 'h2' && !defined('CURL_HTTP_VERSION_2_0')) ||
905 ($method == 'h2c' && !defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE'))) {
906 $this->errstr
= 'HTTP/2 unavailable on this install';
907 return new Response(0, PhpXmlRpc
::$xmlrpcerr['no_http2'], PhpXmlRpc
::$xmlrpcstr['no_http2']);
910 $curl = $this->prepareCurlHandle($req, $server, $port, $timeout, $username, $password,
911 $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
912 $proxyUsername, $proxyPassword, $proxyAuthType, $method, $keepAlive, $key,
913 $keyPass, $sslVersion);
915 $result = curl_exec($curl);
917 if ($this->debug
> 1) {
918 $message = "---CURL INFO---\n";
919 foreach (curl_getinfo($curl) as $name => $val) {
920 if (is_array($val)) {
921 $val = implode("\n", $val);
923 $message .= $name . ': ' . $val . "\n";
925 $message .= '---END---';
926 $this->getLogger()->debugMessage($message);
930 /// @todo we should use a better check here - what if we get back '' or '0'?
932 $this->errstr
= 'no response';
933 $resp = new Response(0, PhpXmlRpc
::$xmlrpcerr['curl_fail'], PhpXmlRpc
::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
936 $this->xmlrpc_curl_handle
= null;
942 $resp = $req->parseResponse($result, true, $this->return_type
);
943 // if we got back a 302, we can not reuse the curl handle for later calls
944 if ($resp->faultCode() == PhpXmlRpc
::$xmlrpcerr['http_error'] && $keepAlive) {
946 $this->xmlrpc_curl_handle
= null;
953 protected function prepareCurlHandle($req, $server, $port, $timeout = 0, $username = '', $password = '',
954 $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
955 $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
956 $keyPass = '', $sslVersion = 0)
959 if (in_array($method, array('http', 'http10', 'http11', 'h2c'))) {
966 // Only create the payload if it was not created previously
967 if (empty($req->payload
)) {
968 $req->serialize($this->request_charset_encoding
);
971 // Deflate request body and set appropriate request headers
972 $payload = $req->payload
;
973 if (function_exists('gzdeflate') && ($this->request_compression
== 'gzip' ||
$this->request_compression
== 'deflate')) {
974 if ($this->request_compression
== 'gzip') {
975 $a = @gzencode
($payload);
978 $encodingHdr = 'Content-Encoding: gzip';
981 $a = @gzcompress
($payload);
984 $encodingHdr = 'Content-Encoding: deflate';
991 if (!$keepAlive ||
!$this->xmlrpc_curl_handle
) {
992 if ($method == 'http11' ||
$method == 'http10' ||
$method == 'h2c') {
995 if ($method == 'h2') {
1002 $curl = curl_init($protocol . '://' . $server . ':' . $port . $this->path
);
1004 $this->xmlrpc_curl_handle
= $curl;
1007 $curl = $this->xmlrpc_curl_handle
;
1010 // results into variable
1011 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, true);
1013 if ($this->debug
> 1) {
1014 curl_setopt($curl, CURLOPT_VERBOSE
, true);
1015 /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
1017 curl_setopt($curl, CURLOPT_USERAGENT
, $this->user_agent
);
1018 // required for XMLRPC: post the data
1019 curl_setopt($curl, CURLOPT_POST
, 1);
1021 curl_setopt($curl, CURLOPT_POSTFIELDS
, $payload);
1023 // return the header too
1024 curl_setopt($curl, CURLOPT_HEADER
, 1);
1026 // NB: if we set an empty string, CURL will add http header indicating
1027 // ALL methods it is supporting. This is possibly a better option than letting the user tell what curl can / cannot do...
1028 if (is_array($this->accepted_compression
) && count($this->accepted_compression
)) {
1029 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
1030 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1031 if (count($this->accepted_compression
) == 1) {
1032 curl_setopt($curl, CURLOPT_ENCODING
, $this->accepted_compression
[0]);
1034 curl_setopt($curl, CURLOPT_ENCODING
, '');
1038 $headers = array('Content-Type: ' . $req->content_type
, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings
));
1039 // if no keepalive is wanted, let the server know it in advance
1041 $headers[] = 'Connection: close';
1043 // request compression header
1045 $headers[] = $encodingHdr;
1048 // Fix the HTTP/1.1 417 Expectation Failed Bug (curl by default adds a 'Expect: 100-continue' header when POST
1049 // size exceeds 1025 bytes, apparently)
1050 $headers[] = 'Expect:';
1052 curl_setopt($curl, CURLOPT_HTTPHEADER
, $headers);
1053 // timeout is borked
1055 curl_setopt($curl, CURLOPT_TIMEOUT
, $timeout == 1 ?
1 : $timeout - 1);
1060 curl_setopt($curl, CURLOPT_HTTP_VERSION
, CURL_HTTP_VERSION_1_0
);
1063 curl_setopt($curl, CURLOPT_HTTP_VERSION
, CURL_HTTP_VERSION_1_1
);
1066 curl_setopt($curl, CURLOPT_HTTP_VERSION
, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE
);
1069 curl_setopt($curl, CURLOPT_HTTP_VERSION
, CURL_HTTP_VERSION_2_0
);
1073 if ($username && $password) {
1074 curl_setopt($curl, CURLOPT_USERPWD
, $username . ':' . $password);
1075 if (defined('CURLOPT_HTTPAUTH')) {
1076 curl_setopt($curl, CURLOPT_HTTPAUTH
, $authType);
1077 } elseif ($authType != 1) {
1078 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__
. ': warning. Only Basic auth is supported by the current PHP/curl install');
1082 if ($method == 'https' ||
$method == 'h2') {
1085 curl_setopt($curl, CURLOPT_SSLCERT
, $cert);
1087 // set cert password
1089 curl_setopt($curl, CURLOPT_SSLCERTPASSWD
, $certPass);
1091 // whether to verify remote host's cert
1092 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, $this->verifypeer
);
1093 // set ca certificates file/dir
1095 curl_setopt($curl, CURLOPT_CAINFO
, $caCert);
1098 curl_setopt($curl, CURLOPT_CAPATH
, $caCertDir);
1100 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1102 curl_setopt($curl, CURLOPT_SSLKEY
, $key);
1104 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1106 curl_setopt($curl, CURLOPT_SSLKEYPASSWD
, $keyPass);
1108 // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that
1109 // it matches the hostname used
1110 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST
, $this->verifyhost
);
1111 // allow usage of different SSL versions
1112 curl_setopt($curl, CURLOPT_SSLVERSION
, $sslVersion);
1117 if ($proxyPort == 0) {
1118 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
1120 curl_setopt($curl, CURLOPT_PROXY
, $proxyHost . ':' . $proxyPort);
1121 if ($proxyUsername) {
1122 curl_setopt($curl, CURLOPT_PROXYUSERPWD
, $proxyUsername . ':' . $proxyPassword);
1123 if (defined('CURLOPT_PROXYAUTH')) {
1124 curl_setopt($curl, CURLOPT_PROXYAUTH
, $proxyAuthType);
1125 } elseif ($proxyAuthType != 1) {
1126 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__
. ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1131 // NB: should we build cookie http headers by hand rather than let CURL do it?
1132 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes set to client obj the the user...
1133 if (count($this->cookies
)) {
1135 foreach ($this->cookies
as $name => $cookie) {
1136 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
1138 curl_setopt($curl, CURLOPT_COOKIE
, substr($cookieHeader, 0, -2));
1141 foreach ($this->extracurlopts
as $opt => $val) {
1142 curl_setopt($curl, $opt, $val);
1145 if ($this->debug
> 1) {
1146 $this->getLogger()->debugMessage("---SENDING---\n$payload\n---END---");
1153 * Send an array of requests and return an array of responses.
1155 * Unless $this->no_multicall has been set to true, it will try first to use one single xmlrpc call to server method
1156 * system.multicall, and revert to sending many successive calls in case of failure.
1157 * This failure is also stored in $this->no_multicall for subsequent calls.
1158 * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported,
1159 * so there is no way to reliably distinguish between that and a temporary failure.
1160 * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the
1161 * fourth parameter to FALSE.
1163 * NB: trying to shoehorn extra functionality into existing syntax has resulted
1164 * in pretty much convoluted code...
1166 * @param Request[] $reqs an array of Request objects
1167 * @param integer $timeout connection timeout (in seconds). See the details in the docs for the send() method
1168 * @param string $method the http protocol variant to be used. See the details in the docs for the send() method
1169 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be
1172 * @return Response[]
1174 public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
1176 if ($method == '') {
1177 $method = $this->method
;
1179 if (!$this->no_multicall
) {
1180 $results = $this->_try_multicall($reqs, $timeout, $method);
1181 if (is_array($results)) {
1182 // System.multicall succeeded
1185 // either system.multicall is unsupported by server,
1186 // or call failed for some other reason.
1188 // Don't try it next time...
1189 $this->no_multicall
= true;
1191 if (is_a($results, '\PhpXmlRpc\Response')) {
1194 $result = new Response(0, PhpXmlRpc
::$xmlrpcerr['multicall_error'], PhpXmlRpc
::$xmlrpcstr['multicall_error']);
1199 // override fallback, in case careless user tries to do two
1200 // opposite things at the same time
1206 // system.multicall is (probably) unsupported by server:
1207 // emulate multicall via multiple requests
1208 /// @todo use curl multi_ functions to make this quicker
1209 foreach ($reqs as $req) {
1210 $results[] = $this->send($req, $timeout, $method);
1213 // user does NOT want to fallback on many single calls:
1214 // since we should always return an array of responses,
1215 // return an array with the same error repeated n times
1216 foreach ($reqs as $req) {
1217 $results[] = $result;
1225 * Attempt to boxcar $reqs via system.multicall.
1227 * Returns either an array of Response, a single error Response or false (when received response does not respect
1228 * valid multicall syntax).
1230 * @param Request[] $reqs
1231 * @param int $timeout
1232 * @param string $method
1233 * @return Response[]|false|mixed|Response
1235 private function _try_multicall($reqs, $timeout, $method)
1237 // Construct multicall request
1239 foreach ($reqs as $req) {
1240 $call['methodName'] = new Value($req->method(), 'string');
1241 $numParams = $req->getNumParams();
1243 for ($i = 0; $i < $numParams; $i++
) {
1244 $params[$i] = $req->getParam($i);
1246 $call['params'] = new Value($params, 'array');
1247 $calls[] = new Value($call, 'struct');
1249 $multiCall = new Request('system.multicall');
1250 $multiCall->addParam(new Value($calls, 'array'));
1253 $result = $this->send($multiCall, $timeout, $method);
1255 if ($result->faultCode() != 0) {
1256 // call to system.multicall failed
1260 // Unpack responses.
1261 $rets = $result->value();
1263 if ($this->return_type
== 'xml') {
1265 } elseif ($this->return_type
== 'phpvals') {
1266 /// @todo test this code branch...
1267 $rets = $result->value();
1268 if (!is_array($rets)) {
1269 return false; // bad return type from system.multicall
1271 $numRets = count($rets);
1272 if ($numRets != count($reqs)) {
1273 return false; // wrong number of return values.
1276 $response = array();
1277 for ($i = 0; $i < $numRets; $i++
) {
1279 if (!is_array($val)) {
1282 switch (count($val)) {
1284 if (!isset($val[0])) {
1285 return false; // Bad value
1287 // Normal return value
1288 $response[$i] = new Response($val[0], 0, '', 'phpvals');
1291 /// @todo remove usage of @: it is apparently quite slow
1292 $code = @$val['faultCode'];
1293 if (!is_int($code)) {
1296 $str = @$val['faultString'];
1297 if (!is_string($str)) {
1300 $response[$i] = new Response(0, $code, $str);
1309 // return type == 'xmlrpcvals'
1311 $rets = $result->value();
1312 if ($rets->kindOf() != 'array') {
1313 return false; // bad return type from system.multicall
1315 $numRets = $rets->count();
1316 if ($numRets != count($reqs)) {
1317 return false; // wrong number of return values.
1320 $response = array();
1321 foreach($rets as $val) {
1322 switch ($val->kindOf()) {
1324 if ($val->count() != 1) {
1325 return false; // Bad value
1327 // Normal return value
1328 $response[] = new Response($val[0]);
1331 $code = $val['faultCode'];
1332 /** @var Value $code */
1333 if ($code->kindOf() != 'scalar' ||
$code->scalartyp() != 'int') {
1336 $str = $val['faultString'];
1337 /** @var Value $str */
1338 if ($str->kindOf() != 'scalar' ||
$str->scalartyp() != 'string') {
1341 $response[] = new Response(0, $code->scalarval(), $str->scalarval());