Example #1
0
 /**
  * Create a new CookieJar object and automatically load into it all the 
  * cookies set in an Http_Response object. If $uri is set, it will be 
  * considered as the requested URI for setting default domain and path
  * of the cookie.
  *
  * @param Zend_Http_Response $response HTTP Response object
  * @param Zend_Uri_Http|string $uri The requested URI 
  * @return Zend_Http_CookieJar
  * @todo Add the $uri functionality. 
  */
 public static function fromResponse(Zend_Http_Response $response, $ref_uri)
 {
     $jar = new Zend_Http_CookieJar();
     $jar->addCookiesFromResponse($response, $ref_uri);
     return $jar;
 }
Example #2
0
 /**
  * Prepare the request headers
  *
  * @return array
  */
 protected function _prepareHeaders()
 {
     $headers = array();
     // Set the host header
     if (!isset($this->headers['host'])) {
         $host = $this->uri->getHost();
         // If the port is not default, add it
         if (!($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80 || $this->uri->getScheme() == 'https' && $this->uri->getPort() == 443)) {
             $host .= ':' . $this->uri->getPort();
         }
         $headers[] = "Host: {$host}";
     }
     // Set the connection header
     if (!isset($this->headers['connection'])) {
         if (!$this->config['keepalive']) {
             $headers[] = "Connection: close";
         }
     }
     // Set the Accept-encoding header if not set - depending on whether
     // zlib is available or not.
     if (!isset($this->headers['accept-encoding'])) {
         if (function_exists('gzinflate')) {
             $headers[] = 'Accept-encoding: gzip, deflate';
         } else {
             $headers[] = 'Accept-encoding: identity';
         }
     }
     // Set the Content-Type header
     if (($this->method == self::POST || $this->method == self::PUT) && (!isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
         $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
     }
     // Set the user agent header
     if (!isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
         $headers[] = "User-Agent: {$this->config['useragent']}";
     }
     // Set HTTP authentication if needed
     if (is_array($this->auth)) {
         $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
         $headers[] = "Authorization: {$auth}";
     }
     // Load cookies from cookie jar
     if (isset($this->cookiejar)) {
         $cookstr = $this->cookiejar->getMatchingCookies($this->uri, true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
         if ($cookstr) {
             $headers[] = "Cookie: {$cookstr}";
         }
     }
     // Add all other user defined headers
     foreach ($this->headers as $header) {
         list($name, $value) = $header;
         if (is_array($value)) {
             $value = implode(', ', $value);
         }
         $headers[] = "{$name}: {$value}";
     }
     return $headers;
 }
 public function testIteratorAndCountable()
 {
     $jar = new Zend_Http_CookieJar();
     $cookies = array(Zend_Http_Cookie::fromString('foo1=bar1; domain=.example.com; path=/a/b'), Zend_Http_Cookie::fromString('foo2=bar2; domain=.example.com; path=/a/b/'));
     foreach ($cookies as $cookie) {
         $jar->addCookie($cookie);
     }
     foreach ($jar as $cookie) {
         $this->assertTrue($cookie instanceof Zend_Http_Cookie);
     }
     $this->assertEquals(2, count($jar));
     $this->assertFalse($jar->isEmpty());
     $jar->reset();
     $this->assertTrue($jar->isEmpty());
 }
Example #4
0
 /**
  * Prepare the request headers
  *
  * @return array
  */
 protected function prepare_headers()
 {
     $headers = array();
     // Set the host header
     if (!isset($this->headers['host'])) {
         $host = $this->uri->getHost();
         // If the port is not default, add it
         if (!($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80 || $this->uri->getScheme() == 'https' && $this->uri->getPort() == 443)) {
             $host .= ':' . $this->uri->getPort();
         }
         $headers[] = "Host: {$host}";
     }
     // Set the connection header
     if (!isset($this->headers['connection'])) {
         if (!$this->config['keepalive']) {
             $headers[] = "Connection: close";
         }
     }
     // Set the content-type header
     if ($this->method == self::POST && (!isset($this->headers['content-type']) && isset($this->enctype))) {
         $headers[] = "Content-type: {$this->enctype}";
     }
     // Set the user agent header
     if (!isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
         $headers[] = "User-agent: {$this->config['useragent']}";
     }
     // Set HTTP authentication if needed
     if (is_array($this->auth)) {
         $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
         $headers[] = "Authorization: {$auth}";
     }
     // Load cookies from cookie jar
     if (isset($this->cookiejar)) {
         $cookstr = $this->cookiejar->getMatchingCookies($this->uri, true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
         if ($cookstr) {
             $headers[] = "Cookie: {$cookstr}";
         }
     }
     // Add all other user defined headers
     foreach ($this->headers as $name => $value) {
         if (is_array($value)) {
             $value = implode(', ', $value);
         }
         $headers[] = ucfirst($name) . ": {$value}";
     }
     return $headers;
 }
Example #5
0
 /**
  * Prepare the request headers
  *
  * @return array
  */
 protected function _prepareHeaders()
 {
     $uri = $this->uri;
     $headers = array();
     // Set the host header
     if (!isset($this->headers["host"])) {
         $host = $uri->host;
         $port = (int) $uri->port;
         // If the port is not default, add it
         if (!($uri->scheme === "http" && $port === 80 || $uri->scheme === "https" && $port === 443)) {
             $host .= ":" . $port;
         }
         $headers[] = "Host: {$host}";
     }
     // Set the connection header
     if (!isset($this->headers["connection"])) {
         if (!$this->config["keepalive"]) {
             $headers[] = "Connection: close";
         }
     }
     // Set the Accept-encoding header if not set - depending on whether
     // zlib is available or not.
     if (!isset($this->headers["accept-encoding"])) {
         if (function_exists("gzinflate")) {
             $headers[] = "Accept-encoding: gzip, deflate";
         } else {
             $headers[] = "Accept-encoding: identity";
         }
     }
     // Set the Content-Type header
     if ($this->method === self::POST && (!isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
         $headers[] = self::CONTENT_TYPE . ": " . $this->enctype;
     }
     // Set the user agent header
     if (!isset($this->headers["user-agent"]) && isset($this->config["useragent"])) {
         $headers[] = "User-Agent: {$this->config['useragent']}";
     }
     // Set HTTP authentication if needed
     if (is_array($this->auth)) {
         $auth = self::encodeAuthHeader($this->auth["user"], $this->auth["password"], $this->auth["type"]);
         $headers[] = "Authorization: {$auth}";
     }
     // Load cookies from cookie jar
     if (isset($this->cookiejar)) {
         $cookstr = $this->cookiejar->getMatchingCookies($uri, true, Sabel_Http_CookieJar::COOKIE_STRING_CONCAT);
         if ($cookstr) {
             $headers[] = "Cookie: {$cookstr}";
         }
     }
     // Add all other user defined headers
     foreach ($this->headers as $header) {
         list($name, $value) = $header;
         if (is_array($value)) {
             $value = implode(", ", $value);
         }
         $headers[] = "{$name}: {$value}";
     }
     return $headers;
 }
Example #6
0
 /**
  * Test we can properly set an existing cookie jar
  *
  */
 public function testSetReadyCookieJar()
 {
     $jar = new Zend_Http_CookieJar();
     $jar->addCookie('cookie=value', 'http://www.example.com');
     $jar->addCookie('chocolate=chips; path=/foo', 'http://www.example.com');
     $this->client->setCookieJar($jar);
     // Check we got the right cookiejar
     $this->assertEquals($jar, $this->client->getCookieJar(), '$jar is not the client\'s cookie jar as expected');
 }
 private function _getMatchCookieValue($name, $domain, Zend_Http_CookieJar $jar)
 {
     $cookies = $jar->getMatchingCookies($domain);
     foreach ($cookies as $cookie) {
         /* @var $cookie Zend_Http_Cookie */
         if ($cookie->getName() == $name) {
             return $cookie->getValue();
         }
     }
     return false;
 }
 /**
  * Test we can build a new object from a response object (multiple cookie headers)
  */
 public function testFromResponseMultiHeader()
 {
     $res_str = file_get_contents(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'response_with_cookies');
     $response = Zend_Http_Response::fromString($res_str);
     $jar = Zend_Http_CookieJar::fromResponse($response, 'http://www.example.com');
     $this->assertTrue($jar instanceof Zend_Http_CookieJar, '$jar is not an instance of CookieJar as expected');
     $this->assertEquals(3, count($jar->getAllCookies()), 'CookieJar expected to contain 3 cookies');
 }
 /**
  * Make sure that paths with trailing slashes are matched as well as paths with no trailing slashes
  */
 public function testMatchPathWithTrailingSlash()
 {
 	$jar = new Zend_Http_CookieJar();
 	$cookies = array(
 		Zend_Http_Cookie::fromString('foo1=bar1; domain=.example.com; path=/a/b'),
 		Zend_Http_Cookie::fromString('foo2=bar2; domain=.example.com; path=/a/b/')
 	);
 	
 	foreach ($cookies as $cookie) $jar->addCookie($cookie);
 	$cookies = $jar->getMatchingCookies('http://www.example.com/a/b/file.txt');
 	
 	$this->assertType('array', $cookies);
 	$this->assertEquals(2, count($cookies));    	
 }
 private function _loadPage($uri, $forceAuth = false)
 {
     X_Debug::i("Loading page {$uri}");
     $http = new Zend_Http_Client($uri, array('maxredirects' => $this->config('request.maxredirects', 10), 'timeout' => $this->config('request.timeout', 10), 'keepalive' => true));
     $http->setHeaders(array('User-Agent: vlc-shares/' . X_VlcShares::VERSION . ' animeftw/' . self::VERSION));
     $jarFile = APPLICATION_PATH . '/../data/animeftw/cookie.jar';
     $ns = new Zend_Session_Namespace(__CLASS__);
     if ($this->jar == null) {
         if (false && isset($ns->jar) && $ns->jar instanceof Zend_Http_CookieJar) {
             $this->jar = $ns->jar;
             X_Debug::i('Loading stored authentication in Session');
         } elseif (file_exists($jarFile)) {
             if (filectime($jarFile) < time() - 24 * 60 * 60) {
                 X_Debug::i('Jarfile is old. Refreshing it');
                 @unlink($jarFile);
             } else {
                 $this->jar = new Zend_Http_CookieJar();
                 $cookies = unserialize(file_get_contents($jarFile));
                 foreach ($cookies as $c) {
                     $_c = new Zend_Http_Cookie($c['name'], $c['value'], $c['domain'], $c['exp'], $c['path']);
                     $this->jar->addCookie($_c);
                 }
                 X_Debug::i('Loading stored authentication in File');
             }
         }
     }
     $http->setCookieJar($this->jar);
     $response = $http->request();
     $htmlString = $response->getBody();
     if ($forceAuth && $this->config('auth.username', '') != '' && $this->config('auth.password', '') != '' && !$this->_isAuthenticated($htmlString)) {
         X_Debug::i("Autentication needed");
         $http->setCookieJar(true);
         $pageLogin = $this->config('login.url', self::PAGE_LOGIN);
         $http->setUri($pageLogin);
         $http->setParameterPost(array('username' => (string) $this->config('auth.username', ''), 'password' => (string) $this->config('auth.password', ''), '_submit_check' => '1', 'submit' => 'Sign In', 'remember' => 'on', 'last_page' => 'https://www.animeftw.tv'));
         // TODO remove this
         if (APPLICATION_ENV == 'development') {
             $response = $http->request(Zend_Http_Client::POST);
             if (!$this->_isAuthenticated($response->getBody())) {
                 X_Debug::w('Wrong credentials or authentication procedure doesn\'t work');
             } else {
                 X_Debug::w('Client authenticated. Full access granted');
             }
             //X_Debug::i($response->getBody());
         } else {
             $http->request(Zend_Http_Client::POST);
         }
         $this->jar = $http->getCookieJar();
         // store the cookiejar
         $cks = $this->jar->getAllCookies(Zend_Http_CookieJar::COOKIE_OBJECT);
         foreach ($cks as $i => $c) {
             /* @var $c Zend_Http_Cookie */
             $cks[$i] = array('domain' => $c->getDomain(), 'exp' => $c->getExpiryTime(), 'name' => $c->getName(), 'path' => $c->getPath(), 'value' => $c->getValue());
         }
         if (@file_put_contents($jarFile, serialize($cks), LOCK_EX) === false) {
             X_Debug::e('Error while writing jar file. Check permissions. Everything will work, but much more slower');
         }
         //$ns->jar = $this->jar;
         // time to do a new old request
         //$http->resetParameters();
         $http->setUri($uri);
         $response = $http->request(Zend_Http_Client::GET);
         $htmlString = $response->getBody();
     }
     return $htmlString;
 }
 private function _loadPage($uri, $forceAuth = false)
 {
     X_Debug::i("Loading page {$uri}");
     $http = new Zend_Http_Client($uri, array('maxredirects' => $this->config('request.maxredirects', 10), 'timeout' => $this->config('request.timeout', 10), 'keepalive' => true));
     $http->setHeaders(array($this->config('hide.useragent', false) ? 'User-Agent: vlc-shares/' . X_VlcShares::VERSION : 'User-Agent: Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20101019 Firefox/4.0.1'));
     $jarFile = APPLICATION_PATH . '/../data/animedb/cookie.jar';
     $ns = new Zend_Session_Namespace(__CLASS__);
     if ($this->jar == null) {
         if (false && isset($ns->jar) && $ns->jar instanceof Zend_Http_CookieJar) {
             $this->jar = $ns->jar;
             X_Debug::i('Loading stored authentication in Session');
         } elseif (file_exists($jarFile)) {
             $this->jar = new Zend_Http_CookieJar();
             $cookies = unserialize(file_get_contents($jarFile));
             foreach ($cookies as $c) {
                 $_c = new Zend_Http_Cookie($c['name'], $c['value'], $c['domain'], $c['exp'], $c['path']);
                 $this->jar->addCookie($_c);
             }
             X_Debug::i('Loading stored authentication in File');
         }
     }
     $http->setCookieJar($this->jar);
     //time to make the request
     $response = $http->request();
     $htmlString = $response->getBody();
     //X_Debug::i($htmlString);
     // before return the page, I have to check if i'm authenticated
     // TODO REMOVE AUTH
     if ($forceAuth && $this->config('auth.username', '') != '' && $this->config('auth.password', '') != '' && !$this->_isAuthenticated($htmlString)) {
         X_Debug::i("Autentication needed");
         $token = $this->_getSecurityToken($htmlString);
         //$sValue = $this->_getSValue($htmlString);
         // do new login
         $http->setCookieJar(true);
         $pageLogin = $this->config('login.url', 'http://animedb.tv/forum/login.php?do=login');
         $http->setUri($pageLogin);
         $http->setParameterPost(array('vb_login_username' => (string) $this->config('auth.username', ''), 'vb_login_password' => (string) $this->config('auth.password', ''), 'vb_login_password_hint' => 'Password', 'vb_login_md5password' => '', 'vb_login_md5password_utf' => '', 'securitytoken' => $token, 'do' => 'login', 'cookieuser' => 1, 's' => '', 'x' => 13, 'y' => 30));
         // TODO remove this
         if (APPLICATION_ENV == 'development') {
             $response = $http->request(Zend_Http_Client::POST);
             if (!$this->_isAuthenticated($response->getBody(), '<p class="blockrow restore">Grazie per esserti collegato,')) {
                 X_Debug::w('Wrong credentials or authentication procedure doesn\'t work');
             } else {
                 X_Debug::w('Client authenticated. Full access granted');
             }
             //X_Debug::i($response->getBody());
         } else {
             $http->request(Zend_Http_Client::POST);
         }
         $this->jar = $http->getCookieJar();
         // store the cookiejar
         $cks = $this->jar->getAllCookies(Zend_Http_CookieJar::COOKIE_OBJECT);
         foreach ($cks as $i => $c) {
             /* @var $c Zend_Http_Cookie */
             $cks[$i] = array('domain' => $c->getDomain(), 'exp' => $c->getExpiryTime(), 'name' => $c->getName(), 'path' => $c->getPath(), 'value' => $c->getValue());
         }
         if (@file_put_contents($jarFile, serialize($cks), LOCK_EX) === false) {
             X_Debug::e('Error while writing jar file. Check permissions. Everything will work, but much more slower');
         }
         //$ns->jar = $this->jar;
         // time to do a new old request
         //$http->resetParameters();
         $http->setUri($uri);
         $response = $http->request(Zend_Http_Client::GET);
         $htmlString = $response->getBody();
         //X_Debug::i($htmlString);
     }
     return $htmlString;
 }
Example #12
0
 /**
  * Faz o logou da WIKI e remove os cookies
  * @param string $url (OPCIONAL) URL da API da wiki, se não fornecida irá utilizar a do application.ini
  * @throws Exception
  */
 static function logout($url = null)
 {
     $config = RW_Config::getApplicationIni();
     // Recupera as configurações
     $apiurl = is_null($url) ? $config->wiki->apiurl : $url;
     // Cria o cliente
     $client = new Zend_Http_Client();
     // Recupera os cookies
     $cookies = new Zend_Http_CookieJar();
     foreach ($_COOKIE as $c => $val) {
         $cookies->addCookie(new Zend_Http_Cookie($c, $val, $_SERVER['HTTP_HOST']));
     }
     // Faz o logout
     $client->setUri($apiurl);
     $client->setHeaders('Accept-Encoding', 'none');
     $client->setParameterPost('action', 'logout');
     $client->setParameterPost('format', 'php');
     $client->setCookieJar($cookies);
     $response = $client->request(Zend_Http_Client::POST);
     $result = unserialize($response->getBody());
     //RW_Debug::dump($response->getBody());
     //RW_Debug::dump($response->getHeader('Set-Cookie'));
     //RW_Debug::dump($result);
     // Remove os cookies
     $cookies = $response->getHeader('Set-Cookie');
     foreach ($cookies as $c) {
         $c = explode('=', $c, 2);
         setcookie($c[0], 'deleted', 1, '/', $_SERVER['HTTP_HOST'], false, true);
     }
     // RW_Debug::dump($_COOKIE);
 }
 private function _loadPage($uri)
 {
     X_Debug::i("Loading page {$uri}");
     $http = new Zend_Http_Client($uri, array('maxredirects' => $this->config('request.maxredirects', 10), 'timeout' => $this->config('request.timeout', 10), 'keepalive' => true));
     $http->setHeaders(array($this->config('hide.useragent', false) ? 'User-Agent: vlc-shares/' . X_VlcShares::VERSION : 'User-Agent: Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20101019 Firefox/4.0.1', 'X-Requested-With: XMLHttpRequest', 'Referer: http://www.opfitalia.net/mediacenter/index.php?page=show_streaming', 'Content-Type: application/x-www-form-urlencoded'));
     $jarFile = APPLICATION_PATH . '/../data/opfitalia/cookie.jar';
     //$ns = new Zend_Session_Namespace(__CLASS__);
     if ($this->jar == null) {
         // Session disabled, i'm not sure wiimc can handle sessions
         /*if ( false && isset($ns->jar) && $ns->jar instanceof Zend_Http_CookieJar ) {
         			$this->jar = $ns->jar;
         			X_Debug::i('Loading stored authentication in Session');
         		} else*/
         if (file_exists($jarFile)) {
             $this->jar = new Zend_Http_CookieJar();
             $cookies = unserialize(file_get_contents($jarFile));
             foreach ($cookies as $c) {
                 $_c = new Zend_Http_Cookie($c['name'], $c['value'], $c['domain'], $c['exp'], $c['path']);
                 $this->jar->addCookie($_c);
             }
             X_Debug::i('Loading stored authentication in File');
         } else {
             X_Debug::i('No cookie file');
         }
     }
     $http->setCookieJar($this->jar);
     //time to make the request
     $response = $http->request();
     $jsonString = $response->getBody();
     try {
         $decoded = Zend_Json::decode($jsonString, Zend_Json::TYPE_OBJECT);
         return $decoded;
     } catch (Exception $e) {
         // if the request doesn't return JSON code,
         // maybe user isn't authenticated
         X_Debug::i('User not authenticated');
         if ($this->config('auth.username', '') != '' && $this->config('auth.password', '') != '') {
             X_Debug::i("Autentication needed");
             // do new login
             $http->setCookieJar(true);
             $pageLogin = $this->config('login.url', 'http://www.opfitalia.net/mediacenter/index.php?page=login');
             $http->setUri($pageLogin);
             // TODO remove this
             $http->setParameterPost(array('username' => (string) $this->config('auth.username', ''), 'password' => (string) hash('sha256', $this->config('auth.password', ''), false), 'redirectUrl' => '', 'rememberMe' => '1'));
             // TODO remove this
             if (APPLICATION_ENV == 'development') {
                 $response = $http->request(Zend_Http_Client::POST);
                 if (!$this->_isAuthenticated($response->getBody(), 'correttamente')) {
                     X_Debug::w('Wrong credentials or authentication procedure doesn\'t work');
                 } else {
                     X_Debug::w('Client authenticated. Full access granted');
                 }
                 //X_Debug::i($response->getBody());
             } else {
                 $http->request(Zend_Http_Client::POST);
             }
             $this->jar = $http->getCookieJar();
             // store the cookiejar
             $cks = $this->jar->getAllCookies(Zend_Http_CookieJar::COOKIE_OBJECT);
             foreach ($cks as $i => $c) {
                 /* @var $c Zend_Http_Cookie */
                 $cks[$i] = array('domain' => $c->getDomain(), 'exp' => $c->getExpiryTime(), 'name' => $c->getName(), 'path' => $c->getPath(), 'value' => $c->getValue());
             }
             if (@file_put_contents($jarFile, serialize($cks), LOCK_EX) === false) {
                 X_Debug::e('Error while writing jar file. Check permissions. Everything will work, but much more slower');
             }
             //$ns->jar = $this->jar;
             $http->setUri($uri);
             $http->resetParameters(false);
             $response = $http->request(Zend_Http_Client::GET);
             $jsonString = $response->getBody();
             try {
                 $decoded = Zend_Json::decode($jsonString, Zend_Json::TYPE_OBJECT);
             } catch (Exception $e) {
                 // epic fail
                 // Useless authentication
                 //X_Debug::i('Epic fail page: '.print_r($jsonString, true));
                 throw new Exception('Authetication failed');
             }
         } else {
             throw new Exception('Username/Password not found');
         }
     }
     return $decoded;
 }