make it possible to retrieve from Response error http codes; introduce custom excepti...
[plcapi.git] / src / Client.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\Logger;
6 use PhpXmlRpc\Helper\XMLParser;
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 = XMLParser::RETURN_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->serialize($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
789         $context = stream_context_create($contextOptions);
790
791         if ($timeout <= 0) {
792             $connectTimeout = ini_get('default_socket_timeout');
793         } else {
794             $connectTimeout = $timeout;
795         }
796
797         $this->errno = 0;
798         $this->errstr = '';
799
800         $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $connectTimeout,
801             STREAM_CLIENT_CONNECT, $context);
802         if ($fp) {
803             if ($timeout > 0) {
804                 stream_set_timeout($fp, $timeout);
805             }
806         } else {
807             if ($this->errstr == '') {
808                 $err = error_get_last();
809                 $this->errstr = $err['message'];
810             }
811
812             $this->errstr = 'Connect error: ' . $this->errstr;
813             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
814
815             return $r;
816         }
817
818         if (!fputs($fp, $op, strlen($op))) {
819             fclose($fp);
820             $this->errstr = 'Write error';
821             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
822
823             return $r;
824         }
825
826         // Close socket before parsing.
827         // It should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
828         $ipd = '';
829         do {
830             // shall we check for $data === FALSE?
831             // as per the manual, it signals an error
832             $ipd .= fread($fp, 32768);
833         } while (!feof($fp));
834         fclose($fp);
835
836         $r = $req->parseResponse($ipd, false, $this->return_type);
837
838         return $r;
839     }
840
841     /**
842      * Contributed by Justin Miller <justin@voxel.net>
843      * Requires curl to be built into PHP
844      * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
845      *
846      * @param Request $req
847      * @param string $server
848      * @param int $port
849      * @param int $timeout
850      * @param string $username
851      * @param string $password
852      * @param int $authType
853      * @param string $cert
854      * @param string $certPass
855      * @param string $caCert
856      * @param string $caCertDir
857      * @param string $proxyHost
858      * @param int $proxyPort
859      * @param string $proxyUsername
860      * @param string $proxyPassword
861      * @param int $proxyAuthType
862      * @param string $method 'http' (let curl decide), 'http10', 'http11' or 'https'
863      * @param bool $keepAlive
864      * @param string $key
865      * @param string $keyPass
866      * @param int $sslVersion
867      * @return Response
868      */
869     protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
870         $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
871         $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
872         $keyPass = '', $sslVersion = 0)
873     {
874         if (!function_exists('curl_init')) {
875             $this->errstr = 'CURL unavailable on this install';
876             return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
877         }
878         if ($method == 'https') {
879             if (($info = curl_version()) &&
880                 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
881             ) {
882                 $this->errstr = 'SSL unavailable on this install';
883                 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
884             }
885         }
886
887         if ($port == 0) {
888             if (in_array($method, array('http', 'http10', 'http11'))) {
889                 $port = 80;
890             } else {
891                 $port = 443;
892             }
893         }
894
895         // Only create the payload if it was not created previously
896         if (empty($req->payload)) {
897             $req->serialize($this->request_charset_encoding);
898         }
899
900         // Deflate request body and set appropriate request headers
901         $payload = $req->payload;
902         if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
903             if ($this->request_compression == 'gzip') {
904                 $a = @gzencode($payload);
905                 if ($a) {
906                     $payload = $a;
907                     $encodingHdr = 'Content-Encoding: gzip';
908                 }
909             } else {
910                 $a = @gzcompress($payload);
911                 if ($a) {
912                     $payload = $a;
913                     $encodingHdr = 'Content-Encoding: deflate';
914                 }
915             }
916         } else {
917             $encodingHdr = '';
918         }
919
920         if ($this->debug > 1) {
921             $this->getLogger()->debugMessage("---SENDING---\n$payload\n---END---");
922         }
923
924         if (!$keepAlive || !$this->xmlrpc_curl_handle) {
925             if ($method == 'http11' || $method == 'http10') {
926                 $protocol = 'http';
927             } else {
928                 $protocol = $method;
929             }
930             $curl = curl_init($protocol . '://' . $server . ':' . $port . $this->path);
931             if ($keepAlive) {
932                 $this->xmlrpc_curl_handle = $curl;
933             }
934         } else {
935             $curl = $this->xmlrpc_curl_handle;
936         }
937
938         // results into variable
939         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
940
941         if ($this->debug > 1) {
942             curl_setopt($curl, CURLOPT_VERBOSE, true);
943             /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
944         }
945         curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
946         // required for XMLRPC: post the data
947         curl_setopt($curl, CURLOPT_POST, 1);
948         // the data
949         curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
950
951         // return the header too
952         curl_setopt($curl, CURLOPT_HEADER, 1);
953
954         // NB: if we set an empty string, CURL will add http header indicating
955         // ALL methods it is supporting. This is possibly a better option than letting the user tell what curl can / cannot do...
956         if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
957             //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
958             // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
959             if (count($this->accepted_compression) == 1) {
960                 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
961             } else {
962                 curl_setopt($curl, CURLOPT_ENCODING, '');
963             }
964         }
965         // extra headers
966         $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
967         // if no keepalive is wanted, let the server know it in advance
968         if (!$keepAlive) {
969             $headers[] = 'Connection: close';
970         }
971         // request compression header
972         if ($encodingHdr) {
973             $headers[] = $encodingHdr;
974         }
975
976         // Fix the HTTP/1.1 417 Expectation Failed Bug (curl by default adds a 'Expect: 100-continue' header when POST
977         // size exceeds 1025 bytes, apparently)
978         $headers[] = 'Expect:';
979
980         curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
981         // timeout is borked
982         if ($timeout) {
983             curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
984         }
985
986         if ($method == 'http10') {
987             curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
988         } elseif ($method == 'http11') {
989             curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
990         }
991
992         if ($username && $password) {
993             curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
994             if (defined('CURLOPT_HTTPAUTH')) {
995                 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
996             } elseif ($authType != 1) {
997                 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
998             }
999         }
1000
1001         if ($method == 'https') {
1002             // set cert file
1003             if ($cert) {
1004                 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
1005             }
1006             // set cert password
1007             if ($certPass) {
1008                 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
1009             }
1010             // whether to verify remote host's cert
1011             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
1012             // set ca certificates file/dir
1013             if ($caCert) {
1014                 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
1015             }
1016             if ($caCertDir) {
1017                 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
1018             }
1019             // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1020             if ($key) {
1021                 curl_setopt($curl, CURLOPT_SSLKEY, $key);
1022             }
1023             // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1024             if ($keyPass) {
1025                 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
1026             }
1027             // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that
1028             // it matches the hostname used
1029             curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
1030             // allow usage of different SSL versions
1031             curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
1032         }
1033
1034         // proxy info
1035         if ($proxyHost) {
1036             if ($proxyPort == 0) {
1037                 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
1038             }
1039             curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
1040             if ($proxyUsername) {
1041                 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
1042                 if (defined('CURLOPT_PROXYAUTH')) {
1043                     curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
1044                 } elseif ($proxyAuthType != 1) {
1045                     $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1046                 }
1047             }
1048         }
1049
1050         // NB: should we build cookie http headers by hand rather than let CURL do it?
1051         // the following code does not honour 'expires', 'path' and 'domain' cookie attributes set to client obj the the user...
1052         if (count($this->cookies)) {
1053             $cookieHeader = '';
1054             foreach ($this->cookies as $name => $cookie) {
1055                 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
1056             }
1057             curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
1058         }
1059
1060         foreach ($this->extracurlopts as $opt => $val) {
1061             curl_setopt($curl, $opt, $val);
1062         }
1063
1064         $result = curl_exec($curl);
1065
1066         if ($this->debug > 1) {
1067             $message = "---CURL INFO---\n";
1068             foreach (curl_getinfo($curl) as $name => $val) {
1069                 if (is_array($val)) {
1070                     $val = implode("\n", $val);
1071                 }
1072                 $message .= $name . ': ' . $val . "\n";
1073             }
1074             $message .= '---END---';
1075             $this->getLogger()->debugMessage($message);
1076         }
1077
1078         if (!$result) {
1079             /// @todo we should use a better check here - what if we get back '' or '0'?
1080
1081             $this->errstr = 'no response';
1082             $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
1083             curl_close($curl);
1084             if ($keepAlive) {
1085                 $this->xmlrpc_curl_handle = null;
1086             }
1087         } else {
1088             if (!$keepAlive) {
1089                 curl_close($curl);
1090             }
1091             $resp = $req->parseResponse($result, true, $this->return_type);
1092             // if we got back a 302, we can not reuse the curl handle for later calls
1093             if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
1094                 curl_close($curl);
1095                 $this->xmlrpc_curl_handle = null;
1096             }
1097         }
1098
1099         return $resp;
1100     }
1101
1102     /**
1103      * Send an array of requests and return an array of responses.
1104      *
1105      * Unless $this->no_multicall has been set to true, it will try first to use one single xmlrpc call to server method
1106      * system.multicall, and revert to sending many successive calls in case of failure.
1107      * This failure is also stored in $this->no_multicall for subsequent calls.
1108      * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported,
1109      * so there is no way to reliably distinguish between that and a temporary failure.
1110      * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the
1111      * fourth parameter to FALSE.
1112      *
1113      * NB: trying to shoehorn extra functionality into existing syntax has resulted
1114      * in pretty much convoluted code...
1115      *
1116      * @param Request[] $reqs an array of Request objects
1117      * @param integer $timeout connection timeout (in seconds). See the details in the docs for the send() method
1118      * @param string $method the http protocol variant to be used. See the details in the docs for the send() method
1119      * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be
1120      *                         attempted
1121      *
1122      * @return Response[]
1123      */
1124     public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
1125     {
1126         if ($method == '') {
1127             $method = $this->method;
1128         }
1129         if (!$this->no_multicall) {
1130             $results = $this->_try_multicall($reqs, $timeout, $method);
1131             if (is_array($results)) {
1132                 // System.multicall succeeded
1133                 return $results;
1134             } else {
1135                 // either system.multicall is unsupported by server,
1136                 // or call failed for some other reason.
1137                 if ($fallback) {
1138                     // Don't try it next time...
1139                     $this->no_multicall = true;
1140                 } else {
1141                     if (is_a($results, '\PhpXmlRpc\Response')) {
1142                         $result = $results;
1143                     } else {
1144                         $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
1145                     }
1146                 }
1147             }
1148         } else {
1149             // override fallback, in case careless user tries to do two
1150             // opposite things at the same time
1151             $fallback = true;
1152         }
1153
1154         $results = array();
1155         if ($fallback) {
1156             // system.multicall is (probably) unsupported by server:
1157             // emulate multicall via multiple requests
1158             foreach ($reqs as $req) {
1159                 $results[] = $this->send($req, $timeout, $method);
1160             }
1161         } else {
1162             // user does NOT want to fallback on many single calls:
1163             // since we should always return an array of responses,
1164             // return an array with the same error repeated n times
1165             foreach ($reqs as $req) {
1166                 $results[] = $result;
1167             }
1168         }
1169
1170         return $results;
1171     }
1172
1173     /**
1174      * Attempt to boxcar $reqs via system.multicall.
1175      *
1176      * Returns either an array of Response, a single error Response or false (when received response does not respect
1177      * valid multicall syntax).
1178      *
1179      * @param Request[] $reqs
1180      * @param int $timeout
1181      * @param string $method
1182      * @return Response[]|bool|mixed|Response
1183      */
1184     private function _try_multicall($reqs, $timeout, $method)
1185     {
1186         // Construct multicall request
1187         $calls = array();
1188         foreach ($reqs as $req) {
1189             $call['methodName'] = new Value($req->method(), 'string');
1190             $numParams = $req->getNumParams();
1191             $params = array();
1192             for ($i = 0; $i < $numParams; $i++) {
1193                 $params[$i] = $req->getParam($i);
1194             }
1195             $call['params'] = new Value($params, 'array');
1196             $calls[] = new Value($call, 'struct');
1197         }
1198         $multiCall = new Request('system.multicall');
1199         $multiCall->addParam(new Value($calls, 'array'));
1200
1201         // Attempt RPC call
1202         $result = $this->send($multiCall, $timeout, $method);
1203
1204         if ($result->faultCode() != 0) {
1205             // call to system.multicall failed
1206             return $result;
1207         }
1208
1209         // Unpack responses.
1210         $rets = $result->value();
1211
1212         if ($this->return_type == 'xml') {
1213             return $rets;
1214         } elseif ($this->return_type == 'phpvals') {
1215             /// @todo test this code branch...
1216             $rets = $result->value();
1217             if (!is_array($rets)) {
1218                 return false;       // bad return type from system.multicall
1219             }
1220             $numRets = count($rets);
1221             if ($numRets != count($reqs)) {
1222                 return false;       // wrong number of return values.
1223             }
1224
1225             $response = array();
1226             for ($i = 0; $i < $numRets; $i++) {
1227                 $val = $rets[$i];
1228                 if (!is_array($val)) {
1229                     return false;
1230                 }
1231                 switch (count($val)) {
1232                     case 1:
1233                         if (!isset($val[0])) {
1234                             return false;       // Bad value
1235                         }
1236                         // Normal return value
1237                         $response[$i] = new Response($val[0], 0, '', 'phpvals');
1238                         break;
1239                     case 2:
1240                         /// @todo remove usage of @: it is apparently quite slow
1241                         $code = @$val['faultCode'];
1242                         if (!is_int($code)) {
1243                             return false;
1244                         }
1245                         $str = @$val['faultString'];
1246                         if (!is_string($str)) {
1247                             return false;
1248                         }
1249                         $response[$i] = new Response(0, $code, $str);
1250                         break;
1251                     default:
1252                         return false;
1253                 }
1254             }
1255
1256             return $response;
1257         } else {
1258             // return type == 'xmlrpcvals'
1259
1260             $rets = $result->value();
1261             if ($rets->kindOf() != 'array') {
1262                 return false;       // bad return type from system.multicall
1263             }
1264             $numRets = $rets->count();
1265             if ($numRets != count($reqs)) {
1266                 return false;       // wrong number of return values.
1267             }
1268
1269             $response = array();
1270             foreach($rets as $val) {
1271                 switch ($val->kindOf()) {
1272                     case 'array':
1273                         if ($val->count() != 1) {
1274                             return false;       // Bad value
1275                         }
1276                         // Normal return value
1277                         $response[] = new Response($val[0]);
1278                         break;
1279                     case 'struct':
1280                         $code = $val['faultCode'];
1281                         /** @var Value $code */
1282                         if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1283                             return false;
1284                         }
1285                         $str = $val['faultString'];
1286                         /** @var Value $str */
1287                         if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1288                             return false;
1289                         }
1290                         $response[] = new Response(0, $code->scalarval(), $str->scalarval());
1291                         break;
1292                     default:
1293                         return false;
1294                 }
1295             }
1296
1297             return $response;
1298         }
1299     }
1300 }