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