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