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