private function getSintegraHtmlData($num_cnpj, $proxy = '', $url = 'http://www.sintegra.es.gov.br/resultado.php') { try { // Configurações da conexão HTTP com a página $zendHttpConfig = array('adapter' => 'Zend_Http_Client_Adapter_Socket', 'ssltransport' => 'tls', 'timeout' => 15); if (is_array($proxy)) { $zendHttpConfig['proxy_host'] = $proxy['HOST']; $zendHttpConfig['proxy_port'] = $proxy['PORT']; } // Criar o objeto que fara a requisição HTTP $zendHttpClient = new Zend_Http_Client($url); $zendHttpClient->setConfig($zendHttpConfig); // Definir os parâmetros POST enviados a página // Obs: O parâmetro "botao" é obrigatório $zendHttpClient->setParameterPost('num_cnpj', $num_cnpj); $zendHttpClient->setParameterPost('botao', 'Consultar'); // Fazer requisição da página (método POST) $response = $zendHttpClient->request(Zend_Http_Client::POST); // Retornar o corpo da página if ($response->isError()) { throw new Exception($response->getStatus()); } else { return $response->getBody(); } } catch (Exception $e) { $erro = $e->message; die("Erro ao buscar informações no Sintegra. Erro: " . $erro); } }
/** * */ 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); }
/** * 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 publishUpdate($topicUrls) { if (!isset($topicUrls)) { throw new Kwf_Exception('Please specify a topic url'); } if (!is_array($topicUrls)) { $topicUrls = array($topicUrls); } $client = new Zend_Http_Client($this->_hubUrl); $client->setConfig(array('timeout' => 60, 'persistent' => true)); $client->setMethod(Zend_Http_Client::POST); $data = array('hub.mode' => 'publish'); $client->setParameterPost($data); foreach ($topicUrls as $u) { if (!preg_match("|^https?://|i", $u)) { throw new Kwf_Exception('The specified topic url does not appear to be valid: ' . $topicUrl); } $client->setParameterPost('hub.url', $u); } $response = $client->request(); if ($response->isError()) { throw new Kwf_Exception("publishUpdate failed, response status '{$response->getStatus()}' '{$response->getBody()}'"); } return $response; }
public function add($graph, $turtle) { $post_endpoint = array_shift(split("/sparql/", $this->_endpoint)) . "/data/"; $client = new Zend_Http_Client(); $client->setUri($post_endpoint); $client->setParameterPost('graph', $graph); $client->setParameterPost('data', FourStore_Namespace::to_turtle() . $turtle); $client->setParameterPost('mime-type', 'application/x-turtle'); $response = $client->request('POST'); 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(); }
/** * Set Google authentication credentials. * Must be done before trying to do any Google Data operations that * require authentication. * For example, viewing private data, or posting or deleting entries. * * @param string $email * @param string $password * @param string $service * @param Zend_Http_Client $client * @param string $source * @return Zend_Http_Client * @throws Zend_Gdata_AuthException * @throws Zend_Gdata_HttpException */ public function getHttpClient($email, $password, $service = 'xapi', $client = null, $source = self::DEFAULT_SOURCE) { if (!($email && $password)) { throw new Zend_Gdata_AuthException('Please set your Google credentials before trying to authenticate'); } if ($client == null) { $client = new Zend_Http_Client(); } if (!$client instanceof Zend_Http_Client) { throw new Zend_Gdata_HttpException('Client is not an instance of Zend_Http_Client.'); } // Build the HTTP client for authentication $client->setUri(self::CLIENTLOGIN_URI); $client->setConfig(array('maxredirects' => 0, 'strictredirects' => true)); $client->setParameterPost('accountType', 'HOSTED_OR_GOOGLE'); $client->setParameterPost('Email', (string) $email); $client->setParameterPost('Passwd', (string) $password); $client->setParameterPost('service', (string) $service); $client->setParameterPost('source', (string) $source); // Send the authentication request // For some reason Google's server causes an SSL error. We use the // output buffer to supress an error from being shown. Ugly - but works! ob_start(); try { $response = $client->request('POST'); } catch (Zend_Http_Client_Exception $e) { throw new Zend_Gdata_HttpException($e->getMessage(), $e); } ob_end_clean(); // Parse Google's response $goog_resp = array(); foreach (explode("\n", $response->getBody()) as $l) { $l = chop($l); if ($l) { list($key, $val) = explode('=', chop($l), 2); $goog_resp[$key] = $val; } } if ($response->getStatus() == 200) { $headers['authorization'] = 'GoogleLogin auth=' . $goog_resp['Auth']; $client = new Zend_Http_Client(); $client->setConfig(array('strictredirects' => true)); $client->setHeaders($headers); return $client; } elseif ($response->getStatus() == 403) { throw new Zend_Gdata_AuthException('Authentication with Google failed. Reason: ' . (isset($goog_resp['Error']) ? $goog_resp['Error'] : 'Unspecified.')); } }
/** * Send a POST request to the specified URL with the specified payload. * @param string $url * @param string $data * @return string Remote data **/ public function sendPOST($url, $data = array()) { $data['_fake_status'] = '200'; // Zend makes it easier than the others... $this->instance->setConfig(array('useragent' => sprintf(Imgur::$user_agent, Imgur::$key))); $this->instance->setMethod(Zend_Http_Client::POST); $this->instance->setUri($url); $this->instance->setParameterPost($data); try { /** @var Zend_Http_Response */ $response = $this->instance->request(); return $response->getBody(); } catch (Exception $e) { throw new Imgur_Exception("Unknown Failure during HTTP Request", null, $e); } }
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);*/ } }
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()); } }
/** * @description send REST request * @throws Exception * @return string * @author Se# * @version 0.0.3 */ protected function _sendRestRequest($args, $config) { if (!isset($args['action']) && !isset($config['default']['action'])) { throw new Exception(' Missed "action" in the arguments and configuration'); } $do = isset($args['action']) ? $args['action'] : $config['default']['action']; $doConfig = isset($config['actions'][$do]) ? $config['actions'][$do] : array(); $default = isset($config['default']) ? $config['default'] : array(); $url = $this->_getUrl($args, $doConfig, $default); $required = $this->_getRequired($args, $doConfig, $default); $data = isset($args['data']) ? $args['data'] : array(); $data = $this->_checkDataByRequired($data, $required); /** * Convert rub in copicks */ if (isset($data['amount'])) { $data['amount'] = floor($data['amount'] * 100); } $client = new Zend_Http_Client($url); //print_r($data); foreach ($data as $name => $value) { $client->setParameterPost($name, $value); } /** * FIXME: getRawBody() adds additional characters to response * maybe wrong * Zend-Framework 1.11.4 */ //$result = $client->request('POST')->getRawBody(); $result = $client->request('POST')->getBody(); return $result; }
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(); }
/** * @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 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)); } }
public function updateAction() { $form = new Application_Form_Job(); $form->submit->setLabel('Update'); $this->view->form = $form; if ($this->getRequest()->isPost()) { $jobData = $this->getRequest()->getPost(); if ($form->isValid($jobData)) { $jobData['createTime'] = new MongoDate(); $jobData['modifyTime'] = new MongoDate(); $id = (int) $jobData['id']; $client = new Zend_Http_Client('http://api.dm/public/job/' . $id); var_dump($id); $client->setMethod(Zend_Http_Client::DELETE); $client->request(); $client = new Zend_Http_Client('http://api.dm/public/job'); $client->setMethod(Zend_Http_Client::POST); $client->setParameterPost($jobData); $client->request(); $this->_helper->redirector('index'); } else { $form->populate($jobData); } } else { $id = $this->_getParam('id'); $client = new Zend_Http_Client('http://api.dm/public/job/' . $id); $job = json_decode($client->request()->getBody()); $form->populate((array) $job); } }
static function login($request) { $forumPath = SJB_Settings::getSettingByName('forum_path'); if (empty($forumPath)) { return; } $username = $request['username']; $password = $request['password']; $url = SJB_System::getSystemSettings('SITE_URL') . $forumPath . '/ucp.php?mode=login'; $client = new Zend_Http_Client($url, array('useragent' => SJB_Request::getUserAgent())); $client->setCookie($_COOKIE); $client->setMethod(Zend_Http_Client::POST); $client->setParameterPost(array('username' => $username, 'password' => $password, 'login' => 'Login', 'autologin' => '', 'viewonline' => '')); $client->setCookieJar(); try { $ret = $client->request(); foreach ($ret->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) { } }
/** * 決済開始 * @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 getResponse() { $client = new Zend_Http_Client($this->_uri); $client->setMethod(Zend_Http_Client::POST); $client->setParameterPost(array('apiKey' => $this->getApiKey(), 'token' => $this->getToken())); return $client->request(); }
private function _getClient($uri) { $client = new Zend_Http_Client('http://api.dropbox.com/0/token'); $client->setParameterPost(array( 'oauth_consumer_key' => self::DB_CONSUMER_KEY, 'oauth_consumer_secret' => self::DB_CONSUMER_SECRET, 'email' => self::DB_USER, 'password' => self::DB_PASSWORD, )); $response = $client->request('POST'); $data = json_decode($response->getBody()); $token = $data->token; $secret = $data->secret; $tokenObject = new Zend_Oauth_Token_Access(); $tokenObject->setToken($token); $tokenObject->setTokenSecret($secret); $options = array( 'consumerKey' => self::DB_CONSUMER_KEY, 'consumerSecret' => self::DB_CONSUMER_SECRET, ); return $tokenObject->getHttpClient($options, $uri); }
/** * * @throws Exception * @return Varien_Object */ public function process() { $cacheId = $this->_getCacheKey(); $response = $cacheId ? Mage::app()->loadCache($cacheId) : false; if ($response) { $response = unserialize($response); } if (!$response instanceof Varien_Object) { $client = new Zend_Http_Client(self::API_URI, $this->_clientConfig); $client->setMethod(Zend_Http_Client::POST); $client->setParameterPost($this->getParams()); $result = $client->request(); $data = Zend_Json::decode($result->getBody()); if ($data['status'] != 201) { throw new Exception("Premailer failed to run: {$data['message']} #{$data['status']}"); } $htmlClient = new Zend_Http_Client($data['documents']['html'], $this->_clientConfig); $textClient = new Zend_Http_Client($data['documents']['txt'], $this->_clientConfig); $response = new Varien_Object(); $response->setVersion($data['version']); $response->setHtml($htmlClient->request()->getBody()); $response->setText($textClient->request()->getBody()); if ($cacheId) { $data = Mage::app()->saveCache(serialize($response), $cacheId, array(self::CACHE_KEY), 60 * 60); } } return $response; }
public function executeRequest(TingClientHttpRequest $request) { //Transfer request configuration to Zend Client $method = $request->getMethod(); $class = new ReflectionClass(get_class($this->client)); $this->client->setMethod($class->getConstant($method)); $this->client->setUri($request->getBaseUrl()); $this->client->setParameterGet($request->getParameters(TingClientHttpRequest::GET)); $this->client->setParameterPost($request->getParameters(TingClientHttpRequest::POST)); //Check for errors $response = $this->client->request(); if ($response->isError()) { throw new TingClientException('Unable to excecute Zend Framework HTTP request: ' . $response->getMessage(), $response->getStatus()); } return $response->getBody(); }
/** * Function addeditAction for add and edit the user's information. */ public function addeditAction() { $oForm = new Application_Form_AddUsers(); $oForm->submit->setLabel('Save'); if ($this->getRequest()->getParam('id') != '' && is_numeric($this->getRequest()->getParam('id'))) { unset($oForm->password); } if ($this->getRequest()->isPost()) { if ($oForm->isValid($this->getRequest()->getPost())) { $asUserDetail = $oForm->getValues(); $ssUserDetail = Zend_Json_Encoder::encode($asUserDetail); $client = new Zend_Http_Client($this->ssUri . '/addedit'); $client->setConfig(array('timeout' => 30)); $client->setParameterPost(array('ssUserDetail' => $ssUserDetail, 'bIsRest' => true)); $ssResponse = $client->request('POST'); if ($ssResponse->isSuccessful()) { $ssResponseBody = $ssResponse->getBody(); $asResponse = Zend_Json_Decoder::decode($ssResponseBody, Zend_Json::TYPE_ARRAY); if ($asResponse['status'] == 'success') { $this->_redirect('/restclient/list'); } } } } elseif ($this->getRequest()->getParam('id') != '') { $oUser = Model_UsersTable::findUser($this->getRequest()->getParam('id')); $oForm->populate($oUser[0]); } $this->view->snIdUser = $this->getRequest()->getParam('id') ? $this->getRequest()->getParam('id') : ''; $this->view->form = $oForm; }
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; } }
/** * Test that POST data with mutli-dimentional array is properly encoded as * multipart/form-data * */ public function testFormDataEncodingWithMultiArrayZF7038() { $this->_client->setAdapter('Zend\Http\Client\Adapter\Test'); $this->_client->setUri('http://example.com'); $this->_client->setEncType(HTTPClient::ENC_FORMDATA); $this->_client->setParameterPost('test', array( 'v0.1', 'v0.2', 'k1' => 'v1.0', 'k2' => array( 'v2.1', 'k2.1' => 'v2.1.0' ) )); $this->_client->request('POST'); $expectedLines = file(__DIR__ . '/_files/ZF7038-multipartarrayrequest.txt'); $gotLines = explode("\n", $this->_client->getLastRequest()); $this->assertEquals(count($expectedLines), count($gotLines)); while (($expected = array_shift($expectedLines)) && ($got = array_shift($gotLines))) { $expected = trim($expected); $got = trim($got); $this->assertRegExp("/^$expected$/", $got); } }
function spawn($threadId) { $http = new Zend_Http_Client($this->url, array('timeout' => 3, 'keepalive' => false)); $i = 20; do { if ($i-- < 0) { throw new Exception("To many hash generation failed"); } $salt = rand(1, 1000); $key = time(); $privKey = rand(100000, 999999); $hash = md5("{$salt}{$privKey}{$key}"); } while (!$this->storeRequestKey($hash, $privKey)); $http->setParameterPost('hash', $hash)->setParameterPost('key', $key)->setParameterPost('salt', $salt)->setParameterPost('thread', $threadId); try { $body = $http->request(Zend_Http_Client::POST)->getBody(); $response = @Zend_Json::decode($body); if ($response) { return @$response['success']; } } catch (Exception $e) { // timeout // don't know, assume true X_Debug::w("Request timeout"); return true; } }
/** * 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; } }
public static function login($request) { $blogPath = SJB_Settings::getSettingByName('blog_path'); if (empty($blogPath)) { return; } $username = $request['username']; $password = $request['password']; $userInfo = SJB_UserManager::getUserInfoByUserName($username); $userInfo = $userInfo ? base64_encode(serialize($userInfo)) : false; $url = SJB_System::getSystemSettings('SITE_URL') . $blogPath . '/wp-login.php'; $client = new Zend_Http_Client($url, array('useragent' => SJB_Request::getUserAgent(), 'maxredirects' => 0)); $client->setCookieJar(); $client->setCookie($_COOKIE); $client->setMethod(Zend_Http_Client::POST); $client->setParameterPost(array('log' => $username, 'pwd' => $password, 'noSJB' => 1, 'userInfo' => $userInfo, 'wp-submit' => 'Log in')); try { $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); } } } $_SESSION['wp_cookie_jar'] = @serialize($client->getCookieJar()); } catch (Exception $ex) { } }
/** * Add an media file to mobypicture. * * @param string $filepath * @param string $title * @param string $description * @param string $format * @param array $options * @throws Zend_Http_Client_Exception if HTTP request fails or times out * @throws HausDesign_Service_Mobypicture_Exception If username is not set * @throws HausDesign_Service_Mobypicture_Exception If file can't read. * @throws HausDesign_Service_Mobypicture_Exception If file is larger then 16M. * @return mixed */ public function postMedia($filepath, $title, $description = '', $format = self::FORMAT_XML, $options = array()) { if (null == $this->_username || null == $this->_password) { throw new HausDesign_Service_Mobypicture_Exception('Username and password must be set.'); } if (!is_readable($filepath)) { throw new HausDesign_Service_Mobypicture_Exception('File can\'t be read.'); } if (filesize($filepath) > 16777216) { throw new HausDesign_Service_Mobypicture_Exception('File can\'t be larger then 16M.'); } if (strlen($title) > self::MAX_LENGTH_TITLE) { $title = substr($title, 0, self::MAX_LENGTH_TITLE); } if (strlen($description) > self::MAX_LENGTH_DESCRIPTION) { $title = substr($title, 0, self::MAX_LENGTH_DESCRIPTION); } $options['t'] = $title; if ($description) { $options['d'] = $description; } $this->_localHttpClient->resetParameters(); $this->_localHttpClient->setUri(self::MOBYPICTURE_API); $this->_localHttpClient->setParameterPost('action', 'postMediaUrl'); $this->_localHttpClient->setFileUpload($filepath, 'i'); $this->_localHttpClient->setParameterPost('u', $this->_username); $this->_localHttpClient->setParameterPost('p', $this->_password); $this->_localHttpClient->setParameterPost('k', $this->_apiKey); $this->_localHttpClient->setParameterPost('format', $format); $this->_localHttpClient->setConfig(array('timeout' => 30)); foreach ($options as $option => $value) { $this->_localHttpClient->setParameterPost($option, $value); } return $this->_parseContent($this->_localHttpClient->request('GET')->getBody(), $format); }
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; } }