Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  
   3  namespace PhpXmlRpc;
   4  
   5  use PhpXmlRpc\Helper\Logger;
   6  use PhpXmlRpc\Helper\XMLParser;
   7  
   8  /**
   9   * Used to represent a client of an XML-RPC server.
  10   */
  11  class Client
  12  {
  13      const USE_CURL_NEVER = 0;
  14      const USE_CURL_ALWAYS = 1;
  15      const USE_CURL_AUTO = 2;
  16  
  17      protected static $logger;
  18  
  19      /// @todo: do these need to be public?
  20      public $method = 'http';
  21      public $server;
  22      public $port = 0;
  23      public $path;
  24  
  25      public $errno;
  26      public $errstr;
  27      public $debug = 0;
  28  
  29      public $username = '';
  30      public $password = '';
  31      public $authtype = 1;
  32  
  33      public $cert = '';
  34      public $certpass = '';
  35      public $cacert = '';
  36      public $cacertdir = '';
  37      public $key = '';
  38      public $keypass = '';
  39      public $verifypeer = true;
  40      public $verifyhost = 2;
  41      public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
  42  
  43      public $proxy = '';
  44      public $proxyport = 0;
  45      public $proxy_user = '';
  46      public $proxy_pass = '';
  47      public $proxy_authtype = 1;
  48  
  49      public $cookies = array();
  50      public $extracurlopts = array();
  51      public $use_curl = self::USE_CURL_AUTO;
  52  
  53      /**
  54       * @var bool
  55       *
  56       * This determines whether the multicall() method will try to take advantage of the system.multicall xmlrpc method
  57       * to dispatch to the server an array of requests in a single http roundtrip or simply execute many consecutive http
  58       * calls. Defaults to FALSE, but it will be enabled automatically on the first failure of execution of
  59       * system.multicall.
  60       */
  61      public $no_multicall = false;
  62  
  63      /**
  64       * List of http compression methods accepted by the client for responses.
  65       * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib.
  66       *
  67       * 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
  68       * decide the compression methods it supports. You might check for the presence of 'zlib' in the output of
  69       * curl_version() to determine whether compression is supported or not
  70       */
  71      public $accepted_compression = array();
  72  
  73      /**
  74       * Name of compression scheme to be used for sending requests.
  75       * Either null, gzip or deflate.
  76       */
  77      public $request_compression = '';
  78  
  79      /**
  80       * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
  81       * http://curl.haxx.se/docs/faq.html#7.3).
  82       * @internal
  83       */
  84      public $xmlrpc_curl_handle = null;
  85  
  86      /// Whether to use persistent connections for http 1.1 and https
  87      public $keepalive = false;
  88  
  89      /// Charset encodings that can be decoded without problems by the client
  90      public $accepted_charset_encodings = array();
  91  
  92      /**
  93       * The charset encoding that will be used for serializing request sent by the client.
  94       * It defaults to NULL, which means using US-ASCII and encoding all characters outside of the ASCII printable range
  95       * using their xml character entity representation (this has the benefit that line end characters will not be mangled
  96       * in the transfer, a CR-LF will be preserved as well as a singe LF).
  97       * Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1'.
  98       * For the fastest mode of operation, set your both your app internal encoding as well as this to UTF-8.
  99       */
 100      public $request_charset_encoding = '';
 101  
 102      /**
 103       * Decides the content of Response objects returned by calls to send() and multicall().
 104       * Valid values are 'xmlrpcvals', 'phpvals' or 'xml'.
 105       *
 106       * Determines whether the value returned inside an Response object as results of calls to the send() and multicall()
 107       * methods will be a Value object, a plain php value or a raw xml string.
 108       * Allowed values are 'xmlrpcvals' (the default), 'phpvals' and 'xml'.
 109       * To allow the user to differentiate between a correct and a faulty response, fault responses will be returned as
 110       * Response objects in any case.
 111       * Note that the 'phpvals' setting will yield faster execution times, but some of the information from the original
 112       * response will be lost. It will be e.g. impossible to tell whether a particular php string value was sent by the
 113       * server as an xmlrpc string or base64 value.
 114       */
 115      public $return_type = XMLParser::RETURN_XMLRPCVALS;
 116  
 117      /**
 118       * Sent to servers in http headers.
 119       */
 120      public $user_agent;
 121  
 122      public function getLogger()
 123      {
 124          if (self::$logger === null) {
 125              self::$logger = Logger::instance();
 126          }
 127          return self::$logger;
 128      }
 129  
 130      public static function setLogger($logger)
 131      {
 132          self::$logger = $logger;
 133      }
 134  
 135      /**
 136       * @param string $path either the PATH part of the xmlrpc server URL, or complete server URL (in which case you
 137       *                     should use and empty string for all other parameters)
 138       *                     e.g. /xmlrpc/server.php
 139       *                     e.g. http://phpxmlrpc.sourceforge.net/server.php
 140       *                     e.g. https://james:bond@secret.service.com:444/xmlrpcserver?agent=007
 141       *                     e.g. h2://fast-and-secure-services.org/endpoint
 142       * @param string $server the server name / ip address
 143       * @param integer $port the port the server is listening on, when omitted defaults to 80 or 443 depending on
 144       *                      protocol used
 145       * @param string $method the http protocol variant: defaults to 'http'; 'https', 'http11', 'h2' and 'h2c' can
 146       *                       be used if CURL is installed. The value set here can be overridden in any call to $this->send().
 147       *                       Use 'h2' to make the lib attempt to use http/2 over a secure connection, and 'h2c'
 148       *                       for http/2 without tls. Note that 'h2c' will not use the h2c 'upgrade' method, and be
 149       *                       thus incompatible with any server/proxy not supporting http/2. This is because POST
 150       *                       request are not compatible with h2c upgrade.
 151       */
 152      public function __construct($path, $server = '', $port = '', $method = '')
 153      {
 154          // allow user to specify all params in $path
 155          if ($server == '' && $port == '' && $method == '') {
 156              $parts = parse_url($path);
 157              $server = $parts['host'];
 158              $path = isset($parts['path']) ? $parts['path'] : '';
 159              if (isset($parts['query'])) {
 160                  $path .= '?' . $parts['query'];
 161              }
 162              if (isset($parts['fragment'])) {
 163                  $path .= '#' . $parts['fragment'];
 164              }
 165              if (isset($parts['port'])) {
 166                  $port = $parts['port'];
 167              }
 168              if (isset($parts['scheme'])) {
 169                  $method = $parts['scheme'];
 170              }
 171              if (isset($parts['user'])) {
 172                  $this->username = $parts['user'];
 173              }
 174              if (isset($parts['pass'])) {
 175                  $this->password = $parts['pass'];
 176              }
 177          }
 178          if ($path == '' || $path[0] != '/') {
 179              $this->path = '/' . $path;
 180          } else {
 181              $this->path = $path;
 182          }
 183          $this->server = $server;
 184          if ($port != '') {
 185              $this->port = $port;
 186          }
 187          if ($method != '') {
 188              $this->method = $method;
 189          }
 190  
 191          // if ZLIB is enabled, let the client by default accept compressed responses
 192          if (function_exists('gzinflate') || (
 193                  function_exists('curl_version') && (($info = curl_version()) &&
 194                      ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
 195              )
 196          ) {
 197              $this->accepted_compression = array('gzip', 'deflate');
 198          }
 199  
 200          // keepalives: enabled by default
 201          $this->keepalive = true;
 202  
 203          // by default the xml parser can support these 3 charset encodings
 204          $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
 205  
 206          // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
 207          // http://www.iana.org/assignments/character-sets/character-sets.xhtml
 208          // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
 209          /*if (function_exists('mb_list_encodings')) {
 210  
 211              $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
 212                  'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
 213              $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
 214          }*/
 215  
 216          // initialize user_agent string
 217          $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
 218      }
 219  
 220      /**
 221       * Enable/disable the echoing to screen of the xmlrpc responses received. The default is not no output anything.
 222       *
 223       * The debugging information at level 1 includes the raw data returned from the XML-RPC server it was querying
 224       * (including bot HTTP headers and the full XML payload), and the PHP value the client attempts to create to
 225       * represent the value returned by the server
 226       * At level2, the complete payload of the xmlrpc request is also printed, before being sent t the server.
 227       *
 228       * This option can be very useful when debugging servers as it allows you to see exactly what the client sends and
 229       * the server returns.
 230       *
 231       * @param integer $level values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
 232       */
 233      public function setDebug($level)
 234      {
 235          $this->debug = $level;
 236      }
 237  
 238      /**
 239       * Sets the username and password for authorizing the client to the server.
 240       *
 241       * With the default (HTTP) transport, this information is used for HTTP Basic authorization.
 242       * Note that username and password can also be set using the class constructor.
 243       * With HTTP 1.1 and HTTPS transport, NTLM and Digest authentication protocols are also supported. To enable them use
 244       * the constants CURLAUTH_DIGEST and CURLAUTH_NTLM as values for the auth type parameter.
 245       *
 246       * @param string $user username
 247       * @param string $password password
 248       * @param integer $authType auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC
 249       *                          (basic auth). Note that auth types NTLM and Digest will only work if the Curl php
 250       *                          extension is enabled.
 251       */
 252      public function setCredentials($user, $password, $authType = 1)
 253      {
 254          $this->username = $user;
 255          $this->password = $password;
 256          $this->authtype = $authType;
 257      }
 258  
 259      /**
 260       * Set the optional certificate and passphrase used in SSL-enabled communication with a remote server.
 261       *
 262       * Note: to retrieve information about the client certificate on the server side, you will need to look into the
 263       * environment variables which are set up by the webserver. Different webservers will typically set up different
 264       * variables.
 265       *
 266       * @param string $cert the name of a file containing a PEM formatted certificate
 267       * @param string $certPass the password required to use it
 268       */
 269      public function setCertificate($cert, $certPass = '')
 270      {
 271          $this->cert = $cert;
 272          $this->certpass = $certPass;
 273      }
 274  
 275      /**
 276       * Add a CA certificate to verify server with in SSL-enabled communication when SetSSLVerifypeer has been set to TRUE.
 277       *
 278       * See the php manual page about CURLOPT_CAINFO for more details.
 279       *
 280       * @param string $caCert certificate file name (or dir holding certificates)
 281       * @param bool $isDir set to true to indicate cacert is a dir. defaults to false
 282       */
 283      public function setCaCertificate($caCert, $isDir = false)
 284      {
 285          if ($isDir) {
 286              $this->cacertdir = $caCert;
 287          } else {
 288              $this->cacert = $caCert;
 289          }
 290      }
 291  
 292      /**
 293       * Set attributes for SSL communication: private SSL key.
 294       *
 295       * NB: does not work in older php/curl installs.
 296       * Thanks to Daniel Convissor.
 297       *
 298       * @param string $key The name of a file containing a private SSL key
 299       * @param string $keyPass The secret password needed to use the private SSL key
 300       */
 301      public function setKey($key, $keyPass)
 302      {
 303          $this->key = $key;
 304          $this->keypass = $keyPass;
 305      }
 306  
 307      /**
 308       * Set attributes for SSL communication: verify the remote host's SSL certificate, and cause the connection to fail
 309       * if the cert verification fails.
 310       *
 311       * By default, verification is enabled.
 312       * To specify custom SSL certificates to validate the server with, use the setCaCertificate method.
 313       *
 314       * @param bool $i enable/disable verification of peer certificate
 315       */
 316      public function setSSLVerifyPeer($i)
 317      {
 318          $this->verifypeer = $i;
 319      }
 320  
 321      /**
 322       * Set attributes for SSL communication: verify the remote host's SSL certificate's common name (CN).
 323       *
 324       * Note that support for value 1 has been removed in cURL 7.28.1
 325       *
 326       * @param int $i Set to 1 to only the existence of a CN, not that it matches
 327       */
 328      public function setSSLVerifyHost($i)
 329      {
 330          $this->verifyhost = $i;
 331      }
 332  
 333      /**
 334       * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value): let cURL decide
 335       *
 336       * @param int $i
 337       */
 338      public function setSSLVersion($i)
 339      {
 340          $this->sslversion = $i;
 341      }
 342  
 343      /**
 344       * Set proxy info.
 345       *
 346       * NB: CURL versions before 7.11.10 cannot use a proxy to communicate with https servers.
 347       *
 348       * @param string $proxyHost
 349       * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS
 350       * @param string $proxyUsername Leave blank if proxy has public access
 351       * @param string $proxyPassword Leave blank if proxy has public access
 352       * @param int $proxyAuthType defaults to CURLAUTH_BASIC (Basic authentication protocol); set to constant CURLAUTH_NTLM
 353       *                           to use NTLM auth with proxy (has effect only when the client uses the HTTP 1.1 protocol)
 354       */
 355      public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
 356      {
 357          $this->proxy = $proxyHost;
 358          $this->proxyport = $proxyPort;
 359          $this->proxy_user = $proxyUsername;
 360          $this->proxy_pass = $proxyPassword;
 361          $this->proxy_authtype = $proxyAuthType;
 362      }
 363  
 364      /**
 365       * Enables/disables reception of compressed xmlrpc responses.
 366       *
 367       * This requires the "zlib" extension to be enabled in your php install. If it is, by default xmlrpc_client
 368       * instances will enable reception of compressed content.
 369       * Note that enabling reception of compressed responses merely adds some standard http headers to xmlrpc requests.
 370       * It is up to the xmlrpc server to return compressed responses when receiving such requests.
 371       *
 372       * @param string $compMethod either 'gzip', 'deflate', 'any' or ''
 373       */
 374      public function setAcceptedCompression($compMethod)
 375      {
 376          if ($compMethod == 'any') {
 377              $this->accepted_compression = array('gzip', 'deflate');
 378          } elseif ($compMethod == false) {
 379              $this->accepted_compression = array();
 380          } else {
 381              $this->accepted_compression = array($compMethod);
 382          }
 383      }
 384  
 385      /**
 386       * Enables/disables http compression of xmlrpc request.
 387       *
 388       * This requires the "zlib" extension to be enabled in your php install.
 389       * Take care when sending compressed requests: servers might not support them (and automatic fallback to
 390       * uncompressed requests is not yet implemented).
 391       *
 392       * @param string $compMethod either 'gzip', 'deflate' or ''
 393       */
 394      public function setRequestCompression($compMethod)
 395      {
 396          $this->request_compression = $compMethod;
 397      }
 398  
 399      /**
 400       * Adds a cookie to list of cookies that will be sent to server with every further request (useful e.g. for keeping
 401       * session info outside of the xml-rpc payload).
 402       *
 403       * NB: By default cookies are sent using the 'original/netscape' format, which is also the same as the RFC 2965;
 404       * setting any param but name and value will turn the cookie into a 'version 1' cookie (i.e. RFC 2109 cookie) that
 405       * might not be fully supported by the server. Note that RFC 2109 has currently 'historic' status...
 406       *
 407       * @param string $name nb: will not be escaped in the request's http headers. Take care not to use CTL chars or
 408       *                     separators!
 409       * @param string $value
 410       * @param string $path leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
 411       * @param string $domain leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
 412       * @param int $port leave this empty unless the xml-rpc server only accepts RFC 2109 cookies
 413       *
 414       * @todo check correctness of urlencoding cookie value (copied from php way of doing it, but php is generally sending
 415       *       response not requests. We do the opposite...)
 416       * @todo strip invalid chars from cookie name? As per RFC6265, we should follow RFC2616, Section 2.2
 417       */
 418      public function setCookie($name, $value = '', $path = '', $domain = '', $port = null)
 419      {
 420          $this->cookies[$name]['value'] = rawurlencode($value);
 421          if ($path || $domain || $port) {
 422              $this->cookies[$name]['path'] = $path;
 423              $this->cookies[$name]['domain'] = $domain;
 424              $this->cookies[$name]['port'] = $port;
 425              $this->cookies[$name]['version'] = 1;
 426          } else {
 427              $this->cookies[$name]['version'] = 0;
 428          }
 429      }
 430  
 431      /**
 432       * Directly set cURL options, for extra flexibility (when in cURL mode).
 433       *
 434       * It allows eg. to bind client to a specific IP interface / address.
 435       *
 436       * @param array $options
 437       */
 438      public function setCurlOptions($options)
 439      {
 440          $this->extracurlopts = $options;
 441      }
 442  
 443      /**
 444       * @param int $useCurlMode self::USE_CURL_ALWAYS, self::USE_CURL_AUTO or self::USE_CURL_NEVER
 445       */
 446      public function setUseCurl($useCurlMode)
 447      {
 448          $this->use_curl = $useCurlMode;
 449      }
 450  
 451  
 452      /**
 453       * Set user-agent string that will be used by this client instance in http headers sent to the server.
 454       *
 455       * The default user agent string includes the name of this library and the version number.
 456       *
 457       * @param string $agentString
 458       */
 459      public function setUserAgent($agentString)
 460      {
 461          $this->user_agent = $agentString;
 462      }
 463  
 464      /**
 465       * Send an xmlrpc request to the server.
 466       *
 467       * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the
 468       *                                      complete xml representation of a request.
 469       *                                      When sending an array of Request objects, the client will try to make use of
 470       *                                      a single 'system.multicall' xml-rpc method call to forward to the server all
 471       *                                      the requests in a single HTTP round trip, unless $this->no_multicall has
 472       *                                      been previously set to TRUE (see the multicall method below), in which case
 473       *                                      many consecutive xmlrpc requests will be sent. The method will return an
 474       *                                      array of Response objects in both cases.
 475       *                                      The third variant allows to build by hand (or any other means) a complete
 476       *                                      xmlrpc request message, and send it to the server. $req should be a string
 477       *                                      containing the complete xml representation of the request. It is e.g. useful
 478       *                                      when, for maximal speed of execution, the request is serialized into a
 479       *                                      string using the native php xmlrpc functions (see http://www.php.net/xmlrpc)
 480       * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply.
 481       *                         This timeout value is passed to fsockopen(). It is also used for detecting server
 482       *                         timeouts during communication (i.e. if the server does not send anything to the client
 483       *                         for $timeout seconds, the connection will be closed).
 484       * @param string $method valid values are 'http', 'http11', 'https', 'h2' and 'h2c'. If left unspecified,
 485       *                       the http protocol chosen during creation of the object will be used.
 486       *                       Use 'h2' to make the lib attempt to use http/2 over a secure connection, and 'h2c'
 487       *                       for http/2 without tls. Note that 'h2c' will not use the h2c 'upgrade' method, and be
 488       *                       thus incompatible with any server/proxy not supporting http/2. This is because POST
 489       *                       request are not compatible with h2c upgrade.
 490       *
 491       * @return Response|Response[] Note that the client will always return a Response object, even if the call fails
 492       * @todo allow throwing exceptions instead of returning responses in case of failed calls and/or Fault responses
 493       * @todo refactor: we now support many options besides connection timeout and http version to use. Why only privilege those?
 494       */
 495      public function send($req, $timeout = 0, $method = '')
 496      {
 497          // if user does not specify http protocol, use native method of this client
 498          // (i.e. method set during call to constructor)
 499          if ($method == '') {
 500              $method = $this->method;
 501          }
 502  
 503          if (is_array($req)) {
 504              // $req is an array of Requests
 505              $r = $this->multicall($req, $timeout, $method);
 506  
 507              return $r;
 508          } elseif (is_string($req)) {
 509              $n = new Request('');
 510              $n->payload = $req;
 511              $req = $n;
 512          }
 513  
 514          // where req is a Request
 515          $req->setDebug($this->debug);
 516  
 517          /// @todo we could be smarter about this and force usage of curl in scenarios where it is both available and
 518          ///       needed, such as digest or ntlm auth. Do not attempt to use it for https if not present
 519          $useCurl = ($this->use_curl == self::USE_CURL_ALWAYS) || ($this->use_curl == self::USE_CURL_AUTO &&
 520              (in_array($method, array('https', 'http11', 'h2c', 'h2'))));
 521  
 522          if ($useCurl) {
 523              $r = $this->sendPayloadCURL(
 524                  $req,
 525                  $this->server,
 526                  $this->port,
 527                  $timeout,
 528                  $this->username,
 529                  $this->password,
 530                  $this->authtype,
 531                  $this->cert,
 532                  $this->certpass,
 533                  $this->cacert,
 534                  $this->cacertdir,
 535                  $this->proxy,
 536                  $this->proxyport,
 537                  $this->proxy_user,
 538                  $this->proxy_pass,
 539                  $this->proxy_authtype,
 540                  // bc
 541                  $method == 'http11' ? 'http' : $method,
 542                  $this->keepalive,
 543                  $this->key,
 544                  $this->keypass,
 545                  $this->sslversion
 546              );
 547          } else {
 548              // plain 'http 1.0': default to using socket
 549              $r = $this->sendPayloadSocket(
 550                  $req,
 551                  $this->server,
 552                  $this->port,
 553                  $timeout,
 554                  $this->username,
 555                  $this->password,
 556                  $this->authtype,
 557                  $this->cert,
 558                  $this->certpass,
 559                  $this->cacert,
 560                  $this->cacertdir,
 561                  $this->proxy,
 562                  $this->proxyport,
 563                  $this->proxy_user,
 564                  $this->proxy_pass,
 565                  $this->proxy_authtype,
 566                  $method,
 567                  $this->key,
 568                  $this->keypass,
 569                  $this->sslversion
 570              );
 571          }
 572  
 573          return $r;
 574      }
 575  
 576      /**
 577       * @deprecated
 578       * @param Request $req
 579       * @param string $server
 580       * @param int $port
 581       * @param int $timeout
 582       * @param string $username
 583       * @param string $password
 584       * @param int $authType
 585       * @param string $proxyHost
 586       * @param int $proxyPort
 587       * @param string $proxyUsername
 588       * @param string $proxyPassword
 589       * @param int $proxyAuthType
 590       * @param string $method
 591       * @return Response
 592       */
 593      protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $username = '', $password = '',
 594          $authType = 1, $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
 595          $method='http')
 596      {
 597          //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
 598  
 599          return $this->sendPayloadSocket($req, $server, $port, $timeout, $username, $password, $authType, null, null,
 600              null, null, $proxyHost, $proxyPort, $proxyUsername, $proxyPassword, $proxyAuthType, $method);
 601      }
 602  
 603      /**
 604       * @deprecated
 605       * @param Request $req
 606       * @param string $server
 607       * @param int $port
 608       * @param int $timeout
 609       * @param string $username
 610       * @param string $password
 611       * @param int $authType
 612       * @param string $cert
 613       * @param string $certPass
 614       * @param string $caCert
 615       * @param string $caCertDir
 616       * @param string $proxyHost
 617       * @param int $proxyPort
 618       * @param string $proxyUsername
 619       * @param string $proxyPassword
 620       * @param int $proxyAuthType
 621       * @param bool $keepAlive
 622       * @param string $key
 623       * @param string $keyPass
 624       * @param int $sslVersion
 625       * @return Response
 626       */
 627      protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '',  $password = '',
 628          $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
 629          $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $keepAlive = false, $key = '', $keyPass = '',
 630          $sslVersion = 0)
 631      {
 632          //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
 633  
 634          return $this->sendPayloadCURL($req, $server, $port, $timeout, $username,
 635              $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
 636              $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion);
 637      }
 638  
 639      /**
 640       * @param Request $req
 641       * @param string $server
 642       * @param int $port
 643       * @param int $timeout
 644       * @param string $username
 645       * @param string $password
 646       * @param int $authType only value supported is 1
 647       * @param string $cert
 648       * @param string $certPass
 649       * @param string $caCert
 650       * @param string $caCertDir
 651       * @param string $proxyHost
 652       * @param int $proxyPort
 653       * @param string $proxyUsername
 654       * @param string $proxyPassword
 655       * @param int $proxyAuthType only value supported is 1
 656       * @param string $method 'http' (synonym for 'http10'), 'http10' or 'https'
 657       * @param string $key
 658       * @param string $keyPass @todo not implemented yet.
 659       * @param int $sslVersion @todo not implemented yet. See http://php.net/manual/en/migration56.openssl.php
 660       * @return Response
 661       *
 662       * @todo refactor: we get many options for the call passed in, but some we use from $this. We should clean that up
 663       */
 664      protected function sendPayloadSocket($req, $server, $port, $timeout = 0, $username = '', $password = '',
 665          $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
 666          $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method='http', $key = '', $keyPass = '',
 667          $sslVersion = 0)
 668      {
 669          /// @todo log a warning if passed an unsupported method
 670  
 671          if ($port == 0) {
 672              $port = ( $method === 'https' ) ? 443 : 80;
 673          }
 674  
 675          // Only create the payload if it was not created previously
 676          if (empty($req->payload)) {
 677              $req->serialize($this->request_charset_encoding);
 678          }
 679  
 680          $payload = $req->payload;
 681          // Deflate request body and set appropriate request headers
 682          $encodingHdr = '';
 683          if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
 684              if ($this->request_compression == 'gzip') {
 685                  $a = @gzencode($payload);
 686                  if ($a) {
 687                      $payload = $a;
 688                      $encodingHdr = "Content-Encoding: gzip\r\n";
 689                  }
 690              } else {
 691                  $a = @gzcompress($payload);
 692                  if ($a) {
 693                      $payload = $a;
 694                      $encodingHdr = "Content-Encoding: deflate\r\n";
 695                  }
 696              }
 697          }
 698  
 699          // thanks to Grant Rauscher <grant7@firstworld.net> for this
 700          $credentials = '';
 701          if ($username != '') {
 702              $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
 703              if ($authType != 1) {
 704                  $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0');
 705              }
 706          }
 707  
 708          $acceptedEncoding = '';
 709          if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
 710              $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
 711          }
 712  
 713          $proxyCredentials = '';
 714          if ($proxyHost) {
 715              if ($proxyPort == 0) {
 716                  $proxyPort = 8080;
 717              }
 718              $connectServer = $proxyHost;
 719              $connectPort = $proxyPort;
 720              $transport = 'tcp';
 721              $uri = 'http://' . $server . ':' . $port . $this->path;
 722              if ($proxyUsername != '') {
 723                  if ($proxyAuthType != 1) {
 724                      $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0');
 725                  }
 726                  $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
 727              }
 728          } else {
 729              $connectServer = $server;
 730              $connectPort = $port;
 731              $transport = ( $method === 'https' ) ? 'tls' : 'tcp';
 732              $uri = $this->path;
 733          }
 734  
 735          // Cookie generation, as per rfc2965 (version 1 cookies) or netscape's rules (version 0 cookies)
 736          $cookieHeader = '';
 737          if (count($this->cookies)) {
 738              $version = '';
 739              foreach ($this->cookies as $name => $cookie) {
 740                  if ($cookie['version']) {
 741                      $version = ' $Version="' . $cookie['version'] . '";';
 742                      $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";';
 743                      if ($cookie['path']) {
 744                          $cookieHeader .= ' $Path="' . $cookie['path'] . '";';
 745                      }
 746                      if ($cookie['domain']) {
 747                          $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";';
 748                      }
 749                      if ($cookie['port']) {
 750                          $cookieHeader .= ' $Port="' . $cookie['port'] . '";';
 751                      }
 752                  } else {
 753                      $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";";
 754                  }
 755              }
 756              $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n";
 757          }
 758  
 759          // omit port if default
 760          if (($port == 80 && in_array($method, array('http', 'http10'))) || ($port == 443 && $method == 'https')) {
 761              $port =  '';
 762          } else {
 763              $port = ':' . $port;
 764          }
 765  
 766          $op = 'POST ' . $uri . " HTTP/1.0\r\n" .
 767              'User-Agent: ' . $this->user_agent . "\r\n" .
 768              'Host: ' . $server . $port . "\r\n" .
 769              $credentials .
 770              $proxyCredentials .
 771              $acceptedEncoding .
 772              $encodingHdr .
 773              'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
 774              $cookieHeader .
 775              'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
 776              strlen($payload) . "\r\n\r\n" .
 777              $payload;
 778  
 779          if ($this->debug > 1) {
 780              $this->getLogger()->debugMessage("---SENDING---\n$op\n---END---");
 781          }
 782  
 783          $contextOptions = array();
 784          if ($method == 'https') {
 785              if ($cert != '') {
 786                  $contextOptions['ssl']['local_cert'] = $cert;
 787                  if ($certPass != '') {
 788                      $contextOptions['ssl']['passphrase'] = $certPass;
 789                  }
 790              }
 791              if ($caCert != '') {
 792                  $contextOptions['ssl']['cafile'] = $caCert;
 793              }
 794              if ($caCertDir != '') {
 795                  $contextOptions['ssl']['capath'] = $caCertDir;
 796              }
 797              if ($key != '') {
 798                  $contextOptions['ssl']['local_pk'] = $key;
 799              }
 800              $contextOptions['ssl']['verify_peer'] = $this->verifypeer;
 801              $contextOptions['ssl']['verify_peer_name'] = $this->verifypeer;
 802          }
 803  
 804          $context = stream_context_create($contextOptions);
 805  
 806          if ($timeout <= 0) {
 807              $connectTimeout = ini_get('default_socket_timeout');
 808          } else {
 809              $connectTimeout = $timeout;
 810          }
 811  
 812          $this->errno = 0;
 813          $this->errstr = '';
 814  
 815          $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $connectTimeout,
 816              STREAM_CLIENT_CONNECT, $context);
 817          if ($fp) {
 818              if ($timeout > 0) {
 819                  stream_set_timeout($fp, $timeout);
 820              }
 821          } else {
 822              if ($this->errstr == '') {
 823                  $err = error_get_last();
 824                  $this->errstr = $err['message'];
 825              }
 826  
 827              $this->errstr = 'Connect error: ' . $this->errstr;
 828              $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')');
 829  
 830              return $r;
 831          }
 832  
 833          if (!fputs($fp, $op, strlen($op))) {
 834              fclose($fp);
 835              $this->errstr = 'Write error';
 836              $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr);
 837  
 838              return $r;
 839          }
 840  
 841          // Close socket before parsing.
 842          // It should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
 843          $ipd = '';
 844          do {
 845              // shall we check for $data === FALSE?
 846              // as per the manual, it signals an error
 847              $ipd .= fread($fp, 32768);
 848          } while (!feof($fp));
 849          fclose($fp);
 850  
 851          $r = $req->parseResponse($ipd, false, $this->return_type);
 852  
 853          return $r;
 854      }
 855  
 856      /**
 857       * Contributed by Justin Miller <justin@voxel.net>
 858       * Requires curl to be built into PHP
 859       * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
 860       *
 861       * @param Request $req
 862       * @param string $server
 863       * @param int $port
 864       * @param int $timeout
 865       * @param string $username
 866       * @param string $password
 867       * @param int $authType
 868       * @param string $cert
 869       * @param string $certPass
 870       * @param string $caCert
 871       * @param string $caCertDir
 872       * @param string $proxyHost
 873       * @param int $proxyPort
 874       * @param string $proxyUsername
 875       * @param string $proxyPassword
 876       * @param int $proxyAuthType
 877       * @param string $method 'http' (let curl decide), 'http10', 'http11', 'https', 'h2c' or 'h2'
 878       * @param bool $keepAlive
 879       * @param string $key
 880       * @param string $keyPass
 881       * @param int $sslVersion
 882       * @return Response
 883       *
 884       * @todo refactor: we get many options for the call passed in, but some we use from $this. We should clean that up
 885       */
 886      protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '',
 887          $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
 888          $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
 889          $keyPass = '', $sslVersion = 0)
 890      {
 891          if (!function_exists('curl_init')) {
 892              $this->errstr = 'CURL unavailable on this install';
 893              return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']);
 894          }
 895          if ($method == 'https' || $method == 'h2') {
 896              // q: what about installs where we get back a string, but curl is linked to other ssl libs than openssl?
 897              if (($info = curl_version()) &&
 898                  ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))
 899              ) {
 900                  $this->errstr = 'SSL unavailable on this install';
 901                  return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
 902              }
 903          }
 904          if (($method == 'h2' && !defined('CURL_HTTP_VERSION_2_0')) ||
 905              ($method == 'h2c' && !defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE'))) {
 906              $this->errstr = 'HTTP/2 unavailable on this install';
 907              return new Response(0, PhpXmlRpc::$xmlrpcerr['no_http2'], PhpXmlRpc::$xmlrpcstr['no_http2']);
 908          }
 909  
 910          $curl = $this->prepareCurlHandle($req, $server, $port, $timeout, $username, $password,
 911              $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort,
 912              $proxyUsername, $proxyPassword, $proxyAuthType, $method, $keepAlive, $key,
 913              $keyPass, $sslVersion);
 914  
 915          $result = curl_exec($curl);
 916  
 917          if ($this->debug > 1) {
 918              $message = "---CURL INFO---\n";
 919              foreach (curl_getinfo($curl) as $name => $val) {
 920                  if (is_array($val)) {
 921                      $val = implode("\n", $val);
 922                  }
 923                  $message .= $name . ': ' . $val . "\n";
 924              }
 925              $message .= '---END---';
 926              $this->getLogger()->debugMessage($message);
 927          }
 928  
 929          if (!$result) {
 930              /// @todo we should use a better check here - what if we get back '' or '0'?
 931  
 932              $this->errstr = 'no response';
 933              $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl));
 934              curl_close($curl);
 935              if ($keepAlive) {
 936                  $this->xmlrpc_curl_handle = null;
 937              }
 938          } else {
 939              if (!$keepAlive) {
 940                  curl_close($curl);
 941              }
 942              $resp = $req->parseResponse($result, true, $this->return_type);
 943              // if we got back a 302, we can not reuse the curl handle for later calls
 944              if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) {
 945                  curl_close($curl);
 946                  $this->xmlrpc_curl_handle = null;
 947              }
 948          }
 949  
 950          return $resp;
 951      }
 952  
 953      protected function prepareCurlHandle($req, $server, $port, $timeout = 0, $username = '', $password = '',
 954           $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0,
 955           $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '',
 956           $keyPass = '', $sslVersion = 0)
 957      {
 958          if ($port == 0) {
 959              if (in_array($method, array('http', 'http10', 'http11', 'h2c'))) {
 960                  $port = 80;
 961              } else {
 962                  $port = 443;
 963              }
 964          }
 965  
 966          // Only create the payload if it was not created previously
 967          if (empty($req->payload)) {
 968              $req->serialize($this->request_charset_encoding);
 969          }
 970  
 971          // Deflate request body and set appropriate request headers
 972          $payload = $req->payload;
 973          if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) {
 974              if ($this->request_compression == 'gzip') {
 975                  $a = @gzencode($payload);
 976                  if ($a) {
 977                      $payload = $a;
 978                      $encodingHdr = 'Content-Encoding: gzip';
 979                  }
 980              } else {
 981                  $a = @gzcompress($payload);
 982                  if ($a) {
 983                      $payload = $a;
 984                      $encodingHdr = 'Content-Encoding: deflate';
 985                  }
 986              }
 987          } else {
 988              $encodingHdr = '';
 989          }
 990  
 991          if (!$keepAlive || !$this->xmlrpc_curl_handle) {
 992              if ($method == 'http11' || $method == 'http10' || $method == 'h2c') {
 993                  $protocol = 'http';
 994              } else {
 995                  if ($method == 'h2') {
 996                      $protocol = 'https';
 997                  } else {
 998                      // http, https
 999                      $protocol = $method;
1000                  }
1001              }
1002              $curl = curl_init($protocol . '://' . $server . ':' . $port . $this->path);
1003              if ($keepAlive) {
1004                  $this->xmlrpc_curl_handle = $curl;
1005              }
1006          } else {
1007              $curl = $this->xmlrpc_curl_handle;
1008          }
1009  
1010          // results into variable
1011          curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1012  
1013          if ($this->debug > 1) {
1014              curl_setopt($curl, CURLOPT_VERBOSE, true);
1015              /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
1016          }
1017          curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
1018          // required for XMLRPC: post the data
1019          curl_setopt($curl, CURLOPT_POST, 1);
1020          // the data
1021          curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
1022  
1023          // return the header too
1024          curl_setopt($curl, CURLOPT_HEADER, 1);
1025  
1026          // NB: if we set an empty string, CURL will add http header indicating
1027          // ALL methods it is supporting. This is possibly a better option than letting the user tell what curl can / cannot do...
1028          if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
1029              //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
1030              // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1031              if (count($this->accepted_compression) == 1) {
1032                  curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
1033              } else {
1034                  curl_setopt($curl, CURLOPT_ENCODING, '');
1035              }
1036          }
1037          // extra headers
1038          $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
1039          // if no keepalive is wanted, let the server know it in advance
1040          if (!$keepAlive) {
1041              $headers[] = 'Connection: close';
1042          }
1043          // request compression header
1044          if ($encodingHdr) {
1045              $headers[] = $encodingHdr;
1046          }
1047  
1048          // Fix the HTTP/1.1 417 Expectation Failed Bug (curl by default adds a 'Expect: 100-continue' header when POST
1049          // size exceeds 1025 bytes, apparently)
1050          $headers[] = 'Expect:';
1051  
1052          curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
1053          // timeout is borked
1054          if ($timeout) {
1055              curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
1056          }
1057  
1058          switch($method) {
1059              case 'http10':
1060                  curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
1061                  break;
1062              case 'http11':
1063                  curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
1064                  break;
1065              case 'h2c':
1066                  curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
1067                  break;
1068              case 'h2':
1069                  curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
1070                  break;
1071          }
1072  
1073          if ($username && $password) {
1074              curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
1075              if (defined('CURLOPT_HTTPAUTH')) {
1076                  curl_setopt($curl, CURLOPT_HTTPAUTH, $authType);
1077              } elseif ($authType != 1) {
1078                  $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install');
1079              }
1080          }
1081  
1082          if ($method == 'https' || $method == 'h2') {
1083              // set cert file
1084              if ($cert) {
1085                  curl_setopt($curl, CURLOPT_SSLCERT, $cert);
1086              }
1087              // set cert password
1088              if ($certPass) {
1089                  curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass);
1090              }
1091              // whether to verify remote host's cert
1092              curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
1093              // set ca certificates file/dir
1094              if ($caCert) {
1095                  curl_setopt($curl, CURLOPT_CAINFO, $caCert);
1096              }
1097              if ($caCertDir) {
1098                  curl_setopt($curl, CURLOPT_CAPATH, $caCertDir);
1099              }
1100              // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1101              if ($key) {
1102                  curl_setopt($curl, CURLOPT_SSLKEY, $key);
1103              }
1104              // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1105              if ($keyPass) {
1106                  curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass);
1107              }
1108              // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that
1109              // it matches the hostname used
1110              curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
1111              // allow usage of different SSL versions
1112              curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion);
1113          }
1114  
1115          // proxy info
1116          if ($proxyHost) {
1117              if ($proxyPort == 0) {
1118                  $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080
1119              }
1120              curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
1121              if ($proxyUsername) {
1122                  curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword);
1123                  if (defined('CURLOPT_PROXYAUTH')) {
1124                      curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType);
1125                  } elseif ($proxyAuthType != 1) {
1126                      $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1127                  }
1128              }
1129          }
1130  
1131          // NB: should we build cookie http headers by hand rather than let CURL do it?
1132          // the following code does not honour 'expires', 'path' and 'domain' cookie attributes set to client obj the the user...
1133          if (count($this->cookies)) {
1134              $cookieHeader = '';
1135              foreach ($this->cookies as $name => $cookie) {
1136                  $cookieHeader .= $name . '=' . $cookie['value'] . '; ';
1137              }
1138              curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2));
1139          }
1140  
1141          foreach ($this->extracurlopts as $opt => $val) {
1142              curl_setopt($curl, $opt, $val);
1143          }
1144  
1145          if ($this->debug > 1) {
1146              $this->getLogger()->debugMessage("---SENDING---\n$payload\n---END---");
1147          }
1148  
1149          return $curl;
1150      }
1151  
1152      /**
1153       * Send an array of requests and return an array of responses.
1154       *
1155       * Unless $this->no_multicall has been set to true, it will try first to use one single xmlrpc call to server method
1156       * system.multicall, and revert to sending many successive calls in case of failure.
1157       * This failure is also stored in $this->no_multicall for subsequent calls.
1158       * Unfortunately, there is no server error code universally used to denote the fact that multicall is unsupported,
1159       * so there is no way to reliably distinguish between that and a temporary failure.
1160       * If you are sure that server supports multicall and do not want to fallback to using many single calls, set the
1161       * fourth parameter to FALSE.
1162       *
1163       * NB: trying to shoehorn extra functionality into existing syntax has resulted
1164       * in pretty much convoluted code...
1165       *
1166       * @param Request[] $reqs an array of Request objects
1167       * @param integer $timeout connection timeout (in seconds). See the details in the docs for the send() method
1168       * @param string $method the http protocol variant to be used. See the details in the docs for the send() method
1169       * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be
1170       *                         attempted
1171       *
1172       * @return Response[]
1173       */
1174      public function multicall($reqs, $timeout = 0, $method = '', $fallback = true)
1175      {
1176          if ($method == '') {
1177              $method = $this->method;
1178          }
1179          if (!$this->no_multicall) {
1180              $results = $this->_try_multicall($reqs, $timeout, $method);
1181              if (is_array($results)) {
1182                  // System.multicall succeeded
1183                  return $results;
1184              } else {
1185                  // either system.multicall is unsupported by server,
1186                  // or call failed for some other reason.
1187                  if ($fallback) {
1188                      // Don't try it next time...
1189                      $this->no_multicall = true;
1190                  } else {
1191                      if (is_a($results, '\PhpXmlRpc\Response')) {
1192                          $result = $results;
1193                      } else {
1194                          $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']);
1195                      }
1196                  }
1197              }
1198          } else {
1199              // override fallback, in case careless user tries to do two
1200              // opposite things at the same time
1201              $fallback = true;
1202          }
1203  
1204          $results = array();
1205          if ($fallback) {
1206              // system.multicall is (probably) unsupported by server:
1207              // emulate multicall via multiple requests
1208              /// @todo use curl multi_ functions to make this quicker
1209              foreach ($reqs as $req) {
1210                  $results[] = $this->send($req, $timeout, $method);
1211              }
1212          } else {
1213              // user does NOT want to fallback on many single calls:
1214              // since we should always return an array of responses,
1215              // return an array with the same error repeated n times
1216              foreach ($reqs as $req) {
1217                  $results[] = $result;
1218              }
1219          }
1220  
1221          return $results;
1222      }
1223  
1224      /**
1225       * Attempt to boxcar $reqs via system.multicall.
1226       *
1227       * Returns either an array of Response, a single error Response or false (when received response does not respect
1228       * valid multicall syntax).
1229       *
1230       * @param Request[] $reqs
1231       * @param int $timeout
1232       * @param string $method
1233       * @return Response[]|false|mixed|Response
1234       */
1235      private function _try_multicall($reqs, $timeout, $method)
1236      {
1237          // Construct multicall request
1238          $calls = array();
1239          foreach ($reqs as $req) {
1240              $call['methodName'] = new Value($req->method(), 'string');
1241              $numParams = $req->getNumParams();
1242              $params = array();
1243              for ($i = 0; $i < $numParams; $i++) {
1244                  $params[$i] = $req->getParam($i);
1245              }
1246              $call['params'] = new Value($params, 'array');
1247              $calls[] = new Value($call, 'struct');
1248          }
1249          $multiCall = new Request('system.multicall');
1250          $multiCall->addParam(new Value($calls, 'array'));
1251  
1252          // Attempt RPC call
1253          $result = $this->send($multiCall, $timeout, $method);
1254  
1255          if ($result->faultCode() != 0) {
1256              // call to system.multicall failed
1257              return $result;
1258          }
1259  
1260          // Unpack responses.
1261          $rets = $result->value();
1262  
1263          if ($this->return_type == 'xml') {
1264              return $rets;
1265          } elseif ($this->return_type == 'phpvals') {
1266              /// @todo test this code branch...
1267              $rets = $result->value();
1268              if (!is_array($rets)) {
1269                  return false;       // bad return type from system.multicall
1270              }
1271              $numRets = count($rets);
1272              if ($numRets != count($reqs)) {
1273                  return false;       // wrong number of return values.
1274              }
1275  
1276              $response = array();
1277              for ($i = 0; $i < $numRets; $i++) {
1278                  $val = $rets[$i];
1279                  if (!is_array($val)) {
1280                      return false;
1281                  }
1282                  switch (count($val)) {
1283                      case 1:
1284                          if (!isset($val[0])) {
1285                              return false;       // Bad value
1286                          }
1287                          // Normal return value
1288                          $response[$i] = new Response($val[0], 0, '', 'phpvals');
1289                          break;
1290                      case 2:
1291                          /// @todo remove usage of @: it is apparently quite slow
1292                          $code = @$val['faultCode'];
1293                          if (!is_int($code)) {
1294                              return false;
1295                          }
1296                          $str = @$val['faultString'];
1297                          if (!is_string($str)) {
1298                              return false;
1299                          }
1300                          $response[$i] = new Response(0, $code, $str);
1301                          break;
1302                      default:
1303                          return false;
1304                  }
1305              }
1306  
1307              return $response;
1308          } else {
1309              // return type == 'xmlrpcvals'
1310  
1311              $rets = $result->value();
1312              if ($rets->kindOf() != 'array') {
1313                  return false;       // bad return type from system.multicall
1314              }
1315              $numRets = $rets->count();
1316              if ($numRets != count($reqs)) {
1317                  return false;       // wrong number of return values.
1318              }
1319  
1320              $response = array();
1321              foreach($rets as $val) {
1322                  switch ($val->kindOf()) {
1323                      case 'array':
1324                          if ($val->count() != 1) {
1325                              return false;       // Bad value
1326                          }
1327                          // Normal return value
1328                          $response[] = new Response($val[0]);
1329                          break;
1330                      case 'struct':
1331                          $code = $val['faultCode'];
1332                          /** @var Value $code */
1333                          if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
1334                              return false;
1335                          }
1336                          $str = $val['faultString'];
1337                          /** @var Value $str */
1338                          if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
1339                              return false;
1340                          }
1341                          $response[] = new Response(0, $code->scalarval(), $str->scalarval());
1342                          break;
1343                      default:
1344                          return false;
1345                  }
1346              }
1347  
1348              return $response;
1349          }
1350      }
1351  }