/**
  * Setup a `\HTTP_Request2_Response` with the given type!
  *
  * @param string $func Type of all: getConnection, getUsers
  * @param string $type 'success' or 'failure'
  *
  * @return \HTTP_Request2_Response
  */
 protected function getResponse($func, $type = 'success')
 {
     $response = new \HTTP_Request2_Response('HTTP/1.1 200');
     $json = file_get_contents(dirname(dirname(dirname(__DIR__))) . '/fixtures/' . $func . '/' . $type . '.json');
     $response->appendBody($json);
     return $response;
 }
Exemple #2
0
/**
 * Returns an instance of Services_Twitter.
 *
 * @param string $ep      The endpoint to call (eg. )
 * @param bool   $auth    Whether to authenticate or not
 * @param array  $options An optional options array to pass to the 
 *                        Services_Twitter constructor
 *
 * @return Services_Twitter The twitter instance.
 */
function Services_Twitter_factory($ep, $auth = true, $options = array())
{
    //$options['raw_format'] = true;
    global $config;
    if ($auth) {
        $twitter = new Services_Twitter($config['user'], $config['pass'], $options);
    } else {
        $twitter = new Services_Twitter(null, null, $options);
    }
    if (!$config['live_test']) {
        if ($ep == 'exception1') {
            $resp = new HTTP_Request2_Response('HTTP/1.1 401 Unauthorized', false);
            $resp->appendBody('{"request":"\\/statuses\\/friends_timeline.json", ' . '"error":"Could not authenticate you."}');
        } else {
            if ($ep == 'exception2') {
                $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
            } else {
                $resp = new HTTP_Request2_Response('HTTP/1.1 200 Success', false);
                $file = dirname(__FILE__) . '/data/' . $ep . '.dat';
                $resp->appendBody(file_get_contents($file));
            }
        }
        $mock = new HTTP_Request2_Adapter_Mock();
        $mock->addResponse($resp);
        $request = $twitter->getRequest()->setAdapter($mock);
    }
    return $twitter;
}
 public function testGetDataFromBody()
 {
     $response = new HTTP_Request2_Response('HTTP/1.1 200 OK');
     $response->appendBody('oauth_token=foo&oauth_token_secret=bar');
     $res = new HTTP_OAuth_Consumer_Response($response);
     $this->assertEquals(array('oauth_token' => 'foo', 'oauth_token_secret' => 'bar'), $res->getDataFromBody());
 }
/**
 * Return the Services_GeoNames with either a mock adapter or the real adapter
 * depending whether the SERVICES_GEONAMES_LIVETEST environment variable is set
 * or not.
 *
 * @param string $testname The test name (without extension)
 * @param string $user     Username (optional)
 * @param string $token    Auth token (optional)
 *
 * @return Services_GeoNames
 */
function Services_GeoNames_factory($testname, $user = null, $token = null)
{
    $geo = new Services_GeoNames($user, $token);
    if (!getenv('SERVICES_GEONAMES_LIVETEST')) {
        // test with a mock adapter
        $mock = new HTTP_Request2_Adapter_Mock();
        if ($testname == 'test_other_04') {
            $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
        } else {
            if ($testname == 'test_other_07') {
                $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
                $mock->addResponse($resp);
                $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
                $mock->addResponse($resp);
                $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
            } else {
                $resp = new HTTP_Request2_Response('HTTP/1.1 200 Success', false);
                $file = dirname(__FILE__) . '/data/' . $testname . '.dat';
                $resp->appendBody(file_get_contents($file));
            }
        }
        $mock->addResponse($resp);
        $geo->getRequest()->setAdapter($mock);
    }
    return $geo;
}
 /**
  * Tests the returned result of {@link Solr::query()}.
  */
 function testQuery()
 {
     $response = new HTTP_Request2_Response('HTTP/1.0 200 OK');
     $solrResponse = '{"responseHeader":{"status":0,"QTime":0,"params":{"q":"php","qt":"standard","wt":"json"}},"response":{"numFound":1,"start":0,"docs":[{"id":42,"title":"PHP 5"}]}}';
     $response->appendBody($solrResponse);
     $this->httpClientMock->expects($this->once())->method('sendRequest')->with($this->equalTo('/select?qt=standard&wt=json&q=php'))->will($this->returnValue($response));
     $this->assertEquals(SolrSearchResult::parseResponse($solrResponse), $this->solr->query('php'));
 }
 /**
  * Indicates if there should be a retry or not.
  * 
  * @param integer                 $retryCount The retry count.
  * @param \HTTP_Request2_Response $response   The HTTP response object.
  * 
  * @return boolean
  */
 public function shouldRetry($retryCount, $response)
 {
     if ($retryCount >= $this->_maximumAttempts || array_search($response->getStatus(), $this->_retryableStatusCodes) || is_null($response)) {
         return false;
     } else {
         return true;
     }
 }
 public function validateResponseStatus(Am_Paysystem_Result $result)
 {
     if ($this->response->getStatus() != 200) {
         $result->setErrorMessages(array("Received invalid response from payment server: " . $this->response->getStatus()));
         return false;
     }
     return true;
 }
Exemple #8
0
 protected function extractLinks(\HTTP_Request2_Response $res)
 {
     $mimetype = explode(';', $res->getHeader('content-type'))[0];
     if (!isset(static::$supportedTypes[$mimetype])) {
         Log::info("MIME type not supported for crawling: {$mimetype}");
         return array();
     }
     $class = static::$supportedTypes[$mimetype];
     $extractor = new $class();
     return $extractor->extract($res);
 }
 public function setUp()
 {
     parent::setUp();
     Yii::configure(Yii::$app, ['components' => ['user' => ['class' => 'yii\\web\\User', 'identityClass' => 'common\\models\\User'], 'p24' => ['class' => \merigold\przelewy24\src\Przelewy24Component::className(), 'merchant_id' => $this->merchant_id, 'pos_id' => $this->merchant_id, 'CRC' => $this->CRC]]]);
     Yii::$container->set('HTTP_Request2', function () {
         $response = new HTTP_Request2_Response("HTTP/1.1 200 OK", true);
         $response->appendBody($this->succesresponse);
         $mockAdapter = new HTTP_Request2_Adapter_Mock();
         $mockAdapter->addResponse($response);
         $stub = new HTTP_Request2(\merigold\przelewy24\src\Przelewy24Component::TEST_URL, HTTP_Request2::METHOD_POST);
         $stub->setAdapter($mockAdapter);
         return $stub;
     });
 }
 /**
  * Send request to OSM server and return the response.
  *
  * @param string $url       URL
  * @param string $method    GET (default)/POST/PUT
  * @param string $user      user (optional for read-only actions)
  * @param string $password  password (optional for read-only actions)
  * @param string $body      body (optional)
  * @param array  $post_data (optional)
  * @param array  $headers   (optional)
  *
  * @access public
  * @return HTTP_Request2_Response
  * @todo   Consider just returning the content?
  * @throws Services_OpenStreetMap_Exception If something unexpected has
  *                                          happened while conversing with
  *                                          the server.
  */
 public function getResponse($url, $method = HTTP_Request2::METHOD_GET, $user = null, $password = null, $body = null, array $post_data = null, array $headers = null)
 {
     $arguments = array($url, $method, $user, $password, $body, implode(":", (array) $post_data), implode(":", (array) $headers));
     $id = md5(implode(":", $arguments));
     $data = $this->cache->get($id);
     if ($data) {
         $response = new HTTP_Request2_Response();
         $response->setStatus(200);
         $response->setBody($data);
         return $response;
     }
     $response = parent::getResponse($url, $method, $user, $password, $body, $post_data, $headers);
     $this->cache->save($id, $response->getBody());
     return $response;
 }
 /**
  * Constructor.
  *
  * @param string|HTTP_Request $messageOrResponse a string (UTF-8) describing
  *                                               the error, or the
  *                                               HTTP_Request2_Response that
  *                                               caused the exception.
  * @param int                 $code              the error code.
  */
 public function __construct($messageOrResponse, $code = 0)
 {
     $message = false;
     if ($messageOrResponse instanceof HTTP_Request2_Response) {
         $this->response = $messageOrResponse;
         $contentType = $this->response->getHeader('content-type');
         if ($contentType == 'application/xml' && $this->response->getBody()) {
             $prevUseInternalErrors = libxml_use_internal_errors(true);
             $doc = new DOMDocument();
             $ok = $doc->loadXML($this->response->getBody());
             libxml_use_internal_errors($prevUseInternalErrors);
             if ($ok) {
                 $xPath = new DOMXPath($doc);
                 $this->_amazonErrorCode = $xPath->evaluate('string(/Error/Code)');
                 $message = $xPath->evaluate('string(/Error/Message)');
             }
         }
         if (!$message) {
             $message = 'Bad response from server.';
         }
         if (!$code) {
             $code = $this->response->getStatus();
         }
     } else {
         $message = (string) $messageOrResponse;
     }
     parent::__construct($message, $code);
 }
 /**
  * Processes the reuqest through HTTP pipeline with passed $filters, 
  * sends HTTP request to the wire and process the response in the HTTP pipeline.
  * 
  * @param array $filters HTTP filters which will be applied to the request before
  *                       send and then applied to the response.
  * @param IUrl  $url     Request url.
  * 
  * @throws WindowsAzure\Common\ServiceException
  * 
  * @return string The response body
  */
 public function send($filters, $url = null)
 {
     if (isset($url)) {
         $this->setUrl($url);
         $this->_request->setUrl($this->_requestUrl->getUrl());
     }
     $contentLength = Resources::EMPTY_STRING;
     if (strtoupper($this->getMethod()) != Resources::HTTP_GET && strtoupper($this->getMethod()) != Resources::HTTP_DELETE && strtoupper($this->getMethod()) != Resources::HTTP_HEAD) {
         $contentLength = 0;
         if (!is_null($this->getBody())) {
             $contentLength = strlen($this->getBody());
         }
         $this->_request->setHeader(Resources::CONTENT_LENGTH, $contentLength);
     }
     foreach ($filters as $filter) {
         $this->_request = $filter->handleRequest($this)->_request;
     }
     $this->_response = $this->_request->send();
     $start = count($filters) - 1;
     for ($index = $start; $index >= 0; --$index) {
         $this->_response = $filters[$index]->handleResponse($this, $this->_response);
     }
     self::throwIfError($this->_response->getStatus(), $this->_response->getReasonPhrase(), $this->_response->getBody(), $this->_expectedStatusCodes);
     return $this->_response->getBody();
 }
 /**
  * Returns the next response from the queue built by addResponse()
  *
  * If the queue is empty it will return default empty response with status 400,
  * if an Exception object was added to the queue it will be thrown.
  *
  * @param    HTTP_Request2
  * @return   HTTP_Request2_Response
  * @throws   Exception
  */
 public function sendRequest(HTTP_Request2 $request)
 {
     $environment = base64_encode(serialize($this->buildEnvironment($request)));
     $file = $request->getConfig('index_file');
     $dir = PHPCLIHTTP_FILEPATH_BASE;
     $command = "{$dir}/sendrequest.php {$file} {$environment}";
     exec($command, $output, $return_var);
     if ($return_var !== 0) {
         die("Something went wrong with the request.");
     }
     $output_as_string = trim(implode("\n", $output));
     $output_base64_decoded = base64_decode($output_as_string);
     $output_unserialized = unserialize($output_base64_decoded);
     $response = new HTTP_Request2_Response("HTTP/1.1 200 OK\r\n");
     $response->appendBody($output_unserialized['html']);
     return $response;
 }
 public function testShouldFailGracefullyOnFailedTransaction()
 {
     $response = new HTTP_Request2_Response('HTTP/1.1 200 OK');
     $response->appendBody(file_get_contents(dirname(__FILE__) . '/data/AuthorizeNet/error.html'));
     $mock = new HTTP_Request2_Adapter_Mock();
     $mock->addResponse($response);
     $request = new HTTP_Request2();
     $request->setAdapter($mock);
     $object = Payment_Process2::factory('AuthorizeNet');
     $object->login = '******';
     $object->password = '******';
     $object->amount = 1;
     $object->action = Payment_Process2::ACTION_NORMAL;
     $object->setRequest($request);
     $object->setPayment($this->aValidPayment());
     $result = $object->process();
     $this->assertTrue($result instanceof PEAR_Error);
 }
Exemple #15
0
 /**
  * Sends the request via HTTP_Request2
  * 
  * @return string The HTTP response body
  */
 protected function sendRequest()
 {
     $this->getHTTPRequest2();
     $this->response = $this->request->send();
     if ($this->response->getStatus() !== 200) {
         throw new OpenID_Discover_Exception('Unable to connect to OpenID Provider.');
     }
     return $this->response->getBody();
 }
Exemple #16
0
 /**
  * Callback function called by cURL for saving the response body
  *
  * @param    resource    cURL handle (not used)
  * @param    string      part of the response body
  * @return   integer     number of bytes saved
  * @see      HTTP_Request2_Response::appendBody()
  */
 protected function callbackWriteBody($ch, $string)
 {
     // cURL calls WRITEFUNCTION callback without calling HEADERFUNCTION if
     // response doesn't start with proper HTTP status line (see bug #15716)
     if (empty($this->response)) {
         throw new HTTP_Request2_MessageException("Malformed response: {$string}", HTTP_Request2_Exception::MALFORMED_RESPONSE);
     }
     if ($this->request->getConfig('store_body')) {
         $this->response->appendBody($string);
     }
     $this->request->setLastEvent('receivedBodyPart', $string);
     return strlen($string);
 }
Exemple #17
0
 public function extract(\HTTP_Request2_Response $res)
 {
     $url = $res->getEffectiveUrl();
     $base = new \Net_URL2($url);
     $sx = simplexml_load_string($res->getBody());
     $linkInfos = array();
     $alreadySeen = array();
     foreach ($sx->entry as $entry) {
         $linkTitle = (string) $entry->title;
         foreach ($entry->link as $xlink) {
             $linkUrl = (string) $base->resolve((string) $xlink['href']);
             if (isset($alreadySeen[$linkUrl])) {
                 continue;
             }
             if ($xlink['rel'] == 'alternate') {
                 $linkInfos[] = new LinkInfo($linkUrl, $linkTitle, $url);
             }
             $alreadySeen[$linkUrl] = true;
         }
     }
     return $linkInfos;
 }
 /**
  * Constructor
  *
  * @param string                                         $content Http response
  * as string
  *
  * @param WindowsAzure\Common\Internal\Http\BatchRequest $request Source batch
  * request object
  */
 public function __construct($content, $request = null)
 {
     $params['include_bodies'] = true;
     $params['input'] = $content;
     $mimeDecoder = new \Mail_mimeDecode($content);
     $structure = $mimeDecoder->decode($params);
     $parts = $structure->parts;
     $this->_contexts = array();
     $requestContexts = null;
     if ($request != null) {
         Validate::isA($request, 'WindowsAzure\\Common\\Internal\\Http\\BatchRequest', 'request');
         $requestContexts = $request->getContexts();
     }
     $i = 0;
     foreach ($parts as $part) {
         if (!empty($part->body)) {
             $headerEndPos = strpos($part->body, "\r\n\r\n");
             $header = substr($part->body, 0, $headerEndPos);
             $body = substr($part->body, $headerEndPos + 4);
             $headerStrings = explode("\r\n", $header);
             $response = new \HTTP_Request2_Response(array_shift($headerStrings));
             foreach ($headerStrings as $headerString) {
                 $response->parseHeaderLine($headerString);
             }
             $response->appendBody($body);
             $this->_contexts[] = $response;
             if (is_array($requestContexts)) {
                 $expectedCodes = $requestContexts[$i]->getStatusCodes();
                 $statusCode = $response->getStatus();
                 if (!in_array($statusCode, $expectedCodes)) {
                     $reason = $response->getReasonPhrase();
                     throw new ServiceException($statusCode, $reason, $body);
                 }
             }
             $i++;
         }
     }
 }
Exemple #19
0
 public function validateResponseStatus(Am_Paysystem_Result $result)
 {
     if ($this->response->getStatus() != 200) {
         $result->setFailed(array("Received invalid response from payment server: " . $this->response->getStatus()));
     }
 }
Exemple #20
0
 /**
  * Adds cookies set in HTTP response to the jar
  *
  * @param HTTP_Request2_Response $response HTTP response message
  * @param Net_URL2               $setter   original request URL, needed for
  *                               setting default domain/path
  */
 public function addCookiesFromResponse(HTTP_Request2_Response $response, Net_URL2 $setter)
 {
     foreach ($response->getCookies() as $cookie) {
         $this->store($cookie, $setter);
     }
 }
Exemple #21
0
 /**
  * Based on an XRI, will request the XRD document located at the proxy
  * prefixed URI and parse in search of the XRI Canonical Id. This is
  * a flexible requirement. OpenID 2.0 requires the use of the Canonical
  * ID instead of the raw i-name. 2idi.com, on the other hand, does not.
  *
  * @param string $xri The XRI
  *
  * @todo Imcomplete; requires interface from Yadis main class
  * @return string
  * @throws Services_Yadis_Exception
  */
 public function toCanonicalId($xri = null)
 {
     if (!isset($xri) && !isset($this->uri)) {
         throw new Services_Yadis_Exception('No XRI passed as parameter as required unless called after ' . 'Services_Yadis_Xri:toUri');
     } elseif (isset($xri)) {
         $uri = $this->toUri($xri);
     } else {
         $uri = $this->uri;
     }
     $this->httpResponse = $this->get($uri, null, $this->getHttpRequestOptions());
     if (stripos($this->httpResponse->getHeader('Content-Type'), 'application/xrds+xml') === false) {
         throw new Services_Yadis_Exception('The response header indicates the response body is not ' . 'an XRDS document');
     }
     $xrds = new SimpleXMLElement($this->httpResponse->getBody());
     $this->namespace->registerXpathNamespaces($xrds);
     $id = $xrds->xpath('//xrd:CanonicalID[last()]');
     $this->canonicalID = (string) array_shift($id);
     if (!$this->canonicalID) {
         throw new Services_Yadis_Exception('Unable to determine canonicalID');
     }
     return $xrds;
 }
Exemple #22
0
 protected function readResponseFromFile($filename)
 {
     $fp = fopen(dirname(dirname(__FILE__)) . '/_files/' . $filename, 'rb');
     $response = new HTTP_Request2_Response(fgets($fp));
     do {
         $headerLine = fgets($fp);
         $response->parseHeaderLine($headerLine);
     } while ('' != trim($headerLine));
     while (!feof($fp)) {
         $response->appendBody(fread($fp, 1024));
     }
     return $response;
 }
Exemple #23
0
 /**
  * evaluate response object
  *
  * @param \HTTP_Request2_Response $resp
  *
  * @throws BadRequestError
  * @throws UnauthorizedError
  * @throws ForbiddenError
  * @throws ConflictDuplicateError
  * @throws GoneError
  * @throws InternalServerError
  * @throws NotImplementedError
  * @throws ThrottledError
  * @throws CCException
  *
  * @return string json encoded servers response
  */
 private function _return($resp)
 {
     #
     # And handle the possible responses according to their HTTP STATUS
     # CODES.
     #
     # 200 OK, 201 CREATED and 204 DELETED result in returning the actual
     # response.
     #
     # All non success STATUS CODES raise an exception containing
     # the API error message.
     #
     if (in_array($resp->getStatus(), array(200, 201, 204)) !== false) {
         return $resp->getBody();
     } else {
         if ($resp->getStatus() == 400) {
             throw new BadRequestError($resp->getBody(), $resp->getStatus());
         } else {
             if ($resp->getStatus() == 401) {
                 throw new UnauthorizedError($resp->getBody(), $resp->getStatus());
             } else {
                 if ($resp->getStatus() == 403) {
                     throw new ForbiddenError($resp->getBody(), $resp->getStatus());
                 } else {
                     if ($resp->getStatus() == 409) {
                         throw new ConflictDuplicateError($resp->getBody(), $resp->getStatus());
                     } else {
                         if ($resp->getStatus() == 410) {
                             throw new GoneError($resp->getBody(), $resp->getStatus());
                         } else {
                             if ($resp->getStatus() == 500) {
                                 throw new InternalServerError($resp->getBody(), $resp->getStatus());
                             } else {
                                 if ($resp->getStatus() == 501) {
                                     throw new NotImplementedError($resp->getBody(), $resp->getStatus());
                                 } else {
                                     if ($resp->getStatus() == 503) {
                                         throw new ThrottledError($resp->getBody(), $resp->getStatus());
                                     } else {
                                         throw new CCException($resp->getBody(), $resp->getStatus());
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Exemple #24
0
 /**
  * Returns a DOMXPath object for the XML document in the body of the
  * specified HTTP response. This method is for internal use only.
  *
  * @param HTTP_Request2_Response $response the HTTP response.
  *
  * @return DOMXPath
  * @throws Services_Amazon_S3_ServerErrorException
  */
 public static function getDOMXPath(HTTP_Request2_Response $response)
 {
     if ($response->getHeader('content-type') != 'application/xml') {
         throw new Services_Amazon_S3_ServerErrorException('Response was not of type application/xml', $response);
     }
     $prevUseInternalErrors = libxml_use_internal_errors(true);
     $doc = new DOMDocument();
     $ok = $doc->loadXML($response->getBody());
     libxml_use_internal_errors($prevUseInternalErrors);
     if (!$ok) {
         throw new Services_Amazon_S3_ServerErrorException($response);
     }
     $xPath = new DOMXPath($doc);
     $xPath->registerNamespace('s3', self::NS_S3);
     $xPath->registerNamespace('xsi', self::NS_XSI);
     return $xPath;
 }
Exemple #25
0
 protected function parseResponse(HTTP_Request2_Response $response)
 {
     $this->params = Am_Controller::decodeJson($response->getBody());
 }
Exemple #26
0
 /**
  * Adds cookies set in HTTP response to the jar
  *
  * @param HTTP_Request2_Response $response HTTP response message
  * @param Net_URL2               $setter   original request URL, needed for
  *                               setting default domain/path. If not given,
  *                               effective URL from response will be used.
  *
  * @return bool whether all cookies were successfully stored
  * @throws HTTP_Request2_LogicException
  */
 public function addCookiesFromResponse(HTTP_Request2_Response $response, Net_URL2 $setter = null)
 {
     if (null === $setter) {
         if (!($effectiveUrl = $response->getEffectiveUrl())) {
             throw new HTTP_Request2_LogicException('Response URL required for adding cookies from response', HTTP_Request2_Exception::MISSING_VALUE);
         }
         $setter = new Net_URL2($effectiveUrl);
     }
     $success = true;
     foreach ($response->getCookies() as $cookie) {
         $success = $this->store($cookie, $setter) && $success;
     }
     return $success;
 }
Exemple #27
0
 /**
  * Creates a new HTTP_Request2_Response object from a file
  *
  * @param    resource    file pointer returned by fopen()
  * @return   HTTP_Request2_Response
  * @throws   HTTP_Request2_Exception
  */
 public static function createResponseFromFile($fp)
 {
     $response = new HTTP_Request2_Response(fgets($fp));
     do {
         $headerLine = fgets($fp);
         $response->parseHeaderLine($headerLine);
     } while ('' != trim($headerLine));
     while (!feof($fp)) {
         $response->appendBody(fread($fp, 8192));
     }
     return $response;
 }
Exemple #28
0
 /**
  * Reads the remote server's response
  *
  * @return   HTTP_Request2_Response
  * @throws   HTTP_Request2_Exception
  */
 protected function readResponse()
 {
     $bufferSize = $this->request->getConfig('buffer_size');
     do {
         $response = new HTTP_Request2_Response($this->readLine($bufferSize), true);
         do {
             $headerLine = $this->readLine($bufferSize);
             $response->parseHeaderLine($headerLine);
         } while ('' != $headerLine);
     } while (in_array($response->getStatus(), array(100, 101)));
     $this->request->setLastEvent('receivedHeaders', $response);
     // No body possible in such responses
     if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod() || HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() && 200 <= $response->getStatus() && 300 > $response->getStatus() || in_array($response->getStatus(), array(204, 304))) {
         return $response;
     }
     $chunked = 'chunked' == $response->getHeader('transfer-encoding');
     $length = $response->getHeader('content-length');
     $hasBody = false;
     if ($chunked || null === $length || 0 < intval($length)) {
         // RFC 2616, section 4.4:
         // 3. ... If a message is received with both a
         // Transfer-Encoding header field and a Content-Length header field,
         // the latter MUST be ignored.
         $toRead = $chunked || null === $length ? null : $length;
         $this->chunkLength = 0;
         while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {
             if ($chunked) {
                 $data = $this->readChunked($bufferSize);
             } elseif (is_null($toRead)) {
                 $data = $this->fread($bufferSize);
             } else {
                 $data = $this->fread(min($toRead, $bufferSize));
                 $toRead -= strlen($data);
             }
             if ('' == $data && (!$this->chunkLength || feof($this->socket))) {
                 break;
             }
             $hasBody = true;
             if ($this->request->getConfig('store_body')) {
                 $response->appendBody($data);
             }
             if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {
                 $this->request->setLastEvent('receivedEncodedBodyPart', $data);
             } else {
                 $this->request->setLastEvent('receivedBodyPart', $data);
             }
         }
     }
     if ($hasBody) {
         $this->request->setLastEvent('receivedBody', $response);
     }
     return $response;
 }
Exemple #29
0
 /**
  * Compares between two responses by Content-ID header.
  * 
  * @param \HTTP_Request2_Response $r1 The first response object.
  * @param \HTTP_Request2_Response $r2 The second response object.
  * 
  * @return boolean
  */
 private static function _compareUsingContentId($r1, $r2)
 {
     $h1 = array_change_key_case($r1->getHeader());
     $h2 = array_change_key_case($r2->getHeader());
     $c1 = Utilities::tryGetValue($h1, Resources::CONTENT_ID, 0);
     $c2 = Utilities::tryGetValue($h2, Resources::CONTENT_ID, 0);
     return intval($c1) >= intval($c2);
 }
Exemple #30
0
 /**
  * Saves the response body to a specified directory
  *
  * @param  HTTP_Request2_Response $response
  * @return void
  * @throws BuildException
  */
 protected function processResponse(HTTP_Request2_Response $response)
 {
     if ($response->getStatus() != 200) {
         throw new BuildException("Request unsuccessful. Response from server: " . $response->getStatus() . " " . $response->getReasonPhrase());
     }
     $content = $response->getBody();
     $disposition = $response->getHeader('content-disposition');
     if ($this->filename) {
         $filename = $this->filename;
     } elseif ($disposition && 0 == strpos($disposition, 'attachment') && preg_match('/filename="([^"]+)"/', $disposition, $m)) {
         $filename = basename($m[1]);
     } else {
         $filename = basename(parse_url($this->url, PHP_URL_PATH));
     }
     if (!is_writable($this->dir)) {
         throw new BuildException("Cannot write to directory: " . $this->dir);
     }
     $filename = $this->dir . "/" . $filename;
     file_put_contents($filename, $content);
     $this->log("Contents from " . $this->url . " saved to {$filename}");
 }