nitpicks; prepare for release
[plcapi.git] / src / Client.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\Logger;
6
7 /**
8  * Used to represent a client of an XML-RPC server.
9  */
10 class Client
11 {
12     const USE_CURL_NEVER = 0;
13     const USE_CURL_ALWAYS = 1;
14     const USE_CURL_AUTO = 2;
15
16     /// @todo: do these need to be public?
17     public $method = 'http';
18     public $server;
19     public $port = 0;
20     public $path;
21
22     public $errno;
23     public $errstr;
24     public $debug = 0;
25
26     public $username = '';
27     public $password = '';
28     public $authtype = 1;
29
30     public $cert = '';
31     public $certpass = '';
32     public $cacert = '';
33     public $cacertdir = '';
34     public $key = '';
35     public $keypass = '';
36     public $verifypeer = true;
37     public $verifyhost = 2;
38     public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
39
40     public $proxy = '';
41     public $proxyport = 0;
42     public $proxy_user = '';
43     public $proxy_pass = '';
44     public $proxy_authtype = 1;
45
46     public $cookies = array();
47     public $extracurlopts = array();
48     public $use_curl = self::USE_CURL_AUTO;
49
50     /**
51      * @var bool
52      *
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
56      * system.multicall.
57      */
58     public $no_multicall = false;
59
60     /**
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.
63      *
64      * 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
65      * decide the compression methods it supports. You might check for the presence of 'zlib' in the output of
66      * curl_version() to determine whether compression is supported or not
67      */
68     public $accepted_compression = array();
69
70     /**
71      * Name of compression scheme to be used for sending requests.
72      * Either null, gzip or deflate.
73      */
74     public $request_compression = '';
75
76     /**
77      * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
78      * http://curl.haxx.se/docs/faq.html#7.3).
79      * @internal
80      */
81     public $xmlrpc_curl_handle = null;
82
83     /// Whether to use persistent connections for http 1.1 and https
84     public $keepalive = false;
85
86     /// Charset encodings that can be decoded without problems by the client
87     public $accepted_charset_encodings = array();
88
89     /**
90      * The charset encoding that will be used for serializing request sent by the client.
91      * It defaults to NULL, which means using US-ASCII and encoding all characters outside of the ASCII range using
92      * their xml character entity representation (this has the benefit that line end characters will not be mangled in
93      * the transfer, a CR-LF will be preserved as well as a singe LF).
94      * Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1'
95      */
96     public $request_charset_encoding = '';
97
98     /**
99      * Decides the content of Response objects returned by calls to send() and multicall().
100      * Valid values are 'xmlrpcvals', 'phpvals' or 'xml'.
101      *
102      * Determines whether the value returned inside an Response object as results of calls to the send() and multicall()
103      * methods will be a Value object, a plain php value or a raw xml string.
104      * Allowed values are 'xmlrpcvals' (the default), 'phpvals' and 'xml'.
105      * To allow the user to differentiate between a correct and a faulty response, fault responses will be returned as
106      * Response objects in any case.
107      * Note that the 'phpvals' setting will yield faster execution times, but some of the information from the original
108      * response will be lost. It will be e.g. impossible to tell whether a particular php string value was sent by the
109      * server as an xmlrpc string or base64 value.
110      */
111     public $return_type = 'xmlrpcvals';
112
113     /**
114      * Sent to servers in http headers.
115      */
116     public $user_agent;
117
118     /**
119      * @param string $path either the PATH part of the xmlrpc server URL, or complete server URL (in which case you
120      *                     should use and empty string for all other parameters)
121      *                     e.g. /xmlrpc/server.php
122      *                     e.g. http://phpxmlrpc.sourceforge.net/server.php
123      *                     e.g. https://james:bond@secret.service.com:443/xmlrpcserver?agent=007
124      * @param string $server the server name / ip address
125      * @param integer $port the port the server is listening on, when omitted defaults to 80 or 443 depending on
126      *                      protocol used
127      * @param string $method the http protocol variant: defaults to 'http'; 'https' and 'http11' can be used if CURL is
128      *                       installed. The value set here can be overridden in any call to $this->send().
129      */
130     public function __construct($path, $server = '', $port = '', $method = '')
131     {
132         // allow user to specify all params in $path
133         if ($server == '' && $port == '' && $method == '') {
134             $parts = parse_url($path);
135             $server = $parts['host'];
136             $path = isset($parts['path']) ? $parts['path'] : '';
137             if (isset($parts['query'])) {
138                 $path .= '?' . $parts['query'];
139             }
140             if (isset($parts['fragment'])) {
141                 $path .= '#' . $parts['fragment'];
142             }
143             if (isset($parts['port'])) {
144                 $port = $parts['port'];
145             }
146             if (isset($parts['scheme'])) {
147                 $method = $parts['scheme'];
148             }
149             if (isset($parts['user'])) {
150                 $this->username = $parts['user'];
151             }
152             if (isset($parts['pass'])) {
153                 $this->password = $parts['pass'];
154             }
155         }
156         if ($path == '' || $path[0] != '/') {
157             $this->path = '/' . $path;
158         } else {
159             $this->path = $path;
160         }
161         $this->server = $server;
162         if ($port != '') {
163             $this->port = $port;
164         }
165         if ($method != '') {
166             $this->method = $method;
167         }
168
169         // if ZLIB is enabled, let the client by default accept compressed responses
170         if (function_exists('gzinflate') || (
171                 function_exists('curl_version') && (($info = curl_version()) &&
172                     ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
173             )
174         ) {
175             $this->accepted_compression = array('gzip', 'deflate');
176         }
177
178         // keepalives: enabled by default
179         $this->keepalive = true;
180
181         // by default the xml parser can support these 3 charset encodings
182         $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
183
184         // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
185         // http://www.iana.org/assignments/character-sets/character-sets.xhtml
186         // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
187         /*if (function_exists('mb_list_encodings')) {
188
189             $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
190                 'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
191             $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
192         }*/
193
194         // initialize user_agent string
195         $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
196     }
197
198     /**
199      * Enable/disable the echoing to screen of the xmlrpc responses received. The default is not no output anything.
200      *
201      * The debugging information at level 1 includes the raw data returned from the XML-RPC server it was querying
202      * (including bot HTTP headers and the full XML payload), and the PHP value the client attempts to create to
203      * represent the value returned by the server
204      * At level2, the complete payload of the xmlrpc request is also printed, before being sent t the server.
205      *
206      * This option can be very useful when debugging servers as it allows you to see exactly what the client sends and
207      * the server returns.
208      *
209      * @param integer $level values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
210      */
211     public function setDebug($level)
212     {
213         $this->debug = $level;
214     }
215
216     /**
217      * Sets the username and password for authorizing the client to the server.
218      *
219      * With the default (HTTP) transport, this information is used for HTTP Basic authorization.
220      * Note that username and password can also be set using the class constructor.
221      * With HTTP 1.1 and HTTPS transport, NTLM and Digest authentication protocols are also supported. To enable them use
222      * the constants CURLAUTH_DIGEST and CURLAUTH_NTLM as values for the auth type parameter.
223      *
224      * @param string $user username
225      * @param string $password password
226      * @param integer $authType auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC
227      *                          (basic auth). Note that auth types NTLM and Digest will only work if the Curl php
228      *                          extension is enabled.
229      */
230     public function setCredentials($user, $password, $authType = 1)
231     {
232         $this->username = $user;
233         $this->password = $password;
234         $this->authtype = $authType;
235     }
236
237     /**
238      * Set the optional certificate and passphrase used in SSL-enabled communication with a remote server.
239      *
240      * Note: to retrieve information about the client certificate on the server side, you will need to look into the
241      * environment variables which are set up by the webserver. Different webservers will typically set up different
242      * variables.
243      *
244      * @param string $cert the name of a file containing a PEM formatted certificate
245      * @param string $certPass the password required to use it
246      */
247     public function setCertificate($cert, $certPass = '')
248     {
249         $this->cert = $cert;
250         $this->certpass = $certPass;
251     }
252
253     /**
254      * Add a CA certificate to verify server with in SSL-enabled communication when SetSSLVerifypeer has been set to TRUE.
255      *
256      * See the php manual page about CURLOPT_CAINFO for more details.
257      *
258      * @param string $caCert certificate file name (or dir holding certificates)
259      * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
260      */
261     public function setCaCertificate($caCert, $isDir = false)
262     {
263         if ($isDir) {
264             $this->cacertdir = $caCert;
265         } else {
266             $this->cacert = $caCert;
267         }
268     }
269
270     /**
271      * Set attributes for SSL communication: private SSL key.
272      *
273      * NB: does not work in older php/curl installs.
274      * Thanks to Daniel Convissor.
275      *
276      * @param string $key The name of a file containing a private SSL key
277      * @param string $keyPass The secret password needed to use the private SSL key
278      */
279     public function setKey($key, $keyPass)
280     {
281         $this->key = $key;
282         $this->keypass = $keyPass;
283     }
284
285     /**
286      * Set attributes for SSL communication: verify the remote host's SSL certificate, and cause the connection to fail
287      * if the cert verification fails.
288      *
289      * By default, verification is enabled.
290      * To specify custom SSL certificates to validate the server with, use the setCaCertificate method.
291      *
292      * @param bool $i enable/disable verification of peer certificate
293      */
294     public function setSSLVerifyPeer($i)
295     {
296         $this->verifypeer = $i;
297     }
298
299     /**
300      * Set attributes for SSL communication: verify the remote host's SSL certificate's common name (CN).
301      *
302      * Note that support for value 1 has been removed in cURL 7.28.1
303      *
304      * @param int $i Set to 1 to only the existence of a CN, not that it matches
305      */
306     public function setSSLVerifyHost($i)
307     {
308         $this->verifyhost = $i;
309     }
310
311     /**
312      * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide
313      *
314      * @param int $i
315      */
316     public function setSSLVersion($i)
317     {
318         $this->sslversion = $i;
319     }
320
321     /**
322      * Set proxy info.
323      *
324      * NB: CURL versions before 7.11.10 cannot use a proxy to communicate with https servers.
325      *
326      * @param string $proxyHost
327      * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
328      * @param string $proxyUsername Leave blank if proxy has public access
329      * @param string $proxyPassword Leave blank if proxy has public access
330      * @param int $proxyAuthType defaults to CURLAUTH_BASIC (Basic authentication protocol); set to constant CURLAUTH_NTLM
331      *                           to use NTLM auth with proxy (has effect only when the client uses the HTTP 1.1 protocol)
332      */
333     public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
334     {
335         $this->proxy = $proxyHost;
336         $this->proxyport = $proxyPort;
337         $this->proxy_user = $proxyUsername;
338         $this->proxy_pass = $proxyPassword;
339         $this->proxy_authtype = $proxyAuthType;
340     }
341
342     /**
343      * Enables/disables reception of compressed xmlrpc responses.
344      *
345      * This requires the "zlib" extension to be enabled in your php install. If it is, by default xmlrpc_client
346      * instances will enable reception of compressed content.
347      * Note that enabling reception of compressed responses merely adds some standard http headers to xmlrpc requests.
348      * It is up to the xmlrpc server to return compressed responses when receiving such requests.
349      *
350      * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
351      */
352     public function setAcceptedCompression($compMethod)
353     {
354         if ($compMethod == 'any') {
355             $this->accepted_compression = array('gzip', 'deflate');
356         } elseif ($compMethod == false) {
357             $this->accepted_compression = array();
358         } else {
359             $this->accepted_compression = array($compMethod);
360         }
361     }
362
363     /**
364      * Enables/disables http compression of xmlrpc request.
365      *
366      * This requires the "zlib" extension to be enabled in your php install.
367      * Take care when sending compressed requests: servers might not support them (and automatic fallback to
368      * uncompressed requests is not yet implemented).
369      *
370      * @param string $compMethod either 'gzip', 'deflate' or ''
371      */
372     public function setRequestCompression($compMethod)
373     {
374         $this->request_compression = $compMethod;
375     }
376
377     /**
378      * Adds a cookie to list of cookies that will be sent to server with every further request (useful e.g. for keeping
379      * session info outside of the xml-rpc payload).
380      *
381      * NB: By default cookies are sent using the 'original/netscape' format, which is also the same as the RFC 2965;
382      * setting any param but name and value will turn the cookie into a 'version 1' cookie (i.e. RFC 2109 cookie) that
383      * might not be fully supported by the server. Note that RFC 2109 has currently 'historic' status...
384      *
385      * @param string $name nb: will not be escaped in the request's http headers. Take care not to use CTL chars or
386      *                     separators!
387      * @param string $value
388      * @param string $path leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
389      * @param string $domain leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
390      * @param int $port leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
391      *
392      * @todo check correctness of urlencoding cookie value (copied from php way of doing it, but php is generally sending
393      *       response not requests. We do the opposite...)
394      * @todo strip invalid chars from cookie name? As per RFC6265, we should follow RFC2616, Section 2.2
395      */
396     public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
397     {
398         $this->cookies[$name]['value'] = rawurlencode($value);
399         if ($path || $domain || $port) {
400             $this->cookies[$name]['path'] = $path;
401             $this->cookies[$name]['domain'] = $domain;
402             $this->cookies[$name]['port'] = $port;
403             $this->cookies[$name]['version'] = 1;
404         } else {
405             $this->cookies[$name]['version'] = 0;
406         }
407     }
408
409     /**
410      * Directly set cURL options, for extra flexibility (when in cURL mode).
411      *
412      * It allows eg. to bind client to a specific IP interface / address.
413      *
414      * @param array $options
415      */
416     public function setCurlOptions($options)
417     {
418         $this->extracurlopts = $options;
419     }
420
421     /**
422      * @param int $useCurlMode self::USE_CURL_ALWAYS, self::USE_CURL_AUTO or self::USE_CURL_NEVER
423      */
424     public function setUseCurl($useCurlMode)
425     {
426         $this->use_curl = $useCurlMode;
427     }
428
429
430     /**
431      * Set user-agent string that will be used by this client instance in http headers sent to the server.
432      *
433      * The default user agent string includes the name of this library and the version number.
434      *
435      * @param string $agentString
436      */
437     public function setUserAgent($agentString)
438     {
439         $this->user_agent = $agentString;
440     }
441
442     /**
443      * Send an xmlrpc request to the server.
444      *
445      * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the
446      *                                      complete xml representation of a request.
447      *                                      When sending an array of Request objects, the client will try to make use of
448      *                                      a single 'system.multicall' xml-rpc method call to forward to the server all
449      *                                      the requests in a single HTTP round trip, unless $this->no_multicall has
450      *                                      been previously set to TRUE (see the multicall method below), in which case
451      *                                      many consecutive xmlrpc requests will be sent. The method will return an
452      *                                      array of Response objects in both cases.
453      *                                      The third variant allows to build by hand (or any other means) a complete
454      *                                      xmlrpc request message, and send it to the server. $req should be a string
455      *                                      containing the complete xml representation of the request. It is e.g. useful
456      *                                      when, for maximal speed of execution, the request is serialized into a
457      *                                      string using the native php xmlrpc functions (see http://www.php.net/xmlrpc)
458      * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply.
459      *                         This timeout value is passed to fsockopen(). It is also used for detecting server
460      *                         timeouts during communication (i.e. if the server does not send anything to the client
461      *                         for $timeout seconds, the connection will be closed).
462      * @param string $method valid values are 'http', 'http11' and 'https'. If left unspecified, the http protocol
463      *                       chosen during creation of the object will be used.
464      *
465      * @return Response|Response[] Note that the client will always return a Response object, even if the call fails
466      * @todo allow throwing exceptions instead of returning responses in case of failed calls and/or Fault responses
467      */
468     public function send($req, $timeout = 0, $method = '')
469     {
470         // if user does not specify http protocol, use native method of this client
471         // (i.e. method set during call to constructor)
472         if ($method == '') {
473             $method = $this->method;
474         }
475
476         if (is_array($req)) {
477             // $req is an array of Requests
478             $r = $this->multicall($req, $timeout, $method);
479
480             return $r;
481         } elseif (is_string($req)) {
482             $n = new Request('');
483             $n->payload = $req;
484             $req = $n;
485         }
486
487         // where req is a Request
488         $req->setDebug($this->debug);
489
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'));
494
495         if ($useCurl) {
496             $r = $this->sendPayloadCURL(
497                 $req,
498                 $this->server,
499                 $this->port,
500                 $timeout,
501                 $this->username,
502                 $this->password,
503                 $this->authtype,
504                 $this->cert,
505                 $this->certpass,
506                 $this->cacert,
507                 $this->cacertdir,
508                 $this->proxy,
509                 $this->proxyport,
510                 $this->proxy_user,
511                 $this->proxy_pass,
512                 $this->proxy_authtype,
513                 // bc
514                 $method == 'http11' ? 'http' : $method,
515                 $this->keepalive,
516                 $this->key,
517                 $this->keypass,
518                 $this->sslversion
519             );
520         } else {
521             // plain 'http 1.0': default to using socket
522             $r = $this->sendPayloadSocket(
523                 $req,
524                 $this->server,
525                 $this->port,
526                 $timeout,
527                 $this->username,
528                 $this->password,
529                 $this->authtype,
530                 $this->cert,
531                 $this->certpass,
532                 $this->cacert,
533                 $this->cacertdir,
534                 $this->proxy,
535                 $this->proxyport,
536                 $this->proxy_user,
537                 $this->proxy_pass,
538                 $this->proxy_authtype,
539                 $method,
540                 $this->key,
541                 $this->keypass,
542                 $this->sslversion
543             );
544         }
545
546         return $r;
547     }
548
549     /**
550      * @deprecated
551      * @param Request $req
552      * @param string $server
553      * @param int $port
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
564      * @return Response
565      */
566     protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '',
567         $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
568         $method='http')
569     {
570         //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
571
572         return $this->sendPayloadSocket($req, $server, $port, $timeout, $username, $password, $authType, null, null,
573             null, null, $proxyHost, $proxyPort, $proxyUsername, $proxyPassword, $proxyAuthType, $method);
574     }
575
576     /**
577      * @deprecated
578      * @param Request $req
579      * @param string $server
580      * @param int $port
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
595      * @param string $key
596      * @param string $keyPass
597      * @param int $sslVersion
598      * @return Response
599      */
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 = '',
603         $sslVersion = 0)
604     {
605         //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
606
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);
610     }
611
612     /**
613      * @param Request $req
614      * @param string $server
615      * @param int $port
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'
630      * @param string $key
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
633      * @return Response
634      */
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 = '',
638         $sslVersion = 0)
639     {
640         if ($port == 0) {
641             $port = ( $method === 'https' ) ? 443 : 80;
642         }
643
644         // Only create the payload if it was not created previously
645         if (empty($req->payload)) {
646             $req->createPayload($this->request_charset_encoding);
647         }
648
649         $payload = $req->payload;
650         // Deflate request body and set appropriate request headers
651         $encodingHdr = '';
652         if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
653             if ($this->request_compression == 'gzip') {
654                 $a = @gzencode($payload);
655                 if ($a) {
656                     $payload = $a;
657                     $encodingHdr = "Content-Encoding: gzip\r\n";
658                 }
659             } else {
660                 $a = @gzcompress($payload);
661                 if ($a) {
662                     $payload = $a;
663                     $encodingHdr = "Content-Encoding: deflate\r\n";
664                 }
665             }
666         }
667
668         // thanks to Grant Rauscher <grant7@firstworld.net> for this
669         $credentials = '';
670         if ($username != '') {
671             $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
672             if ($authType != 1) {
673                 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
674             }
675         }
676
677         $acceptedEncoding = '';
678         if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
679             $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
680         }
681
682         $proxyCredentials = '';
683         if ($proxyHost) {
684             if ($proxyPort == 0) {
685                 $proxyPort = 8080;
686             }
687             $connectServer = $proxyHost;
688             $connectPort = $proxyPort;
689             $transport = 'tcp';
690             $uri = 'http://' . $server . ':' . $port . $this->path;
691             if ($proxyUsername != '') {
692                 if ($proxyAuthType != 1) {
693                     Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
694                 }
695                 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
696             }
697         } else {
698             $connectServer = $server;
699             $connectPort = $port;
700             $transport = ( $method === 'https' ) ? 'tls' : 'tcp';
701             $uri = $this->path;
702         }
703
704         // Cookie generation, as per rfc2965 (version 1 cookies) or netscape's rules (version 0 cookies)
705         $cookieHeader = '';
706         if (count($this->cookies)) {
707             $version = '';
708             foreach ($this->cookies as $name => $cookie) {
709                 if ($cookie['version']) {
710                     $version = ' $Version="' . $cookie['version'] . '";';
711                     $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
712                     if ($cookie['path']) {
713                         $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
714                     }
715                     if ($cookie['domain']) {
716                         $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
717                     }
718                     if ($cookie['port']) {
719                         $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
720                     }
721                 } else {
722                     $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
723                 }
724             }
725             $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
726         }
727
728         // omit port if default
729         if (($port == 80 && in_array($method, array('http', 'http10'))) || ($port == 443 && $method == 'https')) {
730             $port =  '';
731         } else {
732             $port = ':' . $port;
733         }
734
735         $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
736             'User-Agent: ' . $this->user_agent . "\r\n" .
737             'Host: ' . $server . $port . "\r\n" .
738             $credentials .
739             $proxyCredentials .
740             $acceptedEncoding .
741             $encodingHdr .
742             'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
743             $cookieHeader .
744             'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
745             strlen($payload) . "\r\n\r\n" .
746             $payload;
747
748         if ($this->debug > 1) {
749             Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
750         }
751
752         $contextOptions = array();
753         if ($method == 'https') {
754             if ($cert != '') {
755                 $contextOptions['ssl']['local_cert'] = $cert;
756                 if ($certPass != '') {
757                     $contextOptions['ssl']['passphrase'] = $certPass;
758                 }
759             }
760             if ($caCert != '') {
761                 $contextOptions['ssl']['cafile'] = $caCert;
762             }
763             if ($caCertDir != '') {
764                 $contextOptions['ssl']['capath'] = $caCertDir;
765             }
766             if ($key != '') {
767                 $contextOptions['ssl']['local_pk'] = $key;
768             }
769             $contextOptions['ssl']['verify_peer'] = $this->verifypeer;
770             $contextOptions['ssl']['verify_peer_name'] = $this->verifypeer;
771         }
772         $context = stream_context_create($contextOptions);
773
774         if ($timeout <= 0) {
775             $connectTimeout = ini_get('default_socket_timeout');
776         } else {
777             $connectTimeout = $timeout;
778         }
779
780         $this->errno = 0;
781         $this->errstr = '';
782
783         $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $connectTimeout,
784             STREAM_CLIENT_CONNECT, $context);
785         if ($fp) {
786             if ($timeout > 0) {
787                 stream_set_timeout($fp, $timeout);
788             }
789         } else {
790             if ($this->errstr == '') {
791                 $err = error_get_last();
792                 $this->errstr = $err['message'];
793             }
794             $this->errstr = 'Connect error: ' . $this->errstr;
795             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
796
797             return $r;
798         }
799
800         if (!fputs($fp, $op, strlen($op))) {
801             fclose($fp);
802             $this->errstr = 'Write error';
803             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
804
805             return $r;
806         }
807
808         // Close socket before parsing.
809         // It should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
810         $ipd = '';
811         do {
812             // shall we check for $data === FALSE?
813             // as per the manual, it signals an error
814             $ipd .= fread($fp, 32768);
815         } while (!feof($fp));
816         fclose($fp);
817
818         $r = $req->parseResponse($ipd, false, $this->return_type);
819
820         return $r;
821     }
822
823     /**
824      * Contributed by Justin Miller <justin@voxel.net>
825      * Requires curl to be built into PHP
826      * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
827      *
828      * @param Request $req
829      * @param string $server
830      * @param int $port
831      * @param int $timeout
832      * @param string $username
833      * @param string $password
834      * @param int $authType
835      * @param string $cert
836      * @param string $certPass
837      * @param string $caCert
838      * @param string $caCertDir
839      * @param string $proxyHost
840      * @param int $proxyPort
841      * @param string $proxyUsername
842      * @param string $proxyPassword
843      * @param int $proxyAuthType
844      * @param string $method 'http' (let curl decide), 'http10', 'http11' or 'https'
845      * @param bool $keepAlive
846      * @param string $key
847      * @param string $keyPass
848      * @param int $sslVersion
849      * @return Response
850      */
851     protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
852         $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
853         $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
854         $keyPass = '', $sslVersion = 0)
855     {
856         if (!function_exists('curl_init')) {
857             $this->errstr = 'CURL unavailable on this install';
858             return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
859         }
860         if ($method == 'https') {
861             if (($info = curl_version()) &&
862                 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
863             ) {
864                 $this->errstr = 'SSL unavailable on this install';
865                 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
866             }
867         }
868
869         if ($port == 0) {
870             if (in_array($method, array('http', 'http10', 'http11'))) {
871                 $port = 80;
872             } else {
873                 $port = 443;
874             }
875         }
876
877         // Only create the payload if it was not created previously
878         if (empty($req->payload)) {
879             $req->createPayload($this->request_charset_encoding);
880         }
881
882         // Deflate request body and set appropriate request headers
883         $payload = $req->payload;
884         if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
885             if ($this->request_compression == 'gzip') {
886                 $a = @gzencode($payload);
887                 if ($a) {
888                     $payload = $a;
889                     $encodingHdr = 'Content-Encoding: gzip';
890                 }
891             } else {
892                 $a = @gzcompress($payload);
893                 if ($a) {
894                     $payload = $a;
895                     $encodingHdr = 'Content-Encoding: deflate';
896                 }
897             }
898         } else {
899             $encodingHdr = '';
900         }
901
902         if ($this->debug > 1) {
903             Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
904         }
905
906         if (!$keepAlive || !$this->xmlrpc_curl_handle) {
907             if ($method == 'http11' || $method == 'http10') {
908                 $protocol = 'http';
909             } else {
910                 $protocol = $method;
911             }
912             $curl = curl_init($protocol . '://' . $server . ':' . $port . $this->path);
913             if ($keepAlive) {
914                 $this->xmlrpc_curl_handle = $curl;
915             }
916         } else {
917             $curl = $this->xmlrpc_curl_handle;
918         }
919
920         // results into variable
921         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
922
923         if ($this->debug > 1) {
924             curl_setopt($curl, CURLOPT_VERBOSE, true);
925             /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
926         }
927         curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
928         // required for XMLRPC: post the data
929         curl_setopt($curl, CURLOPT_POST, 1);
930         // the data
931         curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
932
933         // return the header too
934         curl_setopt($curl, CURLOPT_HEADER, 1);
935
936         // NB: if we set an empty string, CURL will add http header indicating
937         // ALL methods it is supporting. This is possibly a better option than letting the user tell what curl can / cannot do...
938         if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
939             //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
940             // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
941             if (count($this->accepted_compression) == 1) {
942                 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
943             } else {
944                 curl_setopt($curl, CURLOPT_ENCODING, '');
945             }
946         }
947         // extra headers
948         $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
949         // if no keepalive is wanted, let the server know it in advance
950         if (!$keepAlive) {
951             $headers[] = 'Connection: close';
952         }
953         // request compression header
954         if ($encodingHdr) {
955             $headers[] = $encodingHdr;
956         }
957
958         // Fix the HTTP/1.1 417 Expectation Failed Bug (curl by default adds a 'Expect: 100-continue' header when POST
959         // size exceeds 1025 bytes, apparently)
960         $headers[] = 'Expect:';
961
962         curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
963         // timeout is borked
964         if ($timeout) {
965             curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
966         }
967
968         if ($method == 'http10') {
969             curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
970         } elseif ($method == 'http11') {
971             curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
972         }
973
974         if ($username && $password) {
975             curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
976             if (defined('CURLOPT_HTTPAUTH')) {
977                 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
978             } elseif ($authType != 1) {
979                 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
980             }
981         }
982
983         if ($method == 'https') {
984             // set cert file
985             if ($cert) {
986                 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
987             }
988             // set cert password
989             if ($certPass) {
990                 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
991             }
992             // whether to verify remote host's cert
993             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
994             // set ca certificates file/dir
995             if ($caCert) {
996                 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
997             }
998             if ($caCertDir) {
999                 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
1000             }
1001             // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1002             if ($key) {
1003                 curl_setopt($curl, CURLOPT_SSLKEY, $key);
1004             }
1005             // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1006             if ($keyPass) {
1007                 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
1008             }
1009             // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that
1010             // it matches the hostname used
1011             curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
1012             // allow usage of different SSL versions
1013             curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
1014         }
1015
1016         // proxy info
1017         if ($proxyHost) {
1018             if ($proxyPort == 0) {
1019                 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
1020             }
1021             curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
1022             if ($proxyUsername) {
1023                 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
1024                 if (defined('CURLOPT_PROXYAUTH')) {
1025                     curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
1026                 } elseif ($proxyAuthType != 1) {
1027                     Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1028                 }
1029             }
1030         }
1031
1032         // NB: should we build cookie http headers by hand rather than let CURL do it?
1033         // the following code does not honour 'expires', 'path' and 'domain' cookie attributes set to client obj the the user...
1034         if (count($this->cookies)) {
1035             $cookieHeader = '';
1036             foreach ($this->cookies as $name => $cookie) {
1037                 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
1038             }
1039             curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
1040         }
1041
1042         foreach ($this->extracurlopts as $opt => $val) {
1043             curl_setopt($curl, $opt, $val);
1044         }
1045
1046         $result = curl_exec($curl);
1047
1048         if ($this->debug > 1) {
1049             $message = "---CURL INFO---\n";
1050             foreach (curl_getinfo($curl) as $name => $val) {
1051                 if (is_array($val)) {
1052                     $val = implode("\n", $val);
1053                 }
1054                 $message .= $name . ': ' . $val . "\n";
1055             }
1056             $message .= '---END---';
1057             Logger::instance()->debugMessage($message);
1058         }
1059
1060         if (!$result) {
1061             /// @todo we should use a better check here - what if we get back '' or '0'?
1062
1063             $this->errstr = 'no response';
1064             $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
1065             curl_close($curl);
1066             if ($keepAlive) {
1067                 $this->xmlrpc_curl_handle = null;
1068             }
1069         } else {
1070             if (!$keepAlive) {
1071                 curl_close($curl);
1072             }
1073             $resp = $req->parseResponse($result, true, $this->return_type);
1074             // if we got back a 302, we can not reuse the curl handle for later calls
1075             if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
1076                 curl_close($curl);
1077                 $this->xmlrpc_curl_handle = null;
1078             }
1079         }
1080
1081         return $resp;
1082     }
1083
1084     /**
1085      * Send an array of requests and return an array of responses.
1086      *
1087      * Unless $this->no_multicall has been set to true, it will try first to use one single xmlrpc call to server method
1088      * system.multicall, and revert to sending many successive calls in case of failure.
1089      * This failure is also stored in $this->no_multicall for subsequent calls.
1090      * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported,
1091      * so there is no way to reliably distinguish between that and a temporary failure.
1092      * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the
1093      * fourth parameter to FALSE.
1094      *
1095      * NB: trying to shoehorn extra functionality into existing syntax has resulted
1096      * in pretty much convoluted code...
1097      *
1098      * @param Request[] $reqs an array of Request objects
1099      * @param integer $timeout connection timeout (in seconds). See the details in the docs for the send() method
1100      * @param string $method the http protocol variant to be used. See the details in the docs for the send() method
1101      * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be
1102      *                         attempted
1103      *
1104      * @return Response[]
1105      */
1106     public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
1107     {
1108         if ($method == '') {
1109             $method = $this->method;
1110         }
1111         if (!$this->no_multicall) {
1112             $results = $this->_try_multicall($reqs, $timeout, $method);
1113             if (is_array($results)) {
1114                 // System.multicall succeeded
1115                 return $results;
1116             } else {
1117                 // either system.multicall is unsupported by server,
1118                 // or call failed for some other reason.
1119                 if ($fallback) {
1120                     // Don't try it next time...
1121                     $this->no_multicall = true;
1122                 } else {
1123                     if (is_a($results, '\PhpXmlRpc\Response')) {
1124                         $result = $results;
1125                     } else {
1126                         $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
1127                     }
1128                 }
1129             }
1130         } else {
1131             // override fallback, in case careless user tries to do two
1132             // opposite things at the same time
1133             $fallback = true;
1134         }
1135
1136         $results = array();
1137         if ($fallback) {
1138             // system.multicall is (probably) unsupported by server:
1139             // emulate multicall via multiple requests
1140             foreach ($reqs as $req) {
1141                 $results[] = $this->send($req, $timeout, $method);
1142             }
1143         } else {
1144             // user does NOT want to fallback on many single calls:
1145             // since we should always return an array of responses,
1146             // return an array with the same error repeated n times
1147             foreach ($reqs as $req) {
1148                 $results[] = $result;
1149             }
1150         }
1151
1152         return $results;
1153     }
1154
1155     /**
1156      * Attempt to boxcar $reqs via system.multicall.
1157      *
1158      * Returns either an array of Response, a single error Response or false (when received response does not respect
1159      * valid multicall syntax).
1160      *
1161      * @param Request[] $reqs
1162      * @param int $timeout
1163      * @param string $method
1164      * @return Response[]|bool|mixed|Response
1165      */
1166     private function _try_multicall($reqs, $timeout, $method)
1167     {
1168         // Construct multicall request
1169         $calls = array();
1170         foreach ($reqs as $req) {
1171             $call['methodName'] = new Value($req->method(), 'string');
1172             $numParams = $req->getNumParams();
1173             $params = array();
1174             for ($i = 0; $i < $numParams; $i++) {
1175                 $params[$i] = $req->getParam($i);
1176             }
1177             $call['params'] = new Value($params, 'array');
1178             $calls[] = new Value($call, 'struct');
1179         }
1180         $multiCall = new Request('system.multicall');
1181         $multiCall->addParam(new Value($calls, 'array'));
1182
1183         // Attempt RPC call
1184         $result = $this->send($multiCall, $timeout, $method);
1185
1186         if ($result->faultCode() != 0) {
1187             // call to system.multicall failed
1188             return $result;
1189         }
1190
1191         // Unpack responses.
1192         $rets = $result->value();
1193
1194         if ($this->return_type == 'xml') {
1195             return $rets;
1196         } elseif ($this->return_type == 'phpvals') {
1197             /// @todo test this code branch...
1198             $rets = $result->value();
1199             if (!is_array($rets)) {
1200                 return false;       // bad return type from system.multicall
1201             }
1202             $numRets = count($rets);
1203             if ($numRets != count($reqs)) {
1204                 return false;       // wrong number of return values.
1205             }
1206
1207             $response = array();
1208             for ($i = 0; $i < $numRets; $i++) {
1209                 $val = $rets[$i];
1210                 if (!is_array($val)) {
1211                     return false;
1212                 }
1213                 switch (count($val)) {
1214                     case 1:
1215                         if (!isset($val[0])) {
1216                             return false;       // Bad value
1217                         }
1218                         // Normal return value
1219                         $response[$i] = new Response($val[0], 0, '', 'phpvals');
1220                         break;
1221                     case 2:
1222                         /// @todo remove usage of @: it is apparently quite slow
1223                         $code = @$val['faultCode'];
1224                         if (!is_int($code)) {
1225                             return false;
1226                         }
1227                         $str = @$val['faultString'];
1228                         if (!is_string($str)) {
1229                             return false;
1230                         }
1231                         $response[$i] = new Response(0, $code, $str);
1232                         break;
1233                     default:
1234                         return false;
1235                 }
1236             }
1237
1238             return $response;
1239         } else {
1240             // return type == 'xmlrpcvals'
1241
1242             $rets = $result->value();
1243             if ($rets->kindOf() != 'array') {
1244                 return false;       // bad return type from system.multicall
1245             }
1246             $numRets = $rets->count();
1247             if ($numRets != count($reqs)) {
1248                 return false;       // wrong number of return values.
1249             }
1250
1251             $response = array();
1252             foreach($rets as $val) {
1253                 switch ($val->kindOf()) {
1254                     case 'array':
1255                         if ($val->count() != 1) {
1256                             return false;       // Bad value
1257                         }
1258                         // Normal return value
1259                         $response[] = new Response($val[0]);
1260                         break;
1261                     case 'struct':
1262                         $code = $val['faultCode'];
1263                         /** @var Value $code */
1264                         if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1265                             return false;
1266                         }
1267                         $str = $val['faultString'];
1268                         /** @var Value $str */
1269                         if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1270                             return false;
1271                         }
1272                         $response[] = new Response(0, $code->scalarval(), $str->scalarval());
1273                         break;
1274                     default:
1275                         return false;
1276                 }
1277             }
1278
1279             return $response;
1280         }
1281     }
1282 }