8fce70452cea1f8d90dabb1fef91da8e8c63a8b8
[plcapi.git] / src / Client.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\Logger;
6
7 class Client
8 {
9     /// @todo: do these need to be public?
10     public $method = 'http';
11     public $server;
12     public $port = 0;
13     public $path;
14
15     public $errno;
16     public $errstr;
17     public $debug = 0;
18
19     public $username = '';
20     public $password = '';
21     public $authtype = 1;
22
23     public $cert = '';
24     public $certpass = '';
25     public $cacert = '';
26     public $cacertdir = '';
27     public $key = '';
28     public $keypass = '';
29     public $verifypeer = true;
30     public $verifyhost = 2;
31     public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
32
33     public $proxy = '';
34     public $proxyport = 0;
35     public $proxy_user = '';
36     public $proxy_pass = '';
37     public $proxy_authtype = 1;
38
39     public $cookies = array();
40     public $extracurlopts = array();
41
42     public $no_multicall = false;
43
44     /**
45      * List of http compression methods accepted by the client for responses.
46      * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib.
47      *
48      * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
49      * in those cases it will be up to CURL to decide the compression methods
50      * it supports. You might check for the presence of 'zlib' in the output of
51      * curl_version() to determine wheter compression is supported or not
52      */
53     public $accepted_compression = array();
54     /**
55      * Name of compression scheme to be used for sending requests.
56      * Either null, gzip or deflate.
57      */
58     public $request_compression = '';
59     /**
60      * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
61      * http://curl.haxx.se/docs/faq.html#7.3).
62      */
63     public $xmlrpc_curl_handle = null;
64     /// Whether to use persistent connections for http 1.1 and https
65     public $keepalive = false;
66     /// Charset encodings that can be decoded without problems by the client
67     public $accepted_charset_encodings = array();
68     /// Charset encoding to be used in serializing request. NULL = use ASCII
69     public $request_charset_encoding = '';
70     /**
71      * Decides the content of Response objects returned by calls to send()
72      * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'.
73      */
74     public $return_type = 'xmlrpcvals';
75     /**
76      * Sent to servers in http headers.
77      */
78     public $user_agent;
79
80     /**
81      * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php
82      * @param string $server the server name / ip address
83      * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used
84      * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed
85      */
86     public function __construct($path, $server = '', $port = '', $method = '')
87     {
88         // allow user to specify all params in $path
89         if ($server == '' and $port == '' and $method == '') {
90             $parts = parse_url($path);
91             $server = $parts['host'];
92             $path = isset($parts['path']) ? $parts['path'] : '';
93             if (isset($parts['query'])) {
94                 $path .= '?' . $parts['query'];
95             }
96             if (isset($parts['fragment'])) {
97                 $path .= '#' . $parts['fragment'];
98             }
99             if (isset($parts['port'])) {
100                 $port = $parts['port'];
101             }
102             if (isset($parts['scheme'])) {
103                 $method = $parts['scheme'];
104             }
105             if (isset($parts['user'])) {
106                 $this->username = $parts['user'];
107             }
108             if (isset($parts['pass'])) {
109                 $this->password = $parts['pass'];
110             }
111         }
112         if ($path == '' || $path[0] != '/') {
113             $this->path = '/' . $path;
114         } else {
115             $this->path = $path;
116         }
117         $this->server = $server;
118         if ($port != '') {
119             $this->port = $port;
120         }
121         if ($method != '') {
122             $this->method = $method;
123         }
124
125         // if ZLIB is enabled, let the client by default accept compressed responses
126         if (function_exists('gzinflate') || (
127                 function_exists('curl_init') && (($info = curl_version()) &&
128                     ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
129             )
130         ) {
131             $this->accepted_compression = array('gzip', 'deflate');
132         }
133
134         // keepalives: enabled by default
135         $this->keepalive = true;
136
137         // by default the xml parser can support these 3 charset encodings
138         $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
139
140         // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
141         // in http://www.iana.org/assignments/character-sets/character-sets.xhtml
142         // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
143         /*if (function_exists('mb_list_encodings')) {
144
145             $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
146                 'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
147             $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
148         }*/
149
150         // initialize user_agent string
151         $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
152     }
153
154     /**
155      * Enables/disables the echoing to screen of the xmlrpc responses received.
156      *
157      * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
158      */
159     public function setDebug($in)
160     {
161         $this->debug = $in;
162     }
163
164     /**
165      * Add some http BASIC AUTH credentials, used by the client to authenticate.
166      *
167      * @param string $u username
168      * @param string $p password
169      * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)
170      */
171     public function setCredentials($u, $p, $t = 1)
172     {
173         $this->username = $u;
174         $this->password = $p;
175         $this->authtype = $t;
176     }
177
178     /**
179      * Add a client-side https certificate.
180      *
181      * @param string $cert
182      * @param string $certPass
183      */
184     public function setCertificate($cert, $certPass)
185     {
186         $this->cert = $cert;
187         $this->certpass = $certPass;
188     }
189
190     /**
191      * Add a CA certificate to verify server with (see man page about
192      * CURLOPT_CAINFO for more details).
193      *
194      * @param string $caCert certificate file name (or dir holding certificates)
195      * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
196      */
197     public function setCaCertificate($caCert, $isDir = false)
198     {
199         if ($isDir) {
200             $this->cacertdir = $caCert;
201         } else {
202             $this->cacert = $caCert;
203         }
204     }
205
206     /**
207      * Set attributes for SSL communication: private SSL key
208      * NB: does not work in older php/curl installs
209      * Thanks to Daniel Convissor.
210      *
211      * @param string $key The name of a file containing a private SSL key
212      * @param string $keyPass The secret password needed to use the private SSL key
213      */
214     public function setKey($key, $keyPass)
215     {
216         $this->key = $key;
217         $this->keypass = $keyPass;
218     }
219
220     /**
221      * Set attributes for SSL communication: verify server certificate.
222      *
223      * @param bool $i enable/disable verification of peer certificate
224      */
225     public function setSSLVerifyPeer($i)
226     {
227         $this->verifypeer = $i;
228     }
229
230     /**
231      * Set attributes for SSL communication: verify match of server cert w. hostname.
232      *
233      * @param int $i
234      */
235     public function setSSLVerifyHost($i)
236     {
237         $this->verifyhost = $i;
238     }
239
240     /**
241      * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide
242      *
243      * @param int $i
244      */
245     public function setSSLVersion($i)
246     {
247         $this->sslversion = $i;
248     }
249
250     /**
251      * Set proxy info.
252      *
253      * @param string $proxyHost
254      * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
255      * @param string $proxyUsername Leave blank if proxy has public access
256      * @param string $proxyPassword Leave blank if proxy has public access
257      * @param int $proxyAuthType set to constant CURLAUTH_NTLM to use NTLM auth with proxy
258      */
259     public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
260     {
261         $this->proxy = $proxyHost;
262         $this->proxyport = $proxyPort;
263         $this->proxy_user = $proxyUsername;
264         $this->proxy_pass = $proxyPassword;
265         $this->proxy_authtype = $proxyAuthType;
266     }
267
268     /**
269      * Enables/disables reception of compressed xmlrpc responses.
270      * Note that enabling reception of compressed responses merely adds some standard
271      * http headers to xmlrpc requests. It is up to the xmlrpc server to return
272      * compressed responses when receiving such requests.
273      *
274      * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
275      */
276     public function setAcceptedCompression($compMethod)
277     {
278         if ($compMethod == 'any') {
279             $this->accepted_compression = array('gzip', 'deflate');
280         } elseif ($compMethod == false) {
281             $this->accepted_compression = array();
282         } else {
283             $this->accepted_compression = array($compMethod);
284         }
285     }
286
287     /**
288      * Enables/disables http compression of xmlrpc request.
289      * Take care when sending compressed requests: servers might not support them
290      * (and automatic fallback to uncompressed requests is not yet implemented).
291      *
292      * @param string $compMethod either 'gzip', 'deflate' or ''
293      */
294     public function setRequestCompression($compMethod)
295     {
296         $this->request_compression = $compMethod;
297     }
298
299     /**
300      * Adds a cookie to list of cookies that will be sent to server.
301      * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:
302      * do not do it unless you know what you are doing.
303      *
304      * @param string $name
305      * @param string $value
306      * @param string $path
307      * @param string $domain
308      * @param int $port
309      *
310      * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)
311      */
312     public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
313     {
314         $this->cookies[$name]['value'] = urlencode($value);
315         if ($path || $domain || $port) {
316             $this->cookies[$name]['path'] = $path;
317             $this->cookies[$name]['domain'] = $domain;
318             $this->cookies[$name]['port'] = $port;
319             $this->cookies[$name]['version'] = 1;
320         } else {
321             $this->cookies[$name]['version'] = 0;
322         }
323     }
324
325     /**
326      * Directly set cURL options, for extra flexibility
327      * It allows eg. to bind client to a specific IP interface / address.
328      *
329      * @param array $options
330      */
331     public function SetCurlOptions($options)
332     {
333         $this->extracurlopts = $options;
334     }
335
336     /**
337      * Set user-agent string that will be used by this client instance
338      * in http headers sent to the server.
339      *
340      * @param string $agentString
341      */
342     public function SetUserAgent($agentString)
343     {
344         $this->user_agent = $agentString;
345     }
346
347     /**
348      * Send an xmlrpc request.
349      *
350      * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the complete xml representation of a request
351      * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply
352      * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used
353      *
354      * @return Response|Response[]
355      */
356     public function send($req, $timeout = 0, $method = '')
357     {
358         // if user does not specify http protocol, use native method of this client
359         // (i.e. method set during call to constructor)
360         if ($method == '') {
361             $method = $this->method;
362         }
363
364         if (is_array($req)) {
365             // $req is an array of Requests
366             $r = $this->multicall($req, $timeout, $method);
367
368             return $r;
369         } elseif (is_string($req)) {
370             $n = new Request('');
371             $n->payload = $req;
372             $req = $n;
373         }
374
375         // where req is a Request
376         $req->setDebug($this->debug);
377
378         if ($method == 'https') {
379             $r = $this->sendPayloadHTTPS(
380                 $req,
381                 $this->server,
382                 $this->port,
383                 $timeout,
384                 $this->username,
385                 $this->password,
386                 $this->authtype,
387                 $this->cert,
388                 $this->certpass,
389                 $this->cacert,
390                 $this->cacertdir,
391                 $this->proxy,
392                 $this->proxyport,
393                 $this->proxy_user,
394                 $this->proxy_pass,
395                 $this->proxy_authtype,
396                 $this->keepalive,
397                 $this->key,
398                 $this->keypass,
399                 $this->sslversion
400             );
401         } elseif ($method == 'http11') {
402             $r = $this->sendPayloadCURL(
403                 $req,
404                 $this->server,
405                 $this->port,
406                 $timeout,
407                 $this->username,
408                 $this->password,
409                 $this->authtype,
410                 null,
411                 null,
412                 null,
413                 null,
414                 $this->proxy,
415                 $this->proxyport,
416                 $this->proxy_user,
417                 $this->proxy_pass,
418                 $this->proxy_authtype,
419                 'http',
420                 $this->keepalive
421             );
422         } else {
423             $r = $this->sendPayloadHTTP10(
424                 $req,
425                 $this->server,
426                 $this->port,
427                 $timeout,
428                 $this->username,
429                 $this->password,
430                 $this->authtype,
431                 $this->proxy,
432                 $this->proxyport,
433                 $this->proxy_user,
434                 $this->proxy_pass,
435                 $this->proxy_authtype,
436                 $method
437             );
438         }
439
440         return $r;
441     }
442
443     /**
444      * @param Request $req
445      * @param string $server
446      * @param int $port
447      * @param int $timeout
448      * @param string $username
449      * @param string $password
450      * @param int $authType
451      * @param string $proxyHost
452      * @param int $proxyPort
453      * @param string $proxyUsername
454      * @param string $proxyPassword
455      * @param int $proxyAuthType
456      * @param string $method
457      * @return Response
458      */
459     protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
460                                        $username = '', $password = '', $authType = 1, $proxyHost = '',
461                                        $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
462                                        $method='http')
463     {
464         if ($port == 0) {
465             $port = ( $method === "https" ) ? 443 : 80;
466         }
467
468         // Only create the payload if it was not created previously
469         if (empty($req->payload)) {
470             $req->createPayload($this->request_charset_encoding);
471         }
472
473         $payload = $req->payload;
474         // Deflate request body and set appropriate request headers
475         if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
476             if ($this->request_compression == 'gzip') {
477                 $a = @gzencode($payload);
478                 if ($a) {
479                     $payload = $a;
480                     $encodingHdr = "Content-Encoding: gzip\r\n";
481                 }
482             } else {
483                 $a = @gzcompress($payload);
484                 if ($a) {
485                     $payload = $a;
486                     $encodingHdr = "Content-Encoding: deflate\r\n";
487                 }
488             }
489         } else {
490             $encodingHdr = '';
491         }
492
493         // thanks to Grant Rauscher <grant7@firstworld.net> for this
494         $credentials = '';
495         if ($username != '') {
496             $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
497             if ($authType != 1) {
498                 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
499             }
500         }
501
502         $acceptedEncoding = '';
503         if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
504             $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
505         }
506
507         $proxyCredentials = '';
508         if ($proxyHost) {
509             if ($proxyPort == 0) {
510                 $proxyPort = 8080;
511             }
512             $connectServer = $proxyHost;
513             $connectPort = $proxyPort;
514             $transport = "tcp";
515             $uri = 'http://' . $server . ':' . $port . $this->path;
516             if ($proxyUsername != '') {
517                 if ($proxyAuthType != 1) {
518                     error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
519                 }
520                 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
521             }
522         } else {
523             $connectServer = $server;
524             $connectPort = $port;
525             /// @todo if supporting https, we should support all its current options as well: peer name verification etc...
526             $transport = ( $method === "https" ) ? "tls" : "tcp";
527             $uri = $this->path;
528         }
529
530         // Cookie generation, as per rfc2965 (version 1 cookies) or
531         // netscape's rules (version 0 cookies)
532         $cookieHeader = '';
533         if (count($this->cookies)) {
534             $version = '';
535             foreach ($this->cookies as $name => $cookie) {
536                 if ($cookie['version']) {
537                     $version = ' $Version="' . $cookie['version'] . '";';
538                     $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
539                     if ($cookie['path']) {
540                         $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
541                     }
542                     if ($cookie['domain']) {
543                         $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
544                     }
545                     if ($cookie['port']) {
546                         $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
547                     }
548                 } else {
549                     $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
550                 }
551             }
552             $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
553         }
554
555         // omit port if 80
556         $port = ($port == 80) ? '' : (':' . $port);
557
558         $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
559             'User-Agent: ' . $this->user_agent . "\r\n" .
560             'Host: ' . $server . $port . "\r\n" .
561             $credentials .
562             $proxyCredentials .
563             $acceptedEncoding .
564             $encodingHdr .
565             'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
566             $cookieHeader .
567             'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
568             strlen($payload) . "\r\n\r\n" .
569             $payload;
570
571         if ($this->debug > 1) {
572             Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
573         }
574
575         if ($timeout > 0) {
576             $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $timeout);
577         } else {
578             $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr);
579         }
580         if ($fp) {
581             if ($timeout > 0) {
582                 stream_set_timeout($fp, $timeout);
583             }
584         } else {
585             $this->errstr = 'Connect error: ' . $this->errstr;
586             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
587
588             return $r;
589         }
590
591         if (!fputs($fp, $op, strlen($op))) {
592             fclose($fp);
593             $this->errstr = 'Write error';
594             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
595
596             return $r;
597         } else {
598             // reset errno and errstr on successful socket connection
599             $this->errstr = '';
600         }
601         // G. Giunta 2005/10/24: close socket before parsing.
602         // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
603         $ipd = '';
604         do {
605             // shall we check for $data === FALSE?
606             // as per the manual, it signals an error
607             $ipd .= fread($fp, 32768);
608         } while (!feof($fp));
609         fclose($fp);
610         $r = $req->parseResponse($ipd, false, $this->return_type);
611
612         return $r;
613     }
614
615     /**
616      * @param Request $req
617      * @param string $server
618      * @param int $port
619      * @param int $timeout
620      * @param string $username
621      * @param string $password
622      * @param int $authType
623      * @param string $cert
624      * @param string $certPass
625      * @param string $caCert
626      * @param string $caCertDir
627      * @param string $proxyHost
628      * @param int $proxyPort
629      * @param string $proxyUsername
630      * @param string $proxyPassword
631      * @param int $proxyAuthType
632      * @param bool $keepAlive
633      * @param string $key
634      * @param string $keyPass
635      * @param int $sslVersion
636      * @return Response
637      */
638     protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '',
639                                       $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
640                                       $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
641                                       $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
642     {
643         return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
644             $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
645             $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
646     }
647
648     /**
649      * Contributed by Justin Miller <justin@voxel.net>
650      * Requires curl to be built into PHP
651      * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
652      *
653      * @param Request $req
654      * @param string $server
655      * @param int $port
656      * @param int $timeout
657      * @param string $username
658      * @param string $password
659      * @param int $authType
660      * @param string $cert
661      * @param string $certPass
662      * @param string $caCert
663      * @param string $caCertDir
664      * @param string $proxyHost
665      * @param int $proxyPort
666      * @param string $proxyUsername
667      * @param string $proxyPassword
668      * @param int $proxyAuthType
669      * @param string $method
670      * @param bool $keepAlive
671      * @param string $key
672      * @param string $keyPass
673      * @param int $sslVersion
674      * @return Response
675      */
676     protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '',
677                                      $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
678                                      $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https',
679                                      $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
680     {
681         if (!function_exists('curl_init')) {
682             $this->errstr = 'CURL unavailable on this install';
683             return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
684         }
685         if ($method == 'https') {
686             if (($info = curl_version()) &&
687                 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
688             ) {
689                 $this->errstr = 'SSL unavailable on this install';
690                 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
691             }
692         }
693
694         if ($port == 0) {
695             if ($method == 'http') {
696                 $port = 80;
697             } else {
698                 $port = 443;
699             }
700         }
701
702         // Only create the payload if it was not created previously
703         if (empty($req->payload)) {
704             $req->createPayload($this->request_charset_encoding);
705         }
706
707         // Deflate request body and set appropriate request headers
708         $payload = $req->payload;
709         if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
710             if ($this->request_compression == 'gzip') {
711                 $a = @gzencode($payload);
712                 if ($a) {
713                     $payload = $a;
714                     $encodingHdr = 'Content-Encoding: gzip';
715                 }
716             } else {
717                 $a = @gzcompress($payload);
718                 if ($a) {
719                     $payload = $a;
720                     $encodingHdr = 'Content-Encoding: deflate';
721                 }
722             }
723         } else {
724             $encodingHdr = '';
725         }
726
727         if ($this->debug > 1) {
728             Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
729         }
730
731         if (!$keepAlive || !$this->xmlrpc_curl_handle) {
732             $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
733             if ($keepAlive) {
734                 $this->xmlrpc_curl_handle = $curl;
735             }
736         } else {
737             $curl = $this->xmlrpc_curl_handle;
738         }
739
740         // results into variable
741         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
742
743         if ($this->debug > 1) {
744             curl_setopt($curl, CURLOPT_VERBOSE, true);
745             /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
746         }
747         curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
748         // required for XMLRPC: post the data
749         curl_setopt($curl, CURLOPT_POST, 1);
750         // the data
751         curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
752
753         // return the header too
754         curl_setopt($curl, CURLOPT_HEADER, 1);
755
756         // NB: if we set an empty string, CURL will add http header indicating
757         // ALL methods it is supporting. This is possibly a better option than
758         // letting the user tell what curl can / cannot do...
759         if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
760             //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
761             // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
762             if (count($this->accepted_compression) == 1) {
763                 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
764             } else {
765                 curl_setopt($curl, CURLOPT_ENCODING, '');
766             }
767         }
768         // extra headers
769         $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
770         // if no keepalive is wanted, let the server know it in advance
771         if (!$keepAlive) {
772             $headers[] = 'Connection: close';
773         }
774         // request compression header
775         if ($encodingHdr) {
776             $headers[] = $encodingHdr;
777         }
778
779         curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
780         // timeout is borked
781         if ($timeout) {
782             curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
783         }
784
785         if ($username && $password) {
786             curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
787             if (defined('CURLOPT_HTTPAUTH')) {
788                 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
789             } elseif ($authType != 1) {
790                 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
791             }
792         }
793
794         if ($method == 'https') {
795             // set cert file
796             if ($cert) {
797                 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
798             }
799             // set cert password
800             if ($certPass) {
801                 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
802             }
803             // whether to verify remote host's cert
804             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
805             // set ca certificates file/dir
806             if ($caCert) {
807                 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
808             }
809             if ($caCertDir) {
810                 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
811             }
812             // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
813             if ($key) {
814                 curl_setopt($curl, CURLOPT_SSLKEY, $key);
815             }
816             // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
817             if ($keyPass) {
818                 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
819             }
820             // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used
821             curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
822             // allow usage of different SSL versions
823             curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
824         }
825
826         // proxy info
827         if ($proxyHost) {
828             if ($proxyPort == 0) {
829                 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
830             }
831             curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
832             if ($proxyUsername) {
833                 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
834                 if (defined('CURLOPT_PROXYAUTH')) {
835                     curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
836                 } elseif ($proxyAuthType != 1) {
837                     error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
838                 }
839             }
840         }
841
842         // NB: should we build cookie http headers by hand rather than let CURL do it?
843         // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
844         // set to client obj the the user...
845         if (count($this->cookies)) {
846             $cookieHeader = '';
847             foreach ($this->cookies as $name => $cookie) {
848                 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
849             }
850             curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
851         }
852
853         foreach ($this->extracurlopts as $opt => $val) {
854             curl_setopt($curl, $opt, $val);
855         }
856
857         $result = curl_exec($curl);
858
859         if ($this->debug > 1) {
860             $message = "---CURL INFO---\n";
861             foreach (curl_getinfo($curl) as $name => $val) {
862                 if (is_array($val)) {
863                     $val = implode("\n", $val);
864                 }
865                 $message .= $name . ': ' . $val . "\n";
866             }
867             $message .= "---END---";
868             Logger::instance()->debugMessage($message);
869         }
870
871         if (!$result) {
872             /// @todo we should use a better check here - what if we get back '' or '0'?
873
874             $this->errstr = 'no response';
875             $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
876             curl_close($curl);
877             if ($keepAlive) {
878                 $this->xmlrpc_curl_handle = null;
879             }
880         } else {
881             if (!$keepAlive) {
882                 curl_close($curl);
883             }
884             $resp = $req->parseResponse($result, true, $this->return_type);
885             // if we got back a 302, we can not reuse the curl handle for later calls
886             if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
887                 curl_close($curl);
888                 $this->xmlrpc_curl_handle = null;
889             }
890         }
891
892         return $resp;
893     }
894
895     /**
896      * Send an array of requests and return an array of responses.
897      * Unless $this->no_multicall has been set to true, it will try first
898      * to use one single xmlrpc call to server method system.multicall, and
899      * revert to sending many successive calls in case of failure.
900      * This failure is also stored in $this->no_multicall for subsequent calls.
901      * Unfortunately, there is no server error code universally used to denote
902      * the fact that multicall is unsupported, so there is no way to reliably
903      * distinguish between that and a temporary failure.
904      * If you are sure that server supports multicall and do not want to
905      * fallback to using many single calls, set the fourth parameter to FALSE.
906      *
907      * NB: trying to shoehorn extra functionality into existing syntax has resulted
908      * in pretty much convoluted code...
909      *
910      * @param Request[] $reqs an array of Request objects
911      * @param integer $timeout connection timeout (in seconds)
912      * @param string $method the http protocol variant to be used
913      * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted
914      *
915      * @return array
916      */
917     public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
918     {
919         if ($method == '') {
920             $method = $this->method;
921         }
922         if (!$this->no_multicall) {
923             $results = $this->_try_multicall($reqs, $timeout, $method);
924             if (is_array($results)) {
925                 // System.multicall succeeded
926                 return $results;
927             } else {
928                 // either system.multicall is unsupported by server,
929                 // or call failed for some other reason.
930                 if ($fallback) {
931                     // Don't try it next time...
932                     $this->no_multicall = true;
933                 } else {
934                     if (is_a($results, '\PhpXmlRpc\Response')) {
935                         $result = $results;
936                     } else {
937                         $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
938                     }
939                 }
940             }
941         } else {
942             // override fallback, in case careless user tries to do two
943             // opposite things at the same time
944             $fallback = true;
945         }
946
947         $results = array();
948         if ($fallback) {
949             // system.multicall is (probably) unsupported by server:
950             // emulate multicall via multiple requests
951             foreach ($reqs as $req) {
952                 $results[] = $this->send($req, $timeout, $method);
953             }
954         } else {
955             // user does NOT want to fallback on many single calls:
956             // since we should always return an array of responses,
957             // return an array with the same error repeated n times
958             foreach ($reqs as $req) {
959                 $results[] = $result;
960             }
961         }
962
963         return $results;
964     }
965
966     /**
967      * Attempt to boxcar $reqs via system.multicall.
968      * Returns either an array of xmlrpc reponses, an xmlrpc error response
969      * or false (when received response does not respect valid multicall syntax).
970      *
971      * @param Request[] $reqs
972      * @param int $timeout
973      * @param string $method
974      * @return array|bool|mixed|Response
975      */
976     private function _try_multicall($reqs, $timeout, $method)
977     {
978         // Construct multicall request
979         $calls = array();
980         foreach ($reqs as $req) {
981             $call['methodName'] = new Value($req->method(), 'string');
982             $numParams = $req->getNumParams();
983             $params = array();
984             for ($i = 0; $i < $numParams; $i++) {
985                 $params[$i] = $req->getParam($i);
986             }
987             $call['params'] = new Value($params, 'array');
988             $calls[] = new Value($call, 'struct');
989         }
990         $multiCall = new Request('system.multicall');
991         $multiCall->addParam(new Value($calls, 'array'));
992
993         // Attempt RPC call
994         $result = $this->send($multiCall, $timeout, $method);
995
996         if ($result->faultCode() != 0) {
997             // call to system.multicall failed
998             return $result;
999         }
1000
1001         // Unpack responses.
1002         $rets = $result->value();
1003
1004         if ($this->return_type == 'xml') {
1005             return $rets;
1006         } elseif ($this->return_type == 'phpvals') {
1007             /// @todo test this code branch...
1008             $rets = $result->value();
1009             if (!is_array($rets)) {
1010                 return false;       // bad return type from system.multicall
1011             }
1012             $numRets = count($rets);
1013             if ($numRets != count($reqs)) {
1014                 return false;       // wrong number of return values.
1015             }
1016
1017             $response = array();
1018             for ($i = 0; $i < $numRets; $i++) {
1019                 $val = $rets[$i];
1020                 if (!is_array($val)) {
1021                     return false;
1022                 }
1023                 switch (count($val)) {
1024                     case 1:
1025                         if (!isset($val[0])) {
1026                             return false;       // Bad value
1027                         }
1028                         // Normal return value
1029                         $response[$i] = new Response($val[0], 0, '', 'phpvals');
1030                         break;
1031                     case 2:
1032                         /// @todo remove usage of @: it is apparently quite slow
1033                         $code = @$val['faultCode'];
1034                         if (!is_int($code)) {
1035                             return false;
1036                         }
1037                         $str = @$val['faultString'];
1038                         if (!is_string($str)) {
1039                             return false;
1040                         }
1041                         $response[$i] = new Response(0, $code, $str);
1042                         break;
1043                     default:
1044                         return false;
1045                 }
1046             }
1047
1048             return $response;
1049         } else {
1050             // return type == 'xmlrpcvals'
1051
1052             $rets = $result->value();
1053             if ($rets->kindOf() != 'array') {
1054                 return false;       // bad return type from system.multicall
1055             }
1056             $numRets = $rets->count();
1057             if ($numRets != count($reqs)) {
1058                 return false;       // wrong number of return values.
1059             }
1060
1061             $response = array();
1062             foreach($rets as $val) {
1063                 switch ($val->kindOf()) {
1064                     case 'array':
1065                         if ($val->count() != 1) {
1066                             return false;       // Bad value
1067                         }
1068                         // Normal return value
1069                         $response[] = new Response($val[0]);
1070                         break;
1071                     case 'struct':
1072                         $code = $val['faultCode'];
1073                         if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1074                             return false;
1075                         }
1076                         $str = $val['faultString'];
1077                         if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1078                             return false;
1079                         }
1080                         $response[] = new Response(0, $code->scalarval(), $str->scalarval());
1081                         break;
1082                     default:
1083                         return false;
1084                 }
1085             }
1086
1087             return $response;
1088         }
1089     }
1090 }