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;
 }
Beispiel #2
0
 /**
  * Callback function called by cURL for saving the response headers
  *
  * @param    resource    cURL handle
  * @param    string      response header (with trailing CRLF)
  * @return   integer     number of bytes saved
  * @see      HTTP_Request2_Response::parseHeaderLine()
  */
 protected function callbackWriteHeader($ch, $string)
 {
     // we may receive a second set of headers if doing e.g. digest auth
     if ($this->eventReceivedHeaders || !$this->eventSentHeaders) {
         // don't bother with 100-Continue responses (bug #15785)
         if (!$this->eventSentHeaders || $this->response->getStatus() >= 200) {
             $this->request->setLastEvent('sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT));
         }
         $this->eventSentHeaders = true;
         // we'll need a new response object
         if ($this->eventReceivedHeaders) {
             $this->eventReceivedHeaders = false;
             $this->response = null;
         }
     }
     if (empty($this->response)) {
         $this->response = new HTTP_Request2_Response($string, false);
     } else {
         $this->response->parseHeaderLine($string);
         if ('' == trim($string)) {
             // don't bother with 100-Continue responses (bug #15785)
             if (200 <= $this->response->getStatus()) {
                 $this->request->setLastEvent('receivedHeaders', $this->response);
             }
             $this->eventReceivedHeaders = true;
         }
     }
     return strlen($string);
 }
 /**
  * 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();
 }
 /**
  * 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);
 }
 /**
  * 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;
     }
 }
Beispiel #6
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();
 }
Beispiel #7
0
 /**
  * Callback function called by cURL for saving the response headers
  *
  * @param    resource    cURL handle
  * @param    string      response header (with trailing CRLF)
  * @return   integer     number of bytes saved
  * @see      HTTP_Request2_Response::parseHeaderLine()
  */
 protected function callbackWriteHeader($ch, $string)
 {
     // we may receive a second set of headers if doing e.g. digest auth
     if ($this->eventReceivedHeaders || !$this->eventSentHeaders) {
         // don't bother with 100-Continue responses (bug #15785)
         if (!$this->eventSentHeaders || $this->response->getStatus() >= 200) {
             $this->request->setLastEvent('sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT));
         }
         $upload = curl_getinfo($ch, CURLINFO_SIZE_UPLOAD);
         // if body wasn't read by a callback, send event with total body size
         if ($upload > $this->position) {
             $this->request->setLastEvent('sentBodyPart', $upload - $this->position);
             $this->position = $upload;
         }
         if ($upload && (!$this->eventSentHeaders || $this->response->getStatus() >= 200)) {
             $this->request->setLastEvent('sentBody', $upload);
         }
         $this->eventSentHeaders = true;
         // we'll need a new response object
         if ($this->eventReceivedHeaders) {
             $this->eventReceivedHeaders = false;
             $this->response = null;
         }
     }
     if (empty($this->response)) {
         $this->response = new HTTP_Request2_Response($string, false);
     } else {
         $this->response->parseHeaderLine($string);
         if ('' == trim($string)) {
             // don't bother with 100-Continue responses (bug #15785)
             if (200 <= $this->response->getStatus()) {
                 $this->request->setLastEvent('receivedHeaders', $this->response);
             }
             if ($this->request->getConfig('follow_redirects') && $this->response->isRedirect()) {
                 $redirectUrl = new Net_URL2($this->response->getHeader('location'));
                 // for versions lower than 5.2.10, check the redirection URL protocol
                 if (!defined('CURLOPT_REDIR_PROTOCOLS') && $redirectUrl->isAbsolute() && !in_array($redirectUrl->getScheme(), array('http', 'https'))) {
                     return -1;
                 }
                 if ($jar = $this->request->getCookieJar()) {
                     $jar->addCookiesFromResponse($this->response, $this->request->getUrl());
                     if (!$redirectUrl->isAbsolute()) {
                         $redirectUrl = $this->request->getUrl()->resolve($redirectUrl);
                     }
                     if ($cookies = $jar->getMatching($redirectUrl, true)) {
                         curl_setopt($ch, CURLOPT_COOKIE, $cookies);
                     }
                 }
             }
             $this->eventReceivedHeaders = true;
         }
     }
     return strlen($string);
 }
Beispiel #8
0
 /**
  *
  * @expectedException HTTP_Request2_MessageException
  */
 public function testParseStatusLine()
 {
     $response = new HTTP_Request2_Response('HTTP/1.1 200 OK');
     $this->assertEquals('1.1', $response->getVersion());
     $this->assertEquals(200, $response->getStatus());
     $this->assertEquals('OK', $response->getReasonPhrase());
     $response2 = new HTTP_Request2_Response('HTTP/1.2 222 Nishtyak!');
     $this->assertEquals('1.2', $response2->getVersion());
     $this->assertEquals(222, $response2->getStatus());
     $this->assertEquals('Nishtyak!', $response2->getReasonPhrase());
     $response3 = new HTTP_Request2_Response('Invalid status line');
 }
Beispiel #9
0
 public function testParseStatusLine()
 {
     $response = new HTTP_Request2_Response('HTTP/1.1 200 OK');
     $this->assertEquals('1.1', $response->getVersion());
     $this->assertEquals(200, $response->getStatus());
     $this->assertEquals('OK', $response->getReasonPhrase());
     $response2 = new HTTP_Request2_Response('HTTP/1.2 222 Nishtyak!');
     $this->assertEquals('1.2', $response2->getVersion());
     $this->assertEquals(222, $response2->getStatus());
     $this->assertEquals('Nishtyak!', $response2->getReasonPhrase());
     try {
         $response3 = new HTTP_Request2_Response('Invalid status line');
     } catch (HTTP_Request2_Exception $e) {
         return;
     }
     $this->fail('Expected HTTP_Request2_Exception was not thrown');
 }
 /**
  * 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;
         }
     }
 }
Beispiel #11
0
 /**
  * Parse the response!
  *
  * @param HttpResponse $response
  * @param bool         $assocParse
  *
  * @return stdClass
  *
  * @throws \RuntimeException         When the API returns an error.
  * @throws \UnexpectedValueExpection When the body is not proper JSON.
  */
 protected function parseResponse(HttpResponse $response, $assocParse = false)
 {
     $json = $response->getBody();
     $body = @json_decode($json, $assocParse);
     if (empty($body)) {
         throw new \UnexpectedValueException('body is not proper JSON, status=' . $response->getStatus() . ', body=' . $json);
     }
     if ($response->getStatus() == 200) {
         return $body;
     }
     $message = '';
     $errors = $body->errors;
     foreach ($errors as $error) {
         if (!empty($message)) {
             $message .= ', ';
         }
         if (is_string($error)) {
             $message .= $error;
         }
     }
     throw new \RuntimeException($message);
 }
Beispiel #12
0
 /**
  * Parse the response
  *
  * This method is used to parse the response that is returned from
  * the request that was made in $this->sendRequest().
  *
  * @throws Services_Capsule_RuntimeException
  *
  * @param  HTTP_Request2_Response $response  The response from the webservice.
  * @return mixed               stdClass|bool A stdClass object of the 
  *                                           json-decode'ed body or true if
  *                                           the code is 201 (created)
  */
 protected function parseResponse(HTTP_Request2_Response $response)
 {
     $body = $response->getBody();
     $return = json_decode($body);
     if (!$return instanceof stdClass) {
         if ($response->getStatus() == 201 || $response->getStatus() == 200) {
             return true;
         }
         throw new Services_Capsule_RuntimeException('Invalid response with no valid json body');
     }
     return $return;
 }
Beispiel #13
0
 protected function validateResponseStatus(HTTP_Request2_Response $response, Am_Paysystem_Result $result)
 {
     if ($response->getStatus() != 200) {
         $result->setFailed(array("Received invalid response from payment server: " . $this->response->getStatus()));
     }
 }
Beispiel #14
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());
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Beispiel #15
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}");
 }
Beispiel #16
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()));
     }
 }
Beispiel #17
0
 /**
  * Verifies that the HTTP response has status code 200 and
  * content-type application/json; charset=utf-8
  *
  * @param HTTP_Request2_Response $res HTTP Response object
  *
  * @return void
  */
 protected function assertResponseJson200(HTTP_Request2_Response $res)
 {
     $this->assertEquals(200, $res->getStatus());
     $this->assertEquals('application/json; charset=utf-8', $res->getHeader('content-type'));
 }
Beispiel #18
0
 /**
  * Evaluate the response and return the data portion.
  *
  * OneAll returns two different stati:
  *  - request status (can be successful, but response can still contain an error)
  *  - response status
  *
  * @param \HTTP_Request2_Response $response The response object from the client.
  *
  * @return \stdClass
  * @throws \RuntimeException When the HTTP status code is not 200.
  * @throws \DomainException  When we cannot parse/evaluate the status of the response.
  * @throw  \RuntimeException When the user did not authenticate. (or something else)
  */
 protected function parseResponse(\HTTP_Request2_Response $response)
 {
     if ($response->getStatus() != 200) {
         throw new \RuntimeException("OneAll API error: " . $response->getBody());
     }
     $json = $response->getBody();
     $answer = json_decode($json);
     if (false === $answer instanceof \stdClass) {
         throw new \DomainException("Could not decode/parse response from OneAll: {$json}");
     }
     $requestStatus = $answer->response->request->status;
     if ($requestStatus->flag == 'error') {
         throw new \RuntimeException("The request failed: {$requestStatus->info}", $requestStatus->code);
     }
     // when new accounts are linked - this is set
     if (isset($answer->response->result->status)) {
         $status = $answer->response->result->status;
         if ($status->flag == 'error') {
             throw new \RuntimeException($status->info, $status->code);
         }
     }
     return $answer->response->result->data;
 }
Beispiel #19
0
 /**
  * Parses the response, returning stdClass of the reponse body
  * 
  * @param HTTP_Request2_Response $response The HTTP_Request2 response
  * 
  * @ignore
  * @throws Services_Digg2_Exception on a non-2XX response
  * @return stdClass (decoded json)
  */
 protected function parseResponse(HTTP_Request2_Response $response)
 {
     $this->lastResponse = $response;
     $body = json_decode($response->getBody());
     if (!is_object($body)) {
         throw new Services_Digg2_Exception('Unabled to decode result: ' . $response->getBody());
     }
     $status = $response->getStatus();
     if (strncmp($status, '2', 1) !== 0) {
         throw new Services_Digg2_Exception($body->error->message, $body->error->code, $status);
     }
     return $body;
 }
Beispiel #20
0
 /**
  * Checks whether another request should be performed with proxy digest auth
  *
  * Several conditions should be satisfied for it to return true:
  *   - response status should be 407
  *   - proxy auth credentials should be set in the request object
  *   - response should contain Proxy-Authenticate header with digest challenge
  *   - there is either no challenge stored for this proxy or new challenge
  *     contains stale=true parameter (in other case we probably just failed
  *     due to invalid username / password)
  *
  * The method stores challenge values in $challenges static property
  *
  * @param    HTTP_Request2_Response  response to check
  * @return   boolean whether another request should be performed
  * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters
  */
 protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)
 {
     if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
         return false;
     }
     if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
         return false;
     }
     $key = 'proxy://' . $this->request->getConfig('proxy_host') . ':' . $this->request->getConfig('proxy_port');
     if (!empty(self::$challenges[$key]) && (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))) {
         $ret = false;
     } else {
         $ret = true;
     }
     self::$challenges[$key] = $challenge;
     return $ret;
 }
Beispiel #21
0
 /**
  * Reads the remote server's response
  *
  * @return   HTTP_Request2_Response
  * @throws   HTTP_Request2_Exception
  */
 protected function readResponse()
 {
     $bufferSize = $this->request->getConfig('buffer_size');
     // http://tools.ietf.org/html/rfc2616#section-8.2.3
     // ...the client SHOULD NOT wait for an indefinite period before sending the request body
     $timeout = $this->expect100Continue ? 1 : null;
     do {
         try {
             $response = new HTTP_Request2_Response($this->socket->readLine($bufferSize, $timeout), true, $this->request->getUrl());
             do {
                 $headerLine = $this->socket->readLine($bufferSize);
                 $response->parseHeaderLine($headerLine);
             } while ('' != $headerLine);
         } catch (HTTP_Request2_MessageException $e) {
             if (HTTP_Request2_Exception::TIMEOUT === $e->getCode() && $this->expect100Continue) {
                 return null;
             }
             throw $e;
         }
         if ($this->expect100Continue && 100 == $response->getStatus()) {
             return $response;
         }
     } 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 (!$this->socket->eof() && (is_null($toRead) || 0 < $toRead)) {
             if ($chunked) {
                 $data = $this->readChunked($bufferSize);
             } elseif (is_null($toRead)) {
                 $data = $this->socket->read($bufferSize);
             } else {
                 $data = $this->socket->read(min($toRead, $bufferSize));
                 $toRead -= strlen($data);
             }
             if ('' == $data && (!$this->chunkLength || $this->socket->eof())) {
                 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;
 }