public function mailgunRequest($type, $domain, $apiKey, $data, $method = Zend_Http_Client::GET, $uriOveride = false) { $client = new Zend_Http_Client(); $client->setAuth("api", $apiKey); $client->setMethod($method); if ($uriOveride) { $client->setUri($uriOveride); } else { $client->setUri($this->apiUrl . $domain . "/" . $type); } if ($method == Zend_Http_Client::POST) { foreach ($data as $key => $value) { $client->setParameterPost($key, $value); } } else { foreach ($data as $key => $value) { $client->setParameterGet($key, $value); } } try { $response = $client->request(); if ($response->getStatus() == 200) { return json_decode($response->getBody()); } else { throw new Zend_Http_Exception("Error connecting to MailGun API. Returned error code: " . $response->getStatus() . " --- " . $response->getBody()); } } catch (Exception $e) { Mage::logException($e); return false; } }
/** * */ 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); }
/** * 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 authenticate($user = null, $password = null) { $cfg = $this->config; $user = $user ? $user : $cfg->getUser(); $password = $password ? $password : $cfg->getPassword(); $url = 'http://' . $cfg->getHost() . ':' . $cfg->getPort() . '/_session'; $response = $this->request->setUri($url)->resetParameters()->setHeaders('Content-Type', 'application/x-www-form-urlencoded')->setRawData("name={$user}&password={$password}")->request(\Zend_Http_Client::POST); return json_decode($response->getBody(), true); }
/** * 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(); }
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(); }
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); }
/** * Enter description here... * * @param Zend_Service_PayPal_Data_AuthInfo $auth_info * @param Zend_Http_Client $httpClient */ public function __construct(Zend_Service_PayPal_Data_AuthInfo $authInfo, $uri = self::SERVICE_URI, $httpClient = null) { $this->authInfo = $authInfo; if ($httpClient instanceof Zend_Http_Client) { $this->httpClient = $httpClient; } else { // Create and configure the default HTTP client $this->httpClient = new Zend_Http_Client(); $this->httpClient->setConfig(array('adapter' => 'Zend_Http_Client_Adapter_Socket', 'maxredirects' => 0, 'timeout' => 60, 'ssltransport' => 'ssl')); } $this->httpClient->setUri($uri); }
/** * {@inheritdoc} */ public function send($url, $payload) { try { $response = $this->client->setUri($url)->setHeaders($this->getHeaders())->setRawData($payload)->request('POST'); } catch (HttpClientAdapterException $e) { throw TcpException::transportError($e); } catch (HttpClientException $e) { throw TcpException::transportError($e); } if ($response->getStatus() !== 200) { throw HttpException::httpError($response->getMessage(), $response->getStatus()); } return $response->getBody(); }
/** * 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(); }
/** * @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'); } }
/** * Get Sizing Chart content from remote resource */ public function getNewSizingChartContent($ptn) { if ($ptn) { $uri = Mage::getStoreConfig('yk_config/asc/url') . $ptn; $client = new Zend_Http_Client(); $client->setUri($uri); $response = $client->request(); if ($html = $response->getBody()) { $dom = new Zend_Dom_Query(); $dom->setDocumentHtml($html); $results = $dom->query(Mage::getStoreConfig('yk_config/asc/container')); if (count($results)) { foreach ($results as $result) { $innerHTML = ''; $children = $result->childNodes; foreach ($children as $child) { $innerHTML .= $child->ownerDocument->saveHTML($child); } return $innerHTML; } } } } return false; }
/** * Action - url * check on the availability of URL * * * Access to the action is possible in the following paths: * - /utility/url * * @return void */ public function urlAction() { // Получим обьект запроса $request = $this->getRequest(); $params = $request->getParams(); $type_action = $params['type_action']; if ($this->_isAjaxRequest) { $jsons = array(); try { if ($type_action == 'check_exist') { $url = $params['url']; $client = new Zend_Http_Client(); $client->setUri($url); $client->setConfig(array('maxredirects' => 0, 'timeout' => 5)); //Zend_Http_Request:: $response = $client->request(); //'CONNECT' if ($response->isSuccessful()) { $jsons['result'] = TRUE; } else { $jsons['result'] = FALSE; } } $this->sendJson($jsons); } catch (Exception $exc) { $jsons['result'] = FALSE; $this->sendJson($jsons); return; } } }
/** * 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); } }
protected function execute($arguments = array(), $options = array()) { require_once realpath(dirname(__FILE__) . '/../../../../lib/vendor/OAuth/OAuth.php'); new sfDatabaseManager($this->configuration); sfContext::createInstance($this->createConfiguration('pc_frontend', 'prod'), 'pc_frontend'); $consumerKey = isset($options['consumer-key']) && $options['consumer-key'] ? $options['consumer-key'] : opOpenSocialToolKit::getOAuthConsumerKey(); $consumer = new OAuthConsumer($consumerKey, null, null); $signatureMethod = new OAuthSignatureMethod_RSA_SHA1_opOpenSocialPlugin(); $httpOptions = opOpenSocialToolKit::getHttpOptions(); $queueGroups = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueueGroups(); $limitRequest = (int) $options['limit-request']; $limitRequestApp = (int) $options['limit-request-app']; $allRequest = 0; foreach ($queueGroups as $group) { $application = Doctrine::getTable('Application')->find($group[0]); $links = $application->getLinks(); $linkHash = array(); foreach ($links as $link) { if (isset($link['rel']) && isset($link['href'])) { $method = isset($link['method']) ? strtolower($link['method']) : ''; $method = 'post' !== $method ? 'get' : 'post'; $linkHash[$link['rel']] = array('href' => $link['href'], 'method' => $method); } } $queues = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueuesByApplicationId($group[0], $limitRequestApp); foreach ($queues as $queue) { if (!isset($linkHash[$queue->getName()])) { $queue->delete(); continue; } $href = $linkHash[$queue->getName()]['href']; $method = $linkHash[$queue->getName()]['method']; $oauthRequest = OAuthRequest::from_consumer_and_token($consumer, null, $method, $href, $queue->getParams()); $oauthRequest->sign_request($signatureMethod, $consumer, null); $client = new Zend_Http_Client(); if ('post' !== $method) { $method = 'get'; $client->setMethod(Zend_Http_Client::GET); $href .= '?' . $oauthRequest->to_postdata(); } else { $client->setMethod(Zend_Http_Client::POST); $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED); $client->setRawData($oauthRequest->to_postdata()); } $client->setConfig($httpOptions); $client->setUri($href); $client->setHeaders($oauthRequest->to_header()); $response = $client->request(); if ($response->isSuccessful()) { $queue->delete(); } $allRequest++; if ($limitRequest && $limitRequest <= $allRequest) { break 2; } } $application->free(true); $queues->free(true); } }
/** * * Private method that queries REST service and returns SimpleXML response set * @param string $service name of Audioscrobbler service file we're accessing * @param string $params parameters that we send to the service if needded * @return SimpleXML result set */ private function getInfo($service, $params = NULL) { $service = (string) $service; $params = (string) $params; try { if ($params == "") { $this->_client->setUri("http://ws.audioscrobbler.com{$service}"); } else { $this->_client->setUri("http://ws.audioscrobbler.com{$service}?{$params}"); } if ($this->testing == TRUE) { $adapter = new Zend_Http_Client_Adapter_Test(); $this->_client->setConfig(array('adapter' => $adapter)); $adapter->setResponse($this->testing_response); } $request = $this->_client->request(); $response = $request->getBody(); if ($response == 'No such path') { throw new Zend_Http_Client_Exception('Could not find: ' . $this->_client->getUri()); } else { if ($response == 'No user exists with this name.') { throw new Zend_Http_Client_Exception('No user exists with this name'); } else { if ($request->isError()) { throw new Zend_Http_Client_Exception('The web service ' . $this->_client->getUri() . ' returned the following status code: ' . $response->getStatus()); } else { return simplexml_load_string($response); } } } } catch (Zend_Http_Client_Exception $e) { throw $e; } }
/** * @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 delete($graph) { $client = new Zend_Http_Client(); $client->setUri($this->_endpoint . $graph); $response = $client->request('DELETE'); return $response; }
/** * @param \ShipperHQ\WS\WebServiceRequest $requestObj * @param $webServicePath * @return mixed|null */ public function sendAndReceive(WebServiceRequestInterface $requestObj, $webServiceURL, $timeout = 30) { $jsonRequest = json_encode($requestObj); $debugRequest = $requestObj; $debugRequest->credentials->password = null; $jsonDebugRequest = json_encode($debugRequest, JSON_PRETTY_PRINT); $debugData['json_request'] = $jsonDebugRequest; $debugData['url'] = $webServiceURL; $responseBody = ''; try { $client = new \Zend_Http_Client(); $client->setUri($webServiceURL); $client->setConfig(['maxredirects' => 0, 'timeout' => $timeout]); $client->setRawData($jsonRequest, 'application/json'); $response = $client->request(\Zend_Http_Client::POST); if (!is_null($response)) { $responseBody = $response->getBody(); } $debugData['response'] = $responseBody; $responseBody = json_decode($responseBody, false); } catch (\Exception $e) { $debugData['error'] = ['error' => $e->getMessage(), 'code' => $e->getCode()]; $debugData['response'] = ''; } $result = ['result' => $responseBody, 'debug' => $debugData]; return $result; }
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(); }
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) { } }
/** * POST xml data to Google with authorization headers set * * @param string $xml * @param string $uri POST URI * @return Zend_Http_Response */ public function post($xml, $uri = null) { if ($uri == null) { $uri = $this->_defaultPostUri; } if ($uri == null) { throw Zend::exception('Zend_Gdata_Exception', 'You must specify an URI to which to post.'); } $this->_httpClient->setUri($uri); $this->_httpClient->setConfig(array('maxredirects' => 0)); $this->_httpClient->setRawData($xml, 'application/atom+xml'); $response = $this->_httpClient->request('POST'); //set "S" cookie to avoid future redirects. if ($cookie = $response->getHeader('Set-cookie')) { list($cookieName, $cookieValue) = explode('=', $cookie, 2); $this->_httpClient->setCookie($cookieName, $cookieValue); } if ($response->isRedirect()) { //this usually happens. Re-POST with redirected URI. $this->_httpClient->setUri($response->getHeader('Location')); $this->_httpClient->setRawData($xml, 'application/atom+xml'); $response = $this->_httpClient->request('POST'); } if (!$response->isSuccessful()) { throw Zend::exception('Zend_Gdata_Exception', 'Post to Google failed.'); } return $response; }
/** * @return Zend_Http_Client */ protected function getHttpClient($url = null) { if ($this->http === null) { $this->http = new Zend_Http_Client(); // maybe it's better to offuscate it //$this->http->setHeaders('User-Agent', "vlc-shares/".X_VlcShares::VERSION." hulu/".X_VlcShares_Plugins_Hulu::VERSION); $this->http->setHeaders(array('User-Agent' => 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0)', 'Accept' => '*/*')); // enable cookies $this->http->setCookieJar(true); /* $this->http->setAdapter("Zend_Http_Client_Adapter_Proxy"); $this->http->setConfig(array( //'proxy_host' => "141.219.252.132", //'proxy_port' => '3128' //'proxy_host' => '131.179.150.72', //'proxy_port' => '3128', //'proxy_host' => '129.82.12.188', //'proxy_port' => '3128', //'proxy_host' => '130.49.221.40', //'proxy_port' => '3128', 'proxy_host' => '65.55.73.222', 'proxy_port' => '80' )); */ } if ($url !== null) { $this->http->setUri($url); } return $this->http; }
/** * 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; } }
/** * 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); }
/** * 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 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) { } }
/** * 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); }
/** * Performs HTTP request to given $url using given HTTP $method. * Send additinal query specified by variable/value array, * On success returns HTTP response without headers, false on failure. * * @param string $url OpenID server url * @param string $method HTTP request method 'GET' or 'POST' * @param array $params additional qwery parameters to be passed with * @param int &$staus HTTP status code * request * @return mixed */ protected function _httpRequest($url, $method = 'GET', array $params = array(), &$status = null) { $client = $this->_httpClient; if ($client === null) { $client = new Zend_Http_Client($url, array('maxredirects' => 4, 'timeout' => 15, 'useragent' => 'Zend_OpenId')); } else { $client->setUri($url); } $client->resetParameters(); if ($method == 'POST') { $client->setMethod(Zend_Http_Client::POST); $client->setParameterPost($params); } else { $client->setMethod(Zend_Http_Client::GET); $client->setParameterGet($params); } try { $response = $client->request(); } catch (Exception $e) { $this->_setError('HTTP Request failed: ' . $e->getMessage()); return false; } $status = $response->getStatus(); $body = $response->getBody(); if ($status == 200 || $status == 400 && !empty($body)) { return $body; } else { $this->_setError('Bad HTTP response'); return false; } }
/** * Looks up an user using the given service data. * * @param string $service Service to look up with. * @param mixed $data Data relevant to the service. * @return Qwerly_API_Response|null * @throws Qwerly_API_ErrorException * @throws Qwerly_API_NotFoundException */ private function _lookUpBy($service, $data) { $batch = false; $urlFormat = self::$URLS[$service]; if (is_array($data)) { $data = implode(',', $data); $batch = true; } $url = self::BASE_URL . sprintf($urlFormat, urlencode($data)) . sprintf(self::API_KEY, $this->_apiKey); $this->_client->setUri($url); $request = $this->_client->request(); $data = json_decode($request->getBody(), true); if ($request->getStatus() == self::TRY_AGAIN_LATER_CODE || $request->getStatus() == self::NOT_FOUND_CODE) { throw new \Thin\Exception($data['message'], $data['status']); } else { if ($request->getStatus() == 400) { throw new \Thin\Exception($data['message'], $data['status']); } else { if (!$request->isSuccessful()) { throw new \Thin\Exception($request->getBody()); } } } if ($batch) { return new \Thin\Html\Qwerly\Batch($data); } else { return new \Thin\Html\Qwerly\User($data); } }