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