/**
  * 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();
 }
Example #3
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();
 }
Example #4
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;
 }
Example #5
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;
 }
Example #6
0
 protected function parseResponse(HTTP_Request2_Response $response)
 {
     $this->params = Am_Controller::decodeJson($response->getBody());
 }
Example #7
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());
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #8
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}");
 }
Example #9
0
 /**
  * Assuming this user is hosting a third party sourced identity under an
  * alias personal URL, we'll need to check if the website's HTML body
  * has a http-equiv meta element with a content attribute pointing to where
  * we can fetch the XRD document.
  *
  * @param HTTP_Request2_Response $response Instance of HTTP_Request2_Response
  *
  * @return boolean
  * @throws Services_Yadis_Exception
  */
 protected function isMetaHttpEquiv(HTTP_Request2_Response $response)
 {
     $location = null;
     if (!in_array($response->getHeader('Content-Type'), $this->validHtmlContentTypes)) {
         return false;
     }
     /**
      * Find a match for a relevant <meta> element, then iterate through the
      * results to see if a valid http-equiv value and matching content URI
      * exist.
      */
     $html = new DOMDocument();
     $html->loadHTML($response->getBody());
     $head = $html->getElementsByTagName('head');
     if ($head->length > 0) {
         $metas = $head->item(0)->getElementsByTagName('meta');
         if ($metas->length > 0) {
             foreach ($metas as $meta) {
                 $equiv = strtolower($meta->getAttribute('http-equiv'));
                 if ($equiv == 'x-xrds-location' || $equiv == 'x-yadis-location') {
                     $location = $meta->getAttribute('content');
                 }
             }
         }
     }
     if (is_null($location)) {
         return false;
     } elseif (!self::validateURI($location)) {
         throw new Services_Yadis_Exception('The URI parsed from the HTML Alias document appears to be invalid, ' . 'or could not be found: ' . htmlentities($location, ENT_QUOTES, 'utf-8'));
     }
     /**
      * Should now contain the content value of the http-equiv type pointing
      * to an XRDS resource for the user's Identity Provider, as found by
      * passing the meta regex across the response body.
      */
     $this->metaHttpEquivUrl = $location;
     return true;
 }
Example #10
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;
 }
Example #11
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;
 }
Example #12
0
 /**
  * Checks whether response body matches the given regexp
  *
  * @param  HTTP_Request2_Response $response
  * @return void
  * @throws BuildException
  */
 protected function processResponse(HTTP_Request2_Response $response)
 {
     if ($this->responseRegex !== '') {
         $matches = array();
         preg_match($this->responseRegex, $response->getBody(), $matches);
         if (count($matches) === 0) {
             throw new BuildException('The received response body did not match the given regular expression');
         } else {
             $this->log('The response body matched the provided regex.');
         }
     }
 }
Example #13
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;
 }
Example #14
0
 public function extract(\HTTP_Request2_Response $res)
 {
     $url = Helper::removeAnchor($res->getEffectiveUrl());
     $linkInfos = array();
     //FIXME: mime type switch for cdata
     $doc = new \DOMDocument();
     //@ to hide parse warning messages in invalid html
     @$doc->loadHTML($res->getBody());
     //FIXME: extract base url from html
     $base = new \Net_URL2($url);
     $dx = new \DOMXPath($doc);
     $xbase = $dx->evaluate('/html/head/base[@href]')->item(0);
     if ($xbase) {
         $base = $base->resolve($xbase->attributes->getNamedItem('href')->textContent);
     }
     $meta = $dx->evaluate('/html/head/meta[@name="robots" and @content]')->item(0);
     if ($meta) {
         $robots = $meta->attributes->getNamedItem('content')->textContent;
         foreach (explode(',', $robots) as $value) {
             if (trim($value) == 'nofollow') {
                 //we shall not follow the links
                 return array();
             }
         }
     }
     $links = $dx->evaluate('//a');
     //FIXME: link rel, img, video
     $alreadySeen = array($url => true);
     foreach ($links as $link) {
         $linkTitle = Helper::sanitizeTitle($link->textContent);
         $href = '';
         foreach ($link->attributes as $attribute) {
             if ($attribute->name == 'href') {
                 $href = $attribute->textContent;
             } else {
                 if ($attribute->name == 'rel') {
                     foreach (explode(',', $attribute->textContent) as $value) {
                         if (trim($value) == 'nofollow') {
                             //we shall not follow this link
                             continue 3;
                         }
                     }
                 }
             }
         }
         if ($href == '' || $href[0] == '#') {
             //link on this page
             continue;
         }
         $linkUrlObj = $base->resolve($href);
         $linkUrlObj->setFragment(false);
         $linkUrl = (string) $linkUrlObj;
         if (isset($alreadySeen[$linkUrl])) {
             continue;
         }
         switch ($linkUrlObj->getScheme()) {
             case 'http':
             case 'https':
                 break;
             default:
                 continue 2;
         }
         //FIXME: check target type
         $linkInfos[] = new LinkInfo($linkUrl, $linkTitle, $url);
         $alreadySeen[$linkUrl] = true;
     }
     return $linkInfos;
 }
Example #15
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);
 }
Example #16
0
 /**
  * Parse the response (from {@link self::makeRequest()}.
  *
  * @param HTTP_Request2_Response $resp The response returned from the API.
  *
  * @return mixed
  * @throws RuntimeException In case the API returned an error.
  */
 protected function parseResponse(HTTP_Request2_Response $resp)
 {
     $body = $resp->getBody();
     $headers = $resp->getHeader();
     if (isset($headers['content-type'])) {
         if ($headers['content-type'] == 'text/calendar; charset=utf-8') {
             return $body;
         }
     }
     switch ($body) {
         case 'Access Denied':
             throw new RuntimeException("API response: {$body}");
         case 'Item Deleted Successfully':
         case 'Meeting Deleted Successfully':
         case 'Note Deleted Successfully':
             return $body;
         default:
             $resp = json_decode($body);
             if (isset($resp->status)) {
                 switch ($resp->status) {
                     case 'internal_server_error':
                         throw new RuntimeException($resp->message);
                 }
             }
             return $resp;
     }
 }
Example #17
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;
 }
Example #18
0
 /**
  * Parse the response. This will do a little more in future iterations.
  *
  * @param HTTP_Request2_Response $response Response object.
  *
  * @return array
  */
 protected function parseResponse(HTTP_Request2_Response $response)
 {
     return json_decode($response->getBody());
 }