Implement interface ArrayAccess in the Value class
[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                 $method
427             );
428         }
429
430         return $r;
431     }
432
433     /**
434      * @param Request $req
435      * @param string $server
436      * @param int $port
437      * @param int $timeout
438      * @param string $username
439      * @param string $password
440      * @param int $authType
441      * @param string $proxyHost
442      * @param int $proxyPort
443      * @param string $proxyUsername
444      * @param string $proxyPassword
445      * @param int $proxyAuthType
446      * @param string $method
447      * @return Response
448      */
449     protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
450                                        $username = '', $password = '', $authType = 1, $proxyHost = '',
451                                        $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
452                                        $method='http')
453     {
454         if ($port == 0) {
455             $port = ( $method === "https" ) ? 443 : 80;
456         }
457
458         // Only create the payload if it was not created previously
459         if (empty($req->payload)) {
460             $req->createPayload($this->request_charset_encoding);
461         }
462
463         $payload = $req->payload;
464         // Deflate request body and set appropriate request headers
465         if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
466             if ($this->request_compression == 'gzip') {
467                 $a = @gzencode($payload);
468                 if ($a) {
469                     $payload = $a;
470                     $encodingHdr = "Content-Encoding: gzip\r\n";
471                 }
472             } else {
473                 $a = @gzcompress($payload);
474                 if ($a) {
475                     $payload = $a;
476                     $encodingHdr = "Content-Encoding: deflate\r\n";
477                 }
478             }
479         } else {
480             $encodingHdr = '';
481         }
482
483         // thanks to Grant Rauscher <grant7@firstworld.net> for this
484         $credentials = '';
485         if ($username != '') {
486             $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
487             if ($authType != 1) {
488                 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
489             }
490         }
491
492         $acceptedEncoding = '';
493         if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
494             $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
495         }
496
497         $proxyCredentials = '';
498         if ($proxyHost) {
499             if ($proxyPort == 0) {
500                 $proxyPort = 8080;
501             }
502             $connectServer = $proxyHost;
503             $connectPort = $proxyPort;
504             $transport = "tcp";
505             $uri = 'http://' . $server . ':' . $port . $this->path;
506             if ($proxyUsername != '') {
507                 if ($proxyAuthType != 1) {
508                     error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
509                 }
510                 $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
511             }
512         } else {
513             $connectServer = $server;
514             $connectPort = $port;
515             /// @todo if supporting https, we should support all its current options as well: peer name verification etc...
516             $transport = ( $method === "https" ) ? "tls" : "tcp";
517             $uri = $this->path;
518         }
519
520         // Cookie generation, as per rfc2965 (version 1 cookies) or
521         // netscape's rules (version 0 cookies)
522         $cookieHeader = '';
523         if (count($this->cookies)) {
524             $version = '';
525             foreach ($this->cookies as $name => $cookie) {
526                 if ($cookie['version']) {
527                     $version = ' $Version="' . $cookie['version'] . '";';
528                     $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
529                     if ($cookie['path']) {
530                         $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
531                     }
532                     if ($cookie['domain']) {
533                         $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
534                     }
535                     if ($cookie['port']) {
536                         $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
537                     }
538                 } else {
539                     $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
540                 }
541             }
542             $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
543         }
544
545         // omit port if 80
546         $port = ($port == 80) ? '' : (':' . $port);
547
548         $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
549             'User-Agent: ' . $this->user_agent . "\r\n" .
550             'Host: ' . $server . $port . "\r\n" .
551             $credentials .
552             $proxyCredentials .
553             $acceptedEncoding .
554             $encodingHdr .
555             'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
556             $cookieHeader .
557             'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
558             strlen($payload) . "\r\n\r\n" .
559             $payload;
560
561         if ($this->debug > 1) {
562             Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
563         }
564
565         if ($timeout > 0) {
566             $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $timeout);
567         } else {
568             $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr);
569         }
570         if ($fp) {
571             if ($timeout > 0) {
572                 stream_set_timeout($fp, $timeout);
573             }
574         } else {
575             $this->errstr = 'Connect error: ' . $this->errstr;
576             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
577
578             return $r;
579         }
580
581         if (!fputs($fp, $op, strlen($op))) {
582             fclose($fp);
583             $this->errstr = 'Write error';
584             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
585
586             return $r;
587         } else {
588             // reset errno and errstr on successful socket connection
589             $this->errstr = '';
590         }
591         // G. Giunta 2005/10/24: close socket before parsing.
592         // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
593         $ipd = '';
594         do {
595             // shall we check for $data === FALSE?
596             // as per the manual, it signals an error
597             $ipd .= fread($fp, 32768);
598         } while (!feof($fp));
599         fclose($fp);
600         $r = $req->parseResponse($ipd, false, $this->return_type);
601
602         return $r;
603     }
604
605     /**
606      * @param Request $req
607      * @param string $server
608      * @param int $port
609      * @param int $timeout
610      * @param string $username
611      * @param string $password
612      * @param int $authType
613      * @param string $cert
614      * @param string $certPass
615      * @param string $caCert
616      * @param string $caCertDir
617      * @param string $proxyHost
618      * @param int $proxyPort
619      * @param string $proxyUsername
620      * @param string $proxyPassword
621      * @param int $proxyAuthType
622      * @param bool $keepAlive
623      * @param string $key
624      * @param string $keyPass
625      * @param int $sslVersion
626      * @return Response
627      */
628     protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '',
629                                       $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
630                                       $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
631                                       $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
632     {
633         return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
634             $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
635             $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
636     }
637
638     /**
639      * Contributed by Justin Miller <justin@voxel.net>
640      * Requires curl to be built into PHP
641      * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
642      *
643      * @param Request $req
644      * @param string $server
645      * @param int $port
646      * @param int $timeout
647      * @param string $username
648      * @param string $password
649      * @param int $authType
650      * @param string $cert
651      * @param string $certPass
652      * @param string $caCert
653      * @param string $caCertDir
654      * @param string $proxyHost
655      * @param int $proxyPort
656      * @param string $proxyUsername
657      * @param string $proxyPassword
658      * @param int $proxyAuthType
659      * @param string $method
660      * @param bool $keepAlive
661      * @param string $key
662      * @param string $keyPass
663      * @param int $sslVersion
664      * @return Response
665      */
666     protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '',
667                                      $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '',
668                                      $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https',
669                                      $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0)
670     {
671         if (!function_exists('curl_init')) {
672             $this->errstr = 'CURL unavailable on this install';
673             return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
674         }
675         if ($method == 'https') {
676             if (($info = curl_version()) &&
677                 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
678             ) {
679                 $this->errstr = 'SSL unavailable on this install';
680                 return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
681             }
682         }
683
684         if ($port == 0) {
685             if ($method == 'http') {
686                 $port = 80;
687             } else {
688                 $port = 443;
689             }
690         }
691
692         // Only create the payload if it was not created previously
693         if (empty($req->payload)) {
694             $req->createPayload($this->request_charset_encoding);
695         }
696
697         // Deflate request body and set appropriate request headers
698         $payload = $req->payload;
699         if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
700             if ($this->request_compression == 'gzip') {
701                 $a = @gzencode($payload);
702                 if ($a) {
703                     $payload = $a;
704                     $encodingHdr = 'Content-Encoding: gzip';
705                 }
706             } else {
707                 $a = @gzcompress($payload);
708                 if ($a) {
709                     $payload = $a;
710                     $encodingHdr = 'Content-Encoding: deflate';
711                 }
712             }
713         } else {
714             $encodingHdr = '';
715         }
716
717         if ($this->debug > 1) {
718             Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
719         }
720
721         if (!$keepAlive || !$this->xmlrpc_curl_handle) {
722             $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
723             if ($keepAlive) {
724                 $this->xmlrpc_curl_handle = $curl;
725             }
726         } else {
727             $curl = $this->xmlrpc_curl_handle;
728         }
729
730         // results into variable
731         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
732
733         if ($this->debug > 1) {
734             curl_setopt($curl, CURLOPT_VERBOSE, true);
735             /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
736         }
737         curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
738         // required for XMLRPC: post the data
739         curl_setopt($curl, CURLOPT_POST, 1);
740         // the data
741         curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
742
743         // return the header too
744         curl_setopt($curl, CURLOPT_HEADER, 1);
745
746         // NB: if we set an empty string, CURL will add http header indicating
747         // ALL methods it is supporting. This is possibly a better option than
748         // letting the user tell what curl can / cannot do...
749         if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
750             //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
751             // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
752             if (count($this->accepted_compression) == 1) {
753                 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
754             } else {
755                 curl_setopt($curl, CURLOPT_ENCODING, '');
756             }
757         }
758         // extra headers
759         $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
760         // if no keepalive is wanted, let the server know it in advance
761         if (!$keepAlive) {
762             $headers[] = 'Connection: close';
763         }
764         // request compression header
765         if ($encodingHdr) {
766             $headers[] = $encodingHdr;
767         }
768
769         curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
770         // timeout is borked
771         if ($timeout) {
772             curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
773         }
774
775         if ($username && $password) {
776             curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
777             if (defined('CURLOPT_HTTPAUTH')) {
778                 curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
779             } elseif ($authType != 1) {
780                 error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
781             }
782         }
783
784         if ($method == 'https') {
785             // set cert file
786             if ($cert) {
787                 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
788             }
789             // set cert password
790             if ($certPass) {
791                 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
792             }
793             // whether to verify remote host's cert
794             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
795             // set ca certificates file/dir
796             if ($caCert) {
797                 curl_setopt($curl, CURLOPT_CAINFO, $caCert);
798             }
799             if ($caCertDir) {
800                 curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
801             }
802             // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
803             if ($key) {
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                 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
809             }
810             // 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
811             curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
812             // allow usage of different SSL versions
813             curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
814         }
815
816         // proxy info
817         if ($proxyHost) {
818             if ($proxyPort == 0) {
819                 $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
820             }
821             curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
822             if ($proxyUsername) {
823                 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
824                 if (defined('CURLOPT_PROXYAUTH')) {
825                     curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
826                 } elseif ($proxyAuthType != 1) {
827                     error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
828                 }
829             }
830         }
831
832         // NB: should we build cookie http headers by hand rather than let CURL do it?
833         // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
834         // set to client obj the the user...
835         if (count($this->cookies)) {
836             $cookieHeader = '';
837             foreach ($this->cookies as $name => $cookie) {
838                 $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
839             }
840             curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
841         }
842
843         foreach ($this->extracurlopts as $opt => $val) {
844             curl_setopt($curl, $opt, $val);
845         }
846
847         $result = curl_exec($curl);
848
849         if ($this->debug > 1) {
850             $message = "---CURL INFO---\n";
851             foreach (curl_getinfo($curl) as $name => $val) {
852                 if (is_array($val)) {
853                     $val = implode("\n", $val);
854                 }
855                 $message .= $name . ': ' . $val . "\n";
856             }
857             $message .= "---END---";
858             Logger::instance()->debugMessage($message);
859         }
860
861         if (!$result) {
862             /// @todo we should use a better check here - what if we get back '' or '0'?
863
864             $this->errstr = 'no response';
865             $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
866             curl_close($curl);
867             if ($keepAlive) {
868                 $this->xmlrpc_curl_handle = null;
869             }
870         } else {
871             if (!$keepAlive) {
872                 curl_close($curl);
873             }
874             $resp = $req->parseResponse($result, true, $this->return_type);
875             // if we got back a 302, we can not reuse the curl handle for later calls
876             if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
877                 curl_close($curl);
878                 $this->xmlrpc_curl_handle = null;
879             }
880         }
881
882         return $resp;
883     }
884
885     /**
886      * Send an array of requests and return an array of responses.
887      * Unless $this->no_multicall has been set to true, it will try first
888      * to use one single xmlrpc call to server method system.multicall, and
889      * revert to sending many successive calls in case of failure.
890      * This failure is also stored in $this->no_multicall for subsequent calls.
891      * Unfortunately, there is no server error code universally used to denote
892      * the fact that multicall is unsupported, so there is no way to reliably
893      * distinguish between that and a temporary failure.
894      * If you are sure that server supports multicall and do not want to
895      * fallback to using many single calls, set the fourth parameter to FALSE.
896      *
897      * NB: trying to shoehorn extra functionality into existing syntax has resulted
898      * in pretty much convoluted code...
899      *
900      * @param Request[] $reqs an array of Request objects
901      * @param integer $timeout connection timeout (in seconds)
902      * @param string $method the http protocol variant to be used
903      * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted
904      *
905      * @return array
906      */
907     public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
908     {
909         if ($method == '') {
910             $method = $this->method;
911         }
912         if (!$this->no_multicall) {
913             $results = $this->_try_multicall($reqs, $timeout, $method);
914             if (is_array($results)) {
915                 // System.multicall succeeded
916                 return $results;
917             } else {
918                 // either system.multicall is unsupported by server,
919                 // or call failed for some other reason.
920                 if ($fallback) {
921                     // Don't try it next time...
922                     $this->no_multicall = true;
923                 } else {
924                     if (is_a($results, '\PhpXmlRpc\Response')) {
925                         $result = $results;
926                     } else {
927                         $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
928                     }
929                 }
930             }
931         } else {
932             // override fallback, in case careless user tries to do two
933             // opposite things at the same time
934             $fallback = true;
935         }
936
937         $results = array();
938         if ($fallback) {
939             // system.multicall is (probably) unsupported by server:
940             // emulate multicall via multiple requests
941             foreach ($reqs as $req) {
942                 $results[] = $this->send($req, $timeout, $method);
943             }
944         } else {
945             // user does NOT want to fallback on many single calls:
946             // since we should always return an array of responses,
947             // return an array with the same error repeated n times
948             foreach ($reqs as $req) {
949                 $results[] = $result;
950             }
951         }
952
953         return $results;
954     }
955
956     /**
957      * Attempt to boxcar $reqs via system.multicall.
958      * Returns either an array of xmlrpc reponses, an xmlrpc error response
959      * or false (when received response does not respect valid multicall syntax).
960      *
961      * @param Request[] $reqs
962      * @param int $timeout
963      * @param string $method
964      * @return array|bool|mixed|Response
965      */
966     private function _try_multicall($reqs, $timeout, $method)
967     {
968         // Construct multicall request
969         $calls = array();
970         foreach ($reqs as $req) {
971             $call['methodName'] = new Value($req->method(), 'string');
972             $numParams = $req->getNumParams();
973             $params = array();
974             for ($i = 0; $i < $numParams; $i++) {
975                 $params[$i] = $req->getParam($i);
976             }
977             $call['params'] = new Value($params, 'array');
978             $calls[] = new Value($call, 'struct');
979         }
980         $multiCall = new Request('system.multicall');
981         $multiCall->addParam(new Value($calls, 'array'));
982
983         // Attempt RPC call
984         $result = $this->send($multiCall, $timeout, $method);
985
986         if ($result->faultCode() != 0) {
987             // call to system.multicall failed
988             return $result;
989         }
990
991         // Unpack responses.
992         $rets = $result->value();
993
994         if ($this->return_type == 'xml') {
995             return $rets;
996         } elseif ($this->return_type == 'phpvals') {
997             /// @todo test this code branch...
998             $rets = $result->value();
999             if (!is_array($rets)) {
1000                 return false;       // bad return type from system.multicall
1001             }
1002             $numRets = count($rets);
1003             if ($numRets != count($reqs)) {
1004                 return false;       // wrong number of return values.
1005             }
1006
1007             $response = array();
1008             for ($i = 0; $i < $numRets; $i++) {
1009                 $val = $rets[$i];
1010                 if (!is_array($val)) {
1011                     return false;
1012                 }
1013                 switch (count($val)) {
1014                     case 1:
1015                         if (!isset($val[0])) {
1016                             return false;       // Bad value
1017                         }
1018                         // Normal return value
1019                         $response[$i] = new Response($val[0], 0, '', 'phpvals');
1020                         break;
1021                     case 2:
1022                         /// @todo remove usage of @: it is apparently quite slow
1023                         $code = @$val['faultCode'];
1024                         if (!is_int($code)) {
1025                             return false;
1026                         }
1027                         $str = @$val['faultString'];
1028                         if (!is_string($str)) {
1029                             return false;
1030                         }
1031                         $response[$i] = new Response(0, $code, $str);
1032                         break;
1033                     default:
1034                         return false;
1035                 }
1036             }
1037
1038             return $response;
1039         } else {
1040             // return type == 'xmlrpcvals'
1041
1042             $rets = $result->value();
1043             if ($rets->kindOf() != 'array') {
1044                 return false;       // bad return type from system.multicall
1045             }
1046             $numRets = $rets->count();
1047             if ($numRets != count($reqs)) {
1048                 return false;       // wrong number of return values.
1049             }
1050
1051             $response = array();
1052             //for ($i = 0; $i < $numRets; $i++) {
1053             foreach($rets as $val) {
1054                 //$val = $rets->arraymem($i);
1055                 switch ($val->kindOf()) {
1056                     case 'array':
1057                         if ($val->count() != 1) {
1058                             return false;       // Bad value
1059                         }
1060                         // Normal return value
1061                         //$response[] = new Response($val->arraymem(0));
1062                         $response[] = new Response($val[0]);
1063                         break;
1064                     case 'struct':
1065                         //$code = $val->structmem('faultCode');
1066                         $code = $val['faultCode'];
1067                         if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1068                             return false;
1069                         }
1070                         //$str = $val->structmem('faultString');
1071                         $str = $val['faultString'];
1072                         if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1073                             return false;
1074                         }
1075                         $response[] = new Response(0, $code->scalarval(), $str->scalarval());
1076                         break;
1077                     default:
1078                         return false;
1079                 }
1080             }
1081
1082             return $response;
1083         }
1084     }
1085 }