Exemplo n.º 1
0
 /**
  * @param Zend_Http_Response $response
  * @return json string
  * @throws
  */
 public function parseZendResponse(Zend_Http_Response $response)
 {
     if ($response->getStatus() == 200) {
         return $response->getBody();
     } else {
         throw new Exception("Error: Status is: " . $response->getStatus() . " message: " . $response->getMessage());
     }
 }
Exemplo n.º 2
0
 /** Set up the response rendering
  * 
  * @param string $response
  */
 public function formatResponse(Zend_Http_Response $response)
 {
     if ('json' === $this->getResponseType()) {
         return json_decode($response->getBody());
     } else {
         return new Zend_Rest_Client_Result($response->getBody());
     }
 }
Exemplo n.º 3
0
 public function task(Zend_Http_Response $response, Zend_Http_Client $client)
 {
     $query = new Zend_Dom_Query($response->getBody());
     $images = $query->query('img');
     foreach ($images as $image) {
         $this->images[] = $image->getAttribute('src');
     }
     $this->images = array_unique($this->images);
 }
Exemplo n.º 4
0
 /**
  *
  *
  * @param Zend_Http_Response $response JSON response from the PinPayments gateway
  * @throws Dwyera_Pinpay_Model_ResponseParseException If an invalid JSON response object is passed
  */
 public function __construct(Zend_Http_Response $response)
 {
     $this->response = $response;
     $this->httpResponseCode = $response->getStatus();
     $this->msgObj = json_decode($response->getBody());
     if ($this->msgObj == null) {
         throw new Dwyera_Pinpay_Model_ResponseParseException("Could not parse PinPayments gateway response");
     }
 }
Exemplo n.º 5
0
 /**
  * Retrieve latitude and longitude from the API response
  *
  * @param Zend_Http_Response|boolean $response
  * @return array|boolean
  */
 protected function _parseResponse($response)
 {
     if ($response->isSuccessful() && $response->getStatus() == 200) {
         $_response = json_decode($response->getBody());
         $_coordinates = $_response->results[0]->geometry->location;
         $geo = array('lat' => $_coordinates->lat, 'lng' => $_coordinates->lng);
         return $geo;
     }
     return false;
 }
Exemplo n.º 6
0
 /**
  * (non-PHPdoc)
  * @see Tid_Rest_Processor_Input_Abstract::processInputData()
  */
 public function processInputData(Zend_Http_Response $response = null)
 {
     try {
         return isset($response) ? Zend_Json::decode($response->getBody()) : array();
     } catch (Exception $e) {
         $this->getRestService()->log("Error parsing JSON response: " . $e->getMessage(), Zend_Log::ERR);
         $this->getRestService()->log($e, Zend_Log::ERR);
         throw new App_Rest_Processor_Input_Exception('Error response: [code] ' . $response->getStatus() . ' [error] ' . $response->getMessage());
     }
 }
Exemplo n.º 7
0
 /**
  * base constructor for Response objects
  *
  * @param Zend_Http_Response $response
  */
 public function __construct($response)
 {
     if ($response instanceof Zend_Http_Response) {
         $this->_response = WirecardCEE_Stdlib_SerialApi::decode($response->getBody());
     } elseif (is_array($response)) {
         $this->_response = $response;
     } else {
         throw new WirecardCEE_Stdlib_Exception_InvalidResponseException(sprintf('Invalid response from WirecardCEE thrown in %s.', __METHOD__));
     }
 }
Exemplo n.º 8
0
 public function run()
 {
     if ($this->debugMode) {
         echo "Restricting crawl to {$this->domain}\n";
     }
     //loop across available items in the queue of pages to crawl
     while (!$this->queue->isEmpty()) {
         if (isset($this->limit) && $this->counter >= $this->limit) {
             break;
         }
         $this->counter++;
         //get a new url to crawl
         $url = $this->queue->pop();
         if ($this->debugMode) {
             echo "Queue Length: " . $this->queue->queueLength() . "\n";
             echo "Crawling " . $url . "\n";
         }
         //set the url into the http client
         $this->client->setUri($url);
         //make the request to the remote server
         $this->currentResponse = $this->client->request();
         //don't bother trying to parse this if it's not text
         if (stripos($this->currentResponse->getHeader('Content-type'), 'text') === false) {
             continue;
         }
         //search for <a> tags in the document
         $body = $this->currentResponse->getBody();
         $linksQuery = new Zend_Dom_Query($body);
         $links = $linksQuery->query('a');
         if ($this->debugMode) {
             echo "\tFound " . count($links) . " links...\n";
         }
         foreach ($links as $link) {
             //get the href of the link and find out if it links to the current host
             $href = $link->getAttribute('href');
             $urlparts = parse_url($href);
             if ($this->stayOnDomain && isset($urlparts["host"]) && $urlparts["host"] != $this->domain) {
                 continue;
             }
             //if it's an absolute link without a domain or a scheme, attempt to fix it
             if (!isset($urlparts["host"])) {
                 $href = 'http://' . $this->domain . $href;
                 //this is a really naive way of doing this!
             }
             //push this link into the queue to be crawled
             $this->queue->push($href);
         }
         //for each page that we see, run every registered task across it
         foreach ($this->tasks as $task) {
             $task->task($this->currentResponse, $this->client);
         }
     }
     //after we're done with everything, call the shutdown hook on all the tasks
     $this->shutdownTasks();
 }
Exemplo n.º 9
0
 /**
  * Constructeur
  *
  * Affecte la réponse HTTP à une propriété, ainsi que le body.
  * Il tente ensuite de déchiffrer le corps en tant que JSON.
  *
  * @param  Zend_Http_Response $httpResponse
  * @throws SDIS62_Service_Generic_Exception
  */
 public function __construct(Zend_Http_Response $httpResponse)
 {
     $this->httpResponse = $httpResponse;
     $this->rawBody = $httpResponse->getBody();
     try {
         $jsonBody = Zend_Json::decode($this->rawBody, Zend_Json::TYPE_OBJECT);
         $this->jsonBody = $jsonBody;
     } catch (Zend_Json_Exception $e) {
         throw new SDIS62_Service_Generic_Exception('impossible de décoder la réponse: ' . $e->getMessage(), 0, $e);
     }
 }
Exemplo n.º 10
0
 public function __construct(Zend_Http_Response $response)
 {
     $body = $response->getRawBody();
     $json = Zend_Json::decode($body);
     $this->_id = $json['id'];
     if (null !== $json['error']) {
         $this->_error = $json['error'];
     } else {
         $this->_result = $json['result'];
     }
 }
Exemplo n.º 11
0
 public function load(\Zend_Http_Response $httpResponse)
 {
     $this->_reset();
     if ($httpResponse->getBody()) {
         set_error_handler(array($this, 'handleLoadErrors'));
         $this->_simpleXml = simplexml_load_string($httpResponse->getBody());
         restore_error_handler();
     }
     $this->_httpResponse = $httpResponse;
     return $this;
 }
Exemplo n.º 12
0
 public function load(\Zend_Http_Response $httpResponse)
 {
     $this->_reset();
     if ($httpResponse->getBody()) {
         set_error_handler(array($this, 'handleLoadErrors'));
         $this->_json = json_decode($httpResponse->getBody());
         restore_error_handler();
     }
     $this->_httpResponse = $httpResponse;
     return $this;
 }
Exemplo n.º 13
0
 /**
  * Decode request response
  *
  * @param Zend_Http_Response $response response of request
  * @throws Zend_Db_Exception
  * @return array
  */
 protected function _decodeResponse(Zend_Http_Response $response)
 {
     $result = Zend_Json::decode($response->getBody());
     if (is_null($result)) {
         throw new Zend_Db_Exception($response->getMessage());
     }
     if ($result["error"]) {
         throw new Exception($result["reason"], $this->_errors[$result["error"]]);
     }
     return $result;
 }
 /**
  * base ctor for Response objects
  * @param Zend_Http_Response $response
  */
 public function __construct($response)
 {
     if ($response instanceof Zend_Http_Response) {
         $this->_response = WirecardCEE_SerialApi::decode($response->getBody());
     } else {
         if (is_array($response)) {
             $this->_response = $response;
         } else {
             throw new WirecardCEE_Exception('Invalid response from WirecardCEE');
         }
     }
 }
Exemplo n.º 15
0
 public function load(\Zend_Http_Response $httpResponse)
 {
     $this->_reset();
     if ($httpResponse->getBody()) {
         set_error_handler(array($this, 'handleLoadErrors'));
         $this->_dom = new \DOMDocument();
         $this->_dom->loadXml($httpResponse->getBody());
         restore_error_handler();
     }
     $this->_httpResponse = $httpResponse;
     return $this;
 }
Exemplo n.º 16
0
 public function processResponse(Zend_Http_Response $response)
 {
     $serviceName = $this->getRestService()->getServiceName();
     if (!$serviceName) {
         throw new \Application\Exceptions\UnexpectedException("Service Name doesn't exist");
     }
     $this->checkAlarmTimeSpent($serviceName);
     if ($response->isSuccessful()) {
         App::alarm()->notifyInvalidHttpCode($serviceName);
     } else {
         App::alarm()->notifyInvalidHttpCode($serviceName, $response->getStatus());
     }
 }
Exemplo n.º 17
0
 /**
  *
  * @param string $path
  * @param array $options
  */
 protected function _callApi($path, $options)
 {
     $param['format'] = 'json';
     $this->_response = $restClient->restGet($path, $options);
     switch ($param['format']) {
         case 'json':
             $this->_data = json_decode($this->_response->getBody());
             break;
         case 'xml':
             throw new \Thin\Exception('Not yet implemented. Please use json format.');
             break;
     }
     $this->_checkErrors();
     return $this->_data['data'];
 }
Exemplo n.º 18
0
 protected function processMessages(Zend_Http_Response $response)
 {
     $lastMessageId = 0;
     $messages = json_decode($response->getBody(), true);
     if (!$messages) {
         return $lastMessageId;
     }
     foreach ($messages['messages'] as $message) {
         if ($message) {
             $this->triggerEvents($message);
             $lastMessageId = $message['id'];
         }
     }
     return $lastMessageId;
 }
Exemplo n.º 19
0
 /**
  * Retrieve latitude and longitude from the API response
  *
  * @param Zend_Http_Response|boolean $response
  * @return array|boolean
  */
 protected function _parseResponse($response)
 {
     if ($response->isSuccessful() && $response->getStatus() == 200) {
         $_response = json_decode($response->getBody());
         if (is_array($_response->postalcodes)) {
             $_response = array_shift($_response->postalcodes);
         }
         if ($_response) {
             $geo = array('lat' => $_response->lat, 'lng' => $_response->lng);
         } else {
             $geo = false;
         }
         return $geo;
     }
     return false;
 }
 /**
  * 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.');
     }
 }
 public function getLatLng($address)
 {
     # address identifier
     $address_identifier = 'latlng_' . str_replace(array(' '), array('_'), $address);
     $address_identifier = preg_replace('/[^a-z0-9_]+/i', '', $address);
     # registry
     $registry = Zend_Registry::getInstance();
     # caching
     $frontendOptions = array('lifetime' => 2592000, 'automatic_serialization' => true);
     $backendOptions = array('cache_dir' => $registry->config->application->logs->tmpDir . '/cache/');
     $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
     # get data
     if (($data = $cache->load($address_identifier)) === false) {
         new Custom_Logging('Hit Google: Lat/Lng for ' . $address, Zend_Log::INFO);
         $client = new Zend_Http_Client('http://maps.google.com/maps/geo?q=' . urlencode($address), array('maxredirects' => 0, 'timeout' => 30));
         $request = $client->request();
         $response = Zend_Http_Response::fromString($request);
         $body = Zend_Json::decode($response->getBody());
         $data = array();
         $data['latitude'] = !empty($body['Placemark'][0]['Point']['coordinates'][1]) ? $body['Placemark'][0]['Point']['coordinates'][1] : null;
         $data['longitude'] = !empty($body['Placemark'][0]['Point']['coordinates'][0]) ? $body['Placemark'][0]['Point']['coordinates'][0] : null;
         $cache->save($data, $address_identifier);
     } else {
         new Custom_Logging('(local cache) Hit Google: Lat/Lng for ' . $address, Zend_Log::INFO);
     }
     return $data;
 }
Exemplo n.º 22
0
 /**
  * Handle all API errors.
  */
 public function errorAction()
 {
     $data = array();
     $exception = $this->_getParam('error_handler')->exception;
     // Add code and message to response.
     $code = $exception->getCode();
     if (!$code) {
         $code = self::DEFAULT_HTTP_RESPONSE_CODE;
     }
     $message = $exception->getMessage();
     if (!$message) {
         $message = Zend_Http_Response::responseCodeAsText($code);
     }
     $data['message'] = $message;
     // Add errors to response.
     if ($exception instanceof Omeka_Controller_Exception_Api) {
         if ($errors = $exception->getErrors()) {
             $data['errors'] = $errors;
         }
     }
     try {
         $this->getResponse()->setHttpResponseCode($code);
     } catch (Zend_Controller_Exception $e) {
         // The response code was invalid. Set the default.
         $this->getResponse()->setHttpResponseCode(self::DEFAULT_HTTP_RESPONSE_CODE);
     }
     $this->_helper->json($data);
 }
Exemplo n.º 23
0
    /**
     * Gets the document object for this response
     *
     * @return DOMDocument the DOM Document for this response.
     */
    public function getDocument()
    {
        try {
            $body = $this->_httpResponse->getBody();
        } catch (\Zend\Http\Exception $e) {
            $body = false;
        }

        if ($this->_document === null) {
            if ($body !== false) {
                // turn off libxml error handling
                $errors = libxml_use_internal_errors();

                $this->_document = new \DOMDocument();
                if (!$this->_document->loadXML($body)) {
                    $this->_document = false;
                }

                // reset libxml error handling
                libxml_clear_errors();
                libxml_use_internal_errors($errors);
            } else {
                $this->_document = false;
            }
        }

        return $this->_document;
    }
Exemplo n.º 24
0
 /**
  * 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;
 }
Exemplo n.º 25
0
 public function testClearBody()
 {
     $this->_response->append('some', "some content\n");
     $this->assertTrue($this->_response->clearBody());
     $body = $this->_response->getBody(true);
     $this->assertTrue(is_array($body));
     $this->assertEquals(0, count($body));
 }
Exemplo n.º 26
0
 /**
  * Parses response body and generates NP_Gravatar_Profile
  * instance.
  *
  * @param Zend_Http_Response $response
  * @return NP_Service_Gravatar_Profiles_Profile|Zend_Http_Response
  */
 public static function profileFromHttpResponse(Zend_Http_Response $response)
 {
     $body = $response->getBody();
     $profile = @unserialize($body);
     if ($profile === false) {
         require_once 'NP/Service/Gravatar/Profiles/ResponseFormat/Exception.php';
         throw new NP_Service_Gravatar_Profiles_ResponseFormat_Exception('Invalid PHP response.');
     }
     if (is_array($profile) && isset($profile['entry'])) {
         //Valid response?
         require_once 'NP/Service/Gravatar/Profiles/Profile.php';
         return new NP_Service_Gravatar_Profiles_Profile($profile['entry'][0]);
     } else {
         //Probably unexisting user is supplied.
         return $response;
     }
 }
 protected function _processProtoMessage(Zend_Http_Response $response = null)
 {
     if (isset($this->getRestMethod()->inputProtoMessageClass) && substr((string) $response->getStatus(), 0, 1) == '2') {
         $protoMessageClass = $this->getRestMethod()->inputProtoMessageClass;
         try {
             $response = new $protoMessageClass($response->getBody());
             return $response;
         } catch (Exception $e) {
             $this->getRestService()->log("Error loading proto message class: " . $protoMessageClass, Zend_Log::ERR);
             $this->getRestService()->log($e, Zend_Log::ERR);
             throw $e;
         }
     }
     //Errors which are taking place on input processing phase should throw
     //this Exception Subclass
     throw new App_Rest_Processor_Input_Exception('Error response: [code] ' . $response->getStatus() . ' [error] ' . $response->getMessage());
 }
Exemplo n.º 28
0
 /**
  * Parses the JSON encoded request body returned by the Recensus API and 
  * returns a PHP array representing the resourse.
  * 
  * @return array
  */
 protected function parseResponse()
 {
     $parseResult = json_decode($this->lastResponse->getBody(), true);
     if (!$parseResult) {
         $this->handleError("Error decoding response from API.");
     }
     return $parseResult;
 }
Exemplo n.º 29
0
 public function testGetExceptionByCode()
 {
     $this->assertFalse($this->_response->getExceptionByCode(200));
     $this->_response->setException(new Zend_Controller_Response_Exception('FooBar', 200));
     $exceptions = $this->_response->getExceptionByCode(200);
     $this->assertTrue(0 < count($exceptions));
     $this->assertEquals(200, $exceptions[0]->getCode());
 }
Exemplo n.º 30
0
 /**
  * Parses response body and generates NP_Gravatar_Profile
  * instance.
  *
  * @param Zend_Http_Response $response
  * @return NP_Service_Gravatar_Profiles_Profile|Zend_Http_Response
  */
 public static function profileFromHttpResponse(Zend_Http_Response $response)
 {
     $body = $response->getBody();
     try {
         $xml = simplexml_load_string($body);
     } catch (Exception $ex) {
         require_once 'NP/Service/Gravatar/Profiles/ResponseFormat/Exception.php';
         throw new NP_Service_Gravatar_Profiles_ResponseFormat_Exception('Invalid XML response.');
     }
     if (!$xml->entry) {
         //Probably unexisting user is supplied.
         return $response;
     }
     $profileData = self::_xmlToArray($xml->entry[0]);
     require_once 'NP/Service/Gravatar/Profiles/Profile.php';
     return new NP_Service_Gravatar_Profiles_Profile($profileData);
 }