improve https via socket
[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
65      * in those cases it will be up to CURL to decide the compression methods
66      * it supports. You might check for the presence of 'zlib' in the output of
67      * curl_version() to determine wheter compression is supported or not
68      */
69     public $accepted_compression = array();
70
71     /**
72      * Name of compression scheme to be used for sending requests.
73      * Either null, gzip or deflate.
74      */
75
76     public $request_compression = '';
77
78     /**
79      * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
80      * http://curl.haxx.se/docs/faq.html#7.3).
81      */
82     public $xmlrpc_curl_handle = null;
83
84     /// Whether to use persistent connections for http 1.1 and https
85     public $keepalive = false;
86
87     /// Charset encodings that can be decoded without problems by the client
88     public $accepted_charset_encodings = array();
89
90     /**
91      * The charset encoding that will be used for serializing request sent by the client.
92      * It defaults to NULL, which means using US-ASCII and encoding all characters outside of the ASCII range using
93      * their xml character entity representation (this has the benefit that line end characters will not be mangled in
94      * the transfer, a CR-LF will be preserved as well as a singe LF).
95      *  Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1'
96      */
97     public $request_charset_encoding = '';
98
99     /**
100      * Decides the content of Response objects returned by calls to send() and multicall().
101      * Valid values are 'xmlrpcvals', 'phpvals' or 'xml'.
102      *
103      * Determines whether the value returned inside an Response object as results of calls to the send() and multicall()
104      * methods will be a Value object, a plain php value or a raw xml string.
105      * Allowed values are 'xmlrpcvals' (the default), 'phpvals' and 'xml'.
106      * To allow the user to differentiate between a correct and a faulty response, fault responses will be returned as
107      * Response objects in any case.
108      * Note that the 'phpvals' setting will yield faster execution times, but some of the information from the original
109      * response will be lost. It will be e.g. impossible to tell whether a particular php string value was sent by the
110      * server as an xmlrpc string or base64 value.
111      */
112     public $return_type = 'xmlrpcvals';
113
114     /**
115      * Sent to servers in http headers.
116      */
117     public $user_agent;
118
119     /**
120      * @param string $path either the PATH part of the xmlrpc server URL, or complete server URL (in which case you
121      *                     should use and empty string for all other parameters)
122      *                     e.g. /xmlrpc/server.php
123      *                     e.g. http://phpxmlrpc.sourceforge.net/server.php
124      *                     e.g. https://james:bond@secret.service.com:443/xmlrpcserver?agent=007
125      * @param string $server the server name / ip address
126      * @param integer $port the port the server is listening on, when omitted defaults to 80 or 443 depending on
127      *                      protocol used
128      * @param string $method the http protocol variant: defaults to 'http'; 'https' and 'http11' can be used if CURL is
129      *                       installed. The value set here can be overridden in any call to $this->send().
130      */
131     public function __construct($path, $server = '', $port = '', $method = '')
132     {
133         // allow user to specify all params in $path
134         if ($server == '' && $port == '' && $method == '') {
135             $parts = parse_url($path);
136             $server = $parts['host'];
137             $path = isset($parts['path']) ? $parts['path'] : '';
138             if (isset($parts['query'])) {
139                 $path .= '?' . $parts['query'];
140             }
141             if (isset($parts['fragment'])) {
142                 $path .= '#' . $parts['fragment'];
143             }
144             if (isset($parts['port'])) {
145                 $port = $parts['port'];
146             }
147             if (isset($parts['scheme'])) {
148                 $method = $parts['scheme'];
149             }
150             if (isset($parts['user'])) {
151                 $this->username = $parts['user'];
152             }
153             if (isset($parts['pass'])) {
154                 $this->password = $parts['pass'];
155             }
156         }
157         if ($path == '' || $path[0] != '/') {
158             $this->path = '/' . $path;
159         } else {
160             $this->path = $path;
161         }
162         $this->server = $server;
163         if ($port != '') {
164             $this->port = $port;
165         }
166         if ($method != '') {
167             $this->method = $method;
168         }
169
170         // if ZLIB is enabled, let the client by default accept compressed responses
171         if (function_exists('gzinflate') || (
172                 function_exists('curl_init') && (($info = curl_version()) &&
173                     ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
174             )
175         ) {
176             $this->accepted_compression = array('gzip', 'deflate');
177         }
178
179         // keepalives: enabled by default
180         $this->keepalive = true;
181
182         // by default the xml parser can support these 3 charset encodings
183         $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
184
185         // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
186         // http://www.iana.org/assignments/character-sets/character-sets.xhtml
187         // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
188         /*if (function_exists('mb_list_encodings')) {
189
190             $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
191                 'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
192             $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
193         }*/
194
195         // initialize user_agent string
196         $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
197     }
198
199     /**
200      * Enable/disable the echoing to screen of the xmlrpc responses received. The default is not no output anything.
201      *
202      * The debugging information at level 1 includes the raw data returned from the XML-RPC server it was querying
203      * (including bot HTTP headers and the full XML payload), and the PHP value the client attempts to create to
204      * represent the value returned by the server
205      * At level2, the complete payload of the xmlrpc request is also printed, before being sent t the server.
206      *
207      * This option can be very useful when debugging servers as it allows you to see exactly what the client sends and
208      * the server returns.
209      *
210      * @param integer $level values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
211      */
212     public function setDebug($level)
213     {
214         $this->debug = $level;
215     }
216
217     /**
218      * Sets the username and password for authorizing the client to the server.
219      *
220      * With the default (HTTP) transport, this information is used for HTTP Basic authorization.
221      * Note that username and password can also be set using the class constructor.
222      * With HTTP 1.1 and HTTPS transport, NTLM and Digest authentication protocols are also supported. To enable them use
223      * the constants CURLAUTH_DIGEST and CURLAUTH_NTLM as values for the auth type parameter.
224      *
225      * @param string $user username
226      * @param string $password password
227      * @param integer $authType auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC
228      *                          (basic auth). Note that auth types NTLM and Digest will only work if the Curl php
229      *                          extension is enabled.
230      */
231     public function setCredentials($user, $password, $authType = 1)
232     {
233         $this->username = $user;
234         $this->password = $password;
235         $this->authtype = $authType;
236     }
237
238     /**
239      * Set the optional certificate and passphrase used in SSL-enabled communication with a remote server.
240      *
241      * Note: to retrieve information about the client certificate on the server side, you will need to look into the
242      * environment variables which are set up by the webserver. Different webservers will typically set up different
243      * variables.
244      *
245      * @param string $cert the name of a file containing a PEM formatted certificate
246      * @param string $certPass the password required to use it
247      */
248     public function setCertificate($cert, $certPass = '')
249     {
250         $this->cert = $cert;
251         $this->certpass = $certPass;
252     }
253
254     /**
255      * Add a CA certificate to verify server with in SSL-enabled communication when SetSSLVerifypeer has been set to TRUE.
256      *
257      * See the php manual page about CURLOPT_CAINFO for more details.
258      *
259      * @param string $caCert certificate file name (or dir holding certificates)
260      * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
261      */
262     public function setCaCertificate($caCert, $isDir = false)
263     {
264         if ($isDir) {
265             $this->cacertdir = $caCert;
266         } else {
267             $this->cacert = $caCert;
268         }
269     }
270
271     /**
272      * Set attributes for SSL communication: private SSL key.
273      *
274      * NB: does not work in older php/curl installs.
275      * Thanks to Daniel Convissor.
276      *
277      * @param string $key The name of a file containing a private SSL key
278      * @param string $keyPass The secret password needed to use the private SSL key
279      */
280     public function setKey($key, $keyPass)
281     {
282         $this->key = $key;
283         $this->keypass = $keyPass;
284     }
285
286     /**
287      * Set attributes for SSL communication: verify the remote host's SSL certificate, and cause the connection to fail
288      * if the cert verification fails.
289      *
290      * By default, verification is enabled.
291      * To specify custom SSL certificates to validate the server with, use the setCaCertificate method.
292      *
293      * @param bool $i enable/disable verification of peer certificate
294      */
295     public function setSSLVerifyPeer($i)
296     {
297         $this->verifypeer = $i;
298     }
299
300     /**
301      * Set attributes for SSL communication: verify the remote host's SSL certificate's common name (CN).
302      *
303      * Note that support for value 1 has been removed in cURL 7.28.1
304      *
305      * @param int $i Set to 1 to only the existence of a CN, not that it matches
306      */
307     public function setSSLVerifyHost($i)
308     {
309         $this->verifyhost = $i;
310     }
311
312     /**
313      * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide
314      *
315      * @param int $i
316      */
317     public function setSSLVersion($i)
318     {
319         $this->sslversion = $i;
320     }
321
322     /**
323      * Set proxy info.
324      *
325      * NB: CURL versions before 7.11.10 cannot use a proxy to communicate with https servers.
326      *
327      * @param string $proxyHost
328      * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
329      * @param string $proxyUsername Leave blank if proxy has public access
330      * @param string $proxyPassword Leave blank if proxy has public access
331      * @param int $proxyAuthType defaults to CURLAUTH_BASIC (Basic authentication protocol); set to constant CURLAUTH_NTLM
332      *                           to use NTLM auth with proxy (has effect only when the client uses the HTTP 1.1 protocol)
333      */
334     public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
335     {
336         $this->proxy = $proxyHost;
337         $this->proxyport = $proxyPort;
338         $this->proxy_user = $proxyUsername;
339         $this->proxy_pass = $proxyPassword;
340         $this->proxy_authtype = $proxyAuthType;
341     }
342
343     /**
344      * Enables/disables reception of compressed xmlrpc responses.
345      *
346      * This requires the "zlib" extension to be enabled in your php install. If it is, by default xmlrpc_client
347      * instances will enable reception of compressed content.
348      * Note that enabling reception of compressed responses merely adds some standard http headers to xmlrpc requests.
349      * It is up to the xmlrpc server to return compressed responses when receiving such requests.
350      *
351      * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
352      */
353     public function setAcceptedCompression($compMethod)
354     {
355         if ($compMethod == 'any') {
356             $this->accepted_compression = array('gzip', 'deflate');
357         } elseif ($compMethod == false) {
358             $this->accepted_compression = array();
359         } else {
360             $this->accepted_compression = array($compMethod);
361         }
362     }
363
364     /**
365      * Enables/disables http compression of xmlrpc request.
366      *
367      * This requires the "zlib" extension to be enabled in your php install.
368      * Take care when sending compressed requests: servers might not support them (and automatic fallback to
369      * uncompressed requests is not yet implemented).
370      *
371      * @param string $compMethod either 'gzip', 'deflate' or ''
372      */
373     public function setRequestCompression($compMethod)
374     {
375         $this->request_compression = $compMethod;
376     }
377
378     /**
379      * Adds a cookie to list of cookies that will be sent to server with every further request (useful e.g. for keeping
380      * session info outside of the xml-rpc payload).
381      *
382      * NB: By default cookies are sent using the 'original/netscape' format, which is also the same as the RFC 2965;
383      * setting any param but name and value will turn the cookie into a 'version 1' cookie (i.e. RFC 2109 cookie) that
384      * might not be fully supported by the server. Note that RFC 2109 has currently 'historic' status...
385      *
386      * @param string $name nb: will not be escaped in the request's http headers. Take care not to use CTL chars or
387      *                     separators!
388      * @param string $value
389      * @param string $path leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
390      * @param string $domain leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
391      * @param int $port leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
392      *
393      * @todo check correctness of urlencoding cookie value (copied from php way of doing it, but php is generally sending
394      *       response not requests. We do the opposite...)
395      * @todo strip invalid chars from cookie name? As per RFC6265, we should follow RFC2616, Section 2.2
396      */
397     public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
398     {
399         $this->cookies[$name]['value'] = urlencode($value);
400         if ($path || $domain || $port) {
401             $this->cookies[$name]['path'] = $path;
402             $this->cookies[$name]['domain'] = $domain;
403             $this->cookies[$name]['port'] = $port;
404             $this->cookies[$name]['version'] = 1;
405         } else {
406             $this->cookies[$name]['version'] = 0;
407         }
408     }
409
410     /**
411      * Directly set cURL options, for extra flexibility (when in cURL mode).
412      *
413      * It allows eg. to bind client to a specific IP interface / address.
414      *
415      * @param array $options
416      */
417     public function setCurlOptions($options)
418     {
419         $this->extracurlopts = $options;
420     }
421
422     /**
423      * @param int $useCurlMode self::USE_CURL_ALWAYS, self::USE_CURL_AUTO or self::USE_CURL_NEVER
424      */
425     public function setUseCurl($useCurlMode)
426     {
427         $this->use_curl = $useCurlMode;
428     }
429
430
431     /**
432      * Set user-agent string that will be used by this client instance in http headers sent to the server.
433      *
434      * The default user agent string includes the name of this library and the version number.
435      *
436      * @param string $agentString
437      */
438     public function setUserAgent($agentString)
439     {
440         $this->user_agent = $agentString;
441     }
442
443     /**
444      * Send an xmlrpc request to the server.
445      *
446      * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the
447      *                                      complete xml representation of a request.
448      *                                      When sending an array of Request objects, the client will try to make use of
449      *                                      a single 'system.multicall' xml-rpc method call to forward to the server all
450      *                                      the requests in a single HTTP round trip, unless $this->no_multicall has
451      *                                      been previously set to TRUE (see the multicall method below), in which case
452      *                                      many consecutive xmlrpc requests will be sent. The method will return an
453      *                                      array of Response objects in both cases.
454      *                                      The third variant allows to build by hand (or any other means) a complete
455      *                                      xmlrpc request message, and send it to the server. $req should be a string
456      *                                      containing the complete xml representation of the request. It is e.g. useful
457      *                                      when, for maximal speed of execution, the request is serialized into a
458      *                                      string using the native php xmlrpc functions (see http://www.php.net/xmlrpc)
459      * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply.
460      *                         This timeout value is passed to fsockopen(). It is also used for detecting server
461      *                         timeouts during communication (i.e. if the server does not send anything to the client
462      *                         for $timeout seconds, the connection will be closed).
463      * @param string $method valid values are 'http', 'http11' and 'https'. If left unspecified, the http protocol
464      *                       chosen during creation of the object will be used.
465      *
466      * @return Response|Response[] Note that the client will always return a Response object, even if the call fails
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->keepalive,
541                 $this->key,
542                 $this->keypass,
543                 $this->sslversion
544             );
545         }
546
547         return $r;
548     }
549
550     /**
551      * @deprecated
552      * @param Request $req
553      * @param string $server
554      * @param int $port
555      * @param int $timeout
556      * @param string $username
557      * @param string $password
558      * @param int $authType
559      * @param string $proxyHost
560      * @param int $proxyPort
561      * @param string $proxyUsername
562      * @param string $proxyPassword
563      * @param int $proxyAuthType
564      * @param string $method
565      * @return Response
566      */
567     protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '',
568         $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
569         $method='http')
570     {
571         return $this->sendPayloadSocket($req, $server, $port, $timeout, $username, $password, $authType, null, null,
572             null, null, $proxyHost, $proxyPort, $proxyUsername, $proxyPassword, $proxyAuthType);
573     }
574
575     /**
576      * @deprecated
577      * @param Request $req
578      * @param string $server
579      * @param int $port
580      * @param int $timeout
581      * @param string $username
582      * @param string $password
583      * @param int $authType
584      * @param string $cert
585      * @param string $certPass
586      * @param string $caCert
587      * @param string $caCertDir
588      * @param string $proxyHost
589      * @param int $proxyPort
590      * @param string $proxyUsername
591      * @param string $proxyPassword
592      * @param int $proxyAuthType
593      * @param bool $keepAlive
594      * @param string $key
595      * @param string $keyPass
596      * @param int $sslVersion
597      * @return Response
598      */
599     protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '',  $password = '',
600         $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
601         $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $keepAlive = false, $key = '', $keyPass = '',
602         $sslVersion = 0)
603     {
604         return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
605             $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
606             $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
607     }
608
609     /**
610      * @param Request $req
611      * @param string $server
612      * @param int $port
613      * @param int $timeout
614      * @param string $username
615      * @param string $password
616      * @param int $authType only value supported is 1
617      * @param string $cert
618      * @param string $certPass
619      * @param string $caCert
620      * @param string $caCertDir
621      * @param string $proxyHost
622      * @param int $proxyPort
623      * @param string $proxyUsername
624      * @param string $proxyPassword
625      * @param int $proxyAuthType only value supported is 1
626      * @param string $method 'http' (synonym for 'http10'), 'http10' or 'https'
627      * @param string $key
628      * @param string $keyPass @todo not implemented yet.
629      * @param int $sslVersion @todo not implemented yet. See http://php.net/manual/en/migration56.openssl.php
630      * @return Response
631      */
632     protected function sendPayloadSocket($req, $server, $port, $timeout = 0, $username = '', $password = '',
633         $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
634         $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method='http', $key = '', $keyPass = '',
635         $sslVersion = 0)
636     {
637         if ($port == 0) {
638             $port = ( $method === 'https' ) ? 443 : 80;
639         }
640
641         // Only create the payload if it was not created previously
642         if (empty($req->payload)) {
643             $req->createPayload($this->request_charset_encoding);
644         }
645
646         $payload = $req->payload;
647         // Deflate request body and set appropriate request headers
648         if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
649             if ($this->request_compression == 'gzip') {
650                 $a = @gzencode($payload);
651                 if ($a) {
652                     $payload = $a;
653                     $encodingHdr = "Content-Encoding: gzip\r\n";
654                 }
655             } else {
656                 $a = @gzcompress($payload);
657                 if ($a) {
658                     $payload = $a;
659                     $encodingHdr = "Content-Encoding: deflate\r\n";
660                 }
661             }
662         } else {
663             $encodingHdr = '';
664         }
665
666         // thanks to Grant Rauscher <grant7@firstworld.net> for this
667         $credentials = '';
668         if ($username != '') {
669             $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
670             if ($authType != 1) {
671                 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
672             }
673         }
674
675         $acceptedEncoding = '';
676         if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
677             $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
678         }
679
680         $proxyCredentials = '';
681         if ($proxyHost) {
682             if ($proxyPort == 0) {
683                 $proxyPort = 8080;
684             }
685             $connectServer = $proxyHost;
686             $connectPort = $proxyPort;
687             $transport = 'tcp';
688             $uri = 'http://' . $server . ':' . $port . $this->path;
689             if ($proxyUsername != '') {
690                 if ($proxyAuthType != 1) {
691                     error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
692                 }
693                 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
694             }
695         } else {
696             $connectServer = $server;
697             $connectPort = $port;
698             $transport = ( $method === 'https' ) ? 'tls' : 'tcp';
699             $uri = $this->path;
700         }
701
702         // Cookie generation, as per rfc2965 (version 1 cookies) or
703         // netscape's rules (version 0 cookies)
704         $cookieHeader = '';
705         if (count($this->cookies)) {
706             $version = '';
707             foreach ($this->cookies as $name => $cookie) {
708                 if ($cookie['version']) {
709                     $version = ' $Version="' . $cookie['version'] . '";';
710                     $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
711                     if ($cookie['path']) {
712                         $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
713                     }
714                     if ($cookie['domain']) {
715                         $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
716                     }
717                     if ($cookie['port']) {
718                         $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
719                     }
720                 } else {
721                     $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
722                 }
723             }
724             $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
725         }
726
727         // omit port if default
728         if (($port == 80 && in_array($method, array('http', 'http10'))) || ($port == 443 && $method == 'https')) {
729             $port =  '';
730         } else {
731             $port = ':' . $port;
732         }
733
734         $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
735             'User-Agent: ' . $this->user_agent . "\r\n" .
736             'Host: ' . $server . $port . "\r\n" .
737             $credentials .
738             $proxyCredentials .
739             $acceptedEncoding .
740             $encodingHdr .
741             'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
742             $cookieHeader .
743             'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
744             strlen($payload) . "\r\n\r\n" .
745             $payload;
746
747         if ($this->debug > 1) {
748             Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
749         }
750
751         $contextOptions = array();
752         if ($method == 'https') {
753             if ($cert != '') {
754                 $contextOptions['ssl']['local_cert'] = $cert;
755                 if ($certPass != '') {
756                     $contextOptions['ssl']['passphrase'] = $certPass;
757                 }
758             }
759             if ($caCert != '') {
760                 $contextOptions['ssl']['cafile'] = $caCert;
761             }
762             if ($caCertDir != '') {
763                 $contextOptions['ssl']['capath'] = $caCertDir;
764             }
765             if ($key != '') {
766                 $contextOptions['ssl']['local_pk'] = $key;
767             }
768             $contextOptions['ssl']['verify_peer'] = $this->verifypeer;
769             $contextOptions['ssl']['verify_peer_name'] = $this->verifypeer;
770         }
771         $context = stream_context_create($contextOptions);
772
773         if ($timeout <= 0) {
774             $connectTimeout = ini_get('default_socket_timeout');
775         } else {
776             $connectTimeout = $timeout;
777         }
778
779         $this->errno = 0;
780         $this->errstr = '';
781
782         $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $connectTimeout,
783             STREAM_CLIENT_CONNECT, $context);
784         if ($fp) {
785             if ($timeout > 0) {
786                 stream_set_timeout($fp, $timeout);
787             }
788         } else {
789             if ($this->errstr == '') {
790                 $err = error_get_last();
791                 $this->errstr = $err['message'];
792             }
793             $this->errstr = 'Connect error: ' . $this->errstr;
794             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
795
796             return $r;
797         }
798
799         if (!fputs($fp, $op, strlen($op))) {
800             fclose($fp);
801             $this->errstr = 'Write error';
802             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
803
804             return $r;
805         }
806
807         // G. Giunta 2005/10/24: close socket before parsing.
808         // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
809         $ipd = '';
810         do {
811             // shall we check for $data === FALSE?
812             // as per the manual, it signals an error
813             $ipd .= fread($fp, 32768);
814         } while (!feof($fp));
815         fclose($fp);
816
817         $r = $req->parseResponse($ipd, false, $this->return_type);
818
819         return $r;
820     }
821
822     /**
823      * Contributed by Justin Miller <justin@voxel.net>
824      * Requires curl to be built into PHP
825      * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
826      *
827      * @param Request $req
828      * @param string $server
829      * @param int $port
830      * @param int $timeout
831      * @param string $username
832      * @param string $password
833      * @param int $authType
834      * @param string $cert
835      * @param string $certPass
836      * @param string $caCert
837      * @param string $caCertDir
838      * @param string $proxyHost
839      * @param int $proxyPort
840      * @param string $proxyUsername
841      * @param string $proxyPassword
842      * @param int $proxyAuthType
843      * @param string $method 'http' (let curl decide), 'http10', 'http11' or 'https'
844      * @param bool $keepAlive
845      * @param string $key
846      * @param string $keyPass
847      * @param int $sslVersion
848      * @return Response
849      */
850     protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
851         $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
852         $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
853         $keyPass = '', $sslVersion = 0)
854     {
855         if (!function_exists('curl_init')) {
856             $this->errstr = 'CURL unavailable on this install';
857             return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
858         }
859         if ($method == 'https') {
860             if (($info = curl_version()) &&
861                 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
862             ) {
863                 $this->errstr = 'SSL unavailable on this install';
864                 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
865             }
866         }
867
868         if ($port == 0) {
869             if (in_array($method, array('http', 'http10', 'http11'))) {
870                 $port = 80;
871             } else {
872                 $port = 443;
873             }
874         }
875
876         // Only create the payload if it was not created previously
877         if (empty($req->payload)) {
878             $req->createPayload($this->request_charset_encoding);
879         }
880
881         // Deflate request body and set appropriate request headers
882         $payload = $req->payload;
883         if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
884             if ($this->request_compression == 'gzip') {
885                 $a = @gzencode($payload);
886                 if ($a) {
887                     $payload = $a;
888                     $encodingHdr = 'Content-Encoding: gzip';
889                 }
890             } else {
891                 $a = @gzcompress($payload);
892                 if ($a) {
893                     $payload = $a;
894                     $encodingHdr = 'Content-Encoding: deflate';
895                 }
896             }
897         } else {
898             $encodingHdr = '';
899         }
900
901         if ($this->debug > 1) {
902             Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
903         }
904
905         if (!$keepAlive || !$this->xmlrpc_curl_handle) {
906             if ($method == 'http11' || $method == 'http10') {
907                 $protocol = 'http';
908             } else {
909                 $protocol = $method;
910             }
911             $curl = curl_init($protocol . '://' . $server . ':' . $port . $this->path);
912             if ($keepAlive) {
913                 $this->xmlrpc_curl_handle = $curl;
914             }
915         } else {
916             $curl = $this->xmlrpc_curl_handle;
917         }
918
919         // results into variable
920         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
921
922         if ($this->debug > 1) {
923             curl_setopt($curl, CURLOPT_VERBOSE, true);
924             /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
925         }
926         curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
927         // required for XMLRPC: post the data
928         curl_setopt($curl, CURLOPT_POST, 1);
929         // the data
930         curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
931
932         // return the header too
933         curl_setopt($curl, CURLOPT_HEADER, 1);
934
935         // NB: if we set an empty string, CURL will add http header indicating
936         // ALL methods it is supporting. This is possibly a better option than
937         // 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                 error_log('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 it matches the hostname used
1010             curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
1011             // allow usage of different SSL versions
1012             curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
1013         }
1014
1015         // proxy info
1016         if ($proxyHost) {
1017             if ($proxyPort == 0) {
1018                 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
1019             }
1020             curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
1021             if ($proxyUsername) {
1022                 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
1023                 if (defined('CURLOPT_PROXYAUTH')) {
1024                     curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
1025                 } elseif ($proxyAuthType != 1) {
1026                     error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1027                 }
1028             }
1029         }
1030
1031         // NB: should we build cookie http headers by hand rather than let CURL do it?
1032         // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
1033         // 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                         if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1264                             return false;
1265                         }
1266                         $str = $val['faultString'];
1267                         if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1268                             return false;
1269                         }
1270                         $response[] = new Response(0, $code->scalarval(), $str->scalarval());
1271                         break;
1272                     default:
1273                         return false;
1274                 }
1275             }
1276
1277             return $response;
1278         }
1279     }
1280 }