A cookie jar is an object that holds and maintains cookies across HTTP requests
and responses.
public setCookieJar ( Zend_Http_CookieJar | boolean $cookiejar = true ) : Zend_Http_Client | ||
$cookiejar | Zend_Http_CookieJar | boolean | Existing cookiejar object, true to create a new one, false to disable |
return | Zend_Http_Client |
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) { } }
/** * Fetches the contents of a URL. * * @param string $url * @param bool $useCookieJar * @param bool $ignoreHttpError * @return string * @throws Yadda_Feed_Exception */ protected function _fetch($url, $useCookieJar = false, $ignoreHttpError = false) { $config = Zend_Registry::get('config'); $retries = 3; // try 3 times $client = new Zend_Http_Client($url, array('timeout' => 30, 'useragent' => $config->userAgent)); if ($useCookieJar === true) { $client->setCookieJar(true); } for ($i = 0; $i < $retries; $i++) { try { $response = $client->request(); if ((bool) $ignoreHttpError === false) { if ($response->getStatus() != 200) { throw new Zend_Http_Exception('Didn\'t get 200 OK.'); } } // request was successful, so break out of retry loop break; } catch (Zend_Exception $e) { // if we're on the last retry, throw an exception if ($i == $retries - 1) { throw new Yadda_Feed_Exception('Error fetching URL: ' . (string) $e); } } // retry! sleep(1); } return $response->getBody(); }
function wrapper_getFirstImageFromContent($section_id, $exec_droplets = true) { global $database; $settings = $database->query(sprintf('SELECT `url` FROM `%smod_wrapper` WHERE section_id = "%d"', CAT_TABLE_PREFIX, $section_id)); if ($settings->numRows()) { $row = $settings->fetchRow(); ini_set('include_path', CAT_PATH . '/modules/lib_zendlite'); include 'Zend/Http/Client.php'; $client = new Zend_Http_Client($row['url'], array('timeout' => '30', 'adapter' => 'Zend_Http_Client_Adapter_Proxy')); $client->setCookieJar(); $client->setHeaders(array('Pragma' => 'no-cache', 'Cache-Control' => 'no-cache', 'Accept-Encoding' => '')); try { $response = $client->request(Zend_Http_Client::GET); if ($response->getStatus() == '200') { $content = $response->getBody(); if ($content != '') { $doc = new DOMDocument(); libxml_use_internal_errors(true); // avoid HTML5 errors $doc->loadHTML($content); libxml_clear_errors(); $img = $doc->getElementsByTagName('img'); return $img->item(0)->getAttribute('src'); } } } catch (Zend_HTTP_Client_Adapter_Exception $e) { } return NULL; } }
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) { } }
/** * @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; }
/** * Make sure using an invalid cookie jar object throws an exception * */ public function testSetInvalidCookieJar() { $this->setExpectedException( 'Zend\Http\Client\Exception\InvalidArgumentException', 'Invalid parameter type passed as CookieJar'); $this->_client->setCookieJar('cookiejar'); }
/** * Make sure using an invalid cookie jar object throws an exception * */ public function testSetInvalidCookieJar() { try { $this->client->setCookieJar('cookiejar'); $this->fail('Invalid cookiejar exception was not thrown'); } catch (Exception $e) { // We're good } }
public function __construct($uri, $email, $password, $consumer_key, $consumer_secret, $oauth_realm, $cookieJarFile = './OX3_Api_CookieJar.txt', $sso = array(), $proxy = array()) { parent::__construct($uri); $aUrl = parse_url($uri); if (empty($sso)) { $sso = array('siteUrl' => 'https://sso.openx.com/api/index/initiate', 'requestTokenUrl' => 'https://sso.openx.com/api/index/initiate', 'accessTokenUrl' => 'https://sso.openx.com/api/index/token', 'authorizeUrl' => 'https://sso.openx.com/login/login', 'loginUrl' => 'https://sso.openx.com/login/process'); } // Set the proxy['adapter'] if $proxy config was passed in if (!empty($proxy)) { $proxy['adapter'] = 'Zend_Http_Client_Adapter_Proxy'; } // Initilize the cookie jar, from the $cookieJarFile if present $client = self::getHttpClient(); $cookieJar = false; if (is_readable($cookieJarFile)) { $cookieJar = @unserialize(file_get_contents($cookieJarFile)); } if (!$cookieJar instanceof Zend_Http_CookieJar) { $cookieJar = new Zend_Http_CookieJar(); } $client->setCookieJar($cookieJar); $client->setConfig($proxy); $result = $this->put('/a/session/validate'); // See if the openx3_access_token is still valid... if ($result->isError()) { // Get Request Token $config = array('siteUrl' => $sso['siteUrl'], 'requestTokenUrl' => $sso['requestTokenUrl'], 'accessTokenUrl' => $sso['accessTokenUrl'], 'authorizeUrl' => $sso['authorizeUrl'], 'consumerKey' => $consumer_key, 'consumerSecret' => $consumer_secret, 'realm' => $oauth_realm); $oAuth = new OX3_Oauth_Consumer($config); $requestToken = $oAuth->getRequestToken(); // Authenticate to SSO $loginClient = new Zend_Http_Client($sso['loginUrl']); $loginClient->setCookieJar(); $loginClient->setConfig($proxy); $loginClient->setParameterPost(array('email' => $email, 'password' => $password, 'oauth_token' => $requestToken->getToken())); $loginClient->request(Zend_Http_Client::POST); $loginBody = $loginClient->getLastResponse()->getBody(); // Parse response, sucessful headless logins will return oob?oauth_token=<token>&oauth_verifier=<verifier> as the body if (substr($loginBody, 0, 4) == 'oob?') { $vars = array(); @parse_str(substr($loginBody, 4), $vars); if (empty($vars['oauth_token'])) { throw new Exception('Error parsing SSO login response'); } // Swap the (authorized) request token for an access token: $accessToken = $oAuth->getAccessToken($vars, $requestToken)->getToken(); $client->setCookie(new Zend_Http_Cookie('openx3_access_token', $accessToken, $aUrl['host'])); $result = $this->put('/a/session/validate'); if ($result->isSuccessful()) { file_put_contents($cookieJarFile, serialize($client->getCookieJar()), LOCK_EX); chmod($cookieJarFile, 0666); } } else { throw new Exception('SSO Authentication error'); } } }
/** * constructor for Zend_Service_Tine20 * @param string $url the url of the Tine 2.0 installation * @param Zend_Http_Client $httpClient * @return void */ public function __construct($url, $httpClient = null) { $this->_url = $url; if (!$httpClient instanceof Zend_Http_Client) { $httpClient = new Zend_Http_Client(); } if (!$httpClient->getCookieJar() instanceof Zend_Http_CookieJar) { $httpClient->setCookieJar(); } parent::__construct($url, $httpClient); }
/** * Initializes the HTTP client object. * * @return Zend_Http_Client */ protected function _initHttpClient() { $serverUri = $this->getOption('server_uri'); if (!$serverUri) { throw new AcApi_Transport_Adapter_Exception('No server URI set.'); } try { $client = new Zend_Http_Client($serverUri); } catch (Zend_Uri_Exception $e) { throw new AcApi_Transport_Exception(sprintf("%s '%s'", $e->getMessage(), $serverUri)); } $client->setCookieJar(); return $client; }
/** * Make sure we can set cookie objects with a jar * */ public function testSetCookieObjectJar() { $this->client->setUri($this->baseuri . 'testCookies.php'); $this->client->setCookieJar(); $refuri = $this->client->getUri(); $cookies = array(Zend_Http_Cookie::fromString('chocolate=chips', $refuri), Zend_Http_Cookie::fromString('crumble=apple', $refuri)); $strcookies = array(); foreach ($cookies as $c) { $this->client->setCookie($c); $strcookies[$c->getName()] = $c->getValue(); } $res = $this->client->request(); $this->assertEquals($res->getBody(), serialize($strcookies), 'Response body does not contain the expected cookies'); }
/** * * @param string $url * @param array $param * @param string $method * @return string */ protected function _request($url, $param = array(), $method = Zend_Http_Client::POST) { if ($this->_client === null) { $config = array('useragent' => 'Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/44.0', 'encodecookies' => false, 'timeout' => 180); $this->_client = new Zend_Http_Client($url, $config); $this->_client->setCookieJar(); } $this->_client->resetParameters()->setUri($url); if (count($param['post']) > 0) { foreach ($param['post'] as $name => $value) { $this->_client->setParameterPost($name, $value); } } if (count($param['get']) > 0) { foreach ($param['get'] as $name => $value) { $this->_client->setParameterPost($name, $value); } } if (count($param['file']) > 0) { foreach ($param['file'] as $name => $value) { $this->_client->setFileUpload($value, $name); } } if (count($param['cookie']) > 0) { foreach ($param['cookie'] as $name => $value) { $this->_client->setCookie($name, $value); } } if (count($this->_cookies) > 0) { foreach ($this->_cookies as $cookie) { $this->_client->setCookie($cookie); } } $response = $this->_client->request($method); $this->_cookies = $this->_client->getCookieJar()->getAllCookies(); return $response->getBody(); }
/** * * @return Zend_Http_Client */ public function getHttpClient() { if (is_null($this->httpClient)) { $config = array('adapter' => 'Zend_Http_Client_Adapter_Proxy', 'useragent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31', 'timeout' => 30); $headers = array('Referer' => $this->uriStartPage, 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding' => 'gzip,deflate', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4', 'DNT' => '1'); if (function_exists('curl_exec') && is_callable('curl_exec')) { $config['adapter'] = 'Zend_Http_Client_Adapter_Curl'; } $client = new Zend_Http_Client(null, $config); $client->setCookieJar(); $client->setHeaders($headers); $this->httpClient = $client; } return $this->httpClient; }
/** * 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; }
/** * 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]; } $http = new Zend_Http_Client("http://www.dailymotion.com/video/" . $url, array('headers' => array('User-Agent' => "vlc-shares/" . X_VlcShares::VERSION . " dailymotion/" . X_VlcShares_Plugins_DailyMotion::VERSION))); $http->setCookieJar(true); $http->getCookieJar()->addCookie(new Zend_Http_Cookie('family_filter', 'off', 'www.dailymotion.com')); $datas = $http->request()->getBody(); if (preg_match('/<title>(.*)404(.*)<\\/title>/', $datas)) { throw new Exception("Invalid ID {{$url}}", self::E_ID_INVALID); } $matches = array(); if (!preg_match('/\\.addVariable\\(\\"sequence\\", \\"(?P<sequence>.*?)\\"/', $datas, $matches)) { throw new Exception("Invalid ID {{$url}}, sequence not found", self::E_ID_INVALID); } $sequence = urldecode($matches['sequence']); $matches = array(); if (!preg_match('/videotitle\\=(?P<title>[^&]+)&/', $sequence, $matches)) { $title = ""; } $title = urldecode($matches['title']); $matches = array(); if (!preg_match('/\\"videoDescription\\"\\:\\"(?P<description>[^\\"]*)\\"/', $sequence, $matches)) { $description = ''; } $description = urldecode($matches['description']); $matches = array(); if (!preg_match('/\\"duration\\"\\:(?P<length>.*)\\,/', $sequence, $matches)) { $length = ''; } $length = $matches['length']; $thumbnail = "http://www.dailymotion.com/thumbnail/320x240/video/{$url}"; $matches = array(); if (!preg_match('/\\"sdURL\\"\\:\\"(?P<video>[^\\"]+)\\"/', $sequence, $matches)) { $video = ''; } $video = stripslashes($matches['video']); $infos = array('title' => $title, 'description' => $description, 'length' => $length, 'thumbnail' => $thumbnail, 'url' => $video); // add in cache $this->info_cache[$url] = $infos; return $infos; }
function __construct($parserType, $config = array(), $url = null) { // Create Zend_Http_Client object $this->client = new Zend_Http_Client($url); // attach a new cookie jar to your Zend_Http_Client object $this->client->setCookieJar(); // Сохраним последнюю конфигурацию $this->last_config = $this->_setConfig($config); // Last URL if ($url) { $this->last_url = $url; } // Set parser type if ($parserType) { $this->parserType = $parserType; } }
public static function authenticate() { $zendClient = new Zend_Http_Client(); $zendClient->setCookieJar(); $zendClient->setUri(BASE_URI_ . '/public/editor/login/authenticate'); $zendClient->setConfig(array('maxredirects' => 2, 'timeout' => 30)); $zendClient->SetHeaders(array('Accept' => 'text/html,application/xhtml+xml,application/xml', 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept-Language' => 'en-US,en', 'Accept-Encoding' => 'gzip, deflate', 'Referer' => BASE_URI_ . '/public/editor/login', 'Connection' => 'keep-alive')); $zendClient->setParameterPost('username', USERNAME); $zendClient->setParameterPost('tenant', TENANT); $zendClient->setParameterPost('password', PASSWORD); $zendClient->setParameterPost('rememberme', '0'); $zendClient->setParameterPost('login', 'Login'); $responseAuth = $zendClient->request(Zend_Http_Client::POST); print "\n Authentication response status: " . $responseAuth->getStatus(); print "\n Authentication response message: " . $responseAuth->getMessage() . "\n"; return $zendClient; }
public function import($feed) { $stubs = array(); // select city $retries = 3; for ($i = 0; $i < $retries; $i++) { try { $config = Zend_Registry::get('config'); $client = new Zend_Http_Client($feed->url, array('useragent' => $config->userAgent, 'timeout' => 20)); $client->setCookieJar(true); $client->request(); // success! break; } catch (Zend_Http_Exception $e) { // if last retry fails, throw error if ($i == $retries - 1) { throw new Yadda_Feed_Exception('Error selecting city.'); } } // retry sleep(1); } // fetch home page try { $client->setUri('https://www.daddysdeals.co.za/'); $response = $client->request(); } catch (Zend_Http_Exception $e) { throw new Yadda_Feed_Exception('Error downloading feed.'); } $html = $response->getBody(); $matches = array(); @preg_match_all('#<div class="deal-content">.*<h1><a href="([^"]+)"[^>]*>(.*)</a>.*<div class="deal-gallery">.*<img src="([^"]+)".*<div class="deal-info-buy">.*<span>R([0-9\\.]+)</span>.*</div>.*<div class="deal-content-highlights">.*<h3>At a glance</h3>(.*)</div>.*</div>#sU', $html, $matches); for ($i = 0; $i < sizeof($matches[0]); $i++) { $stub = new Yadda_Feed_Stub(); $stub->setLink($this->_sanitize($matches[1][$i])); $stub->setGuid($this->_sanitize($matches[1][$i])); $stub->setTitle($this->_sanitize($matches[2][$i])); $stub->addImage($this->_sanitize($matches[3][$i])); $stub->setPrice((double) $matches[4][$i]); $stub->setDescription($this->_sanitize($matches[5][$i])); $stubs[] = $stub; } return $stubs; }
/** * Test that when the encodecookies flag is set to FALSE, cookies captured * from a response by Zend_Http_CookieJar are not encoded * * @group ZF-1850 */ public function testCaptureCookiesNoEncodeZF1850() { $cookieName = "cookieWithSpecialChars"; $cookieValue = "HID=XXXXXX&UN=XXXXXXX&UID=XXXXX"; $adapter = new Zend_Http_Client_Adapter_Test(); $adapter->setResponse("HTTP/1.0 200 OK\r\n" . "Content-type: text/plain\r\n" . "Content-length: 2\r\n" . "Connection: close\r\n" . "Set-Cookie: {$cookieName}={$cookieValue}; path=/\r\n" . "\r\n" . "OK"); $this->_client->setUri('http://example.example/test'); $this->_client->setConfig(array('adapter' => $adapter, 'encodecookies' => false)); $this->_client->setCookieJar(); // First request is expected to set the cookie $this->_client->request(); // Next request should contain the cookie $this->_client->request(); $request = $this->_client->getLastRequest(); if (!preg_match("/^Cookie: {$cookieName}=([^;]+)/m", $request, $match)) { $this->fail("Could not find cookie in request"); } $this->assertEquals($cookieValue, $match[1]); }
/** * Create a new Spizer Engine object * * @param array $config Configuration array */ public function __construct(array $config = array()) { // Load configuration foreach ($config as $k => $v) { $this->_config[$k] = $v; } // Set up the HTTP client $this->_httpClient = new Zend_Http_Client(); if ($this->_config['savecookies']) { $this->_httpClient->setCookieJar(); } if (isset($this->_config['httpOpts']) && is_array($this->_config['httpOpts'])) { $httpOpts = $this->_config['httpOpts']; } else { $httpOpts = array(); } $httpOpts['maxredirects'] = 0; $this->_httpClient->setConfig($httpOpts); // Set up the queue $this->_queue = new Spizer_Queue($this->_config['lifo']); }
function loadWidget($widgetUrl, $widgetAuthActionUrl) { Zend_Loader::loadClass('Zend_Http_Client'); Zend_Loader::loadClass('Kutu_Crypt_Password'); $auth = Zend_Auth::getInstance(); $password = ''; $userName = ''; if ($auth->hasIdentity()) { $crypt = new Kutu_Crypt_Password(); $password = $crypt->decryptPassword($auth->getIdentity()->password); $userName = $auth->getIdentity()->username; } $client = new Zend_Http_Client($widgetUrl, array('keepalive' => true)); $client->setCookieJar(); $client->setUri($widgetAuthActionUrl); $client->setParameterPost(array('username' => $userName, 'password' => $password)); $userAgent = $_SERVER['HTTP_USER_AGENT']; $client->setHeaders("User-Agent: {$userAgent}"); $response = $client->request(Zend_Http_Client::POST); $client->setUri($widgetUrl); $response = $client->request(Zend_Http_Client::GET); return $response->getBody(); }
private function getHttpClient($userEmail, $password, $proxyHost = null, $proxyPort = null, $retry = 5) { $url = "https://secure.metacafe.com/account/login/"; $client = null; if (isset($userEmail) && isset($password)) { if (isset($proxyHost)) { $httpConfig = array('adapter' => 'Zend_Http_Client_Adapter_Proxy', 'proxy_host' => $proxyHost, 'proxy_port' => $proxyPort, 'maxredirects' => 5, 'timeout' => $this->timeout, 'keepalive' => true); try { // creates a proxied client to use for authentication $client = new Zend_Http_Client($url, $httpConfig); //echo ("Using Proxy: $proxyHost port: $proxyPort"); } catch (Zend_Exception $e) { //echo("Error Using Proxy: $proxyHost port: $proxyPort<br>" . $e->getMessage()); $client = new Zend_Http_Client($url, array('maxredirects' => 5, 'timeout' => $this->timeout, 'keepalive' => true)); } } else { //echo("Not Using Proxy"); $client = new Zend_Http_Client($url, array('maxredirects' => 5, 'timeout' => $this->timeout, 'keepalive' => true)); } // To turn cookie stickiness on, set a Cookie Jar $client->setCookieJar(); $client->setParameterPost(array('email' => $userEmail, 'password' => $password, 'submit' => 'Sign+In', 'pageToLoad' => '1', 'remember' => 'on')); // Authenticate Login try { $client->request(Zend_Http_Client::POST); } catch (Zend_Exception $e) { //echo("Error: Logging In - " . $e->getMessage() . "<br>"); $client = null; } } if (!isset($client) && $retry > 0) { sleep(10); $client = $this->getHttpClient($userEmail, $password, $proxyHost, $proxyPort, $retry--); } return $client; }
/** * connects to request tracker * * @return void */ protected function _connect() { if (!$this->_config->rest || $this->_config->rest->url) { throw new Tinebase_Exception_NotFound('Could not connect to RequestTracker: No REST url given!'); } $config = array('url' => $this->_config->rest->url, 'useragent' => 'Tine 2.0 remote client (rv: 0.2)', 'keepalive' => true); $this->_httpClient = new Zend_Http_Client($this->_config->rest->url, $config); $this->_httpClient->setCookieJar(); // login $this->_httpClient->setMethod(Zend_Http_Client::POST); $this->_httpClient->setUri($this->_config->rest->url . "/REST/1.0/ticket/"); $loginName = Tinebase_Core::getUser()->accountLoginName; if ($this->_config->useCustomCredendials) { $this->_httpClient->setAuth($this->_config->customCredentials->{$loginName}->username, $this->_config->customCredentials->{$loginName}->password); } else { $credentialCache = Tinebase_Core::getUserCredentialCache(); Tinebase_Auth_CredentialCache::getInstance()->getCachedCredentials($credentialCache); $this->_httpClient->setAuth(Tinebase_Core::getUser()->accountLoginName, $credentialCache->password); } $response = $this->_httpClient->request(); if ($response->getStatus() != 200) { throw new Tinebase_Exception_Record_NotAllowed($response->getMessage(), $response->getStatus()); } }
public function getPlainHttpClient($url, $proxyHost = null, $proxyPort = null) { $client = null; if (isset($proxyHost) && isset($proxyPort)) { $httpConfig = array('adapter' => 'Zend_Http_Client_Adapter_Proxy', 'proxy_host' => $proxyHost, 'proxy_port' => $proxyPort, 'maxredirects' => 10, 'timeout' => 120, 'keepalive' => true); try { // creates a proxied client to use for authentication $client = new Zend_Http_Client($url, $httpConfig); // echo ( "Using Proxy: $proxyHost port: $proxyPort" ); } catch (Exception $e) { echo "Error Using Proxy: {$proxyHost} port: {$proxyPort}<br>" . $e->getMessage(); $client = new Zend_Http_Client($url, array('maxredirects' => 5, 'timeout' => 120, 'keepalive' => true)); } } else { try { // echo ( "Not Using Proxy" ); $client = new Zend_Http_Client($url, array('maxredirects' => 10, 'timeout' => 120, 'keepalive' => true)); } catch (Exception $e) { echo "Error getting HTTP Client: " . $e->getMessage(); } } if (isset($client)) { // To turn cookie stickiness on, set a Cookie Jar $client->setCookieJar(); } return $client; }
/** * @todo Figure out how to handle authentication and authorization * using human intervention and outside of the test functions */ public function testGetToken() { /** * Scrape the web site to authenticate and just get delete * permissions so all operations will be allowed */ $url = self::$_rtm->getAuthUrl(Zend_Service_RememberTheMilk::PERMS_DELETE, self::$_frob); $parsed = parse_url($url); $query = $parsed['query']; $params = array('username' => self::$_username, 'password' => self::$_password, 'remember' => 'on', 'login' => 'Login', 'continue' => 'home', 'api' => $query, 'u' => '1'); $config = array('useragent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'); $http = new Zend_Http_Client(); $http->setCookieJar(); $http->setMethod(Zend_Http_Client::POST); $http->setConfig($config); $http->setUri('https://www.rememberthemilk.com/auth.rtm'); $http->setHeaders('Referer', $url); $http->setParameterPost($params); $response = $http->request(); /*if (!$response->isSuccessful()) { throw new Zend_Service_Exception('Authentication failed'); } sleep(1); $params = array( 'authorize_yes' => 'Yes, go for it!' ); $http->setUri('http://www.rememberthemilk.com/services/auth/?' . $query); $http->setParameterPost($params); $response = $http->request();*/ if (!$response->isSuccessful() || !strpos($response->getBody(), 'Application successfully authorized')) { throw new Zend_Service_Exception('Authorization failed'); } sleep(1); /** * Authentication and authorization logic ends here */ self::$_token = self::$_rtm->getToken(self::$_frob); $this->assertTrue(self::$_token instanceof Zend_Service_RememberTheMilk_Token, 'Returned token is not an instance'); $this->assertRegExp('/^[a-f0-9]{40}$/', self::$_token->getToken(), 'Returned token string appears to be invalid'); $this->assertEquals(self::$_token->getPerms(), Zend_Service_RememberTheMilk::PERMS_DELETE, 'Permissions are inconsistent'); $user = self::$_token->getUser(); $this->assertTrue($user instanceof Zend_Service_RememberTheMilk_Contact, 'Token user is not an instance'); }
protected function fetch($url, $retry = true) { if ($this->options->get('username', '') == '' || $this->options->get('password', '') == '') { X_Debug::e("Account missing"); return false; } $http = new Zend_Http_Client(); $http->setCookieJar(true); // load cookies from file try { /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache'); $cookies = unserialize($cacheHelper->retrieveItem("realdebrid::cookies")); X_Debug::i("Using cached authentication"); foreach ($cookies as $c) { $_c = new Zend_Http_Cookie($c['name'], $c['value'], $c['domain'], $c['exp'], $c['path']); $http->getCookieJar()->addCookie($_c); } } catch (Exception $e) { // no cache plugin or no authentication performed // perform a new authentication X_Debug::i("Authentication required: {$e->getMessage()}"); try { $http->setUri(sprintf(self::API_URL_LOGIN, $this->options->get('username'), md5($this->options->get('password')), time())); $loginBody = Zend_Json::decode($http->request()->getBody()); } catch (Exception $e) { if ($retry) { X_Debug::e("Login request failed, try again: {$e->getMessage()}"); return $this->fetch($url, false); } else { X_Debug::e("Login request failed (2nd time): {$e->getMessage()}"); throw $e; } } if ($loginBody['error'] != 0) { // invalid login info throw new Exception("Invalid Real-Debrid account"); } else { X_Debug::i("Authentication performed, valid account"); // login ok, store information in cache (try) try { /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache'); $cks = $http->getCookieJar()->getAllCookies(Zend_Http_CookieJar::COOKIE_OBJECT); $minValidity = 99999999999; foreach ($cks as $i => $c) { /* @var $c Zend_Http_Cookie */ $expire = $c->getExpiryTime(); if ($expire != null && $expire < $minValidity) { $minValidity = $expire; } $cks[$i] = array('domain' => $c->getDomain(), 'exp' => $c->getExpiryTime(), 'name' => $c->getName(), 'path' => $c->getPath(), 'value' => $c->getValue()); } $minValidity = (int) ($minValidity - time() / 60) - 1; if ($minValidity < 0) { $minValidity = 5; } // if error, set to 5 minutes // perform a new authentication every 7 days $cacheHelper->storeItem("realdebrid::cookies", serialize($cks), $minValidity); } catch (Exception $e) { X_Debug::e("Real Debrid requires cache plugin, but it's disabled!!!"); } } } $url = urlencode($url); $url = sprintf(self::API_URL_FETCH, $url, time()); X_Debug::i("Fetching: {$url}"); $http->setUri($url)->setHeaders(array('User-Agent: vlc-shares/' . X_VlcShares::VERSION . ' realdebrid/' . X_VlcShares_Plugins_RealDebrid::VERSION)); // always add "showlink=1" and "lang=en" in the cookies //$http //->setCookie('showlink', '1') //->setCookie('lang','en'); $links = $http->request()->getBody(); //X_Debug::i("Request: ".var_export( $http->getLastRequest() , true)); //X_Debug::i("Real debrid response: ".$links); $json = Zend_Json::decode($links); if (isset($json['error'])) { switch ($json['error']) { case '0': // everything ok break; case '2': // invalid login // invalid account or login missing. // Try 1 more time only forcing relogin if ($retry) { return $this->fetch($url, false); } else { return false; } case '5': // expired account return false; default: // maybe invalid links? return false; } } $links = array(); /* Minecraft MindCrack - S3E266 - Revisiting Arkas.mp4 (720p)|-|http:\/\/s08.real-debrid.com\/dl\/94i41374r203339931\/Minecraft%20MindCrack%20-%20S3E266%20-%20Revisiting%20Arkas.mp4|--|Minecraft MindCrack - S3E266 - Revisiting Arkas.flv (HQ)|-|http:\/\/s08.real-debrid.com\/dl\/94i41374r203434188\/Minecraft%20MindCrack%20-%20S3E266%20-%20Revisiting%20Arkas.flv|--|Minecraft MindCrack - S3E266 - Revisiting Arkas.flv (SD)|-|http:\/\/s08.real-debrid.com\/dl\/94i41374r203537640\/Minecraft%20MindCrack%20-%20S3E266%20-%20Revisiting%20Arkas.flv|--|Minecraft MindCrack - S3E266 - Revisiting Arkas.flv (240p)|-|http:\/\/s08.real-debrid.com\/dl\/94i41374r203631597\/Minecraft%20MindCrack%20-%20S3E266%20-%20Revisiting%20Arkas.flv" */ $linksS = $json['generated_links']; $xLinksS = explode('|--|', $linksS); foreach ($xLinksS as $xLinkS) { // $xLinkS = Minecraft MindCrack - S3E266 - Revisiting Arkas.mp4 (720p)|-|http:\/\/s08.real-debrid.com\/dl\/94i41374r203339931\/Minecraft%20MindCrack%20-%20S3E266%20-%20Revisiting%20Arkas.mp4 $xLink = explode('|-|', $xLinkS); $links[] = $xLink[1]; } if (count($links) > 1) { $links = array_reverse($links, false); } return $links; }
/** * Make an AJAX request. * * @param array See $options http://docs.jquery.com/Ajax/jQuery.ajax#toptions * Additional options are: * 'document' - document for global events, @see phpQuery::getDocumentID() * 'referer' - implemented * 'requested_with' - TODO; not implemented (X-Requested-With) * @return Zend_Http_Client * @link http://docs.jquery.com/Ajax/jQuery.ajax * * @TODO $options['cache'] * @TODO $options['processData'] * @TODO $options['xhr'] * @TODO $options['data'] as string * @TODO XHR interface */ public static function ajax($options = array(), $xhr = null) { $options = array_merge(self::$ajaxSettings, $options); $documentID = isset($options['document']) ? self::getDocumentID($options['document']) : null; if ($xhr) { // reuse existing XHR object, but clean it up $client = $xhr; // $client->setParameterPost(null); // $client->setParameterGet(null); $client->setAuth(false); $client->setHeaders("If-Modified-Since", null); $client->setHeaders("Referer", null); $client->resetParameters(); } else { // create new XHR object require_once 'Zend/Http/Client.php'; $client = new Zend_Http_Client(); $client->setCookieJar(); } if (isset($options['timeout'])) { $client->setConfig(array('timeout' => $options['timeout'])); } // 'maxredirects' => 0, foreach (self::$ajaxAllowedHosts as $k => $host) { if ($host == '.' && isset($_SERVER['HTTP_HOST'])) { self::$ajaxAllowedHosts[$k] = $_SERVER['HTTP_HOST']; } } $host = parse_url($options['url'], PHP_URL_HOST); if (!in_array($host, self::$ajaxAllowedHosts)) { throw new Exception("Request not permitted, host '{$host}' not present in " . "phpQuery::\$ajaxAllowedHosts"); } // JSONP $jsre = "/=\\?(&|\$)/"; if (isset($options['dataType']) && $options['dataType'] == 'jsonp') { $jsonpCallbackParam = $options['jsonp'] ? $options['jsonp'] : 'callback'; if (strtolower($options['type']) == 'get') { if (!preg_match($jsre, $options['url'])) { $sep = strpos($options['url'], '?') ? '&' : '?'; $options['url'] .= "{$sep}{$jsonpCallbackParam}=?"; } } else { if ($options['data']) { $jsonp = false; foreach ($options['data'] as $n => $v) { if ($v == '?') { $jsonp = true; } } if (!$jsonp) { $options['data'][$jsonpCallbackParam] = '?'; } } } $options['dataType'] = 'json'; } if (isset($options['dataType']) && $options['dataType'] == 'json') { $jsonpCallback = 'json_' . md5(microtime()); $jsonpData = $jsonpUrl = false; if ($options['data']) { foreach ($options['data'] as $n => $v) { if ($v == '?') { $jsonpData = $n; } } } if (preg_match($jsre, $options['url'])) { $jsonpUrl = true; } if ($jsonpData !== false || $jsonpUrl) { // remember callback name for httpData() $options['_jsonp'] = $jsonpCallback; if ($jsonpData !== false) { $options['data'][$jsonpData] = $jsonpCallback; } if ($jsonpUrl) { $options['url'] = preg_replace($jsre, "={$jsonpCallback}\\1", $options['url']); } } } $client->setUri($options['url']); $client->setMethod(strtoupper($options['type'])); if (isset($options['referer']) && $options['referer']) { $client->setHeaders('Referer', $options['referer']); } $client->setHeaders(array('User-Agent' => 'Mozilla/5.0 (X11; U; Linux x86; en-US; rv:1.9.0.5) Gecko' . '/2008122010 Firefox/3.0.5', 'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept-Language' => 'en-us,en;q=0.5')); if ($options['username']) { $client->setAuth($options['username'], $options['password']); } if (isset($options['ifModified']) && $options['ifModified']) { $client->setHeaders("If-Modified-Since", self::$lastModified ? self::$lastModified : "Thu, 01 Jan 1970 00:00:00 GMT"); } $client->setHeaders("Accept", isset($options['dataType']) && isset(self::$ajaxSettings['accepts'][$options['dataType']]) ? self::$ajaxSettings['accepts'][$options['dataType']] . ", */*" : self::$ajaxSettings['accepts']['_default']); // TODO $options['processData'] if ($options['data'] instanceof phpQueryObject) { $serialized = $options['data']->serializeArray($options['data']); $options['data'] = array(); foreach ($serialized as $r) { $options['data'][$r['name']] = $r['value']; } } if (strtolower($options['type']) == 'get') { $client->setParameterGet($options['data']); } else { if (strtolower($options['type']) == 'post') { $client->setEncType($options['contentType']); $client->setParameterPost($options['data']); } } if (self::$active == 0 && $options['global']) { phpQueryEvents::trigger($documentID, 'ajaxStart'); } self::$active++; // beforeSend callback if (isset($options['beforeSend']) && $options['beforeSend']) { phpQuery::callbackRun($options['beforeSend'], array($client)); } // ajaxSend event if ($options['global']) { phpQueryEvents::trigger($documentID, 'ajaxSend', array($client, $options)); } if (phpQuery::$debug) { self::debug("{$options['type']}: {$options['url']}\n"); self::debug("Options: <pre>" . var_export($options, true) . "</pre>\n"); // if ($client->getCookieJar()) // self::debug("Cookies: <pre>".var_export($client->getCookieJar()->getMatchingCookies($options['url']), true)."</pre>\n"); } // request $response = $client->request(); if (phpQuery::$debug) { self::debug('Status: ' . $response->getStatus() . ' / ' . $response->getMessage()); self::debug($client->getLastRequest()); self::debug($response->getHeaders()); } if ($response->isSuccessful()) { // XXX tempolary self::$lastModified = $response->getHeader('Last-Modified'); $data = self::httpData($response->getBody(), $options['dataType'], $options); if (isset($options['success']) && $options['success']) { phpQuery::callbackRun($options['success'], array($data, $response->getStatus(), $options)); } if ($options['global']) { phpQueryEvents::trigger($documentID, 'ajaxSuccess', array($client, $options)); } } else { if (isset($options['error']) && $options['error']) { phpQuery::callbackRun($options['error'], array($client, $response->getStatus(), $response->getMessage())); } if ($options['global']) { phpQueryEvents::trigger($documentID, 'ajaxError', array($client, $response->getMessage(), $options)); } } if (isset($options['complete']) && $options['complete']) { phpQuery::callbackRun($options['complete'], array($client, $response->getStatus())); } if ($options['global']) { phpQueryEvents::trigger($documentID, 'ajaxComplete', array($client, $options)); } if ($options['global'] && !--self::$active) { phpQueryEvents::trigger($documentID, 'ajaxStop'); } return $client; // if (is_null($domId)) // $domId = self::$defaultDocumentID ? self::$defaultDocumentID : false; // return new phpQueryAjaxResponse($response, $domId); }
/** * 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.sockshare.com/embed/" . $url, array('headers' => array('User-Agent' => "vlc-shares/" . X_VlcShares::VERSION . " sockshare/" . X_VlcShares_Plugins_SockShare::VERSION))); $xml = $http->request()->getBody(); if (preg_match('/<div class\\=\\"message t_0\\">This file doesn\'t exist, or has been removed\\.<\\/div>/', $xml)) { X_Debug::e("Invalid ID {{$url}} or file removed"); throw new Exception("Invalid ID {{$url}}", self::E_ID_INVALID); } $matches = array(); if (!preg_match('/<strong>(?P<title>[^<]+)<\\/strong>/', $xml, $matches)) { $title = X_Env::_('p_sockshare_title_not_setted'); X_Debug::w("Title not found"); } else { $title = $matches['title']; } $description = ''; if (!preg_match('/<input type\\=\\"hidden\\" value\\=\\"(?P<hash>[^\\"]+)\\" name\\=\\"(?P<arg>[^\\"]+)\\">/', $xml, $matches)) { X_Debug::w("Couldn't find hash for file {{$url}}"); throw new Exception("Couldn't find hash for file {{$url}}", self::E_ID_INVALID); } $hash = $matches['hash']; $arg = $matches['arg']; // To turn cookie stickiness on, set a Cookie Jar $http->setCookieJar(); // First request: log in and start a session $http->setUri("http://www.sockshare.com/embed/" . $url); $http->setParameterPost($arg, $hash); $http->setParameterPost('confirm', 'Close Ad and Watch as Free User'); $http->request('POST'); $xml = $http->request()->getBody(); $matches = array(); if (!preg_match('/<img src="(?P<thumbnail>.+?)" name="bg" style=".+?" id="bg"\\/>/', $xml, $matches)) { X_Debug::w("No thumbnail found"); $thumbnail = ''; } else { $thumbnail = $matches['thumbnail']; } X_Debug::i("Thumbnail found {{$thumbnail}}"); $matches = array(); if (!preg_match("/playlist: '(?P<playlist>[^']+)'/", $xml, $matches)) { $playlist = ''; X_Debug::w("Couldn't find playlist for file " . $url . "!"); throw new Exception("Couldn't find playlist for file {{$url}}", self::E_ID_INVALID); } $playlist = $matches['playlist']; $http->setUri("http://www.sockshare.com" . $playlist); $http->request('GET'); $xml = $http->request()->getBody(); $matches = array(); if (!preg_match('/<media:content url\\=\\"(?P<video>[^\\"]+)\\" type\\=\\"video\\/x-flv\\" duration\\=\\"(?P<length>[^\\"]+)\\" \\/>/', $xml, $matches)) { X_Debug::w("Couldn't find video link for file " . $url . "!"); throw new Exception("Couldn't find video link for file {{$url}}", self::E_ID_INVALID); } $length = $matches['length']; $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 setupHttpClient(Zend_Http_Client $httpClient) { $this->_restSession = new Zend_Session_Namespace('App_Rest_Service_' . $this->getRestService()->getServiceName() . '_Session'); $httpClient->setCookieJar(isset($this->_restSession->cookieJar) ? $this->_restSession->cookieJar : null); }
/** * Create and return the http client, defined in a separate method * for testing purposes * * @return Zend_Http_Client */ protected function getClient($uri) { // TODO For some reason the Alfresco client goes into an infinite loop when returning // the children of an item (when you call getChildren on the company home) // it returns itself as its own child, unless you recreate the client. It seems // to maintain all the request body... or something weird. if (!$this->httpClient || !$this->maintainSession) { $this->httpClient = new Zend_Http_Client($uri, array('maxredirects' => 0, 'timeout' => 10)); if ($this->useCookies) { $this->httpClient->setCookieJar(); } } else { $this->httpClient->setUri($uri); } // clear it out if ($this->maintainSession) { $this->httpClient->resetParameters(); } if ($this->authInfo) { $this->httpClient->setAuth($this->authInfo['user'], $this->authInfo['pass']); } return $this->httpClient; }