Example #1
0
 /**
  * Add a cookie to the request. If the client has no Cookie Jar, the cookies
  * will be added directly to the headers array as "Cookie" headers.
  *
  * @param Zend_Http_Cookie|string $cookie
  * @param string|null $value If "cookie" is a string, this is the cookie value.
  * @return Zend_Http_Client
  * @throws Zend_Http_Client_Exception
  */
 public function setCookie($cookie, $value = null)
 {
     Zend_Loader::loadClass('Zend_Http_Cookie');
     if (is_array($cookie)) {
         foreach ($cookie as $c => $v) {
             if (is_string($c)) {
                 $this->setCookie($c, $v);
             } else {
                 $this->setCookie($v);
             }
         }
         return $this;
     }
     if ($value !== null && $this->config['encodecookies']) {
         $value = urlencode($value);
     }
     if (isset($this->cookiejar)) {
         if ($cookie instanceof Zend_Http_Cookie) {
             $this->cookiejar->addCookie($cookie);
         } elseif (is_string($cookie) && $value !== null) {
             $cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}", $this->uri, $this->config['encodecookies']);
             $this->cookiejar->addCookie($cookie);
         }
     } else {
         if ($cookie instanceof Zend_Http_Cookie) {
             $name = $cookie->getName();
             $value = $cookie->getValue();
             $cookie = $name;
         }
         if (preg_match("/[=,; \t\r\n\v\f]/", $cookie)) {
             /** @see Zend_Http_Client_Exception */
             require_once 'Zend/Http/Client/Exception.php';
             throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\v\f ({$cookie})");
         }
         $value = addslashes($value);
         if (!isset($this->headers['cookie'])) {
             $this->headers['cookie'] = array('Cookie', '');
         }
         $this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
     }
     return $this;
 }
Example #2
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');
 }
 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());
 }
 /**
  * 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->assertType('array', $cookies, '$cookies is expected to be an array, but it is not');
     $this->assertType('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->assertType('string', $cookies, '$cookies is expected to be a string');
 }
Example #5
0
 /**
  * Add a cookie to the request. If the client has no Cookie Jar, the cookies
  * will be added directly to the headers array as "Cookie" headers.
  *
  * @param Zend_Http_Cookie|string $cookie
  * @param string|null $value If "cookie" is a string, this is the cookie value.
  * @return Zend_Http_Client
  * @throws Zend_Http_Client_Exception
  */
 public function setCookie($cookie, $value = null)
 {
     if (is_array($cookie)) {
         foreach ($cookie as $c => $v) {
             if (is_string($c)) {
                 $this->setCookie($c, $v);
             } else {
                 $this->setCookie($v);
             }
         }
         return $this;
     }
     if ($value !== null) {
         $value = urlencode($value);
     }
     if (isset($this->cookiejar)) {
         if ($cookie instanceof Sabel_Http_Cookie) {
             $this->cookiejar->addCookie($cookie);
         } elseif (is_string($cookie) && $value !== null) {
             $cookie = Sabel_Http_Cookie::fromString("{$cookie}={$value}", $this->uri);
             $this->cookiejar->addCookie($cookie);
         }
     } else {
         if ($cookie instanceof Sabel_Http_Cookie) {
             $name = $cookie->getName();
             $value = $cookie->getValue();
             $cookie = $name;
         }
         if (preg_match("/[=,; \t\r\n\v\f]/", $cookie)) {
             $message = __METHOD__ . "() Cookie name cannot contain these characters: =,; \t\r\n\v\f ({$cookie})";
             throw new Sabel_Exception_Runtime($message);
         }
         $value = addslashes($value);
         if (!isset($this->headers["cookie"])) {
             $this->headers["cookie"] = array("Cookie", "");
         }
         $this->headers["cookie"][1] .= $cookie . "=" . $value . "; ";
     }
     return $this;
 }
Example #6
0
    /**
     * Add a cookie to the request. If the client has no Cookie Jar, the cookies
     * will be added directly to the headers array as "Cookie" headers.
     *
     * @param Zend_Http_Cookie|string $cookie
     * @param string|null $value If "cookie" is a string, this is the cookie value.
     * @return Zend_Http_Client
     */
    public function setCookie($cookie, $value = null)
    {
        if (! class_exists('Zend_Http_Cookie'))
            require_once 'Zend/Http/Cookie.php';

        if (is_array($cookie)) {
            foreach ($cookie as $c => $v) {
                if (is_string($c)) {
                    $this->setCookie($c, $v);
                } else {
                    $this->setCookie($v);
                }
            }

            return $this;
        }

        if ($value !== null) $value = urlencode($value);

        if (isset($this->cookiejar)) {
            if ($cookie instanceof Zend_Http_Cookie) {
                $this->cookiejar->addCookie($cookie);
            } elseif (is_string($cookie) && $value !== null) {
                $cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}", $this->uri);
                $this->cookiejar->addCookie($cookie);
            }
        } else {
            if ($cookie instanceof Zend_Http_Cookie) {
                $name = $cookie->getName();
                $value = $cookie->getValue();
                $cookie = $name;
            }

            if (preg_match("/[=,; \t\r\n\013\014]/", $cookie))
                throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");

            $value = addslashes($value);

            if (! isset($this->headers['cookie'])) $this->headers['cookie'] = '';
            $this->headers['cookie'] .= $cookie . '=' . $value . '; ';
        }

        return $this;
    }
 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);
 }
 /**
  * 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 #11
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;
 }