/** * 決済開始 * @args $args['cardnumber'] ハイフンなしのカード番号 * @args $args['expyy'] 年(2桁) * @args $args['expmm'] 月(2桁) * @args $args['telno'] ハイフンなしの電話番号 * @args $args['email'] メールアドレス * @args $args['sendid'] 注文ID * @args $args['username'] スペースなしのユーザー名(英字) * @args $args['money'] 決済金額(総額) * @args $args['div'] 分割数(01/03/05/06/10) */ public static function execute($args) { $config = Zend_Registry::get('config'); $params['clientip'] = $config->zeus->clientip; $params['cardnumber'] = $args['cardnumber']; $params['expyy'] = $args['expyy']; $params['expmm'] = $args['expmm']; $params['telno'] = $args['telno']; $params['email'] = $args['email']; $params['sendid'] = $args['sendid']; $params['username'] = $args['username']; $params['money'] = $args['money']; $params['sendpoint'] = 'eccube'; $params['send'] = 'mall'; $params['pubsec'] = ''; $params['div'] = $args['div']; // 0円のときは決済しない if (!$args['money']) { return false; } // 決済開始 $client = new Zend_Http_Client($config->zeus->api_url); $client->setParameterPost($params); $response = $client->request('POST'); // 結果の判定 if ($response->getBody() === 'Success_order') { return true; } else { return false; } }
public function icsAction() { $this->api_user = Mage::getModel('core/variable')->setStoreId(Mage::app()->getStore()->getId())->loadByCode('pmt_api_user')->getValue('text'); $this->api_password = Mage::getModel('core/variable')->setStoreId(Mage::app()->getStore()->getId())->loadByCode('pmt_api_password')->getValue('text'); // get prescription id $prescriptionRepeatId = Mage::app()->getRequest()->getParam('id'); $customer = Mage::getSingleton('customer/session')->getCustomer(); $client = new Zend_Http_Client($this->api_get_prescripton_url . $prescriptionRepeatId); $params = ['pmt_user_id' => $customer->getId(), 'prescription_repeat_id' => $prescriptionRepeatId]; // set some parameters $client->setParameterPost($params); $client->setAuth($this->api_user, $this->api_password, \Zend_Http_Client::AUTH_BASIC); // POST request $result = $client->request(Zend_Http_Client::POST); // decode response $jsonData = json_decode($result->getBody()); // var_dump($prescriptionRepeatId . $customer->getId()); // var_dump($result); // exit(); if (!$jsonData->status == 'success') { // create error message, before redirecting // redirect to prescriptions page $this->redirectDashboard(); } $this->loadLayout(); $block = $this->getLayout()->getBlock('prescriptions_ics'); $block->assign(['repeat' => $jsonData->data->repeats[0], 'product' => $jsonData->data->prescription]); $this->renderLayout(); }
/** * The default action - show the home page */ public function studentAction() { $this->_helper->viewRenderer->setNoRender(false); $request = $this->getRequest(); $department = $request->getParam('department_id'); $degree = $request->getParam('degree_id'); $batch = $request->getParam('batch'); if (isset($degree) and isset($department) and isset($batch)) { $client = new Zend_Http_Client('http://' . CORE_SERVER . '/batch/getbatchstudent' . "?department_id={$department}" . "°ree_id={$degree}" . "&batch_id={$batch}"); $client->setCookie('PHPSESSID', $_COOKIE['PHPSESSID']); $response = $client->request(); if ($response->isError()) { $remoteErr = 'REMOTE ERROR: (' . $response->getStatus() . ') ' . $response->getHeader('Message'); throw new Zend_Exception($remoteErr, Zend_Log::ERR); } else { $jsonContent = $response->getBody($response); $students = Zend_Json::decode($jsonContent); $this->_helper->logger($jsonContent); $this->view->assign('students', $students); $this->view->assign('department', $department); $this->view->assign('degree', $degree); $this->view->assign('batch', $batch); } } }
public function processException(Exception $exception) { if ($exception instanceof Zend_Exception) { $this->_httpClient->getAdapter()->close(); } parent::processException($exception); }
/** * @param Mage_Shipping_Model_Rate_Request $request * @return Mage_Shipping_Model_Rate_Result */ public function collectRates(Mage_Shipping_Model_Rate_Request $request) { /** @var Mage_Shipping_Model_Rate_Result $result */ $result = Mage::getModel('shipping/rate_result'); $totalWeight = 0; foreach ($request->getAllItems() as $item) { $totalWeight += $item->getWeight() * $item->getQty(); } /** @var string $hostname */ $hostname = $this->getConfigData('hostname'); /** @var string $port */ $port = $this->getConfigData('port'); try { $client = new Zend_Http_Client(); $response = $client->setUri("http://{$hostname}:{$port}/")->setRawData(json_encode(['totalWeight' => $totalWeight]))->setEncType('application/json')->request('POST'); switch ($response->getStatus()) { case 200: $responseBody = json_decode($response->getBody()); $result->append($this->_getShippingMethod($responseBody->rate)); break; case 500: // Handle 500 Error break; default: } } catch (Exception $e) { var_dump($e); } return $result; }
public function validate($username, $password) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Options: ' . print_r($this->_options, true)); } $url = isset($this->_options['url']) ? $this->_options['url'] : 'https://localhost/validate/check'; $adapter = new Zend_Http_Client_Adapter_Socket(); $adapter->setStreamContext($this->_options = array('ssl' => array('verify_peer' => isset($this->_options['ignorePeerName']) ? false : true, 'allow_self_signed' => isset($this->_options['allowSelfSigned']) ? true : false))); $client = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => 30)); $client->setAdapter($adapter); $params = array('user' => $username, 'pass' => $password); $client->setParameterPost($params); try { $response = $client->request(Zend_Http_Client::POST); } catch (Zend_Http_Client_Adapter_Exception $zhcae) { Tinebase_Exception::log($zhcae); return Tinebase_Auth::FAILURE; } $body = $response->getBody(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Request: ' . $client->getLastRequest()); } if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Response: ' . $body); } if ($response->getStatus() !== 200) { return Tinebase_Auth::FAILURE; } $result = Tinebase_Helper::jsonDecode($body); if (isset($result['result']) && $result['result']['status'] === true && $result['result']['value'] === true) { return Tinebase_Auth::SUCCESS; } else { return Tinebase_Auth::FAILURE; } }
public function responseAction() { // Get User Configuration $epayphId = Mage::getStoreConfig('payment/epayphPaymentModule/epayphId'); $apiKey = Mage::getStoreConfig('payment/epayphPaymentModule/epayphApiKey'); $apiSecret = Mage::getStoreConfig('payment/epayphPaymentModule/epayphApiSecret'); $url = 'https://epay.ph/api/validateIPN'; $json = json_encode($_POST); $client = new Zend_Http_Client($url); $client->setHeaders(array('Accept: application/json')); $_POST['cmd'] = '_notify-validate'; $client->setParameterPost($_POST); $request = $client->request('POST'); if ($request->getBody() == '{"return":"VERIFIED"}') { $order = Mage::getModel('sales/order'); $order->loadByIncrementId($_POST['invoice']); $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, "Epay.ph Gateway informed us: the payment's Transaction ID is {$_POST['txn_id']}"); $order->sendNewOrderEmail(); $order->setEmailSent(true); $order->save(); Mage::getSingleton('checkout/session')->unsQuoteId(); Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/success', array('_secure' => true)); } else { $this->cancelAction(FALSE, 'Epay.ph signature did not validate'); Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/failure', array('_secure' => true)); } }
protected function getPluginList() { $list = array(); $config = null; if ($proxy = parse_url(sfConfig::get('op_http_proxy'))) { $config = array('adapter' => 'Zend_Http_Client_Adapter_Proxy'); if (isset($proxy['host'])) { $config['proxy_host'] = $proxy['host']; } if (isset($proxy['port'])) { $config['proxy_port'] = $proxy['port']; } if (isset($proxy['user'])) { $config['proxy_user'] = $proxy['user']; } if (isset($proxy['pass'])) { $config['proxy_pass'] = $proxy['pass']; } } try { $client = new Zend_Http_Client('http://' . opPluginManager::OPENPNE_PLUGIN_CHANNEL . '/packages/' . OPENPNE_VERSION . '.yml', $config); $response = $client->request(); if ($response->isSuccessful()) { $list = sfYaml::load($response->getBody()); $list = $this->applyLocalPluginList($list); } else { $str = "Failed to download plugin list."; $this->logBlock($str, 'ERROR'); } } catch (Zend_Http_Client_Adapter_Exception $e) { $str = "Failed to download plugins list."; $this->logBlock($str, 'ERROR'); } return $list; }
/** * 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; } } }
public function logoutAction() { $serverUrl = 'http://' . AUTH_SERVER . self::AUTH_PATH . '/logout'; $client = new Zend_Http_Client($serverUrl, array('timeout' => 30)); try { if (isset($_COOKIE[self::AUTH_SID])) { $moduleName = $this->getRequest()->getModuleName(); $client->setCookie('PHPSESSID', $_COOKIE[self::AUTH_SID]); $client->setCookie('moduleName', $moduleName); $response = $client->request(); if ($response->isError()) { $remoteErr = $response->getStatus() . ' : ' . $response->getMessage() . '<br/>' . $response->getBody(); throw new Zend_Exception($remoteErr, Zend_Log::ERR); } } else { $this->_helper->logger('No remote cookie found'); } } catch (Zend_Exception $e) { echo $e->getMessage(); } if (isset($_COOKIE[self::AUTH_SID])) { preg_match('/[^.]+\\.[^.]+$/', $_SERVER['SERVER_NAME'], $domain); setcookie(self::AUTH_SID, '', time() - 360000, self::AUTH_PATH, ".{$domain['0']}"); } Zend_Auth::getInstance()->clearIdentity(); Zend_Session::destroy(); }
/** * returns the content of this item * * @return string content */ public function getContent() { if ($this->items !== false && $this->valid()) { try { // load entry page $client = new Zend_Http_Client($this->getLink() . '?page=all'); $response = $client->request(); $content = $response->getBody(); $content = utf8_decode($content); // parse content $dom = new Zend_Dom_Query($content); $text = $dom->query('.article'); $innerHTML = ''; // convert innerHTML from DOM to string // taken from http://us2.php.net/domelement (patrick smith) $children = $text->current()->childNodes; foreach ($children as $child) { $tmp_doc = new DOMDocument(); $tmp_doc->appendChild($tmp_doc->importNode($child, true)); if (count($tmp_doc->getElementById('comments')) > 0) { continue; } // convert to text $innerHTML .= @$tmp_doc->saveHTML(); } return $innerHTML; } catch (Exception $e) { // return default content return current($this->items)->get_content(); } } }
/** * */ protected function _request($url, $params, $method = Zend_Http_Client::GET) { $this->_client->setUri($url)->resetParameters(); if (count($params['header'])) { foreach ($params['header'] as $name => $value) { $this->_client->setHeaders($name, $value); } } if (count($params['post'])) { foreach ($params['post'] as $name => $value) { $this->_client->setParameterPost($name, $value); } } if (count($params['get'])) { foreach ($params['get'] as $name => $value) { $this->_client->setParameterGet($name, $value); } } if (count($params['json'])) { //$this->_client->setHeaders('Content-type','application/json'); $rawJson = json_encode($params['json']); //$this->_client->setRawData($rawJson); $this->_client->setRawData($rawJson, 'application/json'); } $response = $this->_client->request($method); $result = $response->getBody(); #echo $result . "\n\n <br>"; return json_decode($result); }
/** * Gibt die Geokoordinaten anhand einer Adresse zurück * * @param string $address Die Adresse die geocodet werden woll * @return array|null $geocode Ein Array mit key 'lat' und 'lng' */ public static function getCoordinates($address) { $q = $address; $q = str_replace(array('ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü', 'ß'), array('ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue', 'ss'), $q); $getParams = array('address' => $q, 'sensor' => 'false'); $httpClientConfig = array('timeout' => 20, 'persistent' => false); $config = Kwf_Registry::get('config'); if ($config->http && $config->http->proxy && $config->http->proxy->host && $config->http->proxy->port) { $httpClientConfig['adapter'] = 'Zend_Http_Client_Adapter_Proxy'; $httpClientConfig['proxy_host'] = $config->http->proxy->host; $httpClientConfig['proxy_port'] = $config->http->proxy->port; } $client = new Zend_Http_Client("http://maps.googleapis.com/maps/api/geocode/json", $httpClientConfig); $client->setMethod(Zend_Http_Client::GET); $client->setParameterGet($getParams); $body = utf8_encode($client->request()->getBody()); try { $result = Zend_Json::decode($body); } catch (Zend_Json_Exception $e) { $e = new Kwf_Exception_Other($e); $e->logOrThrow(); } if (isset($result['results'][0]['geometry']['location']['lat']) && isset($result['results'][0]['geometry']['location']['lng'])) { return array('lat' => $result['results'][0]['geometry']['location']['lat'], 'lng' => $result['results'][0]['geometry']['location']['lng']); } return null; }
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 curlAction() { $base_url = "http://localhost:8080/NRServices/services/hello/hello/jack"; $config = array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => true)); $http_client = new Zend_Http_Client($base_url, $config); $this->view->response = $http_client->request(Zend_Http_Client::GET); }
/** * Process all servers */ protected function _purgeCacheServers(array $headers) { $servers = $this->_getVarnishServers(); if (empty($servers)) { return; } // process all servers foreach ($servers as $server) { // compile url string with scheme, domain/server and port $uri = 'http://' . $server; if ($port = trim(Mage::getStoreConfig(self::XML_PATH_VARNISH_PORT))) { $uri .= ':' . $port; } $uri .= '/'; try { // create HTTP client $client = new Zend_Http_Client(); $client->setUri($uri)->setHeaders($headers)->setConfig(array('timeout' => 15)); // send PURGE request $response = $client->request('PURGE'); // check response if ($response->getStatus() != '200') { throw new Exception('Return status ' . $response->getStatus()); } } catch (Exception $e) { Mage::helper('varnishcache')->debug('Purging on server ' . $server . ' failed (' . $e->getMessage() . ').'); } } }
public function shutdownHttpClient(Zend_Http_Client $httpClient) { if (!isset($this->_restSession)) { $this->_restSession = new Zend_Session_Namespace('App_Rest_Service_' . $this->getRestService()->getServiceName() . '_Session'); } $this->_restSession->cookieJar = $httpClient->getCookieJar(); }
public function buildThumb($mediaID, $thumbURL) { $targetLoc = XenForo_Helper_File::getExternalDataPath() . '/media/' . $mediaID . '.jpg'; $thumbLoc = XenForo_Helper_File::getTempDir() . '/media' . $mediaID; if (substr($thumbURL, 0, 7) == 'http://') { $client = new Zend_Http_Client($thumbURL); $response = $client->request(); $image = $response->getBody(); file_put_contents($thumbLoc, $image); } else { copy($thumbURL, $thumbLoc); } $imageInfo = getimagesize($thumbLoc); if ($image = XenForo_Image_Abstract::createFromFile($thumbLoc, $imageInfo[2])) { $ratio = 160 / 90; $width = $image->getWidth(); $height = $image->getHeight(); if ($width / $height > $ratio) { $image->thumbnail($width, '90'); } else { $image->thumbnail('160', $height); } $width = $image->getWidth(); $height = $image->getHeight(); $offWidth = ($width - 160) / 2; $offHeight = ($height - 90) / 2; $image->crop($offWidth, $offHeight, '160', '90'); $image->output(IMAGETYPE_JPEG, $targetLoc); } if (file_exists($thumbLoc)) { unlink($thumbLoc); } }
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; }
/** * * Меджик метод для вызова удаленных процедур * @param string $methodName * @param array $params * @return array * @author NuR * @throws Zend_Http_Client_Exception * @example * * $data = array( * 'Service' => 'Citizen', 'Method' => 'showOrderList', 'userid' => 1 ); Evil_Json_Rpc::make($data); */ public static function __callStatic($methodName, $params) { $client = self::$_client; if (null == $client) { /** * дефолтный адрес */ if (null == self::$rpcUrl) { $config = Zend_Registry::get('config'); self::$rpcUrl = isset($config['jsonrpc']['url']) ? $config['jsonrpc']['url'] : null; } $options = array('maxredirects' => 5, 'timeout' => 300, 'useragent' => 'Evil_Json_Rpc'); $client = new Zend_Http_Client(self::$rpcUrl); $client->setConfig($options); self::$_client = $client; } $requestParams = array('method' => $methodName, 'params' => $params, 'id' => self::$_requestId++); $request = Zend_Json::encode($requestParams); $client->setHeaders('Content-type', 'application/json'); $client->setRawData($request); $response = $client->request('POST'); try { return Zend_Json::decode($response->getBody()); } catch (Exception $e) { return array('ex' => $e->__toString(), 'response' => $response->getBody()); } }
/** * @see Console\Command\Command */ protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output) { $supportSend = \SystemPref::get('support_send'); if ($supportSend) { $stats = $this->getHelper('container')->getService('stat')->getAll(); $statsUrl = 'http://stat.sourcefabric.org'; $parameters = array('p' => 'newscoop'); $parameters['installation_id'] = $stats['installationId']; $parameters['server'] = \SystemPref::get('support_stats_server'); $parameters['ip_address'] = \SystemPref::get('support_stats_ip_address'); $parameters['ram_used'] = $stats['ramUsed']; $parameters['ram_total'] = \SystemPref::get('support_stats_ram_total'); $parameters['version'] = $stats['version']; $parameters['install_method'] = $stats['installMethod']; $parameters['publications'] = $stats['publications']; $parameters['issues'] = $stats['issues']; $parameters['sections'] = $stats['sections']; $parameters['articles'] = $stats['articles']; $parameters['articles_published'] = $stats['articlesPublished']; $parameters['languages'] = $stats['languages']; $parameters['authors'] = $stats['authors']; $parameters['subscribers'] = $stats['subscribers']; $parameters['backend_users'] = $stats['backendUsers']; $parameters['images'] = $stats['images']; $parameters['attachments'] = $stats['attachments']; $parameters['topics'] = $stats['topics']; $parameters['comments'] = $stats['comments']; $parameters['hits'] = $stats['hits']; $client = new \Zend_Http_Client(); $client->setUri($statsUrl); $client->setParameterPost($parameters); $response = $client->request('POST'); } }
public function logoutAction() { $this->_helper->layout()->disableLayout(); $serverUrl = 'http://' . AUTH_SERVER . self::AUTH_PATH . '/logout'; $client = new Zend_Http_Client($serverUrl, array('timeout' => 30)); try { if (isset($_COOKIE[self::AUTH_SID])) { $moduleName = $this->getRequest()->getModuleName(); $client->setCookie('PHPSESSID', $_COOKIE[self::AUTH_SID]); $client->setCookie('moduleName', $moduleName); $response = $client->request(); if ($response->isError()) { $remoteErr = $remoteErr = 'REMOTE ERROR: (' . $response->getStatus() . ') ' . $response->getMessage() . ', i.e. ' . $response->getHeader('Message'); throw new Zend_Exception($remoteErr, Zend_Log::ERR); } } else { $this->_helper->logger('No remote cookie found. So, not requesting AUTH_SERVER to logout.'); } } catch (Zend_Exception $e) { echo $e->getMessage(); } preg_match('/[^.]+\\.[^.]+$/', $_SERVER['SERVER_NAME'], $domain); if (isset($_COOKIE[self::AUTH_SID])) { setcookie(self::AUTH_SID, '', time() - 360000, self::AUTH_PATH, ".{$domain['0']}"); } if (isset($_COOKIE['last'])) { setcookie('last', '', time() - 36000, '/', ".{$domain['0']}"); } if (isset($_COOKIE['identity'])) { setcookie('identity', '', time() - 36000, '/', ".{$domain['0']}"); } Zend_Auth::getInstance()->clearIdentity(); Zend_Session::destroy(); Zend_Session::regenerateId(); }
/** * @return void */ public function setUp() { $httpClient = new Zend_Http_Client(); $httpClient->setConfig(array('useragent' => 'Zend_Service_Delicious - Unit tests/0.1', 'keepalive' => true)); Zend_Rest_Client::setHttpClient($httpClient); $this->_delicious = new Zend_Service_Delicious(); }
public function makeRequest($payload) { try { $payload = array_merge($payload, $this->_getPayloadBase()); $client = new Zend_Http_Client(self::REMARKETY_URI, $this->_getRequestConfig()); $client->setParameterPost($payload); $response = $client->request(self::REMARKETY_METHOD); Mage::log(var_export($payload, true), null, 'remarkety-ext.log'); Mage::log($response->getStatus(), null, 'remarkety-ext.log'); Mage::log($response->getBody(), null, 'remarkety-ext.log'); $body = (array) json_decode($response->getBody()); Mage::getSingleton('core/session')->setRemarketyLastResponseStatus($response->getStatus() === 200 ? 1 : 0); Mage::getSingleton('core/session')->setRemarketyLastResponseMessage(serialize($body)); switch ($response->getStatus()) { case '200': return $body; case '400': throw new Exception('Request failed. ' . $body['message']); default: throw new Exception('Request to remarkety servers failed (' . $response->getStatus() . ')'); } } catch (Exception $e) { Mage::log($e->getMessage(), null, 'remarkety-ext.log'); throw new Mage_Core_Exception($e->getMessage()); } }
public static function logout() { $blogPath = SJB_Settings::getSettingByName('blog_path'); if (empty($blogPath)) { return; } $url = SJB_System::getSystemSettings('SITE_URL') . $blogPath . '/'; $client = new Zend_Http_Client($url, array('useragent' => SJB_Request::getUserAgent(), 'maxredirects' => 0)); if (isset($_SESSION['wp_cookie_jar'])) { $client->setCookieJar(@unserialize($_SESSION['wp_cookie_jar'])); } try { $response = $client->request(); $matches = array(); if (preg_match('/_wpnonce=([\\w\\d]+)"/', $response->getBody(), $matches)) { $wpnonce = $matches[1]; $url = $url . 'wp-login.php?action=logout&_wpnonce=' . $wpnonce . '&noSJB=1'; $client->setUri($url); $response = $client->request(); foreach ($response->getHeaders() as $key => $header) { if ('set-cookie' == strtolower($key)) { if (is_array($header)) { foreach ($header as $val) { header("Set-Cookie: " . $val, false); } } else { header("Set-Cookie: " . $header, false); } } } } } catch (Exception $ex) { } }
public function viewemailidsAction() { $this->_helper->viewRenderer->setNoRender(true); $this->_helper->layout()->disableLayout(); $member_ids = array(1, 2, 3, 4, 5); $httpClient = new Zend_Http_Client('http://' . CORE_SERVER . '/student/fetchemailids'); //$httpClient->setCookie('PHPSESSID', $_COOKIE['PHPSESSID']); $httpClient->setMethod('POST'); $call_back = 'viewbatchinfo'; $httpClient->setParameterPost(array('member_ids' => $member_ids, 'format' => 'json', 'call_back' => $call_back)); $response = $httpClient->request(); if ($response->isError()) { $remoteErr = 'REMOTE ERROR: (' . $response->getStatus() . ') ' . $response->getHeader('Message') . $response->getBody(); throw new Zend_Exception($remoteErr, Zend_Log::ERR); } else { $jsonContent = $response->getBody($response); Zend_Registry::get('logger')->debug($jsonContent); Zend_Registry::get('logger')->debug(Zend_Json_Decoder::decode($jsonContent)); Zend_Registry::get('logger')->debug(json_decode($jsonContent)); /*Zend_Registry::get('logger')->debug( Zend_Json_Decoder::decode($jsonContent));*/ /*$r = Zend_Json_Decoder::decode($jsonContent); $batch_info = $r['batch_info']; Zend_Registry::get('logger')->debug($batch_info);*/ } }
/** * Gets our JSON response * * @param String $url Url to query * @return Zend_Json $result Our JSON response * */ protected function _getJsonResponse($url) { $client = new Zend_Http_Client($url); $response = $client->request(); $this->_checkResponse($response); return Zend_Json::decode($response->getBody(), Zend_Json::TYPE_OBJECT); }
public function getProperDimensionsPictureUrl($twitterId, $pictureUrl) { $pictureUrl = str_replace('_normal', '', $pictureUrl); $url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'le' . '/' . 'sociallogin' . '/' . 'twitter' . '/' . $twitterId; $filename = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . 'le' . DS . 'sociallogin' . DS . 'twitter' . DS . $twitterId; $directory = dirname($filename); if (!file_exists($directory) || !is_dir($directory)) { if (!@mkdir($directory, 0777, true)) { return null; } } if (!file_exists($filename) || file_exists($filename) && time() - filemtime($filename) >= 3600) { $client = new Zend_Http_Client($pictureUrl); $client->setStream(); $response = $client->request('GET'); stream_copy_to_stream($response->getStream(), fopen($filename, 'w')); $imageObj = new Varien_Image($filename); $imageObj->constrainOnly(true); $imageObj->keepAspectRatio(true); $imageObj->keepFrame(false); $imageObj->resize(150, 150); $imageObj->save($filename); } return $url; }
/** * Sends a request to the REST API service and does initial processing * on the response. * * @param string $op Name of the operation for the request * @param array $query Query data for the request (optional) * @throws Zend_Service_Exception * @return DOMDocument Parsed XML response */ protected function _makeRequest($op, $query = null) { if ($query != null) { $query = array_diff($query, array_filter($query, 'is_null')); $query = '?' . http_build_query($query); } $this->_http->setUri($this->_baseUri . $op . '.do' . $query); $response = $this->_http->request('GET'); if ($response->isSuccessful()) { $doc = new DOMDocument(); $doc->loadXML($response->getBody()); $xpath = new DOMXPath($doc); $list = $xpath->query('/status/code'); if ($list->length > 0) { $code = $list->item(0)->nodeValue; if ($code != 0) { $list = $xpath->query('/status/message'); $message = $list->item(0)->nodeValue; /** * @see Zend_Service_Exception */ require_once 'Zend/Service/Exception.php'; throw new Zend_Service_Exception($message, $code); } } return $doc; } /** * @see Zend_Service_Exception */ require_once 'Zend/Service/Exception.php'; throw new Zend_Service_Exception($response->getMessage(), $response->getStatus()); }
/** * @param $value * @param bool $forceDownload * @return string */ public function getYouTubeImage($value, $forceDownload = false) { $baseDir = Mage::getBaseDir('media'); $localDir = 'gallery' . DS . 'data' . DS . 'thumbnail'; if (is_dir($localDir)) { mkdir($localDir, 0777, true); } $fileName = Varien_File_Uploader::getNewFileName($baseDir . DS . $localDir . DS . $value . '.jpg'); $absPath = $baseDir . DS . $localDir . DS . $fileName; if ($forceDownload || !is_file($absPath)) { try { $url = sprintf('http://img.youtube.com/vi/%s/0.jpg', $value); $client = new Zend_Http_Client($url); $response = $client->request(Zend_Http_Client::GET); if (200 != $response->getStatus()) { Mage::throwException("Can't download youtube thumbnail"); } if (!is_dir($baseDir . DS . $localDir)) { mkdir($baseDir . DS . $localDir, 0777, true); } file_put_contents($absPath, $response->getBody()); } catch (Exception $e) { Mage::logException($e); return false; } } return $localDir . DS . $fileName; }