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