Update and rename README to README.md
[plcapi.git] / lib / xmlrpc_client.php
1 <?php
2
3 class xmlrpc_client
4 {
5     /// @todo: do these need to be public?
6     public $path;
7     public $server;
8     public $port=0;
9     public $method='http';
10     public $errno;
11     public $errstr;
12     public $debug=0;
13     public $username='';
14     public $password='';
15     public $authtype=1;
16     public $cert='';
17     public $certpass='';
18     public $cacert='';
19     public $cacertdir='';
20     public $key='';
21     public $keypass='';
22     public $verifypeer=true;
23     public $verifyhost=2;
24     public $no_multicall=false;
25     public $proxy='';
26     public $proxyport=0;
27     public $proxy_user='';
28     public $proxy_pass='';
29     public $proxy_authtype=1;
30     public $cookies=array();
31     public $extracurlopts=array();
32
33     /**
34      * List of http compression methods accepted by the client for responses.
35      * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
36      *
37      * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
38      * in those cases it will be up to CURL to decide the compression methods
39      * it supports. You might check for the presence of 'zlib' in the output of
40      * curl_version() to determine wheter compression is supported or not
41      */
42     public $accepted_compression = array();
43     /**
44      * Name of compression scheme to be used for sending requests.
45      * Either null, gzip or deflate
46      */
47     public $request_compression = '';
48     /**
49      * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
50      * http://curl.haxx.se/docs/faq.html#7.3)
51      */
52     public $xmlrpc_curl_handle = null;
53     /// Whether to use persistent connections for http 1.1 and https
54     public $keepalive = false;
55     /// Charset encodings that can be decoded without problems by the client
56     public $accepted_charset_encodings = array();
57     /// Charset encoding to be used in serializing request. NULL = use ASCII
58     public $request_charset_encoding = '';
59     /**
60      * Decides the content of xmlrpcresp objects returned by calls to send()
61      * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'
62      */
63     public $return_type = 'xmlrpcvals';
64     /**
65      * Sent to servers in http headers
66      */
67     public $user_agent;
68
69     /**
70      * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php
71      * @param string $server the server name / ip address
72      * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used
73      * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed
74      */
75     function __construct($path, $server='', $port='', $method='')
76     {
77         $xmlrpc = Phpxmlrpc::instance();
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 = $xmlrpc->xmlrpcName . ' ' . $xmlrpc->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 message object, or an array of messages 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 xmlrpcresp
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 xmlrpcmsg's
341             $r = $this->multicall($msg, $timeout, $method);
342             return $r;
343         }
344         elseif(is_string($msg))
345         {
346             $n = new xmlrpcmsg('');
347             $n->payload = $msg;
348             $msg = $n;
349         }
350
351         // where msg is an xmlrpcmsg
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         $xmlrpc = Phpxmlrpc::instance();
427
428         if($port==0)
429         {
430             $port=80;
431         }
432
433         // Only create the payload if it was not created previously
434         if(empty($msg->payload))
435         {
436             $msg->createPayload($this->request_charset_encoding);
437         }
438
439         $payload = $msg->payload;
440         // Deflate request body and set appropriate request headers
441         if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
442         {
443             if($this->request_compression == 'gzip')
444             {
445                 $a = @gzencode($payload);
446                 if($a)
447                 {
448                     $payload = $a;
449                     $encoding_hdr = "Content-Encoding: gzip\r\n";
450                 }
451             }
452             else
453             {
454                 $a = @gzcompress($payload);
455                 if($a)
456                 {
457                     $payload = $a;
458                     $encoding_hdr = "Content-Encoding: deflate\r\n";
459                 }
460             }
461         }
462         else
463         {
464             $encoding_hdr = '';
465         }
466
467         // thanks to Grant Rauscher <grant7@firstworld.net> for this
468         $credentials='';
469         if($username!='')
470         {
471             $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
472             if ($authtype != 1)
473             {
474                 error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported with HTTP 1.0');
475             }
476         }
477
478         $accepted_encoding = '';
479         if(is_array($this->accepted_compression) && count($this->accepted_compression))
480         {
481             $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
482         }
483
484         $proxy_credentials = '';
485         if($proxyhost)
486         {
487             if($proxyport == 0)
488             {
489                 $proxyport = 8080;
490             }
491             $connectserver = $proxyhost;
492             $connectport = $proxyport;
493             $uri = 'http://'.$server.':'.$port.$this->path;
494             if($proxyusername != '')
495             {
496                 if ($proxyauthtype != 1)
497                 {
498                     error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported with HTTP 1.0');
499                 }
500                 $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n";
501             }
502         }
503         else
504         {
505             $connectserver = $server;
506             $connectport = $port;
507             $uri = $this->path;
508         }
509
510         // Cookie generation, as per rfc2965 (version 1 cookies) or
511         // netscape's rules (version 0 cookies)
512         $cookieheader='';
513         if (count($this->cookies))
514         {
515             $version = '';
516             foreach ($this->cookies as $name => $cookie)
517             {
518                 if ($cookie['version'])
519                 {
520                     $version = ' $Version="' . $cookie['version'] . '";';
521                     $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";';
522                     if ($cookie['path'])
523                         $cookieheader .= ' $Path="' . $cookie['path'] . '";';
524                     if ($cookie['domain'])
525                         $cookieheader .= ' $Domain="' . $cookie['domain'] . '";';
526                     if ($cookie['port'])
527                         $cookieheader .= ' $Port="' . $cookie['port'] . '";';
528                 }
529                 else
530                 {
531                     $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";";
532                 }
533             }
534             $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n";
535         }
536
537         // omit port if 80
538         $port = ($port == 80) ? '' : (':' . $port);
539
540         $op= 'POST ' . $uri. " HTTP/1.0\r\n" .
541             'User-Agent: ' . $this->user_agent . "\r\n" .
542             'Host: '. $server . $port . "\r\n" .
543             $credentials .
544             $proxy_credentials .
545             $accepted_encoding .
546             $encoding_hdr .
547             'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
548             $cookieheader .
549             'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " .
550             strlen($payload) . "\r\n\r\n" .
551             $payload;
552
553         if($this->debug > 1)
554         {
555             print "<PRE>\n---SENDING---\n" . htmlentities($op) . "\n---END---\n</PRE>";
556             // let the client see this now in case http times out...
557             flush();
558         }
559
560         if($timeout>0)
561         {
562             $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout);
563         }
564         else
565         {
566             $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr);
567         }
568         if($fp)
569         {
570             if($timeout>0 && function_exists('stream_set_timeout'))
571             {
572                 stream_set_timeout($fp, $timeout);
573             }
574         }
575         else
576         {
577             $this->errstr='Connect error: '.$this->errstr;
578             $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
579             return $r;
580         }
581
582         if(!fputs($fp, $op, strlen($op)))
583         {
584             fclose($fp);
585             $this->errstr='Write error';
586             $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr);
587             return $r;
588         }
589         else
590         {
591             // reset errno and errstr on successful socket connection
592             $this->errstr = '';
593         }
594         // G. Giunta 2005/10/24: close socket before parsing.
595         // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
596         $ipd='';
597         do
598         {
599             // shall we check for $data === FALSE?
600             // as per the manual, it signals an error
601             $ipd.=fread($fp, 32768);
602         } while(!feof($fp));
603         fclose($fp);
604         $r =& $msg->parseResponse($ipd, false, $this->return_type);
605         return $r;
606
607     }
608
609     private function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='',
610         $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='',
611         $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1,
612         $keepalive=false, $key='', $keypass='')
613     {
614         $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username,
615             $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport,
616             $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass);
617         return $r;
618     }
619
620     /**
621      * Contributed by Justin Miller <justin@voxel.net>
622      * Requires curl to be built into PHP
623      * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
624      */
625     private function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='',
626         $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='',
627         $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https',
628         $keepalive=false, $key='', $keypass='')
629     {
630         $xmlrpc = Phpxmlrpc::instance();
631
632         if(!function_exists('curl_init'))
633         {
634             $this->errstr='CURL unavailable on this install';
635             $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_curl'], $xmlrpc->xmlrpcstr['no_curl']);
636             return $r;
637         }
638         if($method == 'https')
639         {
640             if(($info = curl_version()) &&
641                 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))))
642             {
643                 $this->errstr='SSL unavailable on this install';
644                 $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_ssl'], $xmlrpc->xmlrpcstr['no_ssl']);
645                 return $r;
646             }
647         }
648
649         if($port == 0)
650         {
651             if($method == 'http')
652             {
653                 $port = 80;
654             }
655             else
656             {
657                 $port = 443;
658             }
659         }
660
661         // Only create the payload if it was not created previously
662         if(empty($msg->payload))
663         {
664             $msg->createPayload($this->request_charset_encoding);
665         }
666
667         // Deflate request body and set appropriate request headers
668         $payload = $msg->payload;
669         if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
670         {
671             if($this->request_compression == 'gzip')
672             {
673                 $a = @gzencode($payload);
674                 if($a)
675                 {
676                     $payload = $a;
677                     $encoding_hdr = 'Content-Encoding: gzip';
678                 }
679             }
680             else
681             {
682                 $a = @gzcompress($payload);
683                 if($a)
684                 {
685                     $payload = $a;
686                     $encoding_hdr = 'Content-Encoding: deflate';
687                 }
688             }
689         }
690         else
691         {
692             $encoding_hdr = '';
693         }
694
695         if($this->debug > 1)
696         {
697             print "<PRE>\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n</PRE>";
698             // let the client see this now in case http times out...
699             flush();
700         }
701
702         if(!$keepalive || !$this->xmlrpc_curl_handle)
703         {
704             $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
705             if($keepalive)
706             {
707                 $this->xmlrpc_curl_handle = $curl;
708             }
709         }
710         else
711         {
712             $curl = $this->xmlrpc_curl_handle;
713         }
714
715         // results into variable
716         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
717
718         if($this->debug)
719         {
720             curl_setopt($curl, CURLOPT_VERBOSE, 1);
721         }
722         curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
723         // required for XMLRPC: post the data
724         curl_setopt($curl, CURLOPT_POST, 1);
725         // the data
726         curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
727
728         // return the header too
729         curl_setopt($curl, CURLOPT_HEADER, 1);
730
731         // NB: if we set an empty string, CURL will add http header indicating
732         // ALL methods it is supporting. This is possibly a better option than
733         // letting the user tell what curl can / cannot do...
734         if(is_array($this->accepted_compression) && count($this->accepted_compression))
735         {
736             //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
737             // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
738             if (count($this->accepted_compression) == 1)
739             {
740                 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
741             }
742             else
743                 curl_setopt($curl, CURLOPT_ENCODING, '');
744         }
745         // extra headers
746         $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
747         // if no keepalive is wanted, let the server know it in advance
748         if(!$keepalive)
749         {
750             $headers[] = 'Connection: close';
751         }
752         // request compression header
753         if($encoding_hdr)
754         {
755             $headers[] = $encoding_hdr;
756         }
757
758         curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
759         // timeout is borked
760         if($timeout)
761         {
762             curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
763         }
764
765         if($username && $password)
766         {
767             curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password);
768             if (defined('CURLOPT_HTTPAUTH'))
769             {
770                 curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype);
771             }
772             else if ($authtype != 1)
773             {
774                 error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported by the current PHP/curl install');
775             }
776         }
777
778         if($method == 'https')
779         {
780             // set cert file
781             if($cert)
782             {
783                 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
784             }
785             // set cert password
786             if($certpass)
787             {
788                 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass);
789             }
790             // whether to verify remote host's cert
791             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
792             // set ca certificates file/dir
793             if($cacert)
794             {
795                 curl_setopt($curl, CURLOPT_CAINFO, $cacert);
796             }
797             if($cacertdir)
798             {
799                 curl_setopt($curl, CURLOPT_CAPATH, $cacertdir);
800             }
801             // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
802             if($key)
803             {
804                 curl_setopt($curl, CURLOPT_SSLKEY, $key);
805             }
806             // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
807             if($keypass)
808             {
809                 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass);
810             }
811             // 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
812             curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
813         }
814
815         // proxy info
816         if($proxyhost)
817         {
818             if($proxyport == 0)
819             {
820                 $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080
821             }
822             curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport);
823             //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport);
824             if($proxyusername)
825             {
826                 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword);
827                 if (defined('CURLOPT_PROXYAUTH'))
828                 {
829                     curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype);
830                 }
831                 else if ($proxyauthtype != 1)
832                 {
833                     error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
834                 }
835             }
836         }
837
838         // NB: should we build cookie http headers by hand rather than let CURL do it?
839         // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
840         // set to client obj the the user...
841         if (count($this->cookies))
842         {
843             $cookieheader = '';
844             foreach ($this->cookies as $name => $cookie)
845             {
846                 $cookieheader .= $name . '=' . $cookie['value'] . '; ';
847             }
848             curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2));
849         }
850
851         foreach ($this->extracurlopts as $opt => $val)
852         {
853             curl_setopt($curl, $opt, $val);
854         }
855
856         $result = curl_exec($curl);
857
858         if ($this->debug > 1)
859         {
860             print "<PRE>\n---CURL INFO---\n";
861             foreach(curl_getinfo($curl) as $name => $val)
862             {
863                 if (is_array($val))
864                 {
865                     $val = implode("\n", $val);
866                 }
867                 print $name . ': ' . htmlentities($val) . "\n";
868             }
869
870             print "---END---\n</PRE>";
871         }
872
873         if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'?
874         {
875             $this->errstr='no response';
876             $resp=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['curl_fail'], $xmlrpc->xmlrpcstr['curl_fail']. ': '. curl_error($curl));
877             curl_close($curl);
878             if($keepalive)
879             {
880                 $this->xmlrpc_curl_handle = null;
881             }
882         }
883         else
884         {
885             if(!$keepalive)
886             {
887                 curl_close($curl);
888             }
889             $resp =& $msg->parseResponse($result, true, $this->return_type);
890             // if we got back a 302, we can not reuse the curl handle for later calls
891             if($resp->faultCode() == $xmlrpc->xmlrpcerr['http_error'] && $keepalive)
892             {
893                 curl_close($curl);
894                 $this->xmlrpc_curl_handle = null;
895             }
896         }
897         return $resp;
898     }
899
900     /**
901      * Send an array of request messages and return an array of responses.
902      * Unless $this->no_multicall has been set to true, it will try first
903      * to use one single xmlrpc call to server method system.multicall, and
904      * revert to sending many successive calls in case of failure.
905      * This failure is also stored in $this->no_multicall for subsequent calls.
906      * Unfortunately, there is no server error code universally used to denote
907      * the fact that multicall is unsupported, so there is no way to reliably
908      * distinguish between that and a temporary failure.
909      * If you are sure that server supports multicall and do not want to
910      * fallback to using many single calls, set the fourth parameter to FALSE.
911      *
912      * NB: trying to shoehorn extra functionality into existing syntax has resulted
913      * in pretty much convoluted code...
914      *
915      * @param array $msgs an array of xmlrpcmsg objects
916      * @param integer $timeout connection timeout (in seconds)
917      * @param string $method the http protocol variant to be used
918      * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted
919      * @return array
920      */
921     public function multicall($msgs, $timeout=0, $method='', $fallback=true)
922     {
923         $xmlrpc = Phpxmlrpc::instance();
924
925         if ($method == '')
926         {
927             $method = $this->method;
928         }
929         if(!$this->no_multicall)
930         {
931             $results = $this->_try_multicall($msgs, $timeout, $method);
932             if(is_array($results))
933             {
934                 // System.multicall succeeded
935                 return $results;
936             }
937             else
938             {
939                 // either system.multicall is unsupported by server,
940                 // or call failed for some other reason.
941                 if ($fallback)
942                 {
943                     // Don't try it next time...
944                     $this->no_multicall = true;
945                 }
946                 else
947                 {
948                     if (is_a($results, 'xmlrpcresp'))
949                     {
950                         $result = $results;
951                     }
952                     else
953                     {
954                         $result = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['multicall_error'], $xmlrpc->xmlrpcstr['multicall_error']);
955                     }
956                 }
957             }
958         }
959         else
960         {
961             // override fallback, in case careless user tries to do two
962             // opposite things at the same time
963             $fallback = true;
964         }
965
966         $results = array();
967         if ($fallback)
968         {
969             // system.multicall is (probably) unsupported by server:
970             // emulate multicall via multiple requests
971             foreach($msgs as $msg)
972             {
973                 $results[] =& $this->send($msg, $timeout, $method);
974             }
975         }
976         else
977         {
978             // user does NOT want to fallback on many single calls:
979             // since we should always return an array of responses,
980             // return an array with the same error repeated n times
981             foreach($msgs as $msg)
982             {
983                 $results[] = $result;
984             }
985         }
986         return $results;
987     }
988
989     /**
990      * Attempt to boxcar $msgs via system.multicall.
991      * Returns either an array of xmlrpcreponses, an xmlrpc error response
992      * or false (when received response does not respect valid multicall syntax)
993      */
994     private function _try_multicall($msgs, $timeout, $method)
995     {
996         // Construct multicall message
997         $calls = array();
998         foreach($msgs as $msg)
999         {
1000             $call['methodName'] = new xmlrpcval($msg->method(),'string');
1001             $numParams = $msg->getNumParams();
1002             $params = array();
1003             for($i = 0; $i < $numParams; $i++)
1004             {
1005                 $params[$i] = $msg->getParam($i);
1006             }
1007             $call['params'] = new xmlrpcval($params, 'array');
1008             $calls[] = new xmlrpcval($call, 'struct');
1009         }
1010         $multicall = new xmlrpcmsg('system.multicall');
1011         $multicall->addParam(new xmlrpcval($calls, 'array'));
1012
1013         // Attempt RPC call
1014         $result =& $this->send($multicall, $timeout, $method);
1015
1016         if($result->faultCode() != 0)
1017         {
1018             // call to system.multicall failed
1019             return $result;
1020         }
1021
1022         // Unpack responses.
1023         $rets = $result->value();
1024
1025         if ($this->return_type == 'xml')
1026         {
1027                 return $rets;
1028         }
1029         else if ($this->return_type == 'phpvals')
1030         {
1031             ///@todo test this code branch...
1032             $rets = $result->value();
1033             if(!is_array($rets))
1034             {
1035                 return false;       // bad return type from system.multicall
1036             }
1037             $numRets = count($rets);
1038             if($numRets != count($msgs))
1039             {
1040                 return false;       // wrong number of return values.
1041             }
1042
1043             $response = array();
1044             for($i = 0; $i < $numRets; $i++)
1045             {
1046                 $val = $rets[$i];
1047                 if (!is_array($val)) {
1048                     return false;
1049                 }
1050                 switch(count($val))
1051                 {
1052                     case 1:
1053                         if(!isset($val[0]))
1054                         {
1055                             return false;       // Bad value
1056                         }
1057                         // Normal return value
1058                         $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals');
1059                         break;
1060                     case 2:
1061                         /// @todo remove usage of @: it is apparently quite slow
1062                         $code = @$val['faultCode'];
1063                         if(!is_int($code))
1064                         {
1065                             return false;
1066                         }
1067                         $str = @$val['faultString'];
1068                         if(!is_string($str))
1069                         {
1070                             return false;
1071                         }
1072                         $response[$i] = new xmlrpcresp(0, $code, $str);
1073                         break;
1074                     default:
1075                         return false;
1076                 }
1077             }
1078             return $response;
1079         }
1080         else // return type == 'xmlrpcvals'
1081         {
1082             $rets = $result->value();
1083             if($rets->kindOf() != 'array')
1084             {
1085                 return false;       // bad return type from system.multicall
1086             }
1087             $numRets = $rets->arraysize();
1088             if($numRets != count($msgs))
1089             {
1090                 return false;       // wrong number of return values.
1091             }
1092
1093             $response = array();
1094             for($i = 0; $i < $numRets; $i++)
1095             {
1096                 $val = $rets->arraymem($i);
1097                 switch($val->kindOf())
1098                 {
1099                     case 'array':
1100                         if($val->arraysize() != 1)
1101                         {
1102                             return false;       // Bad value
1103                         }
1104                         // Normal return value
1105                         $response[$i] = new xmlrpcresp($val->arraymem(0));
1106                         break;
1107                     case 'struct':
1108                         $code = $val->structmem('faultCode');
1109                         if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int')
1110                         {
1111                             return false;
1112                         }
1113                         $str = $val->structmem('faultString');
1114                         if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string')
1115                         {
1116                             return false;
1117                         }
1118                         $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval());
1119                         break;
1120                     default:
1121                         return false;
1122                 }
1123             }
1124             return $response;
1125         }
1126     }
1127 }