/** * Read response from server * * @return string */ public function read() { // First, read headers only $response = ''; $gotStatus = false; while ($line = @fgets($this->socket)) { $gotStatus = $gotStatus || strpos($line, 'HTTP') !== false; if ($gotStatus) { $response .= $line; if (!chop($line)) { break; } } } // Handle 100 and 101 responses internally by restarting the read again if (Zend_Http_Response::extractCode($response) == 100 || Zend_Http_Response::extractCode($response) == 101) { return $this->read(); } // If this was a HEAD request, return after reading the header (no need to read body) if ($this->method == Zend_Http_Client::HEAD) { return $response; } // Check headers to see what kind of connection / transfer encoding we have $headers = Zend_Http_Response::extractHeaders($response); // if the connection is set to close, just read until socket closes if (isset($headers['connection']) && $headers['connection'] == 'close') { while ($buff = @fread($this->socket, 8192)) { $response .= $buff; } $this->close(); // Else, if we got a transfer-encoding header (chunked body) } elseif (isset($headers['transfer-encoding'])) { if ($headers['transfer-encoding'] == 'chunked') { do { $chunk = ''; $line = @fgets($this->socket); $chunk .= $line; $hexchunksize = ltrim(chop($line), '0'); $hexchunksize = strlen($hexchunksize) ? strtolower($hexchunksize) : 0; $chunksize = hexdec(chop($line)); if (dechex($chunksize) != $hexchunksize) { @fclose($this->socket); require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' . $hexchunksize . '" unable to read chunked body'); } $left_to_read = $chunksize; while ($left_to_read > 0) { $line = @fread($this->socket, $left_to_read); $chunk .= $line; $left_to_read -= strlen($line); } $chunk .= @fgets($this->socket); $response .= $chunk; } while ($chunksize > 0); } else { throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' . $headers['transfer-encoding'] . '" transfer encoding'); } // Else, if we got the content-length header, read this number of bytes } elseif (isset($headers['content-length'])) { $left_to_read = $headers['content-length']; $chunk = ''; while ($left_to_read > 0) { $chunk = @fread($this->socket, $left_to_read); $left_to_read -= strlen($chunk); $response .= $chunk; } // Fallback: just read the response (should not happen) } else { while ($buff = @fread($this->socket, 8192)) { $response .= $buff; } $this->close(); } return $response; }
/** * Make a HTTP request. * @param string $method * @param array $getParameters * @param array $postParameters * @throws Insulin_Service_Rest_ConnectionFailedException * @throws Insulin_Service_Rest_HttpErrorException */ protected function _doRequest($method, array $getParameters = null, array $postParameters = null) { $link = $this->getLink(); if (!empty($postParameters)) { $link->setParameterPost($postParameters); } if (!empty($getParameters)) { $link->setParameterGet($getParameters); } $link->setUri($this->_endpoint); $link->setMethod($method); require_once 'Zend/Http/Exception.php'; try { $response = $link->request(); } catch (Zend_Http_Exception $e) { require_once 'Insulin/Service/Rest/ConnectionFailedException.php'; throw new Insulin_Service_Rest_ConnectionFailedException(); } if ($response->isError()) { require_once 'Insulin/Service/Rest/HttpErrorException.php'; // extract error code from response $code = Zend_Http_Response::extractCode($response); // extract standard error message from response $msg = Zend_Http_Response::responseCodeAsText($code); throw new Insulin_Service_Rest_HttpErrorException($code, $msg); } return $response; }
/** * Post back to PayPal to check whether this request is a valid one * * @return void * @throws RemoteServiceUnavailableException * @throws \Exception */ protected function _postBack() { $httpAdapter = $this->_curlFactory->create(); $postbackQuery = http_build_query($this->getRequestData()) . '&cmd=_notify-validate'; $postbackUrl = $this->_config->getPayPalIpnUrl(); $this->_addDebugData('postback_to', $postbackUrl); $httpAdapter->setConfig(['verifypeer' => $this->_config->getValue('verifyPeer')]); $httpAdapter->write(\Zend_Http_Client::POST, $postbackUrl, '1.1', ['Connection: close'], $postbackQuery); try { $postbackResult = $httpAdapter->read(); } catch (\Exception $e) { $this->_addDebugData('http_error', ['error' => $e->getMessage(), 'code' => $e->getCode()]); throw $e; } /* * Handle errors on PayPal side. */ $responseCode = \Zend_Http_Response::extractCode($postbackResult); if (empty($postbackResult) || in_array($responseCode, ['500', '502', '503'])) { if (empty($postbackResult)) { $reason = 'Empty response.'; } else { $reason = 'Response code: ' . $responseCode . '.'; } $this->_debugData['exception'] = 'PayPal IPN postback failure. ' . $reason; throw new RemoteServiceUnavailableException(__($reason)); } $response = preg_split('/^\\r?$/m', $postbackResult, 2); $response = trim($response[1]); if ($response != 'VERIFIED') { $this->_addDebugData('postback', $postbackQuery); $this->_addDebugData('postback_result', $postbackResult); throw new \Exception('PayPal IPN postback failure. See system.log for details.'); } }
/** * Check if survey url valid (exists) or not * * @return boolen */ public static function isSurveyUrlValid() { $curl = new Varien_Http_Adapter_Curl(); $curl->setConfig(array('timeout' => 5))->write(Zend_Http_Client::GET, self::getSurveyUrl(), '1.0'); $response = $curl->read(); if (Zend_Http_Response::extractCode($response) == 200) { return true; } return false; }
/** * If file is accessible return true or false * * @return bool */ private function _isFileAccessible() { $defaultUnsecureBaseURL = (string) Mage::getConfig()->getNode('default/' . Mage_Core_Model_Store::XML_PATH_UNSECURE_BASE_URL); $http = new Varien_Http_Adapter_Curl(); $http->setConfig(array('timeout' => $this->_verificationTimeOut)); $http->write(Zend_Http_Client::POST, $defaultUnsecureBaseURL . $this->_filePath); $responseBody = $http->read(); $responseCode = Zend_Http_Response::extractCode($responseBody); $http->close(); return $responseCode == 200; }
/** * Check if survey url valid (exists) or not * * @return bool */ public function isSurveyUrlValid() { $curl = new \Magento\Framework\HTTP\Adapter\Curl(); $curl->setConfig(array('timeout' => 5))->write(\Zend_Http_Client::GET, $this->getSurveyUrl(), '1.0'); $response = $curl->read(); $curl->close(); if (\Zend_Http_Response::extractCode($response) == 200) { return true; } return false; }
public function read() { $this->_applyConfig(); $response = curl_exec($this->_getResource()); // Remove 100 and 101 responses headers while (Zend_Http_Response::extractCode($response) == 100 || Zend_Http_Response::extractCode($response) == 101) { $response = preg_split('/^\\r?$/m', $response, 2); $response = trim($response[1]); } if (stripos($response, "Transfer-Encoding: chunked\r\n")) { $response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $response); } return $response; }
function exec() { if ($this->_resource) { $this->data = curl_exec($this->_resource); if (curl_error($this->_resource)) { $this->error_message = curl_error($this->_resource); $this->error_number = curl_errno($this->_resource); Mage::log($this->error_number . ': ' . $this->error_message, 0, Mage::getStoreConfig('dev/log/exception_file')); } // Remove 100 and 101 responses headers if (Zend_Http_Response::extractCode($this->data) == 100 || Zend_Http_Response::extractCode($this->data) == 101) { $this->data = preg_split('/^\\r?$/m', $this->data, 2); $this->data = trim($this->data[1]); } return $this->data; } else { return false; } }
/** * @param ResultCollection $results */ public function check(ResultCollection $results) { $result = $results->createResult(); $filePath = 'app/etc/local.xml'; $defaultUnsecureBaseURL = (string) \Mage::getConfig()->getNode('default/' . \Mage_Core_Model_Store::XML_PATH_UNSECURE_BASE_URL); $http = new \Varien_Http_Adapter_Curl(); $http->setConfig(array('timeout' => $this->_verificationTimeOut)); $http->write(\Zend_Http_Client::POST, $defaultUnsecureBaseURL . $filePath); $responseBody = $http->read(); $responseCode = \Zend_Http_Response::extractCode($responseBody); $http->close(); if ($responseCode === 200) { $result->setStatus(Result::STATUS_ERROR); $result->setMessage("<error>{$filePath} can be accessed from outside!</error>"); } else { $result->setStatus(Result::STATUS_OK); $result->setMessage("<info><comment>{$filePath}</comment> cannot be accessed from outside.</info>"); } }
public function getFeedData() { $curl = new Varien_Http_Adapter_Curl(); $curl->setConfig(array('timeout' => 1)); $curl->write(Zend_Http_Client::GET, $this->getFeedUrl(), '1.0'); $data = $curl->read(); if ($data === false || Zend_Http_Response::extractCode($data) !== 200) { return false; } $data = preg_split('/^\\r?$/m', $data, 2); $data = trim($data[1]); $curl->close(); try { $xml = new SimpleXMLElement($data); } catch (Exception $e) { return false; } return $xml; }
/** * Read response from server * * @return string */ public function read() { $response = curl_exec($this->_getResource()); // Remove 100 and 101 responses headers while (\Zend_Http_Response::extractCode($response) == 100 || \Zend_Http_Response::extractCode($response) == 101) { $response = preg_split('/^\\r?$/m', $response, 2); $response = trim($response[1]); } // CUrl will handle chunked data but leave the header. $response = preg_replace('/Transfer-Encoding:\\s+chunked\\r?\\n/i', '', $response); return $response; }
/** * Read response from server * * @return string */ public function read() { // First, read headers only $response = ''; $gotStatus = false; while (($line = @fgets($this->socket)) !== false) { $gotStatus = $gotStatus || strpos($line, 'HTTP') !== false; if ($gotStatus) { $response .= $line; if (rtrim($line) === '') { break; } } } $this->_checkSocketReadTimeout(); $statusCode = Zend_Http_Response::extractCode($response); // Handle 100 and 101 responses internally by restarting the read again if ($statusCode == 100 || $statusCode == 101) { return $this->read(); } // Check headers to see what kind of connection / transfer encoding we have $headers = Zend_Http_Response::extractHeaders($response); /** * Responses to HEAD requests and 204 or 304 responses are not expected * to have a body - stop reading here */ if ($statusCode == 304 || $statusCode == 204 || $this->method == Zend_Http_Client::HEAD) { // Close the connection if requested to do so by the server if (isset($headers['connection']) && $headers['connection'] == 'close') { $this->close(); } return $response; } // If we got a 'transfer-encoding: chunked' header if (isset($headers['transfer-encoding'])) { if (strtolower($headers['transfer-encoding']) == 'chunked') { do { $line = @fgets($this->socket); $this->_checkSocketReadTimeout(); $chunk = $line; // Figure out the next chunk size $chunksize = trim($line); if (!ctype_xdigit($chunksize)) { $this->close(); require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' . $chunksize . '" unable to read chunked body'); } // Convert the hexadecimal value to plain integer $chunksize = hexdec($chunksize); // Read next chunk $read_to = ftell($this->socket) + $chunksize; do { $current_pos = ftell($this->socket); if ($current_pos >= $read_to) { break; } $line = @fread($this->socket, $read_to - $current_pos); if ($line === false || strlen($line) === 0) { $this->_checkSocketReadTimeout(); break; } else { $chunk .= $line; } } while (!feof($this->socket)); $chunk .= @fgets($this->socket); $this->_checkSocketReadTimeout(); $response .= $chunk; } while ($chunksize > 0); } else { $this->close(); throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' . $headers['transfer-encoding'] . '" transfer encoding'); } // Else, if we got the content-length header, read this number of bytes } elseif (isset($headers['content-length'])) { $current_pos = ftell($this->socket); $chunk = ''; for ($read_to = $current_pos + $headers['content-length']; $read_to > $current_pos; $current_pos = ftell($this->socket)) { $chunk = @fread($this->socket, $read_to - $current_pos); if ($chunk === false || strlen($chunk) === 0) { $this->_checkSocketReadTimeout(); break; } $response .= $chunk; // Break if the connection ended prematurely if (feof($this->socket)) { break; } } // Fallback: just read the response until EOF } else { do { $buff = @fread($this->socket, 8192); if ($buff === false || strlen($buff) === 0) { $this->_checkSocketReadTimeout(); break; } else { $response .= $buff; } } while (feof($this->socket) === false); $this->close(); } // Close the connection if requested to do so by the server if (isset($headers['connection']) && $headers['connection'] == 'close') { $this->close(); } return $response; }
/** * Read response from server * * @return string */ public function read() { $response = curl_exec($this->_getResource()); // Remove 100 and 101 responses headers if (Zend_Http_Response::extractCode($response) == 100 || Zend_Http_Response::extractCode($response) == 101) { $response = preg_split('/^\\r?$/m', $response, 2); $response = trim($response[1]); } return $response; }
public function testExtractorsOnInvalidString() { // Try with an empty string $response_str = ''; $this->assertTrue(Zend_Http_Response::extractCode($response_str) === false); $this->assertTrue(Zend_Http_Response::extractMessage($response_str) === false); $this->assertTrue(Zend_Http_Response::extractVersion($response_str) === false); $this->assertTrue(Zend_Http_Response::extractBody($response_str) === ''); $this->assertTrue(Zend_Http_Response::extractHeaders($response_str) === array()); }
/** * Read response from server * * @return string */ public function read() { // First, read headers only $response = ''; $gotStatus = false; $stream = !empty($this->config['stream']); while (($line = @fgets($this->socket)) !== false) { $gotStatus = $gotStatus || strpos($line, 'HTTP') !== false; if ($gotStatus) { $response .= $line; if (rtrim($line) === '') { break; } } } $this->_checkSocketReadTimeout(); $statusCode = Zend_Http_Response::extractCode($response); // Handle 100 and 101 responses internally by restarting the read again if ($statusCode == 100 || $statusCode == 101) { return $this->read(); } // Check headers to see what kind of connection / transfer encoding we have $headers = Zend_Http_Response::extractHeaders($response); /** * Responses to HEAD requests and 204 or 304 responses are not expected * to have a body - stop reading here */ if ($statusCode == 304 || $statusCode == 204 || $this->method == Zend_Http_Client::HEAD) { // Close the connection if requested to do so by the server if (isset($headers['connection']) && $headers['connection'] == 'close') { $this->close(); } return $response; } // If we got a 'transfer-encoding: chunked' header if (isset($headers['transfer-encoding'])) { if (strtolower($headers['transfer-encoding']) == 'chunked') { do { $line = @fgets($this->socket); $this->_checkSocketReadTimeout(); $chunk = $line; // Figure out the next chunk size $chunksize = trim($line); if (!ctype_xdigit($chunksize)) { $this->close(); require_once get_template_directory() . '/includes/instagram-php-api/Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' . $chunksize . '" unable to read chunked body'); } // Convert the hexadecimal value to plain integer $chunksize = hexdec($chunksize); // Read next chunk $read_to = ftell($this->socket) + $chunksize; do { $current_pos = ftell($this->socket); if ($current_pos >= $read_to) { break; } if ($this->out_stream) { if (stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) { $this->_checkSocketReadTimeout(); break; } } else { $line = @fread($this->socket, $read_to - $current_pos); if ($line === false || strlen($line) === 0) { $this->_checkSocketReadTimeout(); break; } $chunk .= $line; } } while (!feof($this->socket)); $chunk .= @fgets($this->socket); $this->_checkSocketReadTimeout(); if (!$this->out_stream) { $response .= $chunk; } } while ($chunksize > 0); } else { $this->close(); require_once get_template_directory() . '/includes/instagram-php-api/Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' . $headers['transfer-encoding'] . '" transfer encoding'); } // We automatically decode chunked-messages when writing to a stream // this means we have to disallow the Zend_Http_Response to do it again if ($this->out_stream) { $response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $response); } // Else, if we got the content-length header, read this number of bytes } elseif (isset($headers['content-length'])) { // If we got more than one Content-Length header (see ZF-9404) use // the last value sent if (is_array($headers['content-length'])) { $contentLength = $headers['content-length'][count($headers['content-length']) - 1]; } else { $contentLength = $headers['content-length']; } $current_pos = ftell($this->socket); $chunk = ''; for ($read_to = $current_pos + $contentLength; $read_to > $current_pos; $current_pos = ftell($this->socket)) { if ($this->out_stream) { if (@stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) { $this->_checkSocketReadTimeout(); break; } } else { $chunk = @fread($this->socket, $read_to - $current_pos); if ($chunk === false || strlen($chunk) === 0) { $this->_checkSocketReadTimeout(); break; } $response .= $chunk; } // Break if the connection ended prematurely if (feof($this->socket)) { break; } } // Fallback: just read the response until EOF } else { do { if ($this->out_stream) { if (@stream_copy_to_stream($this->socket, $this->out_stream) == 0) { $this->_checkSocketReadTimeout(); break; } } else { $buff = @fread($this->socket, 8192); if ($buff === false || strlen($buff) === 0) { $this->_checkSocketReadTimeout(); break; } else { $response .= $buff; } } } while (feof($this->socket) === false); $this->close(); } // Close the connection if requested to do so by the server if (isset($headers['connection']) && $headers['connection'] == 'close') { $this->close(); } return $response; }
/** * Preform handshaking with HTTPS proxy using CONNECT method * * @param string $host * @param integer $port * @param string $http_ver * @param array $headers */ protected function connectHandshake($host, $port = 443, $http_ver = '1.1', array &$headers = array()) { $request = "CONNECT {$host}:{$port} HTTP/{$http_ver}\r\n" . "Host: " . $this->config['proxy_host'] . "\r\n"; // Add the user-agent header if (isset($this->config['useragent'])) { $request .= "User-agent: " . $this->config['useragent'] . "\r\n"; } // If the proxy-authorization header is set, send it to proxy but remove // it from headers sent to target host if (isset($headers['proxy-authorization'])) { $request .= "Proxy-authorization: " . $headers['proxy-authorization'] . "\r\n"; unset($headers['proxy-authorization']); } $request .= "\r\n"; // Send the request if (!@fwrite($this->socket, $request)) { require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception("Error writing request to proxy server"); } // Read response headers only $response = ''; $gotStatus = false; while ($line = @fgets($this->socket)) { $gotStatus = $gotStatus || strpos($line, 'HTTP') !== false; if ($gotStatus) { $response .= $line; if (!chop($line)) { break; } } } // Check that the response from the proxy is 200 if (Zend_Http_Response::extractCode($response) != 200) { require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception("Unable to connect to HTTPS proxy. Server response: " . $response); } // If all is good, switch socket to secure mode. We have to fall back // through the different modes $modes = array(STREAM_CRYPTO_METHOD_TLS_CLIENT, STREAM_CRYPTO_METHOD_SSLv3_CLIENT, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); $success = false; foreach ($modes as $mode) { $success = stream_socket_enable_crypto($this->socket, true, $mode); if ($success) { break; } } if (!$success) { require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception("Unable to connect to" . " HTTPS server through proxy: could not negotiate secure connection."); } }
/** * If file is accessible return true or false * * @return bool */ private function _isFileAccessible() { $unsecureBaseURL = $this->_config->getValue(Store::XML_PATH_UNSECURE_BASE_URL, 'default'); /** @var $http \Magento\Framework\HTTP\Adapter\Curl */ $http = $this->_curlFactory->create(); $http->setConfig(['timeout' => $this->_verificationTimeOut]); $http->write(\Zend_Http_Client::POST, $unsecureBaseURL . $this->_filePath); $responseBody = $http->read(); $responseCode = \Zend_Http_Response::extractCode($responseBody); $http->close(); return $responseCode == 200; }
public function sendMessage(Xcom_Xfabric_Model_Message $message, array $options = array()) { $url = $this->prepareUri($message->getTopic()); Mage::getSingleton('xcom_xfabric/debug')->start('Send Request to ' . $url->getUri(), $message->getTopic(), serialize($message->getHeaders()), isset($options['message_data']) ? $options['message_data'] : ''); $adapter = $this->_getAdapter(); $adapter->setConfig($this->_config); $adapter->write(Zend_Http_Client::POST, $url, '1.1', $this->_prepareHeaders($message->getHeaders()), $message->getBody()); $result = $adapter->read(); $error = ''; $httpCode = $adapter->getInfo(CURLINFO_HTTP_CODE); if ($adapter->getErrno()) { $error = $adapter->getError(); } if (!$result || $error) { Mage::getSingleton('xcom_xfabric/debug')->stop('Unable to complete the request.', $message->getTopic(), $result, 'Unable to complete the request. ' . $error); switch ($httpCode) { case '400': $errorText = 'Bad request. '; break; case '401': $errorText = 'Request is unauthorized. '; break; case '403': $errorText = 'Request is forbidden. '; break; case '404': $errorText = 'Not Found. '; break; case '413': $errorText = 'Message is too large'; break; default: $errorText = ''; break; } throw Mage::exception('Xcom_Xfabric', Mage::helper('xcom_xfabric')->__('Unable to complete the request. ') . $errorText . $error); } $zendHttpCode = Zend_Http_Response::extractCode($result); $zendHttpMessage = Zend_Http_Response::extractMessage($result); $zendHttpBody = Zend_Http_Response::extractBody($result); if ($zendHttpCode != '200') { Mage::getSingleton('xcom_xfabric/debug')->stop('Unable to complete the request.', $message->getTopic(), $result, $zendHttpMessage . ' ' . $zendHttpBody); throw Mage::exception('Xcom_Xfabric', $zendHttpMessage . ' ' . $zendHttpBody, $zendHttpCode); } if (!empty($options['synchronous']) && !$error) { $response = $this->_getResponseMessage($message->getCorrelationId()); if (!$response) { Mage::getSingleton('xcom_xfabric/debug')->stop('Response is not received', $message->getTopic(), $result, 'No Errors'); throw Mage::exception('Xcom_Xfabric', Mage::helper('xcom_xfabric')->__('Unable to complete the request. Please refer to the User Guide ' . 'to verify your settings and try again. If the error persists, contact your administrator.')); } return $response; } Mage::getSingleton('xcom_xfabric/debug')->stop('No Response is been waiting', $message->getTopic(), $result, $error); return true; }
/** * Applies the search filter and makes the actual API request * * @param array $searchFilter * @return string */ private function _apiRequest(array $searchFilter) { $this->_setSearchFilter($searchFilter); $serviceUri = $this->_apiEndpoint . ".{$this->_responseFormat}"; $client = new Zend_Http_Client($serviceUri); $client->setParameterGet(array('key' => $this->_apiKey)); foreach ($this->_searchFilter as $key => $value) { if ($key === 'url') { $key = 'q'; } $client->setParameterGet(array($key => $value)); } $response = $client->request(); if (403 === Zend_Http_Response::extractCode($response)) { $codeAsText = strtolower(Zend_Http_Response::responseCodeAsText(403)); throw new Exception("Access to Backtweets API {$codeAsText}, check used API key"); } return $response->getBody(); }
/** * Read response from server * * @return string */ public function read() { // First, read headers only $response = ''; while ($line = fgets($this->socket)) { $response .= $line; if (!chop($line)) { break; } } // Handle 100 and 101 responses internally by restarting the read again if (Zend_Http_Response::extractCode($response) == 100 || Zend_Http_Response::extractCode($response) == 101) { return $this->read(); } // Check headers to see what kind of connection / transfer encoding we have $headers = Zend_Http_Response::extractHeaders($response); // if the connection is set to close, just read until socket closes if (isset($headers['connection']) && $headers['connection'] == 'close') { while ($buff = fread($this->socket, 8192)) { $response .= $buff; } $this->close(); // Else, if we got a transfer-encoding header (chunked body) } elseif (isset($headers['transfer-encoding'])) { if ($headers['transfer-encoding'] == 'chunked') { do { $chunk = ''; $line = fgets($this->socket); $chunk .= $line; $hexchunksize = chop($line); $chunksize = hexdec(chop($line)); if (dechex($chunksize) != $hexchunksize) { fclose($this->socket); throw Zend::exception('Zend_Http_Client_Adapter_Exception', 'Invalid chunk size "' . $hexchunksize . '" unable to read chunked body'); } $left_to_read = $chunksize; while ($left_to_read > 0) { $chunk .= fread($this->socket, $left_to_read); $left_to_read = $chunksize - strlen($chunk); } $chunk .= fgets($this->socket); $response .= $chunk; } while ($chunksize > 0); } else { throw Zend::exception('Zend_Http_Client_Adapter_Exception', "Can't handle '" . $headers['transfer-encoding'] . "' transfer encoding"); } // Else, if we got the content-length header, read this number of bytes } elseif (isset($headers['content-length'])) { $left_to_read = $headers['content-length']; $chunk = ''; while ($left_to_read > 0) { $chunk = fread($this->socket, $left_to_read); $left_to_read -= strlen($chunk); $response .= $chunk; } // Fallback: just read the response (should not happen) } else { while ($buff = fread($this->socket, 8192)) { $response .= $buff; } $this->close(); } return $response; }
/** * Read response from server * * @return string */ public function read() { // First, read headers only $response = ''; $gotStatus = false; while (($line = @fgets($this->socket)) !== false) { $gotStatus = $gotStatus || strpos($line, 'HTTP') !== false; if ($gotStatus) { $response .= $line; if (rtrim($line) === '') { break; } } } $statusCode = Zend_Http_Response::extractCode($response); // Handle 100 and 101 responses internally by restarting the read again if ($statusCode == 100 || $statusCode == 101) { return $this->read(); } /** * Responses to HEAD requests and 204 or 304 responses are not expected * to have a body - stop reading here */ if ($statusCode == 304 || $statusCode == 204 || $this->method == Zend_Http_Client::HEAD) { return $response; } // Check headers to see what kind of connection / transfer encoding we have $headers = Zend_Http_Response::extractHeaders($response); // If we got a 'transfer-encoding: chunked' header if (isset($headers['transfer-encoding'])) { if ($headers['transfer-encoding'] == 'chunked') { do { $chunk = ''; $line = @fgets($this->socket); $chunk .= $line; $hexchunksize = ltrim(chop($line), '0'); $hexchunksize = strlen($hexchunksize) ? strtolower($hexchunksize) : 0; $chunksize = hexdec(chop($line)); if (dechex($chunksize) != $hexchunksize) { @fclose($this->socket); require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' . $hexchunksize . '" unable to read chunked body'); } $left_to_read = $chunksize; while ($left_to_read > 0) { $line = @fread($this->socket, $left_to_read); $chunk .= $line; $left_to_read -= strlen($line); // Break if the connection ended prematurely if (feof($this->socket)) { break; } } $chunk .= @fgets($this->socket); $response .= $chunk; } while ($chunksize > 0); } else { throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' . $headers['transfer-encoding'] . '" transfer encoding'); } // Else, if we got the content-length header, read this number of bytes } elseif (isset($headers['content-length'])) { $left_to_read = $headers['content-length']; $chunk = ''; while ($left_to_read > 0) { $chunk = @fread($this->socket, $left_to_read); $left_to_read -= strlen($chunk); $response .= $chunk; // Break if the connection ended prematurely if (feof($this->socket)) { break; } } // Fallback: just read the response until EOF } else { while (($buff = @fread($this->socket, 8192)) !== false) { $response .= $buff; if (feof($this->socket)) { break; } } $this->close(); } // Close the connection if requested to do so by the server if (isset($headers['connection']) && $headers['connection'] == 'close') { $this->close(); } return $response; }
/** * Preform handshaking with HTTPS proxy using CONNECT method * * @param string $host * @param integer $port * @param string $http_ver * @param array $headers * @return void * @throws Zend_Http_Client_Adapter_Exception */ protected function connectHandshake($host, $port = 443, $http_ver = '1.1', array &$headers = array()) { $request = "CONNECT {$host}:{$port} HTTP/{$http_ver}\r\n" . "Host: " . $this->config['proxy_host'] . "\r\n"; // Process provided headers, including important ones to CONNECT request foreach ($headers as $k => $v) { switch (strtolower(substr($v, 0, strpos($v, ':')))) { case 'proxy-authorization': // break intentionally omitted // break intentionally omitted case 'user-agent': $request .= $v . "\r\n"; break; default: break; } } $request .= "\r\n"; // @see ZF-3189 $this->connectHandshakeRequest = $request; // Send the request if (!@fwrite($this->socket, $request)) { require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Error writing request to proxy server'); } // Read response headers only $response = ''; $gotStatus = false; while ($line = @fgets($this->socket)) { $gotStatus = $gotStatus || strpos($line, 'HTTP') !== false; if ($gotStatus) { $response .= $line; if (!chop($line)) { break; } } } // Check that the response from the proxy is 200 if (Zend_Http_Response::extractCode($response) != 200) { require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Unable to connect to HTTPS proxy. Server response: ' . $response); } // If all is good, switch socket to secure mode. We have to fall back // through the different modes $modes = array(STREAM_CRYPTO_METHOD_TLS_CLIENT, STREAM_CRYPTO_METHOD_SSLv3_CLIENT, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); $success = false; foreach ($modes as $mode) { $success = stream_socket_enable_crypto($this->socket, true, $mode); if ($success) { break; } } if (!$success) { require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Unable to connect to HTTPS server through proxy: could not ' . 'negotiate secure connection.'); } }
/** * Post back to PayPal to check whether this request is a valid one * * @param Zend_Http_Client_Adapter_Interface $httpAdapter */ protected function _postBack(Zend_Http_Client_Adapter_Interface $httpAdapter) { $postbackQuery = http_build_query($this->_request) . '&cmd=_notify-validate'; $postbackUrl = $this->_config->getPaypalUrl(); $this->_debugData['postback_to'] = $postbackUrl; $httpAdapter->setConfig(array('verifypeer' => $this->_config->verifyPeer)); $httpAdapter->write(Zend_Http_Client::POST, $postbackUrl, '1.1', array('Connection: close'), $postbackQuery); try { $postbackResult = $httpAdapter->read(); } catch (Exception $e) { $this->_debugData['http_error'] = array('error' => $e->getMessage(), 'code' => $e->getCode()); throw $e; } /* * Handle errors on PayPal side. */ $responseCode = Zend_Http_Response::extractCode($postbackResult); if (empty($postbackResult) || in_array($responseCode, array('500', '502', '503'))) { if (empty($postbackResult)) { $reason = 'Empty response.'; } else { $reason = 'Response code: ' . $responseCode . '.'; } $this->_debugData['exception'] = 'PayPal IPN postback failure. ' . $reason; throw new Mage_Paypal_UnavailableException($reason); } $response = preg_split('/^\\r?$/m', $postbackResult, 2); $response = trim($response[1]); if ($response != 'VERIFIED') { $this->_debugData['postback'] = $postbackQuery; $this->_debugData['postback_result'] = $postbackResult; throw new Exception('PayPal IPN postback failure. See ' . self::DEFAULT_LOG_FILE . ' for details.'); } }
public function createApiGet($path, $timeout = self::DEFAULT_TIMEOUT) { try { $config = array('timeout' => $timeout); $http = new Varien_Http_Adapter_Curl(); $feed_url = self::YOTPO_UNSECURED_API_URL . "/" . $path; $http->setConfig($config); $http->write(Zend_Http_Client::GET, $feed_url, '1.1', array('Content-Type: application/json')); $resData = $http->read(); return array("code" => Zend_Http_Response::extractCode($resData), "body" => json_decode(Zend_Http_Response::extractBody($resData))); } catch (Exception $e) { Mage::log('error: ' . $e); } }
/** * @param Zend_Http_Response $reponse */ protected function _throwResponseErrorException(Zend_Http_Response $response) { require_once 'Zend/Service/GitHub/Exception.php'; $exceptionMessage = 'The GitHub API interaction failed. ' . '%s: %s'; $exceptionMessage = sprintf($exceptionMessage, $response->extractCode($response->asString()), $response->extractMessage($response->asString())); throw new Zend_Service_GitHub_Exception($exceptionMessage); }