Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
 
3
namespace PhpXmlRpc;
4
 
5
use PhpXmlRpc\Exception\ValueErrorException;
6
use PhpXmlRpc\Helper\XMLParser;
7
use PhpXmlRpc\Traits\CharsetEncoderAware;
8
use PhpXmlRpc\Traits\DeprecationLogger;
9
 
10
/**
11
 * Used to represent a client of an XML-RPC server.
12
 *
13
 * @property int $errno deprecated - public access left in purely for BC.
14
 * @property string $errstr deprecated - public access left in purely for BC.
15
 * @property string $method deprecated - public access left in purely for BC. Access via getUrl()/__construct()
16
 * @property string $server deprecated - public access left in purely for BC. Access via getUrl()/__construct()
17
 * @property int $port deprecated - public access left in purely for BC. Access via getUrl()/__construct()
18
 * @property string $path deprecated - public access left in purely for BC. Access via getUrl()/__construct()
19
 */
20
class Client
21
{
22
    use DeprecationLogger;
23
    //use CharsetEncoderAware;
24
 
25
    const USE_CURL_NEVER = 0;
26
    const USE_CURL_ALWAYS = 1;
27
    const USE_CURL_AUTO = 2;
28
 
29
    const OPT_ACCEPTED_CHARSET_ENCODINGS = 'accepted_charset_encodings';
30
    const OPT_ACCEPTED_COMPRESSION = 'accepted_compression';
31
    const OPT_AUTH_TYPE = 'authtype';
32
    const OPT_CA_CERT = 'cacert';
33
    const OPT_CA_CERT_DIR = 'cacertdir';
34
    const OPT_CERT = 'cert';
35
    const OPT_CERT_PASS = 'certpass';
36
    const OPT_COOKIES = 'cookies';
37
    const OPT_DEBUG = 'debug';
38
    const OPT_EXTRA_CURL_OPTS = 'extracurlopts';
39
    const OPT_EXTRA_SOCKET_OPTS = 'extrasockopts';
40
    const OPT_KEEPALIVE = 'keepalive';
41
    const OPT_KEY = 'key';
42
    const OPT_KEY_PASS = 'keypass';
43
    const OPT_NO_MULTICALL = 'no_multicall';
44
    const OPT_PASSWORD = 'password';
45
    const OPT_PROXY = 'proxy';
46
    const OPT_PROXY_AUTH_TYPE = 'proxy_authtype';
47
    const OPT_PROXY_PASS = 'proxy_pass';
48
    const OPT_PROXY_PORT = 'proxyport';
49
    const OPT_PROXY_USER = 'proxy_user';
50
    const OPT_REQUEST_CHARSET_ENCODING = 'request_charset_encoding';
51
    const OPT_REQUEST_COMPRESSION = 'request_compression';
52
    const OPT_RETURN_TYPE = 'return_type';
53
    const OPT_SSL_VERSION = 'sslversion';
54
    const OPT_TIMEOUT = 'timeout';
55
    const OPT_USERNAME = 'username';
56
    const OPT_USER_AGENT = 'user_agent';
57
    const OPT_USE_CURL = 'use_curl';
58
    const OPT_VERIFY_HOST = 'verifyhost';
59
    const OPT_VERIFY_PEER = 'verifypeer';
60
    const OPT_EXTRA_HEADERS = 'extra_headers';
61
 
62
    /** @var string */
63
    protected static $requestClass = '\\PhpXmlRpc\\Request';
64
    /** @var string */
65
    protected static $responseClass = '\\PhpXmlRpc\\Response';
66
 
67
    /**
68
     * @var int
69
     * @deprecated will be removed in the future
70
     */
71
    protected $errno;
72
    /**
73
     * @var string
74
     * @deprecated will be removed in the future
75
     */
76
    protected $errstr;
77
 
78
    /// @todo: do all the ones below need to be public?
79
 
80
    /**
81
     * @var string
82
     */
83
    protected $method = 'http';
84
    /**
85
     * @var string
86
     */
87
    protected $server;
88
    /**
89
     * @var int
90
     */
91
    protected $port = 0;
92
    /**
93
     * @var string
94
     */
95
    protected $path;
96
 
97
    /**
98
     * @var int
99
     */
100
    protected $debug = 0;
101
    /**
102
     * @var string
103
     */
104
    protected $username = '';
105
    /**
106
     * @var string
107
     */
108
    protected $password = '';
109
    /**
110
     * @var int
111
     */
112
    protected $authtype = 1;
113
    /**
114
     * @var string
115
     */
116
    protected $cert = '';
117
    /**
118
     * @var string
119
     */
120
    protected $certpass = '';
121
    /**
122
     * @var string
123
     */
124
    protected $cacert = '';
125
    /**
126
     * @var string
127
     */
128
    protected $cacertdir = '';
129
    /**
130
     * @var string
131
     */
132
    protected $key = '';
133
    /**
134
     * @var string
135
     */
136
    protected $keypass = '';
137
    /**
138
     * @var bool
139
     */
140
    protected $verifypeer = true;
141
    /**
142
     * @var int
143
     */
144
    protected $verifyhost = 2;
145
    /**
146
     * @var int
147
     */
148
    protected $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT. Other  CURL_SSLVERSION_ values are supported
149
    /**
150
     * @var string
151
     */
152
    protected $proxy = '';
153
    /**
154
     * @var int
155
     */
156
    protected $proxyport = 0;
157
    /**
158
     * @var string
159
     */
160
    protected $proxy_user = '';
161
    /**
162
     * @var string
163
     */
164
    protected $proxy_pass = '';
165
    /**
166
     * @var int
167
     */
168
    protected $proxy_authtype = 1;
169
    /**
170
     * @var array
171
     */
172
    protected $cookies = array();
173
    /**
174
     * @var array
175
     */
176
    protected $extrasockopts = array();
177
    /**
178
     * @var array
179
     */
180
    protected $extracurlopts = array();
181
    /**
182
     * @var int
183
     */
184
    protected $timeout = 0;
185
    /**
186
     * @var int
187
     */
188
    protected $use_curl = self::USE_CURL_AUTO;
189
    /**
190
     * @var bool
191
     *
192
     * This determines whether the multicall() method will try to take advantage of the system.multicall xml-rpc method
193
     * to dispatch to the server an array of requests in a single http roundtrip or simply execute many consecutive http
194
     * calls. Defaults to FALSE, but it will be enabled automatically on the first failure of execution of
195
     * system.multicall.
196
     */
197
    protected $no_multicall = false;
198
    /**
199
     * @var array
200
     *
201
     * List of http compression methods accepted by the client for responses.
202
     * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib.
203
     *
204
     * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since in those cases it will be up to CURL to
205
     * decide the compression methods it supports. You might check for the presence of 'zlib' in the output of
206
     * curl_version() to determine whether compression is supported or not
207
     */
208
    protected $accepted_compression = array();
209
    /**
210
     * @var string|null
211
     *
212
     * Name of compression scheme to be used for sending requests.
213
     * Either null, 'gzip' or 'deflate'.
214
     */
215
    protected $request_compression = '';
216
    /**
217
     * @var bool
218
     *
219
     * Whether to use persistent connections for http 1.1 and https. Value set at constructor time.
220
     */
221
    protected $keepalive = false;
222
    /**
223
     * @var string[]
224
     *
225
     * Charset encodings that can be decoded without problems by the client. Value set at constructor time
226
     */
227
    protected $accepted_charset_encodings = array();
228
    /**
229
     * @var string
230
     *
231
     * The charset encoding that will be used for serializing request sent by the client.
232
     * It defaults to NULL, which means using US-ASCII and encoding all characters outside the ASCII printable range
233
     * using their xml character entity representation (this has the benefit that line end characters will not be mangled
234
     * in the transfer, a CR-LF will be preserved as well as a singe LF).
235
     * Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1'.
236
     * For the fastest mode of operation, set your both your app internal encoding and this to UTF-8.
237
     */
238
    protected $request_charset_encoding = '';
239
    /**
240
     * @var string
241
     *
242
     * Decides the content of Response objects returned by calls to send() and multicall().
243
     * Valid values are 'xmlrpcvals', 'phpvals' or 'xml'.
244
     *
245
     * Determines whether the value returned inside a Response object as results of calls to the send() and multicall()
246
     * methods will be a Value object, a plain php value or a raw xml string.
247
     * Allowed values are 'xmlrpcvals' (the default), 'phpvals' and 'xml'.
248
     * To allow the user to differentiate between a correct and a faulty response, fault responses will be returned as
249
     * Response objects in any case.
250
     * Note that the 'phpvals' setting will yield faster execution times, but some of the information from the original
251
     * response will be lost. It will be e.g. impossible to tell whether a particular php string value was sent by the
252
     * server as an xml-rpc string or base64 value.
253
     */
254
    protected $return_type = XMLParser::RETURN_XMLRPCVALS;
255
    /**
256
     * @var string
257
     *
258
     * Sent to servers in http headers. Value set at constructor time.
259
     */
260
    protected $user_agent;
261
 
262
    /**
263
     * Additional headers to be included in the requests.
264
     *
265
     * @var string[]
266
     */
267
    protected $extra_headers = array();
268
 
269
    /**
270
     * CURL handle: used for keep-alive
271
     * @internal
272
     */
273
    public $xmlrpc_curl_handle = null;
274
 
275
    /**
276
     * @var array
277
     */
278
    protected static $options = array(
279
        self::OPT_ACCEPTED_CHARSET_ENCODINGS,
280
        self::OPT_ACCEPTED_COMPRESSION,
281
        self::OPT_AUTH_TYPE,
282
        self::OPT_CA_CERT,
283
        self::OPT_CA_CERT_DIR,
284
        self::OPT_CERT,
285
        self::OPT_CERT_PASS,
286
        self::OPT_COOKIES,
287
        self::OPT_DEBUG,
288
        self::OPT_EXTRA_CURL_OPTS,
289
        self::OPT_EXTRA_SOCKET_OPTS,
290
        self::OPT_KEEPALIVE,
291
        self::OPT_KEY,
292
        self::OPT_KEY_PASS,
293
        self::OPT_NO_MULTICALL,
294
        self::OPT_PASSWORD,
295
        self::OPT_PROXY,
296
        self::OPT_PROXY_AUTH_TYPE,
297
        self::OPT_PROXY_PASS,
298
        self::OPT_PROXY_USER,
299
        self::OPT_PROXY_PORT,
300
        self::OPT_REQUEST_CHARSET_ENCODING,
301
        self::OPT_REQUEST_COMPRESSION,
302
        self::OPT_RETURN_TYPE,
303
        self::OPT_SSL_VERSION,
304
        self::OPT_TIMEOUT,
305
        self::OPT_USE_CURL,
306
        self::OPT_USER_AGENT,
307
        self::OPT_USERNAME,
308
        self::OPT_VERIFY_HOST,
309
        self::OPT_VERIFY_PEER,
310
        self::OPT_EXTRA_HEADERS,
311
    );
312
 
313
    /**
314
     * @param string $path either the PATH part of the xml-rpc server URL, or complete server URL (in which case you
315
     *                     should use an empty string for all other parameters)
316
     *                     e.g. /xmlrpc/server.php
317
     *                     e.g. http://phpxmlrpc.sourceforge.net/server.php
318
     *                     e.g. https://james:bond@secret.service.com:444/xmlrpcserver?agent=007
319
     *                     e.g. h2://fast-and-secure-services.org/endpoint
320
     * @param string $server the server name / ip address
321
     * @param integer $port the port the server is listening on, when omitted defaults to 80 or 443 depending on
322
     *                      protocol used
323
     * @param string $method the http protocol variant: defaults to 'http'; 'https', 'http11', 'h2' and 'h2c' can
324
     *                       be used if CURL is installed. The value set here can be overridden in any call to $this->send().
325
     *                       Use 'h2' to make the lib attempt to use http/2 over a secure connection, and 'h2c'
326
     *                       for http/2 without tls. Note that 'h2c' will not use the h2c 'upgrade' method, and be
327
     *                       thus incompatible with any server/proxy not supporting http/2. This is because POST
328
     *                       request are not compatible with h2c upgrade.
329
     */
330
    public function __construct($path, $server = '', $port = '', $method = '')
331
    {
332
        // allow user to specify all params in $path
333
        if ($server == '' && $port == '' && $method == '') {
334
            $parts = parse_url($path);
335
            $server = $parts['host'];
336
            $path = isset($parts['path']) ? $parts['path'] : '';
337
            if (isset($parts['query'])) {
338
                $path .= '?' . $parts['query'];
339
            }
340
            if (isset($parts['fragment'])) {
341
                $path .= '#' . $parts['fragment'];
342
            }
343
            if (isset($parts['port'])) {
344
                $port = $parts['port'];
345
            }
346
            if (isset($parts['scheme'])) {
347
                $method = $parts['scheme'];
348
            }
349
            if (isset($parts['user'])) {
350
                $this->username = $parts['user'];
351
            }
352
            if (isset($parts['pass'])) {
353
                $this->password = $parts['pass'];
354
            }
355
        }
356
        if ($path == '' || $path[0] != '/') {
357
            $this->path = '/' . $path;
358
        } else {
359
            $this->path = $path;
360
        }
361
        $this->server = $server;
362
        if ($port != '') {
363
            $this->port = $port;
364
        }
365
        if ($method != '') {
366
            $this->method = $method;
367
        }
368
 
369
        // if ZLIB is enabled, let the client by default accept compressed responses
370
        if (function_exists('gzinflate') || (
371
                function_exists('curl_version') && (($info = curl_version()) &&
372
                    ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
373
            )
374
        ) {
375
            $this->accepted_compression = array('gzip', 'deflate');
376
        }
377
 
378
        // keepalives: enabled by default
379
        $this->keepalive = true;
380
 
381
        // by default the xml parser can support these 3 charset encodings
382
        $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
383
 
384
        // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
385
        //$ch = $this->getCharsetEncoder();
386
        //$this->accepted_charset_encodings = $ch->knownCharsets();
387
 
388
        // initialize user_agent string
389
        $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
390
    }
391
 
392
    /**
393
     * @param string $name see all the OPT_ constants
394
     * @param mixed $value
395
     * @return $this
396
     * @throws ValueErrorException on unsupported option
397
     */
398
    public function setOption($name, $value)
399
    {
400
        if (in_array($name, static::$options)) {
401
            $this->$name = $value;
402
            return $this;
403
        }
404
 
405
        throw new ValueErrorException("Unsupported option '$name'");
406
    }
407
 
408
    /**
409
     * @param string $name see all the OPT_ constants
410
     * @return mixed
411
     * @throws ValueErrorException on unsupported option
412
     */
413
    public function getOption($name)
414
    {
415
        if (in_array($name, static::$options)) {
416
            return $this->$name;
417
        }
418
 
419
        throw new ValueErrorException("Unsupported option '$name'");
420
    }
421
 
422
    /**
423
     * Returns the complete list of Client options, with their value.
424
     * @return array
425
     */
426
    public function getOptions()
427
    {
428
        $values = array();
429
        foreach (static::$options as $opt) {
430
            $values[$opt] = $this->getOption($opt);
431
        }
432
        return $values;
433
    }
434
 
435
    /**
436
     * @param array $options key: any valid option (see all the OPT_ constants)
437
     * @return $this
438
     * @throws ValueErrorException on unsupported option
439
     */
440
    public function setOptions($options)
441
    {
442
        foreach ($options as $name => $value) {
443
            $this->setOption($name, $value);
444
        }
445
 
446
        return $this;
447
    }
448
 
449
    /**
450
     * Enable/disable the echoing to screen of the xml-rpc responses received. The default is not to output anything.
451
     *
452
     * The debugging information at level 1 includes the raw data returned from the XML-RPC server it was querying
453
     * (including bot HTTP headers and the full XML payload), and the PHP value the client attempts to create to
454
     * represent the value returned by the server.
455
     * At level 2, the complete payload of the xml-rpc request is also printed, before being sent to the server.
456
     * At level -1, the Response objects returned by send() calls will not carry information about the http response's
457
     * cookies, headers and body, which might save some memory
458
     *
459
     * This option can be very useful when debugging servers as it allows you to see exactly what the client sends and
460
     * the server returns. Never leave it enabled for production!
461
     *
462
     * @param integer $level values -1, 0, 1 and 2 are supported
463
     * @return $this
464
     */
465
    public function setDebug($level)
466
    {
467
        $this->debug = $level;
468
        return $this;
469
    }
470
 
471
    /**
472
     * Sets the username and password for authorizing the client to the server.
473
     *
474
     * With the default (HTTP) transport, this information is used for HTTP Basic authorization.
475
     * Note that username and password can also be set using the class constructor.
476
     * With HTTP 1.1 and HTTPS transport, NTLM and Digest authentication protocols are also supported. To enable them use
477
     * the constants CURLAUTH_DIGEST and CURLAUTH_NTLM as values for the auth type parameter.
478
     *
479
     * @param string $user username
480
     * @param string $password password
481
     * @param integer $authType auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC
482
     *                          (basic auth). Note that auth types NTLM and Digest will only work if the Curl php
483
     *                          extension is enabled.
484
     * @return $this
485
     */
486
    public function setCredentials($user, $password, $authType = 1)
487
    {
488
        $this->username = $user;
489
        $this->password = $password;
490
        $this->authtype = $authType;
491
        return $this;
492
    }
493
 
494
    /**
495
     * Set the optional certificate and passphrase used in SSL-enabled communication with a remote server.
496
     *
497
     * Note: to retrieve information about the client certificate on the server side, you will need to look into the
498
     * environment variables which are set up by the webserver. Different webservers will typically set up different
499
     * variables.
500
     *
501
     * @param string $cert the name of a file containing a PEM formatted certificate
502
     * @param string $certPass the password required to use it
503
     * @return $this
504
     */
505
    public function setCertificate($cert, $certPass = '')
506
    {
507
        $this->cert = $cert;
508
        $this->certpass = $certPass;
509
        return $this;
510
    }
511
 
512
    /**
513
     * Add a CA certificate to verify server with in SSL-enabled communication when SetSSLVerifypeer has been set to TRUE.
514
     *
515
     * See the php manual page about CURLOPT_CAINFO for more details.
516
     *
517
     * @param string $caCert certificate file name (or dir holding certificates)
518
     * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
519
     * @return $this
520
     */
521
    public function setCaCertificate($caCert, $isDir = false)
522
    {
523
        if ($isDir) {
524
            $this->cacertdir = $caCert;
525
        } else {
526
            $this->cacert = $caCert;
527
        }
528
        return $this;
529
    }
530
 
531
    /**
532
     * Set attributes for SSL communication: private SSL key.
533
     *
534
     * NB: does not work in older php/curl installs.
535
     * Thanks to Daniel Convissor.
536
     *
537
     * @param string $key The name of a file containing a private SSL key
538
     * @param string $keyPass The secret password needed to use the private SSL key
539
     * @return $this
540
     */
541
    public function setKey($key, $keyPass)
542
    {
543
        $this->key = $key;
544
        $this->keypass = $keyPass;
545
        return $this;
546
    }
547
 
548
    /**
549
     * Set attributes for SSL communication: verify the remote host's SSL certificate, and cause the connection to fail
550
     * if the cert verification fails.
551
     *
552
     * By default, verification is enabled.
553
     * To specify custom SSL certificates to validate the server with, use the setCaCertificate method.
554
     *
555
     * @param bool $i enable/disable verification of peer certificate
556
     * @return $this
557
     * @deprecated use setOption
558
     */
559
    public function setSSLVerifyPeer($i)
560
    {
561
        $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
562
 
563
        $this->verifypeer = $i;
564
        return $this;
565
    }
566
 
567
    /**
568
     * Set attributes for SSL communication: verify the remote host's SSL certificate's common name (CN).
569
     *
570
     * Note that support for value 1 has been removed in cURL 7.28.1
571
     *
572
     * @param int $i Set to 1 to only the existence of a CN, not that it matches
573
     * @return $this
574
     * @deprecated use setOption
575
     */
576
    public function setSSLVerifyHost($i)
577
    {
578
        $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
579
 
580
        $this->verifyhost = $i;
581
        return $this;
582
    }
583
 
584
    /**
585
     * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value): let cURL decide
586
     *
587
     * @param int $i see  CURL_SSLVERSION_ constants
588
     * @return $this
589
     * @deprecated use setOption
590
     */
591
    public function setSSLVersion($i)
592
    {
593
        $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
594
 
595
        $this->sslversion = $i;
596
        return $this;
597
    }
598
 
599
    /**
600
     * Set proxy info.
601
     *
602
     * NB: CURL versions before 7.11.10 cannot use a proxy to communicate with https servers.
603
     *
604
     * @param string $proxyHost
605
     * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
606
     * @param string $proxyUsername Leave blank if proxy has public access
607
     * @param string $proxyPassword Leave blank if proxy has public access
608
     * @param int $proxyAuthType defaults to CURLAUTH_BASIC (Basic authentication protocol); set to constant CURLAUTH_NTLM
609
     *                           to use NTLM auth with proxy (has effect only when the client uses the HTTP 1.1 protocol)
610
     * @return $this
611
     */
612
    public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
613
    {
614
        $this->proxy = $proxyHost;
615
        $this->proxyport = $proxyPort;
616
        $this->proxy_user = $proxyUsername;
617
        $this->proxy_pass = $proxyPassword;
618
        $this->proxy_authtype = $proxyAuthType;
619
        return $this;
620
    }
621
 
622
    /**
623
     * Enables/disables reception of compressed xml-rpc responses.
624
     *
625
     * This requires the "zlib" extension to be enabled in your php install. If it is, by default xmlrpc_client
626
     * instances will enable reception of compressed content.
627
     * Note that enabling reception of compressed responses merely adds some standard http headers to xml-rpc requests.
628
     * It is up to the xml-rpc server to return compressed responses when receiving such requests.
629
     *
630
     * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
631
     * @return $this
632
     */
633
    public function setAcceptedCompression($compMethod)
634
    {
635
        if ($compMethod == 'any') {
636
            $this->accepted_compression = array('gzip', 'deflate');
637
        } elseif ($compMethod == false) {
638
            $this->accepted_compression = array();
639
        } else {
640
            $this->accepted_compression = array($compMethod);
641
        }
642
        return $this;
643
    }
644
 
645
    /**
646
     * Enables/disables http compression of xml-rpc request.
647
     *
648
     * This requires the "zlib" extension to be enabled in your php install.
649
     * Take care when sending compressed requests: servers might not support them (and automatic fallback to
650
     * uncompressed requests is not yet implemented).
651
     *
652
     * @param string $compMethod either 'gzip', 'deflate' or ''
653
     * @return $this
654
     * @deprecated use setOption
655
     */
656
    public function setRequestCompression($compMethod)
657
    {
658
        $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
659
 
660
        $this->request_compression = $compMethod;
661
        return $this;
662
    }
663
 
664
    /**
665
     * Adds a cookie to list of cookies that will be sent to server with every further request (useful e.g. for keeping
666
     * session info outside the xml-rpc payload).
667
     *
668
     * NB: by default all cookies set via this method are sent to the server, regardless of path/domain/port. Taking
669
     * advantage of those values is left to the single developer.
670
     *
671
     * @param string $name nb: will not be escaped in the request's http headers. Take care not to use CTL chars or
672
     *                     separators!
673
     * @param string $value
674
     * @param string $path
675
     * @param string $domain
676
     * @param int $port do not use! Cookies are not separated by port
677
     * @return $this
678
     *
679
     * @todo check correctness of urlencoding cookie value (copied from php way of doing it, but php is generally sending
680
     *       response not requests. We do the opposite...)
681
     * @todo strip invalid chars from cookie name? As per RFC 6265, we should follow RFC 2616, Section 2.2
682
     * @todo drop/rename $port parameter. Cookies are not isolated by port!
683
     * @todo feature-creep allow storing 'expires', 'secure', 'httponly' and 'samesite' cookie attributes (we could do
684
     *       as php, and allow $path to be an array of attributes...)
685
     */
686
    public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
687
    {
688
        $this->cookies[$name]['value'] = rawurlencode($value);
689
        if ($path || $domain || $port) {
690
            $this->cookies[$name]['path'] = $path;
691
            $this->cookies[$name]['domain'] = $domain;
692
            $this->cookies[$name]['port'] = $port;
693
        }
694
        return $this;
695
    }
696
 
697
    /**
698
     * Directly set cURL options, for extra flexibility (when in cURL mode).
699
     *
700
     * It allows e.g. to bind client to a specific IP interface / address.
701
     *
702
     * @param array $options
703
     * @return $this
704
     * @deprecated use setOption
705
     */
706
    public function setCurlOptions($options)
707
    {
708
        $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
709
 
710
        $this->extracurlopts = $options;
711
        return $this;
712
    }
713
 
714
    /**
715
     * @param int $useCurlMode self::USE_CURL_ALWAYS, self::USE_CURL_AUTO or self::USE_CURL_NEVER
716
     * @return $this
717
     * @deprecated use setOption
718
     */
719
    public function setUseCurl($useCurlMode)
720
    {
721
        $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
722
 
723
        $this->use_curl = $useCurlMode;
724
        return $this;
725
    }
726
 
727
 
728
    /**
729
     * Set user-agent string that will be used by this client instance in http headers sent to the server.
730
     *
731
     * The default user agent string includes the name of this library and the version number.
732
     *
733
     * @param string $agentString
734
     * @return $this
735
     * @deprecated use setOption
736
     */
737
    public function setUserAgent($agentString)
738
    {
739
        $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
740
 
741
        $this->user_agent = $agentString;
742
        return $this;
743
    }
744
 
745
    /**
746
     * @param null|int $component allowed values: PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_PATH
747
     * @return string|int Notes: the path component will include query string and fragment; NULL is a valid value for port
748
     *                    (in which case the default port for http/https will be used);
749
     * @throws ValueErrorException on unsupported component
750
     */
751
    public function getUrl($component = null)
752
    {
753
        if (is_int($component) || ctype_digit($component)) {
754
            switch ($component) {
755
                case PHP_URL_SCHEME:
756
                    return $this->method;
757
                case PHP_URL_HOST:
758
                    return $this->server;
759
                case PHP_URL_PORT:
760
                    return $this->port;
761
                case  PHP_URL_PATH:
762
                    return $this->path;
763
                case '':
764
 
765
                default:
766
                    throw new ValueErrorException("Unsupported component '$component'");
767
            }
768
        }
769
 
770
        $url = $this->method . '://' . $this->server;
771
        if ($this->port == 0 || ($this->port == 80 && in_array($this->method, array('http', 'http10', 'http11', 'h2c'))) ||
772
            ($this->port == 443 && in_array($this->method, array('https', 'h2')))) {
773
            return $url . $this->path;
774
        } else {
775
            return $url . ':' . $this->port . $this->path;
776
        }
777
    }
778
 
779
    /**
780
     * Send an xml-rpc request to the server.
781
     *
782
     * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the
783
     *                                      complete xml representation of a request.
784
     *                                      When sending an array of Request objects, the client will try to make use of
785
     *                                      a single 'system.multicall' xml-rpc method call to forward to the server all
786
     *                                      the requests in a single HTTP round trip, unless $this->no_multicall has
787
     *                                      been previously set to TRUE (see the multicall method below), in which case
788
     *                                      many consecutive xml-rpc requests will be sent. The method will return an
789
     *                                      array of Response objects in both cases.
790
     *                                      The third variant allows to build by hand (or any other means) a complete
791
     *                                      xml-rpc request message, and send it to the server. $req should be a string
792
     *                                      containing the complete xml representation of the request. It is e.g. useful
793
     *                                      when, for maximal speed of execution, the request is serialized into a
794
     *                                      string using the native php xml-rpc functions (see http://www.php.net/xmlrpc)
795
     * @param integer $timeout deprecated. Connection timeout, in seconds, If unspecified, the timeout set with setOption
796
     *                         will be used. If that is 0, a platform specific timeout will apply.
797
     *                         This timeout value is passed to fsockopen(). It is also used for detecting server
798
     *                         timeouts during communication (i.e. if the server does not send anything to the client
799
     *                         for $timeout seconds, the connection will be closed).
800
     * @param string $method deprecated. Use the same value in the constructor instead.
801
     *                       Valid values are 'http', 'http11', 'https', 'h2' and 'h2c'. If left empty,
802
     *                       the http protocol chosen during creation of the object will be used.
803
     *                       Use 'h2' to make the lib attempt to use http/2 over a secure connection, and 'h2c'
804
     *                       for http/2 without tls. Note that 'h2c' will not use the h2c 'upgrade' method, and be
805
     *                       thus incompatible with any server/proxy not supporting http/2. This is because POST
806
     *                       request are not compatible with h2c upgrade.
807
     * @return Response|Response[] Note that the client will always return a Response object, even if the call fails
808
     *
809
     * @todo allow throwing exceptions instead of returning responses in case of failed calls and/or Fault responses
810
     * @todo refactor: we now support many options besides connection timeout and http version to use. Why only privilege those?
811
     */
812
    public function send($req, $timeout = 0, $method = '')
813
    {
814
        if ($method !== '' || $timeout !== 0) {
815
            $this->logDeprecation("Using non-default values for arguments 'method' and 'timeout' when calling method " . __METHOD__ . ' is deprecated');
816
        }
817
 
818
        // if user does not specify http protocol, use native method of this client
819
        // (i.e. method set during call to constructor)
820
        if ($method == '') {
821
            $method = $this->method;
822
        }
823
 
824
        if ($timeout == 0) {
825
            $timeout = $this->timeout;
826
        }
827
 
828
        if (is_array($req)) {
829
            // $req is an array of Requests
830
            /// @todo switch to the new syntax for multicall
831
            return $this->multicall($req, $timeout, $method);
832
        } elseif (is_string($req)) {
833
            $n = new static::$requestClass('');
834
            /// @todo we should somehow allow the caller to declare a custom contenttype too, esp. for the charset declaration
835
            $n->setPayload($req);
836
            $req = $n;
837
        }
838
 
839
        // where req is a Request
840
        $req->setDebug($this->debug);
841
 
842
        /// @todo we could be smarter about this and not force usage of curl for https if not present as well as use the
843
        ///       presence of curl_extra_opts or socket_extra_opts as a hint
844
        $useCurl = ($this->use_curl == self::USE_CURL_ALWAYS) || ($this->use_curl == self::USE_CURL_AUTO && (
845
            in_array($method, array('https', 'http11', 'h2c', 'h2')) ||
846
            ($this->username != '' && $this->authtype != 1) ||
847
            ($this->proxy != '' && $this->proxy_user != '' && $this->proxy_authtype != 1)
848
        ));
849
 
850
        // BC - we go through sendPayloadCURL/sendPayloadSocket in case some subclass reimplemented those
851
        if ($useCurl) {
852
            $r = $this->sendPayloadCURL(
853
                $req,
854
                $this->server,
855
                $this->port,
856
                $timeout,
857
                $this->username,
858
                $this->password,
859
                $this->authtype,
860
                $this->cert,
861
                $this->certpass,
862
                $this->cacert,
863
                $this->cacertdir,
864
                $this->proxy,
865
                $this->proxyport,
866
                $this->proxy_user,
867
                $this->proxy_pass,
868
                $this->proxy_authtype,
869
                // BC
870
                $method == 'http11' ? 'http' : $method,
871
                $this->keepalive,
872
                $this->key,
873
                $this->keypass,
874
                $this->sslversion
875
            );
876
        } else {
877
            $r = $this->sendPayloadSocket(
878
                $req,
879
                $this->server,
880
                $this->port,
881
                $timeout,
882
                $this->username,
883
                $this->password,
884
                $this->authtype,
885
                $this->cert,
886
                $this->certpass,
887
                $this->cacert,
888
                $this->cacertdir,
889
                $this->proxy,
890
                $this->proxyport,
891
                $this->proxy_user,
892
                $this->proxy_pass,
893
                $this->proxy_authtype,
894
                $method,
895
                $this->key,
896
                $this->keypass,
897
                $this->sslversion
898
            );
899
        }
900
 
901
        return $r;
902
    }
903
 
904
    /**
905
     * @param Request $req
906
     * @param string $method
907
     * @param string $server
908
     * @param int $port
909
     * @param string $path
910
     * @param array $opts
911
     * @return Response
912
     */
913
    protected function sendViaSocket($req, $method, $server, $port, $path, $opts)
914
    {
915
        /// @todo log a warning if passed an unsupported method
916
 
917
        // Only create the payload if it was not created previously
918
        /// @todo what if the request's payload was created with a different encoding?
919
        ///       Also, if we do not call serialize(), the request will not set its content-type to have the charset declared
920
        $payload = $req->getPayload();
921
        if (empty($payload)) {
922
            $payload = $req->serialize($opts['request_charset_encoding']);
923
        }
924
 
925
        // Deflate request body and set appropriate request headers
926
        $encodingHdr = '';
927
        if ($opts['request_compression'] == 'gzip' || $opts['request_compression'] == 'deflate') {
928
            if ($opts['request_compression'] == 'gzip' && function_exists('gzencode')) {
929
                $a = @gzencode($payload);
930
                if ($a) {
931
                    $payload = $a;
932
                    $encodingHdr = "Content-Encoding: gzip\r\n";
933
                } else {
934
                    $this->getLogger()->warning('XML-RPC: ' . __METHOD__ . ': gzencode failure in compressing request');
935
                }
936
            } else if (function_exists('gzcompress')) {
937
                $a = @gzcompress($payload);
938
                if ($a) {
939
                    $payload = $a;
940
                    $encodingHdr = "Content-Encoding: deflate\r\n";
941
                } else {
942
                    $this->getLogger()->warning('XML-RPC: ' . __METHOD__ . ': gzcompress failure in compressing request');
943
                }
944
            } else {
945
                $this->getLogger()->warning('XML-RPC: ' . __METHOD__ . ': desired request compression method is unsupported by this PHP install');
946
            }
947
        } else {
948
            if ($opts['request_compression'] != '') {
949
                $this->getLogger()->warning('XML-RPC: ' . __METHOD__ . ': desired request compression method is unsupported');
950
            }
951
        }
952
 
953
        // thanks to Grant Rauscher
954
        $credentials = '';
955
        if ($opts['username'] != '') {
956
            if ($opts['authtype'] != 1) {
957
                $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
958
                return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['unsupported_option'],
959
                    PhpXmlRpc::$xmlrpcerr['unsupported_option'] . ': only Basic auth is supported with HTTP 1.0');
960
            }
961
            $credentials = 'Authorization: Basic ' . base64_encode($opts['username'] . ':' . $opts['password']) . "\r\n";
962
        }
963
 
964
        $acceptedEncoding = '';
965
        if (is_array($opts['accepted_compression']) && count($opts['accepted_compression'])) {
966
            $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $opts['accepted_compression']) . "\r\n";
967
        }
968
 
969
        if ($port == 0) {
970
            $port = ($method === 'https') ? 443 : 80;
971
        }
972
 
973
        $proxyCredentials = '';
974
        if ($opts['proxy']) {
975
            if ($opts['proxyport'] == 0) {
976
                $opts['proxyport'] = 8080;
977
            }
978
            $connectServer = $opts['proxy'];
979
            $connectPort = $opts['proxyport'];
980
            $transport = 'tcp';
981
            /// @todo check: should we not use https in some cases?
982
            $uri = 'http://' . $server . ':' . $port . $path;
983
            if ($opts['proxy_user'] != '') {
984
                if ($opts['proxy_authtype'] != 1) {
985
                    $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
986
                    return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['unsupported_option'],
987
                        PhpXmlRpc::$xmlrpcerr['unsupported_option'] . ': only Basic auth to proxy is supported with HTTP 1.0');
988
                }
989
                $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($opts['proxy_user'] . ':' .
990
                    $opts['proxy_pass']) . "\r\n";
991
            }
992
        } else {
993
            $connectServer = $server;
994
            $connectPort = $port;
995
            $transport = ($method === 'https') ? 'tls' : 'tcp';
996
            $uri = $path;
997
        }
998
 
999
        // Cookie generation, as per RFC 6265
1000
        // NB: the following code does not honour 'expires', 'path' and 'domain' cookie attributes set to client obj by the user...
1001
        $cookieHeader = '';
1002
        if (count($opts['cookies'])) {
1003
            $version = '';
1004
            foreach ($opts['cookies'] as $name => $cookie) {
1005
                /// @todo should we sanitize the cookie value on behalf of the user? See setCookie comments
1006
                $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
1007
            }
1008
            $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
1009
        }
1010
 
1011
        $extraHeaders = '';
1012
        if (is_array($this->extra_headers) && $this->extra_headers) {
1013
            $extraHeaders = implode("\r\n", $this->extra_headers) . "\r\n";
1014
        }
1015
 
1016
        // omit port if default
1017
        if (($port == 80 && in_array($method, array('http', 'http10'))) || ($port == 443 && $method == 'https')) {
1018
            $port = '';
1019
        } else {
1020
            $port = ':' . $port;
1021
        }
1022
 
1023
        $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
1024
            'User-Agent: ' . $opts['user_agent'] . "\r\n" .
1025
            'Host: ' . $server . $port . "\r\n" .
1026
            $credentials .
1027
            $proxyCredentials .
1028
            $acceptedEncoding .
1029
            $encodingHdr .
1030
            'Accept-Charset: ' . implode(',', $opts['accepted_charset_encodings']) . "\r\n" .
1031
            $cookieHeader .
1032
            'Content-Type: ' . $req->getContentType() . "\r\n" .
1033
            $extraHeaders .
1034
            'Content-Length: ' . strlen($payload) . "\r\n\r\n" .
1035
            $payload;
1036
 
1037
        if ($opts['debug'] > 1) {
1038
            $this->getLogger()->debug("---SENDING---\n$op\n---END---");
1039
        }
1040
 
1041
        $contextOptions = array();
1042
        if ($method == 'https') {
1043
            if ($opts['cert'] != '') {
1044
                $contextOptions['ssl']['local_cert'] = $opts['cert'];
1045
                if ($opts['certpass'] != '') {
1046
                    $contextOptions['ssl']['passphrase'] = $opts['certpass'];
1047
                }
1048
            }
1049
            if ($opts['cacert'] != '') {
1050
                $contextOptions['ssl']['cafile'] = $opts['cacert'];
1051
            }
1052
            if ($opts['cacertdir'] != '') {
1053
                $contextOptions['ssl']['capath'] = $opts['cacertdir'];
1054
            }
1055
            if ($opts['key'] != '') {
1056
                $contextOptions['ssl']['local_pk'] = $opts['key'];
1057
            }
1058
            $contextOptions['ssl']['verify_peer'] = $opts['verifypeer'];
1059
            $contextOptions['ssl']['verify_peer_name'] = $opts['verifypeer'];
1060
 
1061
            if ($opts['sslversion'] != 0) {
1062
                /// @see https://www.php.net/manual/en/function.curl-setopt.php, https://www.php.net/manual/en/migration56.openssl.php
1063
                switch($opts['sslversion']) {
1064
                    /// @todo what does this map to? 1.0-1.3?
1065
                    //case 1: // TLSv1
1066
                    //    break;
1067
                    case 2: // SSLv2
1068
                        $contextOptions['ssl']['crypto_method'] = STREAM_CRYPTO_METHOD_SSLv2_CLIENT;
1069
                        break;
1070
                    case 3: // SSLv3
1071
                        $contextOptions['ssl']['crypto_method'] = STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
1072
                        break;
1073
                    case 4: // TLSv1.0
1074
                        $contextOptions['ssl']['crypto_method'] = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT;
1075
                        break;
1076
                    case 5: // TLSv1.1
1077
                        $contextOptions['ssl']['crypto_method'] = STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
1078
                        break;
1079
                    case 6: // TLSv1.2
1080
                        $contextOptions['ssl']['crypto_method'] = STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
1081
                        break;
1082
                    case 7: // TLSv1.3
1083
                        if (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT')) {
1084
                            $contextOptions['ssl']['crypto_method'] = STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT;
1085
                        } else {
1086
                            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['unsupported_option'],
1087
                                PhpXmlRpc::$xmlrpcerr['unsupported_option'] . ': TLS-1.3 only is supported with PHP 7.4 or later');
1088
                        }
1089
                        break;
1090
                    default:
1091
                        return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['unsupported_option'],
1092
                            PhpXmlRpc::$xmlrpcerr['unsupported_option'] . ': Unsupported required TLS version');
1093
                }
1094
            }
1095
        }
1096
 
1097
        foreach ($opts['extracurlopts'] as $proto => $protoOpts) {
1098
            foreach ($protoOpts as $key => $val) {
1099
                $contextOptions[$proto][$key] = $val;
1100
            }
1101
        }
1102
 
1103
        $context = stream_context_create($contextOptions);
1104
 
1105
        if ($opts['timeout'] <= 0) {
1106
            $connectTimeout = ini_get('default_socket_timeout');
1107
        } else {
1108
            $connectTimeout = $opts['timeout'];
1109
        }
1110
 
1111
        $this->errno = 0;
1112
        $this->errstr = '';
1113
 
1114
        $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $connectTimeout,
1115
            STREAM_CLIENT_CONNECT, $context);
1116
        if ($fp) {
1117
            if ($opts['timeout'] > 0) {
1118
                stream_set_timeout($fp, $opts['timeout'], 0);
1119
            }
1120
        } else {
1121
            if ($this->errstr == '') {
1122
                $err = error_get_last();
1123
                $this->errstr = $err['message'];
1124
            }
1125
 
1126
            $this->errstr = 'Connect error: ' . $this->errstr;
1127
            $r = new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
1128
 
1129
            return $r;
1130
        }
1131
 
1132
        if (!fputs($fp, $op, strlen($op))) {
1133
            fclose($fp);
1134
            $this->errstr = 'Write error';
1135
            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
1136
        }
1137
 
1138
        // Close socket before parsing.
1139
        // It should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
1140
        $ipd = '';
1141
        do {
1142
            // shall we check for $data === FALSE?
1143
            // as per the manual, it signals an error
1144
            $ipd .= fread($fp, 32768);
1145
        } while (!feof($fp));
1146
        fclose($fp);
1147
 
1148
        return $req->parseResponse($ipd, false, $opts['return_type']);
1149
    }
1150
 
1151
    /**
1152
     * Contributed by Justin Miller
1153
     * Requires curl to be built into PHP
1154
     * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
1155
     *
1156
     * @param Request $req
1157
     * @param string $method
1158
     * @param string $server
1159
     * @param int $port
1160
     * @param string $path
1161
     * @param array $opts the keys/values match self::getOptions
1162
     * @return Response
1163
     *
1164
     * @todo the $path arg atm is ignored. What to do if it is != $this->path?
1165
     */
1166
    protected function sendViaCURL($req, $method, $server, $port, $path, $opts)
1167
    {
1168
        if (!function_exists('curl_init')) {
1169
            $this->errstr = 'CURL unavailable on this install';
1170
            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
1171
        }
1172
        if ($method == 'https' || $method == 'h2') {
1173
            // q: what about installs where we get back a string, but curl is linked to other ssl libs than openssl?
1174
            if (($info = curl_version()) &&
1175
                ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
1176
            ) {
1177
                $this->errstr = 'SSL unavailable on this install';
1178
                return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
1179
            }
1180
        }
1181
        if (($method == 'h2' && !defined('CURL_HTTP_VERSION_2_0')) ||
1182
            ($method == 'h2c' && !defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE'))) {
1183
            $this->errstr = 'HTTP/2 unavailable on this install';
1184
            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['no_http2'], PhpXmlRpc::$xmlrpcstr['no_http2']);
1185
        }
1186
 
1187
        // BC - we go through prepareCurlHandle in case some subclass reimplemented it
1188
        $curl = $this->prepareCurlHandle($req, $server, $port, $opts['timeout'], $opts['username'], $opts['password'],
1189
            $opts['authtype'], $opts['cert'], $opts['certpass'], $opts['cacert'], $opts['cacertdir'], $opts['proxy'],
1190
            $opts['proxyport'], $opts['proxy_user'], $opts['proxy_pass'], $opts['proxy_authtype'], $method,
1191
            $opts['keepalive'], $opts['key'], $opts['keypass'], $opts['sslversion']);
1192
 
1193
        if (!$curl) {
1194
            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] .
1195
                ': error during curl initialization. Check php error log for details');
1196
        }
1197
 
1198
        $result = curl_exec($curl);
1199
 
1200
        if ($opts['debug'] > 1) {
1201
            $message = "---CURL INFO---\n";
1202
            foreach (curl_getinfo($curl) as $name => $val) {
1203
                if (is_array($val)) {
1204
                    $val = implode("\n", $val);
1205
                }
1206
                $message .= $name . ': ' . $val . "\n";
1207
            }
1208
            $message .= '---END---';
1209
            $this->getLogger()->debug($message);
1210
        }
1211
 
1212
        if (!$result) {
1213
            /// @todo we should use a better check here - what if we get back '' or '0'?
1214
 
1215
            $this->errstr = 'no response';
1216
            $resp = new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] .
1217
                ': ' . curl_error($curl));
1218
            curl_close($curl);
1219
            if ($opts['keepalive']) {
1220
                $this->xmlrpc_curl_handle = null;
1221
            }
1222
        } else {
1223
            if (!$opts['keepalive']) {
1224
                curl_close($curl);
1225
            }
1226
            $resp = $req->parseResponse($result, true, $opts['return_type']);
1227
            if ($opts['keepalive']) {
1228
                /// @todo if we got back a 302 or 308, we should not reuse the curl handle for later calls
1229
                if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error']) {
1230
                    curl_close($curl);
1231
                    $this->xmlrpc_curl_handle = null;
1232
                }
1233
            }
1234
        }
1235
 
1236
        return $resp;
1237
    }
1238
 
1239
    /**
1240
     * @param Request $req
1241
     * @param string $method
1242
     * @param string $server
1243
     * @param int $port
1244
     * @param string $path
1245
     * @param array $opts the keys/values match self::getOptions
1246
     * @return \CurlHandle|resource|false
1247
     *
1248
     * @todo allow this method to either throw or return a Response, so that we can pass back to caller more info on errors
1249
     */
1250
    protected function createCURLHandle($req, $method, $server, $port, $path, $opts)
1251
    {
1252
        if ($port == 0) {
1253
            if (in_array($method, array('http', 'http10', 'http11', 'h2c'))) {
1254
                $port = 80;
1255
            } else {
1256
                $port = 443;
1257
            }
1258
        }
1259
 
1260
        // Only create the payload if it was not created previously
1261
        $payload = $req->getPayload();
1262
        if (empty($payload)) {
1263
            $payload = $req->serialize($opts['request_charset_encoding']);
1264
        }
1265
 
1266
        // Deflate request body and set appropriate request headers
1267
        $encodingHdr = '';
1268
        if (($opts['request_compression'] == 'gzip' || $opts['request_compression'] == 'deflate')) {
1269
            if ($opts['request_compression'] == 'gzip' && function_exists('gzencode')) {
1270
                $a = @gzencode($payload);
1271
                if ($a) {
1272
                    $payload = $a;
1273
                    $encodingHdr = 'Content-Encoding: gzip';
1274
                } else {
1275
                    $this->getLogger()->warning('XML-RPC: ' . __METHOD__ . ': gzencode failure in compressing request');
1276
                }
1277
            } else if (function_exists('gzcompress')) {
1278
                $a = @gzcompress($payload);
1279
                if ($a) {
1280
                    $payload = $a;
1281
                    $encodingHdr = 'Content-Encoding: deflate';
1282
                } else {
1283
                    $this->getLogger()->warning('XML-RPC: ' . __METHOD__ . ': gzcompress failure in compressing request');
1284
                }
1285
            } else {
1286
                $this->getLogger()->warning('XML-RPC: ' . __METHOD__ . ': desired request compression method is unsupported by this PHP install');
1287
            }
1288
        } else {
1289
            if ($opts['request_compression'] != '') {
1290
                $this->getLogger()->warning('XML-RPC: ' . __METHOD__ . ': desired request compression method is unsupported');
1291
            }
1292
        }
1293
 
1294
        if (!$opts['keepalive'] || !$this->xmlrpc_curl_handle) {
1295
            if ($method == 'http11' || $method == 'http10' || $method == 'h2c') {
1296
                $protocol = 'http';
1297
            } else {
1298
                if ($method == 'h2') {
1299
                    $protocol = 'https';
1300
                } else {
1301
                    // http, https
1302
                    $protocol = $method;
1303
                    if (strpos($protocol, ':') !== false) {
1304
                        $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ": warning - attempted hacking attempt?. The curl protocol requested for the call is: '$protocol'");
1305
                        return false;
1306
                    }
1307
                }
1308
            }
1309
            $curl = curl_init($protocol . '://' . $server . ':' . $port . $path);
1310
            if (!$curl) {
1311
                return false;
1312
            }
1313
            if ($opts['keepalive']) {
1314
                $this->xmlrpc_curl_handle = $curl;
1315
            }
1316
        } else {
1317
            $curl = $this->xmlrpc_curl_handle;
1318
        }
1319
 
1320
        // results into variable
1321
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1322
 
1323
        if ($opts['debug'] > 1) {
1324
            curl_setopt($curl, CURLOPT_VERBOSE, true);
1325
            /// @todo redirect curlopt_stderr to some stream which can be piped to the logger
1326
        }
1327
        curl_setopt($curl, CURLOPT_USERAGENT, $opts['user_agent']);
1328
        // required for XMLRPC: post the data
1329
        curl_setopt($curl, CURLOPT_POST, 1);
1330
        // the data
1331
        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
1332
 
1333
        // return the header too
1334
        curl_setopt($curl, CURLOPT_HEADER, 1);
1335
 
1336
        // NB: if we set an empty string, CURL will add http header indicating
1337
        // ALL methods it is supporting. This is possibly a better option than letting the user tell what curl can / cannot do...
1338
        if (is_array($opts['accepted_compression']) && count($opts['accepted_compression'])) {
1339
            //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $opts['accepted_compression']));
1340
            // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1341
            if (count($opts['accepted_compression']) == 1) {
1342
                curl_setopt($curl, CURLOPT_ENCODING, $opts['accepted_compression'][0]);
1343
            } else {
1344
                curl_setopt($curl, CURLOPT_ENCODING, '');
1345
            }
1346
        }
1347
        // extra headers
1348
        $headers = array('Content-Type: ' . $req->getContentType(), 'Accept-Charset: ' . implode(',', $opts['accepted_charset_encodings']));
1349
        // if no keepalive is wanted, let the server know it in advance
1350
        if (!$opts['keepalive']) {
1351
            $headers[] = 'Connection: close';
1352
        }
1353
        // request compression header
1354
        if ($encodingHdr) {
1355
            $headers[] = $encodingHdr;
1356
        }
1357
 
1358
        if (is_array($this->extra_headers) && $this->extra_headers) {
1359
            $headers = array_merge($headers, $this->extra_headers);
1360
        }
1361
 
1362
        // Fix the HTTP/1.1 417 Expectation Failed Bug (curl by default adds a 'Expect: 100-continue' header when POST
1363
        // size exceeds 1025 bytes, apparently)
1364
        $headers[] = 'Expect:';
1365
 
1366
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
1367
        // timeout is borked
1368
        if ($opts['timeout']) {
1369
            curl_setopt($curl, CURLOPT_TIMEOUT, $opts['timeout'] == 1 ? 1 : $opts['timeout'] - 1);
1370
        }
1371
 
1372
        switch ($method) {
1373
            case 'http10':
1374
                curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1375
                break;
1376
            case 'http11':
1377
                curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1378
                break;
1379
            case 'h2c':
1380
                if (defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE')) {
1381
                    curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
1382
                } else {
1383
                    $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': warning. HTTP2 is not supported by the current PHP/curl install');
1384
                    curl_close($curl);
1385
                    return false;
1386
                }
1387
                break;
1388
            case 'h2':
1389
                curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
1390
                break;
1391
        }
1392
 
1393
        if ($opts['username'] && $opts['password']) {
1394
            curl_setopt($curl, CURLOPT_USERPWD, $opts['username'] . ':' . $opts['password']);
1395
            if (defined('CURLOPT_HTTPAUTH')) {
1396
                curl_setopt($curl, CURLOPT_HTTPAUTH, $opts['authtype']);
1397
            } elseif ($opts['authtype'] != 1) {
1398
                $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
1399
                curl_close($curl);
1400
                return false;
1401
            }
1402
        }
1403
 
1404
        // note: h2c is http2 without the https. No need to have it in this IF
1405
        if ($method == 'https' || $method == 'h2') {
1406
            // set cert file
1407
            if ($opts['cert']) {
1408
                curl_setopt($curl, CURLOPT_SSLCERT, $opts['cert']);
1409
            }
1410
            // set cert password
1411
            if ($opts['certpass']) {
1412
                curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $opts['certpass']);
1413
            }
1414
            // whether to verify remote host's cert
1415
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $opts['verifypeer']);
1416
            // set ca certificates file/dir
1417
            if ($opts['cacert']) {
1418
                curl_setopt($curl, CURLOPT_CAINFO, $opts['cacert']);
1419
            }
1420
            if ($opts['cacertdir']) {
1421
                curl_setopt($curl, CURLOPT_CAPATH, $opts['cacertdir']);
1422
            }
1423
            // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1424
            if ($opts['key']) {
1425
                curl_setopt($curl, CURLOPT_SSLKEY, $opts['key']);
1426
            }
1427
            // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1428
            if ($opts['keypass']) {
1429
                curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $opts['keypass']);
1430
            }
1431
            // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that
1432
            // it matches the hostname used
1433
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $opts['verifyhost']);
1434
            // allow usage of different SSL versions
1435
            curl_setopt($curl, CURLOPT_SSLVERSION, $opts['sslversion']);
1436
        }
1437
 
1438
        // proxy info
1439
        if ($opts['proxy']) {
1440
            if ($opts['proxyport'] == 0) {
1441
                $opts['proxyport'] = 8080; // NB: even for HTTPS, local connection is on port 8080
1442
            }
1443
            curl_setopt($curl, CURLOPT_PROXY, $opts['proxy'] . ':' . $opts['proxyport']);
1444
            if ($opts['proxy_user']) {
1445
                curl_setopt($curl, CURLOPT_PROXYUSERPWD, $opts['proxy_user'] . ':' . $opts['proxy_pass']);
1446
                if (defined('CURLOPT_PROXYAUTH')) {
1447
                    curl_setopt($curl, CURLOPT_PROXYAUTH, $opts['proxy_authtype']);
1448
                } elseif ($opts['proxy_authtype'] != 1) {
1449
                    $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1450
                    curl_close($curl);
1451
                    return false;
1452
                }
1453
            }
1454
        }
1455
 
1456
        // NB: should we build cookie http headers by hand rather than let CURL do it?
1457
        // NB: the following code does not honour 'expires', 'path' and 'domain' cookie attributes set to client obj by the user...
1458
        if (count($opts['cookies'])) {
1459
            $cookieHeader = '';
1460
            foreach ($opts['cookies'] as $name => $cookie) {
1461
                $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
1462
            }
1463
            curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
1464
        }
1465
 
1466
        foreach ($opts['extracurlopts'] as $opt => $val) {
1467
            curl_setopt($curl, $opt, $val);
1468
        }
1469
 
1470
        if ($opts['debug'] > 1) {
1471
            $this->getLogger()->debug("---SENDING---\n$payload\n---END---");
1472
        }
1473
 
1474
        return $curl;
1475
    }
1476
 
1477
    /**
1478
     * Send an array of requests and return an array of responses.
1479
     *
1480
     * Unless $this->no_multicall has been set to true, it will try first to use one single xml-rpc call to server method
1481
     * system.multicall, and revert to sending many successive calls in case of failure.
1482
     * This failure is also stored in $this->no_multicall for subsequent calls.
1483
     * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported,
1484
     * so there is no way to reliably distinguish between that and a temporary failure.
1485
     * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the
1486
     * 2np parameter to FALSE.
1487
     *
1488
     * NB: trying to shoehorn extra functionality into existing syntax has resulted
1489
     * in pretty much convoluted code...
1490
     *
1491
     * @param Request[] $reqs an array of Request objects
1492
     * @param bool $noFallback When true, upon receiving an error during multicall, multiple single calls will not be
1493
     *                         attempted.
1494
     *                         Deprecated alternative, was: int - "connection timeout (in seconds). See the details in the
1495
     *                         docs for the send() method". Please use setOption instead to set a timeout
1496
     * @param string $method deprecated. Was: "the http protocol variant to be used. See the details in the docs for the send() method."
1497
     *                       Please use the constructor to set an http protocol variant.
1498
     * @param boolean $fallback deprecated. Was: "w"hen true, upon receiving an error during multicall, multiple single
1499
     *                          calls will be attempted"
1500
     * @return Response[]
1501
     */
1502
    public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
1503
    {
1504
        // BC
1505
        if (is_bool($timeout) && $fallback === true) {
1506
            $fallback = !$timeout;
1507
            $timeout = 0;
1508
        }
1509
 
1510
        if ($method == '') {
1511
            $method = $this->method;
1512
        }
1513
 
1514
        if (!$this->no_multicall) {
1515
            $results = $this->_try_multicall($reqs, $timeout, $method);
1516
            /// @todo how to handle the case of $this->return_type = xml?
1517
            if (is_array($results)) {
1518
                // System.multicall succeeded
1519
                return $results;
1520
            } else {
1521
                // either system.multicall is unsupported by server, or the call failed for some other reason.
1522
                // Feature creep: is there a way to tell apart unsupported multicall from other faults?
1523
                if ($fallback) {
1524
                    // Don't try it next time...
1525
                    $this->no_multicall = true;
1526
                } else {
1527
                    $result = $results;
1528
                }
1529
            }
1530
        } else {
1531
            // override fallback, in case careless user tries to do two
1532
            // opposite things at the same time
1533
            $fallback = true;
1534
        }
1535
 
1536
        $results = array();
1537
        if ($fallback) {
1538
            // system.multicall is (probably) unsupported by server: emulate multicall via multiple requests
1539
            /// @todo use curl multi_ functions to make this quicker (see the implementation in the parallel.php demo)
1540
            foreach ($reqs as $req) {
1541
                $results[] = $this->send($req, $timeout, $method);
1542
            }
1543
        } else {
1544
            // user does NOT want to fallback on many single calls: since we should always return an array of responses,
1545
            // we return an array with the same error repeated n times
1546
            foreach ($reqs as $req) {
1547
                $results[] = $result;
1548
            }
1549
        }
1550
 
1551
        return $results;
1552
    }
1553
 
1554
    /**
1555
     * Attempt to boxcar $reqs via system.multicall.
1556
     *
1557
     * @param Request[] $reqs
1558
     * @param int $timeout
1559
     * @param string $method
1560
     * @return Response[]|Response a single Response when the call returned a fault / does not conform to what we expect
1561
     *                             from a multicall response
1562
     */
1563
    private function _try_multicall($reqs, $timeout, $method)
1564
    {
1565
        // Construct multicall request
1566
        $calls = array();
1567
        foreach ($reqs as $req) {
1568
            $call['methodName'] = new Value($req->method(), 'string');
1569
            $numParams = $req->getNumParams();
1570
            $params = array();
1571
            for ($i = 0; $i < $numParams; $i++) {
1572
                $params[$i] = $req->getParam($i);
1573
            }
1574
            $call['params'] = new Value($params, 'array');
1575
            $calls[] = new Value($call, 'struct');
1576
        }
1577
        $multiCall = new static::$requestClass('system.multicall');
1578
        $multiCall->addParam(new Value($calls, 'array'));
1579
 
1580
        // Attempt RPC call
1581
        $result = $this->send($multiCall, $timeout, $method);
1582
 
1583
        if ($result->faultCode() != 0) {
1584
            // call to system.multicall failed
1585
            return $result;
1586
        }
1587
 
1588
        // Unpack responses.
1589
        $rets = $result->value();
1590
        $response = array();
1591
 
1592
        if ($this->return_type == 'xml') {
1593
            for ($i = 0; $i < count($reqs); $i++) {
1594
                $response[] = new static::$responseClass($rets, 0, '', 'xml', $result->httpResponse());
1595
            }
1596
 
1597
        } elseif ($this->return_type == 'phpvals') {
1598
            if (!is_array($rets)) {
1599
                // bad return type from system.multicall
1600
                return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1601
                    PhpXmlRpc::$xmlrpcstr['multicall_error'] . ': not an array', 'phpvals', $result->httpResponse());
1602
            }
1603
            $numRets = count($rets);
1604
            if ($numRets != count($reqs)) {
1605
                // wrong number of return values.
1606
                return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1607
                    PhpXmlRpc::$xmlrpcstr['multicall_error'] . ': incorrect number of responses', 'phpvals',
1608
                    $result->httpResponse());
1609
            }
1610
 
1611
            for ($i = 0; $i < $numRets; $i++) {
1612
                $val = $rets[$i];
1613
                if (!is_array($val)) {
1614
                    return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1615
                        PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i is not an array or struct",
1616
                        'phpvals', $result->httpResponse());
1617
                }
1618
                switch (count($val)) {
1619
                    case 1:
1620
                        if (!isset($val[0])) {
1621
                            // Bad value
1622
                            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1623
                                PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i has no value",
1624
                                'phpvals', $result->httpResponse());
1625
                        }
1626
                        // Normal return value
1627
                        $response[$i] = new static::$responseClass($val[0], 0, '', 'phpvals', $result->httpResponse());
1628
                        break;
1629
                    case 2:
1630
                        /// @todo remove usage of @: it is apparently quite slow
1631
                        $code = @$val['faultCode'];
1632
                        if (!is_int($code)) {
1633
                            /// @todo should we check that it is != 0?
1634
                            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1635
                                PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i has invalid or no faultCode",
1636
                                'phpvals', $result->httpResponse());
1637
                        }
1638
                        $str = @$val['faultString'];
1639
                        if (!is_string($str)) {
1640
                            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1641
                                PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i has invalid or no FaultString",
1642
                                'phpvals', $result->httpResponse());
1643
                        }
1644
                        $response[$i] = new static::$responseClass(0, $code, $str, 'phpvals', $result->httpResponse());
1645
                        break;
1646
                    default:
1647
                        return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1648
                            PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i has too many items",
1649
                            'phpvals', $result->httpResponse());
1650
                }
1651
            }
1652
 
1653
        } else {
1654
            // return type == 'xmlrpcvals'
1655
            if ($rets->kindOf() != 'array') {
1656
                return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1657
                    PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i is not an array", 'xmlrpcvals',
1658
                    $result->httpResponse());
1659
            }
1660
            $numRets = $rets->count();
1661
            if ($numRets != count($reqs)) {
1662
                // wrong number of return values.
1663
                return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1664
                    PhpXmlRpc::$xmlrpcstr['multicall_error'] . ': incorrect number of responses', 'xmlrpcvals',
1665
                    $result->httpResponse());
1666
            }
1667
 
1668
            foreach ($rets as $i => $val) {
1669
                switch ($val->kindOf()) {
1670
                    case 'array':
1671
                        if ($val->count() != 1) {
1672
                            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1673
                                PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i has too many items",
1674
                                'phpvals', $result->httpResponse());
1675
                        }
1676
                        // Normal return value
1677
                        $response[] = new static::$responseClass($val[0], 0, '', 'xmlrpcvals', $result->httpResponse());
1678
                        break;
1679
                    case 'struct':
1680
                        if ($val->count() != 2) {
1681
                            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1682
                                PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i has too many items",
1683
                                'phpvals', $result->httpResponse());
1684
                        }
1685
                        /** @var Value $code */
1686
                        $code = $val['faultCode'];
1687
                        if ($code->kindOf() != 'scalar' || $code->scalarTyp() != 'int') {
1688
                            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1689
                                PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i has invalid or no faultCode",
1690
                                'xmlrpcvals', $result->httpResponse());
1691
                        }
1692
                        /** @var Value $str */
1693
                        $str = $val['faultString'];
1694
                        if ($str->kindOf() != 'scalar' || $str->scalarTyp() != 'string') {
1695
                            return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1696
                                PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i has invalid or no faultCode",
1697
                                'xmlrpcvals', $result->httpResponse());
1698
                        }
1699
                        $response[] = new static::$responseClass(0, $code->scalarVal(), $str->scalarVal(), 'xmlrpcvals', $result->httpResponse());
1700
                        break;
1701
                    default:
1702
                        return new static::$responseClass(0, PhpXmlRpc::$xmlrpcerr['multicall_error'],
1703
                            PhpXmlRpc::$xmlrpcstr['multicall_error'] . ": response element $i is not an array or struct",
1704
                            'xmlrpcvals', $result->httpResponse());
1705
                }
1706
            }
1707
        }
1708
 
1709
        return $response;
1710
    }
1711
 
1712
    // *** BC layer ***
1713
 
1714
    /**
1715
     * @deprecated
1716
     *
1717
     * @param Request $req
1718
     * @param string $server
1719
     * @param int $port
1720
     * @param int $timeout
1721
     * @param string $username
1722
     * @param string $password
1723
     * @param int $authType
1724
     * @param string $proxyHost
1725
     * @param int $proxyPort
1726
     * @param string $proxyUsername
1727
     * @param string $proxyPassword
1728
     * @param int $proxyAuthType
1729
     * @param string $method
1730
     * @return Response
1731
     */
1732
    protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '',
1733
        $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
1734
        $method = 'http')
1735
    {
1736
        $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
1737
 
1738
        return $this->sendPayloadSocket($req, $server, $port, $timeout, $username, $password, $authType, null, null,
1739
            null, null, $proxyHost, $proxyPort, $proxyUsername, $proxyPassword, $proxyAuthType, $method);
1740
    }
1741
 
1742
    /**
1743
     * @deprecated
1744
     *
1745
     * @param Request $req
1746
     * @param string $server
1747
     * @param int $port
1748
     * @param int $timeout
1749
     * @param string $username
1750
     * @param string $password
1751
     * @param int $authType
1752
     * @param string $cert
1753
     * @param string $certPass
1754
     * @param string $caCert
1755
     * @param string $caCertDir
1756
     * @param string $proxyHost
1757
     * @param int $proxyPort
1758
     * @param string $proxyUsername
1759
     * @param string $proxyPassword
1760
     * @param int $proxyAuthType
1761
     * @param bool $keepAlive
1762
     * @param string $key
1763
     * @param string $keyPass
1764
     * @param int $sslVersion
1765
     * @return Response
1766
     */
1767
    protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '', $password = '',
1768
        $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
1769
        $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $keepAlive = false, $key = '', $keyPass = '',
1770
        $sslVersion = 0)
1771
    {
1772
        $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
1773
 
1774
        return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
1775
            $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
1776
            $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
1777
    }
1778
 
1779
    /**
1780
     * @deprecated
1781
     *
1782
     * @param Request $req
1783
     * @param string $server
1784
     * @param int $port
1785
     * @param int $timeout
1786
     * @param string $username
1787
     * @param string $password
1788
     * @param int $authType only value supported is 1
1789
     * @param string $cert
1790
     * @param string $certPass
1791
     * @param string $caCert
1792
     * @param string $caCertDir
1793
     * @param string $proxyHost
1794
     * @param int $proxyPort
1795
     * @param string $proxyUsername
1796
     * @param string $proxyPassword
1797
     * @param int $proxyAuthType only value supported is 1
1798
     * @param string $method 'http' (synonym for 'http10'), 'http10' or 'https'
1799
     * @param string $key
1800
     * @param string $keyPass @todo not implemented yet.
1801
     * @param int $sslVersion @todo not implemented yet. See http://php.net/manual/en/migration56.openssl.php
1802
     * @return Response
1803
     */
1804
    protected function sendPayloadSocket($req, $server, $port, $timeout = 0, $username = '', $password = '',
1805
        $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
1806
        $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'http', $key = '', $keyPass = '',
1807
        $sslVersion = 0)
1808
    {
1809
        $this->logDeprecationUnlessCalledBy('send');
1810
 
1811
        return $this->sendViaSocket($req, $method, $server, $port, $this->path, array(
1812
            'accepted_charset_encodings' => $this->accepted_charset_encodings,
1813
            'accepted_compression' => $this->accepted_compression,
1814
            'authtype' => $authType,
1815
            'cacert' => $caCert,
1816
            'cacertdir' => $caCertDir,
1817
            'cert' => $cert,
1818
            'certpass' => $certPass,
1819
            'cookies' => $this->cookies,
1820
            'debug' => $this->debug,
1821
            'extracurlopts' => $this->extracurlopts,
1822
            'extrasockopts' => $this->extrasockopts,
1823
            'keepalive' => $this->keepalive,
1824
            'key' => $key,
1825
            'keypass' => $keyPass,
1826
            'no_multicall' => $this->no_multicall,
1827
            'password' => $password,
1828
            'proxy' => $proxyHost,
1829
            'proxy_authtype' => $proxyAuthType,
1830
            'proxy_pass' => $proxyPassword,
1831
            'proxyport' => $proxyPort,
1832
            'proxy_user' => $proxyUsername,
1833
            'request_charset_encoding' => $this->request_charset_encoding,
1834
            'request_compression' => $this->request_compression,
1835
            'return_type' => $this->return_type,
1836
            'sslversion' => $sslVersion,
1837
            'timeout' => $timeout,
1838
            'username' => $username,
1839
            'user_agent' => $this->user_agent,
1840
            'use_curl' => $this->use_curl,
1841
            'verifyhost' => $this->verifyhost,
1842
            'verifypeer' => $this->verifypeer,
1843
        ));
1844
    }
1845
 
1846
    /**
1847
     * @deprecated
1848
     *
1849
     * @param Request $req
1850
     * @param string $server
1851
     * @param int $port
1852
     * @param int $timeout
1853
     * @param string $username
1854
     * @param string $password
1855
     * @param int $authType
1856
     * @param string $cert
1857
     * @param string $certPass
1858
     * @param string $caCert
1859
     * @param string $caCertDir
1860
     * @param string $proxyHost
1861
     * @param int $proxyPort
1862
     * @param string $proxyUsername
1863
     * @param string $proxyPassword
1864
     * @param int $proxyAuthType
1865
     * @param string $method 'http' (let curl decide), 'http10', 'http11', 'https', 'h2c' or 'h2'
1866
     * @param bool $keepAlive
1867
     * @param string $key
1868
     * @param string $keyPass
1869
     * @param int $sslVersion
1870
     * @return Response
1871
     */
1872
    protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
1873
        $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
1874
        $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
1875
        $keyPass = '', $sslVersion = 0)
1876
    {
1877
        $this->logDeprecationUnlessCalledBy('send');
1878
 
1879
        return $this->sendViaCURL($req, $method, $server, $port, $this->path, array(
1880
            'accepted_charset_encodings' => $this->accepted_charset_encodings,
1881
            'accepted_compression' => $this->accepted_compression,
1882
            'authtype' => $authType,
1883
            'cacert' => $caCert,
1884
            'cacertdir' => $caCertDir,
1885
            'cert' => $cert,
1886
            'certpass' => $certPass,
1887
            'cookies' => $this->cookies,
1888
            'debug' => $this->debug,
1889
            'extracurlopts' => $this->extracurlopts,
1890
            'extrasockopts' => $this->extrasockopts,
1891
            'keepalive' => $keepAlive,
1892
            'key' => $key,
1893
            'keypass' => $keyPass,
1894
            'no_multicall' => $this->no_multicall,
1895
            'password' => $password,
1896
            'proxy' => $proxyHost,
1897
            'proxy_authtype' => $proxyAuthType,
1898
            'proxy_pass' => $proxyPassword,
1899
            'proxyport' => $proxyPort,
1900
            'proxy_user' => $proxyUsername,
1901
            'request_charset_encoding' => $this->request_charset_encoding,
1902
            'request_compression' => $this->request_compression,
1903
            'return_type' => $this->return_type,
1904
            'sslversion' => $sslVersion,
1905
            'timeout' => $timeout,
1906
            'username' => $username,
1907
            'user_agent' => $this->user_agent,
1908
            'use_curl' => $this->use_curl,
1909
            'verifyhost' => $this->verifyhost,
1910
            'verifypeer' => $this->verifypeer,
1911
        ));
1912
    }
1913
 
1914
    /**
1915
     * @deprecated
1916
     *
1917
     * @param $req
1918
     * @param $server
1919
     * @param $port
1920
     * @param $timeout
1921
     * @param $username
1922
     * @param $password
1923
     * @param $authType
1924
     * @param $cert
1925
     * @param $certPass
1926
     * @param $caCert
1927
     * @param $caCertDir
1928
     * @param $proxyHost
1929
     * @param $proxyPort
1930
     * @param $proxyUsername
1931
     * @param $proxyPassword
1932
     * @param $proxyAuthType
1933
     * @param $method
1934
     * @param $keepAlive
1935
     * @param $key
1936
     * @param $keyPass
1937
     * @param $sslVersion
1938
     * @return false|\CurlHandle|resource
1939
     */
1940
    protected function prepareCurlHandle($req, $server, $port, $timeout = 0, $username = '', $password = '',
1941
         $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
1942
         $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
1943
         $keyPass = '', $sslVersion = 0)
1944
    {
1945
        $this->logDeprecationUnlessCalledBy('sendViaCURL');
1946
 
1947
        return $this->createCURLHandle($req, $method, $server, $port, $this->path, array(
1948
            'accepted_charset_encodings' => $this->accepted_charset_encodings,
1949
            'accepted_compression' => $this->accepted_compression,
1950
            'authtype' => $authType,
1951
            'cacert' => $caCert,
1952
            'cacertdir' => $caCertDir,
1953
            'cert' => $cert,
1954
            'certpass' => $certPass,
1955
            'cookies' => $this->cookies,
1956
            'debug' => $this->debug,
1957
            'extracurlopts' => $this->extracurlopts,
1958
            'keepalive' => $keepAlive,
1959
            'key' => $key,
1960
            'keypass' => $keyPass,
1961
            'no_multicall' => $this->no_multicall,
1962
            'password' => $password,
1963
            'proxy' => $proxyHost,
1964
            'proxy_authtype' => $proxyAuthType,
1965
            'proxy_pass' => $proxyPassword,
1966
            'proxyport' => $proxyPort,
1967
            'proxy_user' => $proxyUsername,
1968
            'request_charset_encoding' => $this->request_charset_encoding,
1969
            'request_compression' => $this->request_compression,
1970
            'return_type' => $this->return_type,
1971
            'sslversion' => $sslVersion,
1972
            'timeout' => $timeout,
1973
            'username' => $username,
1974
            'user_agent' => $this->user_agent,
1975
            'use_curl' => $this->use_curl,
1976
            'verifyhost' => $this->verifyhost,
1977
            'verifypeer' => $this->verifypeer,
1978
        ));
1979
    }
1980
 
1981
    // we have to make this return by ref in order to allow calls such as `$resp->_cookies['name'] = ['value' => 'something'];`
1982
    public function &__get($name)
1983
    {
1984
        if (in_array($name, static::$options)) {
1985
            $this->logDeprecation('Getting property Client::' . $name . ' is deprecated');
1986
            return $this->$name;
1987
        }
1988
 
1989
        switch ($name) {
1990
            case 'errno':
1991
            case 'errstr':
1992
            case 'method':
1993
            case 'server':
1994
            case 'port':
1995
            case 'path':
1996
                $this->logDeprecation('Getting property Client::' . $name . ' is deprecated');
1997
                return $this->$name;
1998
            default:
1999
                /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
2000
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
2001
                trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
2002
                $result = null;
2003
                return $result;
2004
        }
2005
    }
2006
 
2007
    public function __set($name, $value)
2008
    {
2009
        if (in_array($name, static::$options)) {
2010
            $this->logDeprecation('Setting property Client::' . $name . ' is deprecated');
2011
            $this->$name = $value;
2012
            return;
2013
        }
2014
 
2015
        switch ($name) {
2016
            case 'errno':
2017
            case 'errstr':
2018
            case 'method':
2019
            case 'server':
2020
            case 'port':
2021
            case 'path':
2022
                $this->logDeprecation('Setting property Client::' . $name . ' is deprecated');
2023
                $this->$name = $value;
2024
                return;
2025
            default:
2026
                /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
2027
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
2028
                trigger_error('Undefined property via __set(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
2029
        }
2030
    }
2031
 
2032
    public function __isset($name)
2033
    {
2034
        if (in_array($name, static::$options)) {
2035
            $this->logDeprecation('Checking property Client::' . $name . ' is deprecated');
2036
            return isset($this->$name);
2037
        }
2038
 
2039
        switch ($name) {
2040
            case 'errno':
2041
            case 'errstr':
2042
            case 'method':
2043
            case 'server':
2044
            case 'port':
2045
            case 'path':
2046
                $this->logDeprecation('Checking property Client::' . $name . ' is deprecated');
2047
                return isset($this->$name);
2048
            default:
2049
                return false;
2050
        }
2051
    }
2052
 
2053
    public function __unset($name)
2054
    {
2055
        if (in_array($name, static::$options)) {
2056
            $this->logDeprecation('Unsetting property Client::' . $name . ' is deprecated');
2057
            unset($this->$name);
2058
            return;
2059
        }
2060
 
2061
        switch ($name) {
2062
            case 'errno':
2063
            case 'errstr':
2064
            case 'method':
2065
            case 'server':
2066
            case 'port':
2067
            case 'path':
2068
                $this->logDeprecation('Unsetting property Client::' . $name . ' is deprecated');
2069
                unset($this->$name);
2070
                return;
2071
            default:
2072
                /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
2073
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
2074
                trigger_error('Undefined property via __unset(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
2075
        }
2076
    }
2077
}