request() public method

Send the HTTP request and return an HTTP response object
public request ( string $method = null ) : Zend_Http_Response
$method string
return Zend_Http_Response
 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) {
     }
 }
Esempio n. 2
0
 static function logout()
 {
     SessionStorage::destroy(SJB_Session::getSessionId());
     $forumPath = SJB_Settings::getSettingByName('forum_path');
     if (empty($forumPath)) {
         return;
     }
     $url = SJB_System::getSystemSettings('SITE_URL') . $forumPath . '/';
     $client = new Zend_Http_Client($url, array('useragent' => SJB_Request::getUserAgent()));
     $client->setCookie($_COOKIE);
     $client->setCookieJar();
     try {
         $response = $client->request();
         $matches = array();
         if (preg_match('/\\.\\/ucp.php\\?mode=logout\\&sid=([\\w\\d]+)"/', $response->getBody(), $matches)) {
             $sid = $matches[1];
             $client->setUri($url . 'ucp.php?mode=logout&sid=' . $sid);
             $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) {
     }
 }
Esempio n. 3
0
 /**
  * Given a url, use the provider to pull from the url
  *
  * @param $url
  *
  * @return string
  */
 protected function _getXml($url)
 {
     if (is_null($this->_xmlProvider)) {
         $this->setXmlProvider(new Varien_Http_Adapter_Curl());
     }
     $this->_client->setUri($url ? $url : 'http');
     $response = $this->_client->request(Zend_Http_Client::GET);
     return $response->getBody();
 }
Esempio n. 4
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();
 }
Esempio n. 5
0
 /**
  * {@inheritdoc}
  */
 protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $this->client->resetParameters(true)->setConfig(array('httpversion' => $internalRequest->getProtocolVersion(), 'timeout' => $this->getConfiguration()->getTimeout(), 'maxredirects' => 0))->setUri($url = (string) $internalRequest->getUrl())->setMethod($internalRequest->getMethod())->setHeaders($this->prepareHeaders($internalRequest))->setRawData($this->prepareBody($internalRequest));
     try {
         $response = $this->client->request();
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse($response->getStatus(), $response->getMessage(), $response->getVersion(), $response->getHeaders(), BodyNormalizer::normalize(function () use($response) {
         return $response instanceof \Zend_Http_Response_Stream ? $response->getStream() : $response->getBody();
     }, $internalRequest->getMethod()));
 }
Esempio n. 6
0
 public function sayRoom($room, $message, $type = 'TextMessage')
 {
     $uri = 'https://' . $this->subdomain . '.campfirenow.com/room/' . $room . '/speak.json';
     $this->client->setUri($uri);
     $params['message']['type'] = $type;
     $params['message']['body'] = $message;
     $this->client->setHeaders('Content-type', 'application/json');
     $this->client->setRawData(json_encode($params));
     $this->client->setMethod(Zend_Http_Client::POST);
     $response = $this->client->request();
     return (bool) ($response->getStatus() == 200);
 }
Esempio n. 7
0
 /**
  * Осуществляет запроса к OpenId-провайдеру
  */
 protected function _request()
 {
     try {
         $responce = $this->_client->request($this->_options['method']);
         $body = $responce->getBody();
     } catch (Exception $e) {
         throw new Exception('OpenId provider does not respond for request' . $this->_options['query'], '500');
     }
     $userData = $this->_normalizeUserData($body);
     if (!$this->_isValid($userData)) {
         throw new Exception('Error recieved from OpenId-provider', 500);
     }
     return $userData;
 }
Esempio n. 8
0
 public static function getData($url, $accesstoken, $redirects = true)
 {
     $client = new \Zend_Http_Client();
     $client->setUri($url);
     $client->setParameterGet('access_token', $accesstoken);
     if ($redirects) {
         $response = $client->request('GET')->getBody();
     } else {
         $client->setConfig(array('maxredirects' => 0));
         $response = $client->request()->getHeader('Location');
         $client->setConfig(array('maxredirects' => 5));
     }
     return $response;
 }
 /**
  * Execute CheddarGetter API request
  *
  * @param string $url Url to the API action
  * @param string $username Username
  * @param string $password Password
  * @param array|null $args HTTP post key value pairs
  * @return string Body of the response from the CheddarGetter API
  * @throws Zend_Http_Client_Exception A Zend_Http_Client_Exception may
  * be thrown under a number of conditions but most likely if the tcp socket
  * fails to connect.
  */
 public function request($url, $username, $password, array $args = null)
 {
     // reset
     $this->_client->setUri($url);
     $this->_client->resetParameters();
     $this->_client->setMethod(Zend_Http_Client::GET);
     $this->_client->setAuth($username, $password);
     if ($args) {
         $this->_client->setMethod(Zend_Http_Client::POST);
         $this->_client->setParameterPost($args);
     }
     $response = $this->_client->request();
     return $response->getBody();
 }
Esempio n. 10
0
 /**
  * get an array with standard information about the playable
  * @param string $url the hoster page or resource ID
  * @param boolean $isId
  * @return array format:
  * 		array(
  * 			'title' => TITLE
  * 			'description' => DESCRIPTION
  * 			'length' => LENGTH
  * 			...
  * 		)
  */
 function getPlayableInfos($url, $isId = true)
 {
     if (!$isId) {
         $url = $this->getResourceId($url);
     }
     // use cached values
     if (array_key_exists($url, $this->info_cache)) {
         return $this->info_cache[$url];
     }
     // use the api
     $http = new Zend_Http_Client("http://www.movshare.net/video/{$url}", array('headers' => array('User-Agent' => "vlc-shares/" . X_VlcShares::VERSION . " movshare/" . X_VlcShares_Plugins_MovShare::VERSION)));
     // this allow to store the cookie for multiple requests
     $http->setCookieJar(true);
     $datas = $http->request()->getBody();
     if (strpos($datas, 'We need you to prove you\'re human') !== false) {
         // I have to do the request, again
         $datas = $http->request()->getBody();
         if (strpos($datas, 'We need you to prove you\'re human') !== false) {
             throw new Exception("Hoster requires interaction");
         }
     }
     // now datas should contains the html
     // time to grab some informations
     if (strpos($datas, 'This file no longer exists on our servers') !== false) {
         throw new Exception("Invalid ID {{$url}}", self::E_ID_INVALID);
     }
     $matches = array();
     if (!preg_match('/Title\\: <\\/strong>(?P<title>[^\\<]+)</', $datas, $matches)) {
         $title = "";
     }
     $title = $matches['title'];
     $matches = array();
     if (!preg_match('/Description\\: <\\/strong>(?P<description>[^\\<]+)</', $datas, $matches)) {
         $description = '';
     }
     $description = $matches['description'];
     $length = 0;
     $thumbnail = '';
     $matches = array();
     if (!preg_match('/param name\\=\\"src\\" value\\=\\"(?P<video>[^\\"]+)\\"/', $datas, $matches)) {
         $video = '';
     }
     $video = $matches['video'];
     $infos = array('title' => $title, 'description' => $description, 'length' => $length, 'thumbnail' => $thumbnail, 'url' => $video);
     // add in cache
     $this->info_cache[$url] = $infos;
     return $infos;
 }
 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();
 }
Esempio n. 12
0
 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;
 }
Esempio n. 13
0
 /**
  * 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();
         }
     }
 }
Esempio n. 14
0
 /**
  * @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');
     }
 }
Esempio n. 15
0
 /**
  * Test that lines that might be evaluated as boolean false do not break
  * the reading prematurely.
  *
  * @see http://framework.zend.com/issues/browse/ZF-4238
  *
  */
 public function testZF4238FalseLinesInResponse()
 {
     $this->client->setUri($this->baseuri . 'ZF4238-zerolineresponse.txt');
     $got = $this->client->request()->getBody();
     $expected = $this->_getTestFileContents('ZF4238-zerolineresponse.txt');
     $this->assertEquals($expected, $got);
 }
Esempio n. 16
0
 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());
     }
 }
Esempio n. 17
0
 /**
  * Load XML response from Correios
  * 
  * @param string $number Tracking Code
  * 
  * @throws Zend_Http_Client_Adapter_Exception
  * 
  * @link http://www.correios.com.br/para-voce/correios-de-a-a-z/pdf/rastreamento-de-objetos/
  * Manual_SROXML_28fev14.pdf
  * 
  * @return SimpleXMLElement
  */
 public function request($number)
 {
     $client = new Zend_Http_Client($this->getConfigData("url_sro_correios"));
     $client->setParameterPost('Usuario', $this->getConfigData('sro_username'));
     $client->setParameterPost('Senha', $this->getConfigData('sro_password'));
     $client->setParameterPost('Tipo', $this->getConfigData('sro_type'));
     $client->setParameterPost('Resultado', $this->getConfigData('sro_result'));
     $client->setParameterPost('Objetos', $number);
     try {
         $response = $client->request(Zend_Http_Client::POST)->getBody();
         if (empty($response)) {
             throw new Zend_Http_Client_Adapter_Exception("Empty response");
         }
         libxml_use_internal_errors(true);
         $this->_xml = simplexml_load_string($response);
         if (!$this->_xml || !isset($this->_xml->objeto)) {
             throw new Zend_Http_Client_Adapter_Exception("Invalid XML");
         }
     } catch (Zend_Http_Exception $e) {
         Mage::log("{$e->getMessage()}");
         Mage::log("TRACKING: {$number}");
         Mage::log("RESPONSE: {$response}");
         return false;
     }
     return $this;
 }
 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));
     }
 }
Esempio n. 19
0
 /**
  * Perform an API request to Amazon
  *
  * @param string $path
  *    REST path e.g. user/profile
  * @param array $postParams
  *    POST paramaters
  * @return result
  */
 public function request($path, array $postParams = array())
 {
     $sandbox = Mage::getStoreConfig('payment/amazon_payments/sandbox') ? 'sandbox.' : '';
     $client = new Zend_Http_Client();
     $client->setUri("https://api.{$sandbox}amazon.com/{$path}");
     $client->setConfig($this->http_client_config);
     $client->setMethod($postParams ? 'POST' : 'GET');
     foreach ($postParams as $key => $value) {
         $client->setParameterPost($key, $value);
     }
     try {
         $response = $client->request();
     } catch (Zend_Http_Client_Adapter_Exception $e) {
         Mage::logException($e);
         return;
     }
     $data = $response->getBody();
     try {
         $data = Zend_Json::decode($data, true);
     } catch (Exception $e) {
         Mage::logException($e);
     }
     if (empty($data)) {
         return false;
     } else {
         return $data;
     }
 }
Esempio n. 20
0
 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;
 }
Esempio n. 22
0
 /**
  * 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}" . "&degree_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);
         }
     }
 }
Esempio n. 23
0
 /**
  * Post a comment.
  *
  * @param string $code
  * @param string $message
  * @param array $options
  * @param string $format
  */
 public function postComment($code, $message, $options = array(), $format = self::FORMAT_XML)
 {
     $defaults = array('name' => '', 'email' => '', 'tweet' => 0);
     $options = array_merge($defaults, $options);
     if (!strlen($options['name']) && !strlen($options['email'])) {
         if (null == $this->_username && null == $this->_password) {
             throw new HausDesign_Service_Mobypicture_Exception('name and email or username and password should by defined');
         }
     }
     $this->_localHttpClient->resetParameters();
     $this->_localHttpClient->setUri(self::MOBYPICTURE_API);
     $this->_localHttpClient->setParameterGet('action', 'postComment');
     if (!strlen($options['name']) && !strlen($options['email'])) {
         $this->_localHttpClient->setParameterGet('u', $this->_username);
         $this->_localHttpClient->setParameterGet('p', $this->_password);
     }
     $this->_localHttpClient->setParameterGet('k', $this->_apiKey);
     $this->_localHttpClient->setParameterGet('tinyurl_code ', $code);
     $this->_localHttpClient->setParameterGet('message', $code);
     $this->_localHttpClient->setParameterGet('format', $format);
     foreach ($options as $option => $value) {
         $this->_localHttpClient->setParameterGet($option, $value);
     }
     return $this->_parseContent($this->_localHttpClient->request('GET')->getBody(), $format);
 }
Esempio n. 24
0
 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);*/
     }
 }
Esempio n. 25
0
 /**
  * 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);
 }
 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;
 }
Esempio n. 27
0
 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);
 }
 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();
 }
Esempio n. 29
0
 /**
  * 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());
 }
 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;
     }
 }