If $config['storeresponse'] is set to false, or no response was
stored yet, will return null
public getLastResponse ( ) : Zend_Http_Response | ||
return | Zend_Http_Response | or null if none |
public function translate($message, $from, $to) { $url = "http://ajax.googleapis.com/ajax/services/language/translate"; $client = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => 30)); $langpair = $from . '|' . $to; $params = array('v' => '1.1', 'q' => $message, 'langpair' => $langpair, 'key' => 'ABQIAAAAMtXAc56OizxVFR_fG__ZZRSrxD5q6_ZpfA55q8xveFjTjZJnShSvPHZq2PGkhSBZ0_OObHUNyy0smw'); /** * Zend_Http_Client */ $client->setParameterPost($params); $client->setHeaders('Referer', 'http://sb6.ru'); $response = $client->request("POST"); //print_r ($response); $data = $response->getBody(); $serverResult = json_decode($data); $status = $serverResult->responseStatus; // should be 200 $result = ''; if ($status == 200) { $result = $serverResult->responseData->translatedText; } else { echo "retry\n"; print_r($client->getLastRequest()); print_r($client->getLastResponse()); die; return $this->translate($message, $from, $to); } return $result; }
public function send() { $me = new self("global"); $sent = array(); $textlink = new Feed_TextLink(); $feed = $textlink->feed(); $items = array(); //we send something only if we have something to send if (empty($feed->feed->entry) == false) { foreach ($feed->feed->entry as &$item) { if (empty($item->forwardlink->href) || isset($sent[$item->forwardlink->hash])) { continue; } $sent[$item->forwardlink->hash] = true; $client = new Zend_Http_Client($item->forwardlink->href, array('timeout' => 60)); if (!empty($feed->feed->entry)) { $client->setParameterPost(array('protocol' => 'forwardlink', 'contribution' => json_encode($feed))); try { $response = $client->request(Zend_Http_Client::POST); $request = $client->getLastResponse(); $result = $response->getBody(); $resultJson = json_decode($response->getBody()); //Here we add the date last updated so that we don't have to send it if not needed, saving load time. if (!empty($resultJson->feed) && $resultJson->feed == "success") { $me->addItem(array('dateLastUpdated' => $item->textlink->dateLastUpdated, 'textlinkHash' => $item->textlink->hash, 'forwardlinkHash' => $item->forwardlink->hash)); } $items[$item->textlink->text] = $result; } catch (Exception $e) { } } } return $items; } }
/** * Validate the license information * * @param string $userId * @param array $spMetadata * @param array $idpMetadata * @return string */ public function validate($userId, array $spMetadata, array $idpMetadata) { if (!$this->_active) { return EngineBlock_LicenseEngine_ValidationManager::LICENSE_UNKNOWN; } $client = new Zend_Http_Client($this->_url); $client->setConfig(array('timeout' => 15)); try { $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/json; charset=utf-8')->setParameterGet('userId', urlencode($userId))->setParameterGet('serviceProviderEntityId', urlencode($spMetadata['EntityId']))->setParameterGet('identityProviderEntityId', urlencode($idpMetadata['EntityId']))->request('GET'); $body = $client->getLastResponse()->getBody(); $response = json_decode($body, true); $status = $response['status']; } catch (Exception $exception) { $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($userId, $idpMetadata['EntityId'], $spMetadata['EntityId'], $exception->getTraceAsString()); EngineBlock_ApplicationSingleton::getLog()->error("Could not connect to License Manager" . $exception->getMessage(), $additionalInfo); return EngineBlock_LicenseEngine_ValidationManager::LICENSE_UNKNOWN; } if ($status['returnUrl']) { $currentResponse = EngineBlock_ApplicationSingleton::getInstance()->getHttpResponse(); $currentResponse->setRedirectUrl($status['returnUrl']); $currentResponse->send(); exit; } else { if ($status['licenseStatus']) { return $status['licenseStatus']; } else { return EngineBlock_LicenseEngine_ValidationManager::LICENSE_UNKNOWN; } } }
/** * Test that getLastResponse returns null when not storing * */ public function testGetLastResponseWhenNotStoring() { $this->client->setUri($this->baseuri . 'testHeaders.php'); $this->client->setConfig(array('storeresponse' => false)); $response = $this->client->request(); $this->assertEquals(null, $this->client->getLastResponse(), 'getLastResponse is expected to be null when not storing'); }
function send() { global $tikilib; $entry = array(); $lastModif = 0; $feed = $this->feed(); foreach ($feed->feed->entry as $item) { if (empty($item->forwardlink->href)) { continue; } $client = new Zend_Http_Client($item->forwardlink->href, array('timeout' => 60)); $info = $tikilib->get_page_info($item->page); if ($info['lastModif'] > $lastModif) { $lastModif = $info['lastModif']; } } if (!empty($feed->feed->entry)) { $client->setParameterGet(array('protocol' => 'forwardlink', 'contribution' => json_encode($feed))); try { $response = $client->request(Zend_Http_Client::POST); $request = $client->getLastResponse(); return $response->getBody(); } catch (Exception $e) { return ""; } } }
public function indexAction() { $client = new Zend_Http_Client('https://ws.pagseguro.uol.com.br/v2/sessions/'); $client->setMethod(Zend_Http_Client::POST); $client->setParameterGet('email', '*****@*****.**'); $client->setParameterGet('token', '9F79900A9B454CE6B18613D7224C0621'); $client->request(); var_dump($client->getLastResponse()->getBody()); }
/** * Test that getLastResponse returns null when not storing * */ public function testGetLastResponseWhenNotStoring() { // Now, test we get a proper response after the request $this->_client->setUri('http://example.com/foo/bar'); $this->_client->setAdapter('Zend_Http_Client_Adapter_Test'); $this->_client->setConfig(array('storeresponse' => false)); $response = $this->_client->request(); $this->assertNull($this->_client->getLastResponse(), 'getLastResponse is expected to be null when not storing'); }
public function __construct($uri, $email, $password, $consumer_key, $consumer_secret, $oauth_realm, $cookieJarFile = './OX3_Api_CookieJar.txt', $sso = array(), $proxy = array()) { parent::__construct($uri); $aUrl = parse_url($uri); if (empty($sso)) { $sso = array('siteUrl' => 'https://sso.openx.com/api/index/initiate', 'requestTokenUrl' => 'https://sso.openx.com/api/index/initiate', 'accessTokenUrl' => 'https://sso.openx.com/api/index/token', 'authorizeUrl' => 'https://sso.openx.com/login/login', 'loginUrl' => 'https://sso.openx.com/login/process'); } // Set the proxy['adapter'] if $proxy config was passed in if (!empty($proxy)) { $proxy['adapter'] = 'Zend_Http_Client_Adapter_Proxy'; } // Initilize the cookie jar, from the $cookieJarFile if present $client = self::getHttpClient(); $cookieJar = false; if (is_readable($cookieJarFile)) { $cookieJar = @unserialize(file_get_contents($cookieJarFile)); } if (!$cookieJar instanceof Zend_Http_CookieJar) { $cookieJar = new Zend_Http_CookieJar(); } $client->setCookieJar($cookieJar); $client->setConfig($proxy); $result = $this->put('/a/session/validate'); // See if the openx3_access_token is still valid... if ($result->isError()) { // Get Request Token $config = array('siteUrl' => $sso['siteUrl'], 'requestTokenUrl' => $sso['requestTokenUrl'], 'accessTokenUrl' => $sso['accessTokenUrl'], 'authorizeUrl' => $sso['authorizeUrl'], 'consumerKey' => $consumer_key, 'consumerSecret' => $consumer_secret, 'realm' => $oauth_realm); $oAuth = new OX3_Oauth_Consumer($config); $requestToken = $oAuth->getRequestToken(); // Authenticate to SSO $loginClient = new Zend_Http_Client($sso['loginUrl']); $loginClient->setCookieJar(); $loginClient->setConfig($proxy); $loginClient->setParameterPost(array('email' => $email, 'password' => $password, 'oauth_token' => $requestToken->getToken())); $loginClient->request(Zend_Http_Client::POST); $loginBody = $loginClient->getLastResponse()->getBody(); // Parse response, sucessful headless logins will return oob?oauth_token=<token>&oauth_verifier=<verifier> as the body if (substr($loginBody, 0, 4) == 'oob?') { $vars = array(); @parse_str(substr($loginBody, 4), $vars); if (empty($vars['oauth_token'])) { throw new Exception('Error parsing SSO login response'); } // Swap the (authorized) request token for an access token: $accessToken = $oAuth->getAccessToken($vars, $requestToken)->getToken(); $client->setCookie(new Zend_Http_Cookie('openx3_access_token', $accessToken, $aUrl['host'])); $result = $this->put('/a/session/validate'); if ($result->isSuccessful()) { file_put_contents($cookieJarFile, serialize($client->getCookieJar()), LOCK_EX); chmod($cookieJarFile, 0666); } } else { throw new Exception('SSO Authentication error'); } } }
protected function sendRequestSync($url) { $client = new Zend_Http_Client($url); Mage::helper('foomanjirafe')->debug($url); $response = $client->request(); //check server response if ($client->getLastResponse()->isError()) { throw new Exception($response->getStatus() . ' ' . $response->getMessage()); } return $response; }
/** * Get Stream Data. * * * $data can also be stream (such as file) to which the data will be save. * * $client->setStream(); // will use temp file * $response = $client->request('GET'); * // copy file * copy($response->getStreamName(), "my/downloads/file"); * // use stream * $fp = fopen("my/downloads/file2", "w"); * stream_copy_to_stream($response->getStream(), $fp); * // Also can write to known file * $client->setStream("my/downloads/myfile")->request('GET'); * * @param resource $data * @param string $enctype * @return Default_Plugin_HttpBox */ function getStreamData($filename = null) { if (is_string($filename)) { $this->client->setStream($filename)->request('GET'); } else { $this->client->setStream(); // will use temp file $this->client->request('GET'); } // Запомним последний запрос в виде строки $this->last_request = $this->client->getLastRequest(); // Запомним последний запрос в виде Zend_Http_Response $this->last_response = $this->client->getLastResponse(); return $this; }
/** * * * @param $userId * @param $attributes * @param $spMetadata * @param $idpMetadata * @return void */ public function provisionUser($userId, $attributes, $spMetadata, $idpMetadata) { if (!$spMetadata['MustProvisionExternally']) { return; } // https://os.XXX.surfconext.nl/provisioning-manager/provisioning/jit.shtml? // provisionDomain=apps.surfnet.nl&provisionAdmin=admin%40apps.surfnet.nl& // provisionPassword=xxxxx&provisionType=GOOGLE&provisionGroups=true $client = new Zend_Http_Client($this->_url); $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/json; charset=utf-8')->setParameterGet('provisionType', $spMetadata['ExternalProvisionType'])->setParameterGet('provisionDomain', $spMetadata['ExternalProvisionDomain'])->setParameterGet('provisionAdmin', $spMetadata['ExternalProvisionAdmin'])->setParameterGet('provisionPassword', $spMetadata['ExternalProvisionPassword'])->setParameterGet('provisionGroups', $spMetadata['ExternalProvisionGroups'])->setRawData(json_encode($this->_getData($userId, $attributes)))->request('POST'); $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($userId, $idpMetadata['EntityId'], $spMetadata['EntityId'], null); EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: Sent HTTP request to provision user using " . __CLASS__, $additionalInfo); EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: URI: " . $client->getUri(true), $additionalInfo); EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: REQUEST: " . $client->getLastRequest(), $additionalInfo); EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: RESPONSE: " . $client->getLastResponse(), $additionalInfo); }
public function translate($message, $from, $to) { $url = "http://api.microsofttranslator.com/v2/Http.svc/Translate"; $client = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => 30)); $langpair = $from . '|' . $to; $params = array('appId' => $this->_appId, 'text' => $message, 'from' => $from, 'to' => $to, 'category' => 'general'); /** * Zend_Http_Client */ $client->setParameterGet($params); $response = $client->request("GET"); $data = $response->getBody(); $result = ''; if ($client->getLastResponse()->getStatus() == 200) { $result = strip_tags(urldecode($data)); } else { $result = $message; } return $result; }
/** * Retorna o ID da sessao para ser usado nas chamadas JavaScript do Checkout Transparente * ou FALSE no caso de erro * @return bool|string */ public function getSessionId() { $client = new Zend_Http_Client($this->getWsUrl('sessions')); $client->setMethod(Zend_Http_Client::POST); $client->setParameterGet('email', $this->getMerchantEmail()); $client->setParameterGet('token', $this->getToken()); $client->setConfig(array('timeout' => 30)); try { $response = $client->request(); } catch (Exception $e) { Mage::logException($e); return false; } $response = $client->getLastResponse()->getBody(); libxml_use_internal_errors(true); $xml = simplexml_load_string($response); if (false === $xml) { $this->writeLog('Falha na autenticação com API do PagSeguro. Verifique email e token cadastrados. Retorno pagseguro: ' . $response); return false; } return (string) $xml->id; }
/** * Make a request to Amazon S3 * * @param string $method * @param string $path * @param array $headers * @return Zend_Http_Response */ private function _makeRequest($method, $path, $headers = array()) { $retry_count = 0; if (!is_array($headers)) { $headers = array($headers); } // Strip off the beginning s3:// (assuming this is the scheme used) if (strpos($path, self::STREAM_ID) !== false) { $path = substr($path, 5); } do { $retry = false; $headers['Date'] = gmdate(DATE_RFC1123, time()); self::addSignature($method, $path, $headers); $client = new Zend_Http_Client(self::S3_ENDPOINT . '/' . $path); $client->setHeaders($headers); if ($method == 'PUT' && $this->_objectBuffer !== null) { if (!isset($headers['Content-type'])) { $headers['Content-type'] = self::getMimeType($path); } $client->setRawData($this->_objectBuffer, $headers['Content-type']); } $response = $client->request($method); if (self::$logger instanceof Zend_Log) { self::$logger->log($client->getLastRequest(), Zend_Log::INFO); Zend_Debug::dump($client->getLastResponse()); //self::$logger->log($response, Zend_Log::INFO); } $response_code = $response->getStatus(); // Some 5xx errors are expected, so retry automatically if ($response_code >= 500 && $response_code < 600 && $retry_count <= 5) { $retry = true; $retry_count++; if (self::$logger instanceof Zend_Log) { self::$logger->log($response_code . ' : retrying ' . $method . ' request (' . $retry_count . ')', Zend_Log::INFO); } sleep($retry_count / 4 * $retry_count); } else { if ($response_code == 307) { echo "We need to redirect"; } else { if ($response_code == 100) { echo "OK to Continue"; } } } } while ($retry); return $response; }
protected function _call($endpoint, $params = null, $method = 'GET', $data = null, $silent = false, $global = false) { if ($params && is_array($params) && count($params) > 0) { $args = array(); foreach ($params as $arg => $val) { $args[] = urlencode($arg) . '=' . urlencode($val); } $endpoint .= '?' . implode('&', $args); } $url = $this->_getUrl($endpoint); $method = strtoupper($method); $client = new Zend_Http_Client($url); $client->setMethod($method); $client->setHeaders(array('Accept' => 'application/json', 'Content-Type' => 'application/json')); $client->setAuth($this->getUsername(), $this->getPassword()); if ($method == 'POST' || $method == "PUT") { $client->setRawData(json_encode($data), 'application/json'); } Mage::log(print_r(array('url' => $url, 'method' => $method, 'data' => json_encode($data)), true), null, 'zendesk.log'); try { $response = $client->request(); } catch (Zend_Http_Client_Exception $ex) { Mage::log('Call to ' . $url . ' resulted in: ' . $ex->getMessage(), Zend_Log::ERR, 'zendesk.log'); Mage::log('--Last Request: ' . $client->getLastRequest(), Zend_Log::ERR, 'zendesk.log'); Mage::log('--Last Response: ' . $client->getLastResponse(), Zend_Log::ERR, 'zendesk.log'); return array(); } $body = json_decode($response->getBody(), true); Mage::log(var_export($body, true), Zend_Log::DEBUG, 'zendesk.log'); if ($response->isError()) { if (is_array($body) && isset($body['error'])) { if (is_array($body['error']) && isset($body['error']['title'])) { if (!$silent) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__($body['error']['title'], $response->getStatus())); return; } else { return $body; } } else { if (!$silent) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__($body['error'], $response->getStatus())); return; } else { return $body; } } } else { if (!$silent) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__($body, $response->getStatus())); return; } else { return $body; } } } return $body; }
if (!isset($_GET['page']) or !$_GET['page']) { Abort(); } # Use the Zend_Uri class purely to validate whether the passed URI looks like a URI require_once 'Zend/Uri.php'; $uri = Zend_Uri::factory($_GET['page']); # Request the page to be parsed /* @var $uri Zend_Uri_Http */ require_once 'Zend/Http/Client.php'; $user_agent = "Stoolball England microformats parser"; if (isset($_SERVER['HTTP_USER_AGENT'])) { $user_agent = $_SERVER['HTTP_USER_AGENT'] . "; {$user_agent}"; } $client = new Zend_Http_Client($uri->__toString(), array('maxredirects' => 0, 'timeout' => 30, 'useragent' => $user_agent)); $client->request(); $response = $client->getLastResponse(); # Check we got a non-error status code if ($response->getStatus() >= 400) { Abort(); } # Check we got some body content to parse /* @var $response Zend_Http_Response */ $body = $response->getBody(); if (!$body) { Abort(); } # Load the XSLT file, which is from suda.co.uk $xslFile = new DOMDocument(); $xslFile->load($_SERVER['DOCUMENT_ROOT'] . '/xhtml2vcal.xsl'); # Remove HTML the parser does not know how to deal with $body = preg_replace('/<\\/?nav>/', "", $body);
/** * @param Zend_Http_Client $xhr */ public static function browserReceive($xhr) { phpQuery::debug("[WebBrowser] Received from " . $xhr->getUri(true)); // TODO handle meta redirects $body = $xhr->getLastResponse()->getBody(); // XXX error ??? if (strpos($body, '<!doctype html>') !== false) { $body = '<html>' . str_replace('<!doctype html>', '', $body) . '</html>'; } $pq = phpQuery::newDocument($body); $pq->document->xhr = $xhr; $pq->document->location = $xhr->getUri(true); $refresh = $pq->find('meta[http-equiv=refresh]')->add('meta[http-equiv=Refresh]'); if ($refresh->size()) { // print htmlspecialchars(var_export($xhr->getCookieJar()->getAllCookies(), true)); // print htmlspecialchars(var_export($xhr->getLastResponse()->getHeader('Set-Cookie'), true)); phpQuery::debug("Meta redirect... '{$refresh->attr('content')}'\n"); // there is a refresh, so get the new url $content = $refresh->attr('content'); $urlRefresh = substr($content, strpos($content, '=') + 1); $urlRefresh = trim($urlRefresh, '\'"'); // XXX not secure ?! phpQuery::ajaxAllowURL($urlRefresh); // $urlRefresh = urldecode($urlRefresh); // make ajax call, passing last $xhr object to preserve important stuff $xhr = phpQuery::ajax(array('type' => 'GET', 'url' => $urlRefresh, 'dataType' => 'html'), $xhr); if ($xhr->getLastResponse()->isSuccessful()) { // if all is ok, repeat this method... return call_user_func_array(array('phpQueryPlugin_WebBrowser', 'browserReceive'), array($xhr)); } } else { return $pq; } }
/** * Debug helper function to log the last request/response pair against the DMS server * * @parma Zend_Http_Client $client Zend Http client object * @return void */ private function _debugRequest(Zend_Http_Client $client) { $config = Zend_Registry::get('params'); $logfile = ''; // Capture DMS service parameters if (isset($config->dms) && isset($config->dms->logfile)) { $logfile = $config->dms->logfile; } if ($logfile != null && APPLICATION_ENV != 'production') { $request = $client->getLastRequest(); $response = $client->getLastResponse(); $fh = fopen($logfile, 'a+'); fwrite($fh, $request); fwrite($fh, "\n\n"); fwrite($fh, $response); fwrite($fh, "\n\n\n\n"); fclose($fh); } }
/** * Retrieve current media datas from provider * * @return boolean * @access protected */ protected function _retrieveDatas() { if ($this->_datas) { return true; } //load provider if (!$this->_getProvider()) { return false; } //set cache lifetime $lifetime = 86400; //(default : 24 hours) //create cache id from files, compression status and last time files access $cacheId = md5(serialize(array('url' => $this->_url, 'maxwidth' => io::isPositiveInteger($this->_maxwidth) ? $this->_maxwidth : '', 'maxheight' => io::isPositiveInteger($this->_maxheight) ? $this->_maxheight : ''))); //create cache object $cache = new CMS_cache($cacheId, 'oembed', $lifetime, false); $datas = ''; if (!$cache->exist() || !($datas = $cache->load())) { try { $client = new Zend_Http_Client(); $client->setUri($this->getProvider()); //HTTP config $httpConfig = array('maxredirects' => 5, 'timeout' => 10, 'useragent' => 'Mozilla/5.0 (compatible; Automne/' . AUTOMNE_VERSION . '; +http://www.automne-cms.org)'); if (defined('APPLICATION_PROXY_HOST') && APPLICATION_PROXY_HOST) { $httpConfig['adapter'] = 'Zend_Http_Client_Adapter_Proxy'; $httpConfig['proxy_host'] = APPLICATION_PROXY_HOST; if (defined('APPLICATION_PROXY_PORT') && APPLICATION_PROXY_PORT) { $httpConfig['proxy_port'] = APPLICATION_PROXY_PORT; } } $client->setConfig($httpConfig); $client->setParameterGet(array('url' => $this->_url, 'format' => 'json')); if (io::isPositiveInteger($this->_maxwidth)) { $client->setParameterGet('maxwidth', $this->_maxwidth); } if (io::isPositiveInteger($this->_maxheight)) { $client->setParameterGet('maxheight', $this->_maxheight); } $client->request(); $response = $client->getLastResponse(); } catch (Zend_Http_Client_Exception $e) { $this->raiseError('Error for url: ' . $this->_url . ' - ' . $e->getMessage()); } if (isset($response) && $response->isSuccessful()) { $jsonString = $response->getBody(); $datas = json_decode($jsonString, true); } else { if (isset($response)) { $this->raiseError('Error for oembed url: ' . $this->_url . ' (Provider: ' . $this->getProvider() . ') - ' . $response->getStatus() . ' - ' . $response->getMessage()); } else { $this->raiseError('Error for oembed url: ' . $this->_url . ' (Provider: ' . $this->getProvider() . ') - no response object'); } //create error datas $datas = array('error' => isset($response) ? $response->getStatus() : '500', 'cache_age' => 7200, 'type' => 'error'); } if ($cache) { if (isset($datas['cache_age']) && io::isPositiveInteger($datas['cache_age']) && $datas['cache_age'] != 86400) { //create cache object with new lifetime $cache = new CMS_cache($cacheId, 'oembed', $datas['cache_age'], false); } $cache->save($datas, array('type' => 'oembed', 'provider' => $this->getProvider())); } } if (!$datas) { return false; } $this->_datas = $datas; return true; }
/** * Retrieves given URL (GET method), forwarding current client headers to target host * @param string $url * @return string response body */ function get_url($url) { // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array(realpath(dirname(__FILE__) . '.'), get_include_path()))); require_once 'Zend/Loader/Autoloader.php'; $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->setFallbackAutoloader(true); $headers = array(); if (function_exists('apache_request_headers')) { $headers = apache_request_headers(); } unset($headers['Via']); unset($headers['X-Forwarded-For']); unset($headers['Host']); $client = new Zend_Http_Client(); $client->setUri($url); $client->setHeaders($headers); $client->request(); $response = $client->getLastResponse(); $body = $response->getBody(); return $body; }
/** * @param Zend_Http_Client $xhr */ public static function browserDownload($xhr) { phpQuery::debug("[WebBrowser] Received from " . $xhr->getUri(true)); // TODO handle meta redirects $body = $xhr->getLastResponse()->getBody(); return $body; }
/** * Grab statuses changes when receiving a new notification code * @param $notificationCode * * @return SimpleXMLElement */ public function getNotificationStatus($notificationCode) { $helper = Mage::helper('ricardomartins_pagseguro'); $url = $helper->getWsUrl('transactions/notifications/' . $notificationCode, false); $client = new Zend_Http_Client($url); $client->setParameterGet(array('token' => $helper->getToken(), 'email' => $helper->getMerchantEmail())); $client->request(); $resposta = $client->getLastResponse()->getBody(); $helper->writeLog(sprintf('Retorno do Pagseguro para notificationCode %s: %s', $notificationCode, $resposta)); libxml_use_internal_errors(true); $xml = simplexml_load_string(trim($resposta)); if (false === $xml) { $helper->writeLog('Retorno de notificacao XML PagSeguro em formato não esperado. Retorno: ' . $resposta); } return $xml; }
/** * Chama API pra realizar um pagamento * @param $params * @param $payment * * @return SimpleXMLElement */ public function callApi($params, $payment) { $helper = Mage::helper('ricardomartins_pagseguro'); $client = new Zend_Http_Client($helper->getWsUrl('transactions')); $client->setMethod(Zend_Http_Client::POST); $client->setConfig(array('timeout' => 30)); $client->setParameterPost($params); //parametros enviados via POST $helper->writeLog('Parametros sendo enviados para API (/transactions): ' . var_export($params, true)); try { $response = $client->request(); //faz o request } catch (Exception $e) { Mage::throwException('Falha na comunicação com Pagseguro (' . $e->getMessage() . ')'); } $response = $client->getLastResponse()->getBody(); $helper->writeLog('Retorno PagSeguro (/transactions): ' . var_export($response, true)); libxml_use_internal_errors(true); $xml = simplexml_load_string($response); if (false === $xml) { switch ($response) { case 'Unauthorized': $helper->writeLog('Token/email não autorizado pelo PagSeguro. Verifique suas configurações no painel.'); break; case 'Forbidden': $helper->writeLog('Acesso não autorizado à Api Pagseguro. Verifique se você tem permissão para usar este serviço. Retorno: ' . var_export($response, true)); break; default: $helper->writeLog('Retorno inesperado do PagSeguro. Retorno: ' . var_export($response, true)); } Mage::throwException('Houve uma falha ao processar seu pedido/pagamento. Por favor entre em contato conosco.'); } return $xml; }
public function getNotificationStatus() { $notificationCode = "06D1FA77-DBDC-405B-8931-D398C90CAE53"; $url = 'https://ws.sandbox.pagseguro.uol.com.br/v2/transactions/notifications/' . $notificationCode; $client = new Zend_Http_Client($url, array('keepalive' => true)); $client->setParameterGet(array('token' => "*****@*****.**", 'email' => "24707C512FF041ED96B762FE807CA552")); $request = $client->request(); //var_dump($request); exit; $resposta = $client->getLastResponse()->getBody(); $stream = @fopen('../log/pagseguroNotification.log', 'a', false); $writer = new Zend_Log_Writer_Stream($stream); $logger = new Zend_Log($writer); $logger->err(sprintf('Retorno do Pagseguro para notificationCode %s: %s', $notificationCode, $resposta)); libxml_use_internal_errors(true); $xml = simplexml_load_string(trim($resposta)); if (false === $xml) { $stream = @fopen('../log/pagseguroNotification.log', 'a', false); $writer = new Zend_Log_Writer_Stream($stream); $logger = new Zend_Log($writer); $logger->err('Retorno de notificacao XML PagSeguro em formato não esperado. Retorno: ' . $resposta); } //return $xml; var_dump($xml); exit; }
/** * Grab statuses changes when receiving a new notification code * @param $notificationCode * * @return SimpleXMLElement */ public function getNotificationStatus($notificationCode) { $helper = Mage::helper('ricardomartins_pagseguro'); $url = $helper->getWsUrl('transactions/notifications/' . $notificationCode, false); $client = new Zend_Http_Client($url); $client->setParameterGet(array('token' => $helper->getToken(), 'email' => $helper->getMerchantEmail())); $client->request(); $resposta = $client->getLastResponse()->getBody(); $helper->writeLog(sprintf('Retorno do Pagseguro para notificationCode %s: %s', $notificationCode, $resposta)); return simplexml_load_string(trim($resposta)); }
public function indexAction() { $this->view->breadcrumb = $this->view->translate("Welcome to Snep version %s", SNEP_VERSION); // Direcionando para o "snep antigo" $config = Zend_Registry::get('config'); $db = Zend_Registry::get('db'); // GOD! $linfoData = new Zend_Http_Client('http://localhost/snep/lib/linfo/index.php?out=xml'); try { $linfoData->request(); $sysInfo = $linfoData->getLastResponse()->getBody(); $sysInfo = simplexml_load_string($sysInfo); } catch (HttpException $ex) { echo $ex; } if (trim($config->ambiente->db->host) == "") { $this->_redirect("/installer/"); } else { $systemInfo = array(); $uptimeRaw = explode(';', $sysInfo->core->uptime); $systemInfo['uptime'] = $uptimeRaw[0]; /* require_once "includes/AsteriskInfo.php"; $astinfo = new AsteriskInfo(); $astVersionRaw = explode('@', $astinfo->status_asterisk("core show version", "", True)); preg_match('/Asterisk (.*) built/', $astVersionRaw[0], $astVersion); */ $systemInfo['asterisk'] = $astVersion[1]; $systemInfo['mysql'] = trim(exec("mysql -V | awk -F, '{ print \$1 }' | awk -F'mysql' '{ print \$2 }'")); $systemInfo['linux_ver'] = $sysInfo->core->os . ' / ' . $sysInfo->core->Distribution; $systemInfo['linux_kernel'] = $sysInfo->core->kernel; $cpuRaw = explode('-', $sysInfo->core->CPU); $systemInfo['hardware'] = $cpuRaw[1]; $cpuNumber = count(explode('<br />', $sysInfo->core->CPU)); $cpuUsageRaw = explode(' ', $sysInfo->core->load); $loadAvarege = ($cpuUsageRaw[0] + $cpuUsageRaw[1] + $cpuUsageRaw[2]) / 3; $systemInfo['usage'] = round($loadAvarege * 100 / ($cpuNumber - 1)); $systemInfo['memory']['ram'] = array('total' => $this->byte_convert(floatval($sysInfo->memory->Physical->total)), 'free' => $this->byte_convert(floatval($sysInfo->memory->Physical->free)), 'used' => $this->byte_convert(floatval($sysInfo->memory->Physical->used)), 'percent' => floatval($sysInfo->memory->Physical->total) > 0 ? round(floatval($sysInfo->memory->Physical->used) / floatval($sysInfo->memory->Physical->total) * 100) : 0); $systemInfo['memory']['swap'] = array('total' => $this->byte_convert(floatval($sysInfo->memory->swap->core->free)), 'free' => $this->byte_convert(floatval($sysInfo->memory->swap->core->total)), 'used' => $this->byte_convert(floatval($sysInfo->memory->swap->core->used)), 'percent' => floatval($sysInfo->memory->swap->core->total) > 0 ? round(floatval($sysInfo->memory->swap->core->used) / floatval($sysInfo->memory->swap->core->total) * 100) : 0); $deviceArray = $sysInfo->mounts->mount; foreach ($deviceArray as $mount) { $systemInfo['space'][] = array('mount_point' => $mount["mountpoint"], 'size' => $this->byte_convert(floatval($mount["size"])), 'free' => $this->byte_convert(floatval($mount["free"])), 'percent' => floatval($mount["size"]) > 0 ? round(floatval($mount["used"]) / floatval($mount["size"]) * 100) : 0); } $netArray = $sysInfo->net->interface; $count = 0; foreach ($netArray as $board) { if ($count < 6) { $systemInfo['net'][] = array('device' => $board["device"], 'up' => $board["state"]); $count++; } } /// @todo tratar isso depois /* $sqlN = "select count(*) from"; $select = $db->query($sqlN . ' peers'); $result = $select->fetch(); $systemInfo['num_peers'] = $result['count(*)']; $select = $db->query($sqlN . ' trunks'); $result = $select->fetch(); $systemInfo['num_trunks'] = $result['count(*)']; $select = $db->query($sqlN . ' regras_negocio'); $result = $select->fetch(); * */ $systemInfo['num_routes'] = $result['count(*)']; $systemInfo['modules'] = array(); $modules = Snep_Modules::getInstance()->getRegisteredModules(); foreach ($modules as $module) { $systemInfo['modules'][] = array("name" => $module->getName(), "version" => $module->getVersion(), "description" => $module->getDescription()); } $this->view->indexData = $systemInfo; // Creates Snep_Inspector Object $objInspector = new Snep_Inspector(); // Get array with status of inspected system requirements $inspect = $objInspector->getInspects(); // Verify errors $this->view->error = false; foreach ($inspect as $log => $message) { if ($message['error'] == 1) { $this->view->error = true; } } // Inspector url $this->view->inspector = $this->getFrontController()->getBaseUrl() . '/inspector/'; } }
public function __construct(Zend_Http_Client $client) { $this->_client = $client; $this->_xml = simplexml_load_string($client->getLastResponse()->getBody()); }