src/Service/Soap/Transport_http.php line 451

Open in your IDE?
  1. <?php
  2. namespace App\Service\Soap;
  3. /**
  4. * transport class for sending/receiving data via HTTP and HTTPS
  5. * NOTE: PHP must be compiled with the CURL extension for HTTPS support
  6. *
  7. * @author   Dietrich Ayala <dietrich@ganx4.com>
  8. * @author   Scott Nichol <snichol@users.sourceforge.net>
  9. * @version  $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
  10. * @access public
  11. */
  12. class Transport_http extends base {
  13.     var $url = '';
  14.     var $uri = '';
  15.     var $digest_uri = '';
  16.     var $scheme = '';
  17.     var $host = '';
  18.     var $port = '';
  19.     var $path = '';
  20.     var $request_method = 'POST';
  21.     var $protocol_version = '1.0';
  22.     var $encoding = '';
  23.     var $outgoing_headers = array();
  24.     var $incoming_headers = array();
  25.     var $incoming_cookies = array();
  26.     var $outgoing_payload = '';
  27.     var $incoming_payload = '';
  28.     var $response_status_line;    // HTTP response status line
  29.     var $useSOAPAction = true;
  30.     var $persistentConnection = false;
  31.     var $ch = false;    // cURL handle
  32.     var $ch_options = array();    // cURL custom options
  33.     var $use_curl = false;        // force cURL use
  34.     var $proxy = null;            // proxy information (associative array)
  35.     var $username = '';
  36.     var $password = '';
  37.     var $authtype = '';
  38.     var $digestRequest = array();
  39.     var $certRequest = array();    // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional)
  40.                                 // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem'
  41.                                 // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem'
  42.                                 // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem'
  43.                                 // passphrase: SSL key password/passphrase
  44.                                 // certpassword: SSL certificate password
  45.                                 // verifypeer: default is 1
  46.                                 // verifyhost: default is 1
  47.     /**
  48.     * constructor
  49.     *
  50.     * @param string $url The URL to which to connect
  51.     * @param array $curl_options User-specified cURL options
  52.     * @param boolean $use_curl Whether to try to force cURL use
  53.     * @access public
  54.     */
  55.     function __construct($url, $curl_options = NULL, $use_curl = false){
  56.         parent::base();
  57.         $this->debug("ctor url=$url use_curl=$use_curl curl_options:");
  58.         $this->appendDebug($this->varDump($curl_options));
  59.         $this->setURL($url);
  60.         if (is_array($curl_options)) {
  61.             $this->ch_options = $curl_options;
  62.         }
  63.         $this->use_curl = $use_curl;
  64.         preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev);
  65.         $this->setHeader('User-Agent', $this->title.'/'.$this->version.' ('.$rev[1].')');
  66.     }
  67.     /**
  68.     * sets a cURL option
  69.     *
  70.     * @param    mixed $option The cURL option (always integer?)
  71.     * @param    mixed $value The cURL option value
  72.     * @access   private
  73.     */
  74.     function setCurlOption($option, $value) {
  75.         $this->debug("setCurlOption option=$option, value=");
  76.         $this->appendDebug($this->varDump($value));
  77.         curl_setopt($this->ch, $option, $value);
  78.     }
  79.     /**
  80.     * sets an HTTP header
  81.     *
  82.     * @param string $name The name of the header
  83.     * @param string $value The value of the header
  84.     * @access private
  85.     */
  86.     function setHeader($name, $value) {
  87.         $this->outgoing_headers[$name] = $value;
  88.         $this->debug("set header $name: $value");
  89.     }
  90.     /**
  91.     * unsets an HTTP header
  92.     *
  93.     * @param string $name The name of the header
  94.     * @access private
  95.     */
  96.     function unsetHeader($name) {
  97.         if (isset($this->outgoing_headers[$name])) {
  98.             $this->debug("unset header $name");
  99.             unset($this->outgoing_headers[$name]);
  100.         }
  101.     }
  102.     /**
  103.     * sets the URL to which to connect
  104.     *
  105.     * @param string $url The URL to which to connect
  106.     * @access private
  107.     */
  108.     function setURL($url) {
  109.         $this->url = $url;
  110.         $u = parse_url($url);
  111.         foreach($u as $k => $v){
  112.             $this->debug("parsed URL $k = $v");
  113.             $this->$k = $v;
  114.         }
  115.         
  116.         // add any GET params to path
  117.         if(isset($u['query']) && $u['query'] != ''){
  118.             $this->path .= '?' . $u['query'];
  119.         }
  120.         
  121.         // set default port
  122.         if(!isset($u['port'])){
  123.             if($u['scheme'] == 'https'){
  124.                 $this->port = 443;
  125.             } else {
  126.                 $this->port = 80;
  127.             }
  128.         }
  129.         
  130.         $this->uri = $this->path;
  131.         $this->digest_uri = $this->uri;
  132.         
  133.         // build headers
  134.         if (!isset($u['port'])) {
  135.             $this->setHeader('Host', $this->host);
  136.         } else {
  137.             $this->setHeader('Host', $this->host.':'.$this->port);
  138.         }
  139.         if (isset($u['user']) && $u['user'] != '') {
  140.             $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : '');
  141.         }
  142.     }
  143.     /**
  144.     * gets the I/O method to use
  145.     *
  146.     * @return    string    I/O method to use (socket|curl|unknown)
  147.     * @access    private
  148.     */
  149.     function io_method() {
  150.         if ($this->use_curl || ($this->scheme == 'https') || ($this->scheme == 'http' && $this->authtype == 'ntlm') || ($this->scheme == 'http' && is_array($this->proxy) && $this->proxy['authtype'] == 'ntlm'))
  151.             return 'curl';
  152.         if (($this->scheme == 'http' || $this->scheme == 'ssl') && $this->authtype != 'ntlm' && (!is_array($this->proxy) || $this->proxy['authtype'] != 'ntlm'))
  153.             return 'socket';
  154.         return 'unknown';
  155.     }
  156.     /**
  157.     * establish an HTTP connection
  158.     *
  159.     * @param    integer $timeout set connection timeout in seconds
  160.     * @param    integer $response_timeout set response timeout in seconds
  161.     * @return    boolean true if connected, false if not
  162.     * @access   private
  163.     */
  164.     function connect($connection_timeout=0,$response_timeout=30){
  165.           // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like
  166.           // "regular" socket.
  167.           // TODO: disabled for now because OpenSSL must be *compiled* in (not just
  168.           //       loaded), and until PHP5 stream_get_wrappers is not available.
  169. //          if ($this->scheme == 'https') {
  170. //              if (version_compare(phpversion(), '4.3.0') >= 0) {
  171. //                  if (extension_loaded('openssl')) {
  172. //                      $this->scheme = 'ssl';
  173. //                      $this->debug('Using SSL over OpenSSL');
  174. //                  }
  175. //              }
  176. //        }
  177.         $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port");
  178.       if ($this->io_method() == 'socket') {
  179.         if (!is_array($this->proxy)) {
  180.             $host = $this->host;
  181.             $port = $this->port;
  182.         } else {
  183.             $host = $this->proxy['host'];
  184.             $port = $this->proxy['port'];
  185.         }
  186.         // use persistent connection
  187.         if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){
  188.             if (!feof($this->fp)) {
  189.                 $this->debug('Re-use persistent connection');
  190.                 return true;
  191.             }
  192.             fclose($this->fp);
  193.             $this->debug('Closed persistent connection at EOF');
  194.         }
  195.         // munge host if using OpenSSL
  196.         if ($this->scheme == 'ssl') {
  197.             $host = 'ssl://' . $host;
  198.         }
  199.         $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout);
  200.         // open socket
  201.         if($connection_timeout > 0){
  202.             $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout);
  203.         } else {
  204.             $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str);
  205.         }
  206.         
  207.         // test pointer
  208.         if(!$this->fp) {
  209.             $msg = 'Couldn\'t open socket connection to server ' . $this->url;
  210.             if ($this->errno) {
  211.                 $msg .= ', Error ('.$this->errno.'): '.$this->error_str;
  212.             } else {
  213.                 $msg .= ' prior to connect().  This is often a problem looking up the host name.';
  214.             }
  215.             $this->debug($msg);
  216.             $this->setError($msg);
  217.             return false;
  218.         }
  219.         
  220.         // set response timeout
  221.         $this->debug('set response timeout to ' . $response_timeout);
  222.         socket_set_timeout( $this->fp, $response_timeout);
  223.         $this->debug('socket connected');
  224.         return true;
  225.       } else if ($this->io_method() == 'curl') {
  226.         if (!extension_loaded('curl')) {
  227. //            $this->setError('cURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS');
  228.             $this->setError('The PHP cURL Extension is required for HTTPS or NLTM.  You will need to re-build or update your PHP to include cURL or change php.ini to load the PHP cURL extension.');
  229.             return false;
  230.         }
  231.         // Avoid warnings when PHP does not have these options
  232.         if (defined('CURLOPT_CONNECTIONTIMEOUT'))
  233.             $CURLOPT_CONNECTIONTIMEOUT = CURLOPT_CONNECTIONTIMEOUT;
  234.         else
  235.             $CURLOPT_CONNECTIONTIMEOUT = 78;
  236.         if (defined('CURLOPT_HTTPAUTH'))
  237.             $CURLOPT_HTTPAUTH = CURLOPT_HTTPAUTH;
  238.         else
  239.             $CURLOPT_HTTPAUTH = 107;
  240.         if (defined('CURLOPT_PROXYAUTH'))
  241.             $CURLOPT_PROXYAUTH = CURLOPT_PROXYAUTH;
  242.         else
  243.             $CURLOPT_PROXYAUTH = 111;
  244.         if (defined('CURLAUTH_BASIC'))
  245.             $CURLAUTH_BASIC = CURLAUTH_BASIC;
  246.         else
  247.             $CURLAUTH_BASIC = 1;
  248.         if (defined('CURLAUTH_DIGEST'))
  249.             $CURLAUTH_DIGEST = CURLAUTH_DIGEST;
  250.         else
  251.             $CURLAUTH_DIGEST = 2;
  252.         if (defined('CURLAUTH_NTLM'))
  253.             $CURLAUTH_NTLM = CURLAUTH_NTLM;
  254.         else
  255.             $CURLAUTH_NTLM = 8;
  256.         $this->debug('connect using cURL');
  257.         // init CURL
  258.         $this->ch = curl_init();
  259.         // set url
  260.         $hostURL = ($this->port != '') ? "$this->scheme://$this->host:$this->port" : "$this->scheme://$this->host";
  261.         // add path
  262.         $hostURL .= $this->path;
  263.         $this->setCurlOption(CURLOPT_URL, $hostURL);
  264.         // follow location headers (re-directs)
  265.         if (ini_get('safe_mode') || ini_get('open_basedir')) {
  266.             $this->debug('safe_mode or open_basedir set, so do not set CURLOPT_FOLLOWLOCATION');
  267.             $this->debug('safe_mode = ');
  268.             $this->appendDebug($this->varDump(ini_get('safe_mode')));
  269.             $this->debug('open_basedir = ');
  270.             $this->appendDebug($this->varDump(ini_get('open_basedir')));
  271.         } else {
  272.             $this->setCurlOption(CURLOPT_FOLLOWLOCATION, 1);
  273.         }
  274.         // ask for headers in the response output
  275.         $this->setCurlOption(CURLOPT_HEADER, 1);
  276.         // ask for the response output as the return value
  277.         $this->setCurlOption(CURLOPT_RETURNTRANSFER, 1);
  278.         // encode
  279.         // We manage this ourselves through headers and encoding
  280. //        if(function_exists('gzuncompress')){
  281. //            $this->setCurlOption(CURLOPT_ENCODING, 'deflate');
  282. //        }
  283.         // persistent connection
  284.         if ($this->persistentConnection) {
  285.             // I believe the following comment is now bogus, having applied to
  286.             // the code when it used CURLOPT_CUSTOMREQUEST to send the request.
  287.             // The way we send data, we cannot use persistent connections, since
  288.             // there will be some "junk" at the end of our request.
  289.             //$this->setCurlOption(CURL_HTTP_VERSION_1_1, true);
  290.             $this->persistentConnection = false;
  291.             $this->setHeader('Connection', 'close');
  292.         }
  293.         // set timeouts
  294.         if ($connection_timeout != 0) {
  295.             $this->setCurlOption($CURLOPT_CONNECTIONTIMEOUT, $connection_timeout);
  296.         }
  297.         if ($response_timeout != 0) {
  298.             $this->setCurlOption(CURLOPT_TIMEOUT, $response_timeout);
  299.         }
  300.         if ($this->scheme == 'https') {
  301.             $this->debug('set cURL SSL verify options');
  302.             // recent versions of cURL turn on peer/host checking by default,
  303.             // while PHP binaries are not compiled with a default location for the
  304.             // CA cert bundle, so disable peer/host checking.
  305.             //$this->setCurlOption(CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt');        
  306.             $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
  307.             $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0);
  308.     
  309.             // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo)
  310.             if ($this->authtype == 'certificate') {
  311.                 $this->debug('set cURL certificate options');
  312.                 if (isset($this->certRequest['cainfofile'])) {
  313.                     $this->setCurlOption(CURLOPT_CAINFO, $this->certRequest['cainfofile']);
  314.                 }
  315.                 if (isset($this->certRequest['verifypeer'])) {
  316.                     $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']);
  317.                 } else {
  318.                     $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 1);
  319.                 }
  320.                 if (isset($this->certRequest['verifyhost'])) {
  321.                     $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']);
  322.                 } else {
  323.                     $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1);
  324.                 }
  325.                 if (isset($this->certRequest['sslcertfile'])) {
  326.                     $this->setCurlOption(CURLOPT_SSLCERT, $this->certRequest['sslcertfile']);
  327.                 }
  328.                 if (isset($this->certRequest['sslkeyfile'])) {
  329.                     $this->setCurlOption(CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']);
  330.                 }
  331.                 if (isset($this->certRequest['passphrase'])) {
  332.                     $this->setCurlOption(CURLOPT_SSLKEYPASSWD, $this->certRequest['passphrase']);
  333.                 }
  334.                 if (isset($this->certRequest['certpassword'])) {
  335.                     $this->setCurlOption(CURLOPT_SSLCERTPASSWD, $this->certRequest['certpassword']);
  336.                 }
  337.             }
  338.         }
  339.         if ($this->authtype && ($this->authtype != 'certificate')) {
  340.             if ($this->username) {
  341.                 $this->debug('set cURL username/password');
  342.                 $this->setCurlOption(CURLOPT_USERPWD, "$this->username:$this->password");
  343.             }
  344.             if ($this->authtype == 'basic') {
  345.                 $this->debug('set cURL for Basic authentication');
  346.                 $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_BASIC);
  347.             }
  348.             if ($this->authtype == 'digest') {
  349.                 $this->debug('set cURL for digest authentication');
  350.                 $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_DIGEST);
  351.             }
  352.             if ($this->authtype == 'ntlm') {
  353.                 $this->debug('set cURL for NTLM authentication');
  354.                 $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_NTLM);
  355.             }
  356.         }
  357.         if (is_array($this->proxy)) {
  358.             $this->debug('set cURL proxy options');
  359.             if ($this->proxy['port'] != '') {
  360.                 $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host'].':'.$this->proxy['port']);
  361.             } else {
  362.                 $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host']);
  363.             }
  364.             if ($this->proxy['username'] || $this->proxy['password']) {
  365.                 $this->debug('set cURL proxy authentication options');
  366.                 $this->setCurlOption(CURLOPT_PROXYUSERPWD, $this->proxy['username'].':'.$this->proxy['password']);
  367.                 if ($this->proxy['authtype'] == 'basic') {
  368.                     $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_BASIC);
  369.                 }
  370.                 if ($this->proxy['authtype'] == 'ntlm') {
  371.                     $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_NTLM);
  372.                 }
  373.             }
  374.         }
  375.         $this->debug('cURL connection set up');
  376.         return true;
  377.       } else {
  378.         $this->setError('Unknown scheme ' . $this->scheme);
  379.         $this->debug('Unknown scheme ' . $this->scheme);
  380.         return false;
  381.       }
  382.     }
  383.     /**
  384.     * sends the SOAP request and gets the SOAP response via HTTP[S]
  385.     *
  386.     * @param    string $data message data
  387.     * @param    integer $timeout set connection timeout in seconds
  388.     * @param    integer $response_timeout set response timeout in seconds
  389.     * @param    array $cookies cookies to send
  390.     * @return    string data
  391.     * @access   public
  392.     */
  393.     function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) {
  394.         
  395.         $this->debug('entered send() with data of length: '.strlen($data));
  396.         $this->tryagain = true;
  397.         $tries = 0;
  398.         while ($this->tryagain) {
  399.             $this->tryagain = false;
  400.             if ($tries++ < 2) {
  401.                 // make connnection
  402.                 if (!$this->connect($timeout, $response_timeout)){
  403.                     return false;
  404.                 }
  405.                 
  406.                 // send request
  407.                 if (!$this->sendRequest($data, $cookies)){
  408.                     return false;
  409.                 }
  410.                 
  411.                 // get response
  412.                 $respdata = $this->getResponse();
  413.             } else {
  414.                 $this->setError("Too many tries to get an OK response ($this->response_status_line)");
  415.             }
  416.         }        
  417.         $this->debug('end of send()');
  418.         return $respdata;
  419.     }
  420.     /**
  421.     * sends the SOAP request and gets the SOAP response via HTTPS using CURL
  422.     *
  423.     * @param    string $data message data
  424.     * @param    integer $timeout set connection timeout in seconds
  425.     * @param    integer $response_timeout set response timeout in seconds
  426.     * @param    array $cookies cookies to send
  427.     * @return    string data
  428.     * @access   public
  429.     * @deprecated
  430.     */
  431.     function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) {
  432.         return $this->send($data, $timeout, $response_timeout, $cookies);
  433.     }
  434.     
  435.     /**
  436.     * if authenticating, set user credentials here
  437.     *
  438.     * @param    string $username
  439.     * @param    string $password
  440.     * @param    string $authtype (basic|digest|certificate|ntlm)
  441.     * @param    array $digestRequest (keys must be nonce, nc, realm, qop)
  442.     * @param    array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
  443.     * @access   public
  444.     */
  445.     function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) {
  446.         $this->debug("setCredentials username=$username authtype=$authtype digestRequest=");
  447.         $this->appendDebug($this->varDump($digestRequest));
  448.         $this->debug("certRequest=");
  449.         $this->appendDebug($this->varDump($certRequest));
  450.         // cf. RFC 2617
  451.         if ($authtype == 'basic') {
  452.             $this->setHeader('Authorization', 'Basic '.base64_encode(str_replace(':','',$username).':'.$password));
  453.         } elseif ($authtype == 'digest') {
  454.             if (isset($digestRequest['nonce'])) {
  455.                 $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1;
  456.                 
  457.                 // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html)
  458.     
  459.                 // A1 = unq(username-value) ":" unq(realm-value) ":" passwd
  460.                 $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password;
  461.     
  462.                 // H(A1) = MD5(A1)
  463.                 $HA1 = md5($A1);
  464.     
  465.                 // A2 = Method ":" digest-uri-value
  466.                 $A2 = $this->request_method . ':' . $this->digest_uri;
  467.     
  468.                 // H(A2)
  469.                 $HA2 =  md5($A2);
  470.     
  471.                 // KD(secret, data) = H(concat(secret, ":", data))
  472.                 // if qop == auth:
  473.                 // request-digest  = <"> < KD ( H(A1),     unq(nonce-value)
  474.                 //                              ":" nc-value
  475.                 //                              ":" unq(cnonce-value)
  476.                 //                              ":" unq(qop-value)
  477.                 //                              ":" H(A2)
  478.                 //                            ) <">
  479.                 // if qop is missing,
  480.                 // request-digest  = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
  481.     
  482.                 $unhashedDigest = '';
  483.                 $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : '';
  484.                 $cnonce = $nonce;
  485.                 if ($digestRequest['qop'] != '') {
  486.                     $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2;
  487.                 } else {
  488.                     $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2;
  489.                 }
  490.     
  491.                 $hashedDigest = md5($unhashedDigest);
  492.     
  493.                 $opaque = '';    
  494.                 if (isset($digestRequest['opaque'])) {
  495.                     $opaque = ', opaque="' . $digestRequest['opaque'] . '"';
  496.                 }
  497.                 $this->setHeader('Authorization', 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . $opaque . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"');
  498.             }
  499.         } elseif ($authtype == 'certificate') {
  500.             $this->certRequest = $certRequest;
  501.             $this->debug('Authorization header not set for certificate');
  502.         } elseif ($authtype == 'ntlm') {
  503.             // do nothing
  504.             $this->debug('Authorization header not set for ntlm');
  505.         }
  506.         $this->username = $username;
  507.         $this->password = $password;
  508.         $this->authtype = $authtype;
  509.         $this->digestRequest = $digestRequest;
  510.     }
  511.     
  512.     /**
  513.     * set the soapaction value
  514.     *
  515.     * @param    string $soapaction
  516.     * @access   public
  517.     */
  518.     function setSOAPAction($soapaction) {
  519.         $this->setHeader('SOAPAction', '"' . $soapaction . '"');
  520.     }
  521.     
  522.     /**
  523.     * use http encoding
  524.     *
  525.     * @param    string $enc encoding style. supported values: gzip, deflate, or both
  526.     * @access   public
  527.     */
  528.     function setEncoding($enc='gzip, deflate') {
  529.         if (function_exists('gzdeflate')) {
  530.             $this->protocol_version = '1.1';
  531.             $this->setHeader('Accept-Encoding', $enc);
  532.             if (!isset($this->outgoing_headers['Connection'])) {
  533.                 $this->setHeader('Connection', 'close');
  534.                 $this->persistentConnection = false;
  535.             }
  536.             // deprecated as of PHP 5.3.0
  537.             //set_magic_quotes_runtime(0);
  538.             $this->encoding = $enc;
  539.         }
  540.     }
  541.     
  542.     /**
  543.     * set proxy info here
  544.     *
  545.     * @param    string $proxyhost use an empty string to remove proxy
  546.     * @param    string $proxyport
  547.     * @param    string $proxyusername
  548.     * @param    string $proxypassword
  549.     * @param    string $proxyauthtype (basic|ntlm)
  550.     * @access   public
  551.     */
  552.     function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') {
  553.         if ($proxyhost) {
  554.             $this->proxy = array(
  555.                 'host' => $proxyhost,
  556.                 'port' => $proxyport,
  557.                 'username' => $proxyusername,
  558.                 'password' => $proxypassword,
  559.                 'authtype' => $proxyauthtype
  560.             );
  561.             if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype = 'basic') {
  562.                 $this->setHeader('Proxy-Authorization', ' Basic '.base64_encode($proxyusername.':'.$proxypassword));
  563.             }
  564.         } else {
  565.             $this->debug('remove proxy');
  566.             $proxy = null;
  567.             unsetHeader('Proxy-Authorization');
  568.         }
  569.     }
  570.     
  571.     /**
  572.      * Test if the given string starts with a header that is to be skipped.
  573.      * Skippable headers result from chunked transfer and proxy requests.
  574.      *
  575.      * @param    string $data The string to check.
  576.      * @returns    boolean    Whether a skippable header was found.
  577.      * @access    private
  578.      */
  579.     function isSkippableCurlHeader(&$data) {
  580.         $skipHeaders = array(    'HTTP/1.1 100',
  581.                                 'HTTP/1.0 301',
  582.                                 'HTTP/1.1 301',
  583.                                 'HTTP/1.0 302',
  584.                                 'HTTP/1.1 302',
  585.                                 'HTTP/1.0 401',
  586.                                 'HTTP/1.1 401',
  587.                                 'HTTP/1.0 200 Connection established');
  588.         foreach ($skipHeaders as $hd) {
  589.             $prefix = substr($data, 0, strlen($hd));
  590.             if ($prefix == $hd) return true;
  591.         }
  592.         return false;
  593.     }
  594.     /**
  595.     * decode a string that is encoded w/ "chunked' transfer encoding
  596.      * as defined in RFC2068 19.4.6
  597.     *
  598.     * @param    string $buffer
  599.     * @param    string $lb
  600.     * @returns    string
  601.     * @access   public
  602.     * @deprecated
  603.     */
  604.     function decodeChunked($buffer, $lb){
  605.         // length := 0
  606.         $length = 0;
  607.         $new = '';
  608.         
  609.         // read chunk-size, chunk-extension (if any) and CRLF
  610.         // get the position of the linebreak
  611.         $chunkend = strpos($buffer, $lb);
  612.         if ($chunkend == FALSE) {
  613.             $this->debug('no linebreak found in decodeChunked');
  614.             return $new;
  615.         }
  616.         $temp = substr($buffer,0,$chunkend);
  617.         $chunk_size = hexdec( trim($temp) );
  618.         $chunkstart = $chunkend + strlen($lb);
  619.         // while (chunk-size > 0) {
  620.         while ($chunk_size > 0) {
  621.             $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size");
  622.             $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size);
  623.               
  624.             // Just in case we got a broken connection
  625.               if ($chunkend == FALSE) {
  626.                   $chunk = substr($buffer,$chunkstart);
  627.                 // append chunk-data to entity-body
  628.                 $new .= $chunk;
  629.                   $length += strlen($chunk);
  630.                   break;
  631.             }
  632.             
  633.               // read chunk-data and CRLF
  634.               $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
  635.               // append chunk-data to entity-body
  636.               $new .= $chunk;
  637.               // length := length + chunk-size
  638.               $length += strlen($chunk);
  639.               // read chunk-size and CRLF
  640.               $chunkstart = $chunkend + strlen($lb);
  641.             
  642.               $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb);
  643.             if ($chunkend == FALSE) {
  644.                 break; //Just in case we got a broken connection
  645.             }
  646.             $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
  647.             $chunk_size = hexdec( trim($temp) );
  648.             $chunkstart = $chunkend;
  649.         }
  650.         return $new;
  651.     }
  652.     
  653.     /**
  654.      * Writes the payload, including HTTP headers, to $this->outgoing_payload.
  655.      *
  656.      * @param    string $data HTTP body
  657.      * @param    string $cookie_str data for HTTP Cookie header
  658.      * @return    void
  659.      * @access    private
  660.      */
  661.     function buildPayload($data, $cookie_str = '') {
  662.         // Note: for cURL connections, $this->outgoing_payload is ignored,
  663.         // as is the Content-Length header, but these are still created as
  664.         // debugging guides.
  665.         // add content-length header
  666.         if ($this->request_method != 'GET') {
  667.             $this->setHeader('Content-Length', strlen($data));
  668.         }
  669.         // start building outgoing payload:
  670.         if ($this->proxy) {
  671.             $uri = $this->url;
  672.         } else {
  673.             $uri = $this->uri;
  674.         }
  675.         $req = "$this->request_method $uri HTTP/$this->protocol_version";
  676.         $this->debug("HTTP request: $req");
  677.         $this->outgoing_payload = "$req\r\n";
  678.         // loop thru headers, serializing
  679.         foreach($this->outgoing_headers as $k => $v){
  680.             $hdr = $k.': '.$v;
  681.             $this->debug("HTTP header: $hdr");
  682.             $this->outgoing_payload .= "$hdr\r\n";
  683.         }
  684.         // add any cookies
  685.         if ($cookie_str != '') {
  686.             $hdr = 'Cookie: '.$cookie_str;
  687.             $this->debug("HTTP header: $hdr");
  688.             $this->outgoing_payload .= "$hdr\r\n";
  689.         }
  690.         // header/body separator
  691.         $this->outgoing_payload .= "\r\n";
  692.         
  693.         // add data
  694.         $this->outgoing_payload .= $data;
  695.     }
  696.     /**
  697.     * sends the SOAP request via HTTP[S]
  698.     *
  699.     * @param    string $data message data
  700.     * @param    array $cookies cookies to send
  701.     * @return    boolean    true if OK, false if problem
  702.     * @access   private
  703.     */
  704.     function sendRequest($data, $cookies = NULL) {
  705.         // build cookie string
  706.         $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https')));
  707.         // build payload
  708.         $this->buildPayload($data, $cookie_str);
  709.       if ($this->io_method() == 'socket') {
  710.         // send payload
  711.         if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
  712.             $this->setError('couldn\'t write message data to socket');
  713.             $this->debug('couldn\'t write message data to socket');
  714.             return false;
  715.         }
  716.         $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload));
  717.         return true;
  718.       } else if ($this->io_method() == 'curl') {
  719.         // set payload
  720.         // cURL does say this should only be the verb, and in fact it
  721.         // turns out that the URI and HTTP version are appended to this, which
  722.         // some servers refuse to work with (so we no longer use this method!)
  723.         //$this->setCurlOption(CURLOPT_CUSTOMREQUEST, $this->outgoing_payload);
  724.         $curl_headers = array();
  725.         foreach($this->outgoing_headers as $k => $v){
  726.             if ($k == 'Connection' || $k == 'Content-Length' || $k == 'Host' || $k == 'Authorization' || $k == 'Proxy-Authorization') {
  727.                 $this->debug("Skip cURL header $k: $v");
  728.             } else {
  729.                 $curl_headers[] = "$k: $v";
  730.             }
  731.         }
  732.         if ($cookie_str != '') {
  733.             $curl_headers[] = 'Cookie: ' . $cookie_str;
  734.         }
  735.         $this->setCurlOption(CURLOPT_HTTPHEADER, $curl_headers);
  736.         $this->debug('set cURL HTTP headers');
  737.         if ($this->request_method == "POST") {
  738.               $this->setCurlOption(CURLOPT_POST, 1);
  739.               $this->setCurlOption(CURLOPT_POSTFIELDS, $data);
  740.             $this->debug('set cURL POST data');
  741.           } else {
  742.           }
  743.         // insert custom user-set cURL options
  744.         foreach ($this->ch_options as $key => $val) {
  745.             $this->setCurlOption($key, $val);
  746.         }
  747.         $this->debug('set cURL payload');
  748.         return true;
  749.       }
  750.     }
  751.     /**
  752.     * gets the SOAP response via HTTP[S]
  753.     *
  754.     * @return    string the response (also sets member variables like incoming_payload)
  755.     * @access   private
  756.     */
  757.     function getResponse(){
  758.         $this->incoming_payload = '';
  759.         
  760.       if ($this->io_method() == 'socket') {
  761.         // loop until headers have been retrieved
  762.         $data = '';
  763.         while (!isset($lb)){
  764.             // We might EOF during header read.
  765.             if(feof($this->fp)) {
  766.                 $this->incoming_payload = $data;
  767.                 $this->debug('found no headers before EOF after length ' . strlen($data));
  768.                 $this->debug("received before EOF:\n" . $data);
  769.                 $this->setError('server failed to send headers');
  770.                 return false;
  771.             }
  772.             $tmp = fgets($this->fp, 256);
  773.             $tmplen = strlen($tmp);
  774.             $this->debug("read line of $tmplen bytes: " . trim($tmp));
  775.             if ($tmplen == 0) {
  776.                 $this->incoming_payload = $data;
  777.                 $this->debug('socket read of headers timed out after length ' . strlen($data));
  778.                 $this->debug("read before timeout: " . $data);
  779.                 $this->setError('socket read of headers timed out');
  780.                 return false;
  781.             }
  782.             $data .= $tmp;
  783.             $pos = strpos($data,"\r\n\r\n");
  784.             if($pos > 1){
  785.                 $lb = "\r\n";
  786.             } else {
  787.                 $pos = strpos($data,"\n\n");
  788.                 if($pos > 1){
  789.                     $lb = "\n";
  790.                 }
  791.             }
  792.             // remove 100 headers
  793.             if (isset($lb) && preg_match('/^HTTP\/1.1 100/',$data)) {
  794.                 unset($lb);
  795.                 $data = '';
  796.             }//
  797.         }
  798.         // store header data
  799.         $this->incoming_payload .= $data;
  800.         $this->debug('found end of headers after length ' . strlen($data));
  801.         // process headers
  802.         $header_data = trim(substr($data,0,$pos));
  803.         $header_array = explode($lb,$header_data);
  804.         $this->incoming_headers = array();
  805.         $this->incoming_cookies = array();
  806.         foreach($header_array as $header_line){
  807.             $arr = explode(':',$header_line, 2);
  808.             if(count($arr) > 1){
  809.                 $header_name = strtolower(trim($arr[0]));
  810.                 $this->incoming_headers[$header_name] = trim($arr[1]);
  811.                 if ($header_name == 'set-cookie') {
  812.                     // TODO: allow multiple cookies from parseCookie
  813.                     $cookie = $this->parseCookie(trim($arr[1]));
  814.                     if ($cookie) {
  815.                         $this->incoming_cookies[] = $cookie;
  816.                         $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
  817.                     } else {
  818.                         $this->debug('did not find cookie in ' . trim($arr[1]));
  819.                     }
  820.                 }
  821.             } else if (isset($header_name)) {
  822.                 // append continuation line to previous header
  823.                 $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
  824.             }
  825.         }
  826.         
  827.         // loop until msg has been received
  828.         if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') {
  829.             $content_length =  2147483647;    // ignore any content-length header
  830.             $chunked = true;
  831.             $this->debug("want to read chunked content");
  832.         } elseif (isset($this->incoming_headers['content-length'])) {
  833.             $content_length = $this->incoming_headers['content-length'];
  834.             $chunked = false;
  835.             $this->debug("want to read content of length $content_length");
  836.         } else {
  837.             $content_length =  2147483647;
  838.             $chunked = false;
  839.             $this->debug("want to read content to EOF");
  840.         }
  841.         $data = '';
  842.         do {
  843.             if ($chunked) {
  844.                 $tmp = fgets($this->fp, 256);
  845.                 $tmplen = strlen($tmp);
  846.                 $this->debug("read chunk line of $tmplen bytes");
  847.                 if ($tmplen == 0) {
  848.                     $this->incoming_payload = $data;
  849.                     $this->debug('socket read of chunk length timed out after length ' . strlen($data));
  850.                     $this->debug("read before timeout:\n" . $data);
  851.                     $this->setError('socket read of chunk length timed out');
  852.                     return false;
  853.                 }
  854.                 $content_length = hexdec(trim($tmp));
  855.                 $this->debug("chunk length $content_length");
  856.             }
  857.             $strlen = 0;
  858.             while (($strlen < $content_length) && (!feof($this->fp))) {
  859.                 $readlen = min(8192, $content_length - $strlen);
  860.                 $tmp = fread($this->fp, $readlen);
  861.                 $tmplen = strlen($tmp);
  862.                 $this->debug("read buffer of $tmplen bytes");
  863.                 if (($tmplen == 0) && (!feof($this->fp))) {
  864.                     $this->incoming_payload = $data;
  865.                     $this->debug('socket read of body timed out after length ' . strlen($data));
  866.                     $this->debug("read before timeout:\n" . $data);
  867.                     $this->setError('socket read of body timed out');
  868.                     return false;
  869.                 }
  870.                 $strlen += $tmplen;
  871.                 $data .= $tmp;
  872.             }
  873.             if ($chunked && ($content_length > 0)) {
  874.                 $tmp = fgets($this->fp, 256);
  875.                 $tmplen = strlen($tmp);
  876.                 $this->debug("read chunk terminator of $tmplen bytes");
  877.                 if ($tmplen == 0) {
  878.                     $this->incoming_payload = $data;
  879.                     $this->debug('socket read of chunk terminator timed out after length ' . strlen($data));
  880.                     $this->debug("read before timeout:\n" . $data);
  881.                     $this->setError('socket read of chunk terminator timed out');
  882.                     return false;
  883.                 }
  884.             }
  885.         } while ($chunked && ($content_length > 0) && (!feof($this->fp)));
  886.         if (feof($this->fp)) {
  887.             $this->debug('read to EOF');
  888.         }
  889.         $this->debug('read body of length ' . strlen($data));
  890.         $this->incoming_payload .= $data;
  891.         $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server');
  892.         
  893.         // close filepointer
  894.         if(
  895.             (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') || 
  896.             (! $this->persistentConnection) || feof($this->fp)){
  897.             fclose($this->fp);
  898.             $this->fp = false;
  899.             $this->debug('closed socket');
  900.         }
  901.         
  902.         // connection was closed unexpectedly
  903.         if($this->incoming_payload == ''){
  904.             $this->setError('no response from server');
  905.             return false;
  906.         }
  907.         
  908.         // decode transfer-encoding
  909. //        if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){
  910. //            if(!$data = $this->decodeChunked($data, $lb)){
  911. //                $this->setError('Decoding of chunked data failed');
  912. //                return false;
  913. //            }
  914.             //print "<pre>\nde-chunked:\n---------------\n$data\n\n---------------\n</pre>";
  915.             // set decoded payload
  916. //            $this->incoming_payload = $header_data.$lb.$lb.$data;
  917. //        }
  918.     
  919.       } else if ($this->io_method() == 'curl') {
  920.         // send and receive
  921.         $this->debug('send and receive with cURL');
  922.         $this->incoming_payload = curl_exec($this->ch);
  923.         $data = $this->incoming_payload;
  924.         $cErr = curl_error($this->ch);
  925.         if ($cErr != '') {
  926.             $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'<br>';
  927.             // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE
  928.             foreach(curl_getinfo($this->ch) as $k => $v){
  929.                 $err .= "$k: $v<br>";
  930.             }
  931.             $this->debug($err);
  932.             $this->setError($err);
  933.             curl_close($this->ch);
  934.             return false;
  935.         } else {
  936.             //echo '<pre>';
  937.             //var_dump(curl_getinfo($this->ch));
  938.             //echo '</pre>';
  939.         }
  940.         // close curl
  941.         $this->debug('No cURL error, closing cURL');
  942.         curl_close($this->ch);
  943.         
  944.         // try removing skippable headers
  945.         $savedata = $data;
  946.         while ($this->isSkippableCurlHeader($data)) {
  947.             $this->debug("Found HTTP header to skip");
  948.             if ($pos = strpos($data,"\r\n\r\n")) {
  949.                 $data = ltrim(substr($data,$pos));
  950.             } elseif($pos = strpos($data,"\n\n") ) {
  951.                 $data = ltrim(substr($data,$pos));
  952.             }
  953.         }
  954.         if ($data == '') {
  955.             // have nothing left; just remove 100 header(s)
  956.             $data = $savedata;
  957.             while (preg_match('/^HTTP\/1.1 100/',$data)) {
  958.                 if ($pos = strpos($data,"\r\n\r\n")) {
  959.                     $data = ltrim(substr($data,$pos));
  960.                 } elseif($pos = strpos($data,"\n\n") ) {
  961.                     $data = ltrim(substr($data,$pos));
  962.                 }
  963.             }
  964.         }
  965.         
  966.         // separate content from HTTP headers
  967.         if ($pos = strpos($data,"\r\n\r\n")) {
  968.             $lb = "\r\n";
  969.         } elseif( $pos = strpos($data,"\n\n")) {
  970.             $lb = "\n";
  971.         } else {
  972.             $this->debug('no proper separation of headers and document');
  973.             $this->setError('no proper separation of headers and document');
  974.             return false;
  975.         }
  976.         $header_data = trim(substr($data,0,$pos));
  977.         $header_array = explode($lb,$header_data);
  978.         $data = ltrim(substr($data,$pos));
  979.         $this->debug('found proper separation of headers and document');
  980.         $this->debug('cleaned data, stringlen: '.strlen($data));
  981.         // clean headers
  982.         foreach ($header_array as $header_line) {
  983.             $arr = explode(':',$header_line,2);
  984.             if(count($arr) > 1){
  985.                 $header_name = strtolower(trim($arr[0]));
  986.                 $this->incoming_headers[$header_name] = trim($arr[1]);
  987.                 if ($header_name == 'set-cookie') {
  988.                     // TODO: allow multiple cookies from parseCookie
  989.                     $cookie = $this->parseCookie(trim($arr[1]));
  990.                     if ($cookie) {
  991.                         $this->incoming_cookies[] = $cookie;
  992.                         $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
  993.                     } else {
  994.                         $this->debug('did not find cookie in ' . trim($arr[1]));
  995.                     }
  996.                 }
  997.             } else if (isset($header_name)) {
  998.                 // append continuation line to previous header
  999.                 $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
  1000.             }
  1001.         }
  1002.       }
  1003.         $this->response_status_line = $header_array[0];
  1004.         $arr = explode(' ', $this->response_status_line, 3);
  1005.         $http_version = $arr[0];
  1006.         $http_status = intval($arr[1]);
  1007.         $http_reason = count($arr) > 2 ? $arr[2] : '';
  1008.          // see if we need to resend the request with http digest authentication
  1009.          if (isset($this->incoming_headers['location']) && ($http_status == 301 || $http_status == 302)) {
  1010.              $this->debug("Got $http_status $http_reason with Location: " . $this->incoming_headers['location']);
  1011.              $this->setURL($this->incoming_headers['location']);
  1012.             $this->tryagain = true;
  1013.             return false;
  1014.         }
  1015.          // see if we need to resend the request with http digest authentication
  1016.          if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) {
  1017.              $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']);
  1018.              if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) {
  1019.                  $this->debug('Server wants digest authentication');
  1020.                  // remove "Digest " from our elements
  1021.                  $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']);
  1022.                  
  1023.                  // parse elements into array
  1024.                  $digestElements = explode(',', $digestString);
  1025.                  foreach ($digestElements as $val) {
  1026.                      $tempElement = explode('=', trim($val), 2);
  1027.                      $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]);
  1028.                  }
  1029.                 // should have (at least) qop, realm, nonce
  1030.                  if (isset($digestRequest['nonce'])) {
  1031.                      $this->setCredentials($this->username, $this->password, 'digest', $digestRequest);
  1032.                      $this->tryagain = true;
  1033.                      return false;
  1034.                  }
  1035.              }
  1036.             $this->debug('HTTP authentication failed');
  1037.             $this->setError('HTTP authentication failed');
  1038.             return false;
  1039.          }
  1040.         
  1041.         if (
  1042.             ($http_status >= 300 && $http_status <= 307) ||
  1043.             ($http_status >= 400 && $http_status <= 417) ||
  1044.             ($http_status >= 501 && $http_status <= 505)
  1045.            ) {
  1046.             $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)");
  1047.             return false;
  1048.         }
  1049.         // decode content-encoding
  1050.         if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){
  1051.             if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){
  1052.                 // if decoding works, use it. else assume data wasn't gzencoded
  1053.                 if(function_exists('gzinflate')){
  1054.                     //$timer->setMarker('starting decoding of gzip/deflated content');
  1055.                     // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress)
  1056.                     // this means there are no Zlib headers, although there should be
  1057.                     $this->debug('The gzinflate function exists');
  1058.                     $datalen = strlen($data);
  1059.                     if ($this->incoming_headers['content-encoding'] == 'deflate') {
  1060.                         if ($degzdata = @gzinflate($data)) {
  1061.                             $data = $degzdata;
  1062.                             $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes');
  1063.                             if (strlen($data) < $datalen) {
  1064.                                 // test for the case that the payload has been compressed twice
  1065.                                 $this->debug('The inflated payload is smaller than the gzipped one; try again');
  1066.                                 if ($degzdata = @gzinflate($data)) {
  1067.                                     $data = $degzdata;
  1068.                                     $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes');
  1069.                                 }
  1070.                             }
  1071.                         } else {
  1072.                             $this->debug('Error using gzinflate to inflate the payload');
  1073.                             $this->setError('Error using gzinflate to inflate the payload');
  1074.                         }
  1075.                     } elseif ($this->incoming_headers['content-encoding'] == 'gzip') {
  1076.                         if ($degzdata = @gzinflate(substr($data, 10))) {    // do our best
  1077.                             $data = $degzdata;
  1078.                             $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes');
  1079.                             if (strlen($data) < $datalen) {
  1080.                                 // test for the case that the payload has been compressed twice
  1081.                                 $this->debug('The un-gzipped payload is smaller than the gzipped one; try again');
  1082.                                 if ($degzdata = @gzinflate(substr($data, 10))) {
  1083.                                     $data = $degzdata;
  1084.                                     $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes');
  1085.                                 }
  1086.                             }
  1087.                         } else {
  1088.                             $this->debug('Error using gzinflate to un-gzip the payload');
  1089.                             $this->setError('Error using gzinflate to un-gzip the payload');
  1090.                         }
  1091.                     }
  1092.                     //$timer->setMarker('finished decoding of gzip/deflated content');
  1093.                     //print "<xmp>\nde-inflated:\n---------------\n$data\n-------------\n</xmp>";
  1094.                     // set decoded payload
  1095.                     $this->incoming_payload = $header_data.$lb.$lb.$data;
  1096.                 } else {
  1097.                     $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
  1098.                     $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
  1099.                 }
  1100.             } else {
  1101.                 $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
  1102.                 $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
  1103.             }
  1104.         } else {
  1105.             $this->debug('No Content-Encoding header');
  1106.         }
  1107.         
  1108.         if(strlen($data) == 0){
  1109.             $this->debug('no data after headers!');
  1110.             $this->setError('no data present after HTTP headers');
  1111.             return false;
  1112.         }
  1113.         
  1114.         return $data;
  1115.     }
  1116.     /**
  1117.      * sets the content-type for the SOAP message to be sent
  1118.      *
  1119.      * @param    string $type the content type, MIME style
  1120.      * @param    mixed $charset character set used for encoding (or false)
  1121.      * @access    public
  1122.      */
  1123.     function setContentType($type, $charset = false) {
  1124.         $this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : ''));
  1125.     }
  1126.     /**
  1127.      * specifies that an HTTP persistent connection should be used
  1128.      *
  1129.      * @return    boolean whether the request was honored by this method.
  1130.      * @access    public
  1131.      */
  1132.     function usePersistentConnection(){
  1133.         if (isset($this->outgoing_headers['Accept-Encoding'])) {
  1134.             return false;
  1135.         }
  1136.         $this->protocol_version = '1.1';
  1137.         $this->persistentConnection = true;
  1138.         $this->setHeader('Connection', 'Keep-Alive');
  1139.         return true;
  1140.     }
  1141.     /**
  1142.      * parse an incoming Cookie into it's parts
  1143.      *
  1144.      * @param    string $cookie_str content of cookie
  1145.      * @return    array with data of that cookie
  1146.      * @access    private
  1147.      */
  1148.     /*
  1149.      * TODO: allow a Set-Cookie string to be parsed into multiple cookies
  1150.      */
  1151.     function parseCookie($cookie_str) {
  1152.         $cookie_str = str_replace('; ', ';', $cookie_str) . ';';
  1153.         $data = preg_split('/;/', $cookie_str);
  1154.         $value_str = $data[0];
  1155.         $cookie_param = 'domain=';
  1156.         $start = strpos($cookie_str, $cookie_param);
  1157.         if ($start > 0) {
  1158.             $domain = substr($cookie_str, $start + strlen($cookie_param));
  1159.             $domain = substr($domain, 0, strpos($domain, ';'));
  1160.         } else {
  1161.             $domain = '';
  1162.         }
  1163.         $cookie_param = 'expires=';
  1164.         $start = strpos($cookie_str, $cookie_param);
  1165.         if ($start > 0) {
  1166.             $expires = substr($cookie_str, $start + strlen($cookie_param));
  1167.             $expires = substr($expires, 0, strpos($expires, ';'));
  1168.         } else {
  1169.             $expires = '';
  1170.         }
  1171.         $cookie_param = 'path=';
  1172.         $start = strpos($cookie_str, $cookie_param);
  1173.         if ( $start > 0 ) {
  1174.             $path = substr($cookie_str, $start + strlen($cookie_param));
  1175.             $path = substr($path, 0, strpos($path, ';'));
  1176.         } else {
  1177.             $path = '/';
  1178.         }
  1179.                         
  1180.         $cookie_param = ';secure;';
  1181.         if (strpos($cookie_str, $cookie_param) !== FALSE) {
  1182.             $secure = true;
  1183.         } else {
  1184.             $secure = false;
  1185.         }
  1186.         $sep_pos = strpos($value_str, '=');
  1187.         if ($sep_pos) {
  1188.             $name = substr($value_str, 0, $sep_pos);
  1189.             $value = substr($value_str, $sep_pos + 1);
  1190.             $cookie= array(    'name' => $name,
  1191.                             'value' => $value,
  1192.                             'domain' => $domain,
  1193.                             'path' => $path,
  1194.                             'expires' => $expires,
  1195.                             'secure' => $secure
  1196.                             );        
  1197.             return $cookie;
  1198.         }
  1199.         return false;
  1200.     }
  1201.   
  1202.     /**
  1203.      * sort out cookies for the current request
  1204.      *
  1205.      * @param    array $cookies array with all cookies
  1206.      * @param    boolean $secure is the send-content secure or not?
  1207.      * @return    string for Cookie-HTTP-Header
  1208.      * @access    private
  1209.      */
  1210.     function getCookiesForRequest($cookies, $secure=false) {
  1211.         $cookie_str = '';
  1212.         if ((! is_null($cookies)) && (is_array($cookies))) {
  1213.             foreach ($cookies as $cookie) {
  1214.                 if (! is_array($cookie)) {
  1215.                     continue;
  1216.                 }
  1217.                 $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']);
  1218.                 if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
  1219.                     if (strtotime($cookie['expires']) <= time()) {
  1220.                         $this->debug('cookie has expired');
  1221.                         continue;
  1222.                     }
  1223.                 }
  1224.                 if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) {
  1225.                     $domain = preg_quote($cookie['domain']);
  1226.                     if (! preg_match("'.*$domain$'i", $this->host)) {
  1227.                         $this->debug('cookie has different domain');
  1228.                         continue;
  1229.                     }
  1230.                 }
  1231.                 if ((isset($cookie['path'])) && (! empty($cookie['path']))) {
  1232.                     $path = preg_quote($cookie['path']);
  1233.                     if (! preg_match("'^$path.*'i", $this->path)) {
  1234.                         $this->debug('cookie is for a different path');
  1235.                         continue;
  1236.                     }
  1237.                 }
  1238.                 if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) {
  1239.                     $this->debug('cookie is secure, transport is not');
  1240.                     continue;
  1241.                 }
  1242.                 $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; ';
  1243.                 $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']);
  1244.             }
  1245.         }
  1246.         return $cookie_str;
  1247.   }
  1248. }