/**
  * Test we can get all matching cookies for a request, and return as strings array / concat
  */
 public function testGetMatchingCookiesAsStrings()
 {
     $jar = new Zend_Http_CookieJar();
     $cookies = array(Zend_Http_Cookie::fromString('foo1=bar1; domain=.foo.com; path=/path; expires=' . date(DATE_COOKIE, time() + 3600)), Zend_Http_Cookie::fromString('foo2=bar2; domain=.foo.com; path=/; expires=' . date(DATE_COOKIE, time() + 3600)), Zend_Http_Cookie::fromString('foo3=bar3; domain=.foo.com; path=/; expires=' . date(DATE_COOKIE, time() - 3600)), Zend_Http_Cookie::fromString('foo4=bar4; domain=.foo.com; path=/;'), Zend_Http_Cookie::fromString('foo5=bar5; domain=.foo.com; path=/; secure; expires=' . date(DATE_COOKIE, time() + 3600)), Zend_Http_Cookie::fromString('foo6=bar6; domain=.foo.com; path=/otherpath; expires=' . date(DATE_COOKIE, time() + 3600)), Zend_Http_Cookie::fromString('foo7=bar7; domain=www.foo.com; path=/path; expires=' . date(DATE_COOKIE, time() + 3600)), Zend_Http_Cookie::fromString('foo8=bar8; domain=subdomain.foo.com; path=/path; expires=' . date(DATE_COOKIE, time() + 3600)));
     foreach ($cookies as $cookie) {
         $jar->addCookie($cookie);
     }
     $this->assertEquals(8, count($jar->getAllCookies()), 'Cookie count is expected to be 8');
     $cookies = $jar->getMatchingCookies('http://www.foo.com/path/file.txt', true, Zend_Http_CookieJar::COOKIE_STRING_ARRAY);
     $this->assertTrue(is_array($cookies), '$cookies is expected to be an array, but it is not');
     $this->assertTrue(is_string($cookies[0]), '$cookies[0] is expected to be a string');
     $cookies = $jar->getMatchingCookies('http://www.foo.com/path/file.txt', true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
     $this->assertTrue(is_string($cookies), '$cookies is expected to be a string');
     $expected = 'foo1=bar1;foo2=bar2;foo4=bar4;foo7=bar7;';
     $this->assertEquals($expected, $cookies, 'Concatenated string is not as expected');
     $cookies = $jar->getMatchingCookies('http://www.foo.com/path/file.txt', true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT_STRICT);
     $this->assertTrue(is_string($cookies), '$cookies is expected to be a string');
     $expected = 'foo1=bar1; foo2=bar2; foo4=bar4; foo7=bar7';
     $this->assertEquals($expected, $cookies, 'Concatenated string is not as expected');
 }
 public function premiumAction()
 {
     // time to get params from get
     /* @var $request Zend_Controller_Request_Http */
     $request = $this->getRequest();
     if (!$this->plugin->config('premium.enabled', true) || $this->plugin->config('premium.username', '') == '' || $this->plugin->config('premium.password', '') == '') {
         throw new Exception(X_Env::_('p_megavideo_err_premiumdisabled'));
     }
     X_Debug::i('Premium account support enabled');
     $videoId = $request->getParam('v', false);
     // video file url
     $qualityType = $request->getParam('q', X_VlcShares_Plugins_Helper_Megavideo::QUALITY_NORMAL);
     // video file url
     if ($videoId === false) {
         // invalid request
         throw new Exception(X_Env::_('p_megavideo_err_invalidrequest'));
         return;
     }
     X_Debug::i("Video: {$videoId}");
     // i check for NOPREMIUM quality: i don't need authentication in NOPREMIUM mode
     if ($qualityType != X_VlcShares_Plugins_Helper_Megavideo::QUALITY_NOPREMIUM) {
         X_Debug::i('Premium features enabled');
         $http = new Zend_Http_Client('http://localhost/', array('maxredirects' => 10, 'timeout' => 10, 'keepalive' => true));
         $http->setHeaders(array('User-Agent: Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20101019 Firefox/4.0.1', 'Accept-Language:it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4'));
         $jarFile = APPLICATION_PATH . '/../data/megavideo/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');
             } else {
                 $this->jar = new Zend_Http_CookieJar();
                 //$this->jar->addCookie(new Zend_Http_Cookie('l', 'it', 'http://www.megavideo.com'));
             }
         }
         $http->setCookieJar($this->jar);
         $userId = false;
         if ($http->getCookieJar() != null) {
             //X_Debug::i(var_export($http->getCookieJar()->getAllCookies(Zend_Http_CookieJar::COOKIE_STRING_ARRAY), true));
             //$userId = $http->getCookieJar()->getCookie($cookieUri, 'user', Zend_Http_CookieJar::COOKIE_STRING_ARRAY);
             $userId = $this->_getMatchCookieValue('user', 'http://www.megavideo.com/', $http->getCookieJar());
             X_Debug::i("First check for userId: {$userId}");
         }
         if ($userId == false) {
             X_Debug::i("No valid userId found in Cookies");
             $this->_authenticateHttp($http, $this->plugin->config('premium.username', ''), $this->plugin->config('premium.password', ''));
             //X_Debug::i(var_export($http->getCookieJar()->getAllCookies(Zend_Http_CookieJar::COOKIE_STRING_ARRAY), true));
             //$userId = $http->getCookieJar()->getCookie($cookieUri, 'user', Zend_Http_CookieJar::COOKIE_STRING_ARRAY);
             $userId = $this->_getMatchCookieValue('user', 'http://www.megavideo.com/', $http->getCookieJar());
             if ($userId == false) {
                 X_Debug::f("Invalid account given");
                 throw new Exception(X_Env::_('p_megavideo_invalidaccount'));
             }
         }
         X_Debug::i("UserId in cookies: {$userId}");
         $uri = "http://www.megavideo.com/xml/player_login.php?u={$userId}&v={$videoId}";
         $http->setUri($uri);
         $response = $http->request();
         $htmlString = $response->getBody();
         if (strpos($htmlString, 'type="premium"') === false) {
             X_Debug::w("Account isn't premium or not authenticated");
             X_Debug::i(var_export($htmlString));
             // invalid cookies
             // need to re-authenticate
             $this->_authenticateHttp($http, $this->plugin->config('premium.username', ''), $this->plugin->config('premium.password', ''));
             $response = $http->request();
             $htmlString = $response->getBody();
             if (strpos($htmlString, 'type="premium"') === false) {
                 X_Debug::f("Invalid premium account");
                 X_Debug::i(var_export($htmlString));
                 throw new Exception(X_Env::_('p_megavideo_invalidpremiumaccount'));
             }
         }
         // time to store the cookie
         $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');
         }
         // in htmlString we should have an xml like this one:
         /*
         	<?xml version="1.0" encoding="UTF-8"?> 
         	<user type="premium" user="******" downloadurl="http%3A%2F%2Fwww444.megavideo.com%2Ffiles%2Fd9ab7ef6313e55ab26240f2aac9dd74f%2FAmerican.Dad.-.1AJN08.-.Tutto.su.Steve.%28All.About.Steve%29.-.DVDMuX.BY.Pi3TRo.%26amp%3B.yodonvito.avi" />		
         */
         // i create context here so i can use the same context
         // for normal link quality video
         $cookies = $http->getCookieJar()->getAllCookies(Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
         $opts = array('http' => array('header' => array("Cookie: {$cookies}")));
     } else {
         X_Debug::i('Premium features NOT enabled');
         // if quality == NOPREMIUM i don't need authentication or context
         // no context needed
         $opts = array('http' => array());
     }
     $context = stream_context_create($opts);
     $videoUrl = null;
     switch ($qualityType) {
         case X_VlcShares_Plugins_Helper_Megavideo::QUALITY_NOPREMIUM:
             X_Debug::w("Premium proxy feature, but NOPREMIUM quality? O_o");
             $megavideo = new X_Megavideo($videoId);
             $videoUrl = $megavideo->get('URL');
             break;
         case X_VlcShares_Plugins_Helper_Megavideo::QUALITY_FULL:
             X_Debug::i("FULL quality selected");
             if (preg_match('/ downloadurl=\\"([^\\"]*)\\" /', $htmlString, $match)) {
                 // match[1] is the video link
                 $videoUrl = urldecode(@$match[1]);
                 // i break the case because 1 have a match
                 break;
             } else {
                 // no videoURL, fallback to normal
                 X_Debug::e('No download url, fallback to NORMAL quality');
                 //X_Debug::i($htmlString);
             }
         case X_VlcShares_Plugins_Helper_Megavideo::QUALITY_NORMAL:
         default:
             $megavideo = new X_Megavideo($videoId, $context, $userId);
             $videoUrl = $megavideo->get('URL');
     }
     X_Debug::i("VideoURL: {$videoUrl}");
     // this action is so special.... no layout or viewRenderer
     $this->_helper->viewRenderer->setNoRender();
     $this->_helper->layout->disableLayout();
     // if user abort request (vlc/wii stop playing), this process ends
     ignore_user_abort(false);
     // close and clean the output buffer, everything will be read and send to device
     ob_end_clean();
     header("Content-Type: video/mp4");
     // readfile open a file and send it directly to output buffer
     readfile($videoUrl, false, $context);
 }
 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;
 }
 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)
 {
     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;
 }