public function errorAction()
 {
     $errors = $this->_getParam('error_handler');
     switch ($errors->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
             // 404 error -- controller or action not found
             $this->getResponse()->setHttpResponseCode(404);
             $this->view->message = 'Page not found';
             break;
         default:
             // application error
             $this->getResponse()->setHttpResponseCode(500);
             $this->view->message = 'Application error';
             break;
     }
     /*
     // Log exception, if logger available
     if ($log = $this->getLog()) {
         $log->crit($this->view->message, $errors->exception);
     }
     */
     X_Debug::f($this->view->message . ": " . $errors->exception->getMessage());
     X_Debug::f($errors->exception->getTraceAsString());
     // conditionally display exceptions
     //if ($this->getInvokeArg('displayExceptions') == true ) {
     $this->view->exception = $errors->exception;
     //}
     $this->view->request = $errors->request;
 }
 public function gen_afterPageBuild(X_Page_ItemList_PItem $items, Zend_Controller_Action $controller)
 {
     if (!$this->isDefaultRenderer()) {
         // to be used, this
         return;
     }
     X_Debug::i("Plugin triggered");
     $request = $controller->getRequest();
     $urlHelper = $controller->getHelper('url');
     if ($request instanceof Zend_Controller_Request_Http) {
         if ($request->isXmlHttpRequest() || $request->getParam('webkit:json', false)) {
             $this->dispatchRequest($request, $items, $controller);
         } else {
             $this->showMainPage($request, $controller);
         }
     } else {
         X_Debug::f("Request isn't HTTP");
     }
 }
 public function getSelectionItems($provider, $location, $pid, Zend_Controller_Action $controller)
 {
     // we want to expose items only if pid is this plugin
     if ($this->getId() != $pid) {
         return;
     }
     X_Debug::i('Plugin triggered');
     $urlHelper = $controller->getHelper('url');
     try {
         /*
         $provider = X_VlcShares_Plugins::broker()->getPlugins($provider);
         $providerClass = get_class($provider);
         
         
         
         // i try to mark current selected profile based on $this->getId() param
         // in $profileLabel i get the name of the current profile
         $currentLabel = false;
         $profileId = $controller->getRequest()->getParam($this->getId(), false);
         if ( $profileId !== false ) {
         	$_profile = new Application_Model_Profile();
         	Application_Model_ProfilesMapper::i()->find($profileId, $_profile);
         	if ( $_profile->getId() != null ) {
         		$currentLabel = $_profile->getLabel();
         	}
         }
         
         
         // if i can resolve the real location of the item
         // i can try to use special profiles
         $codecCond = null; 
         if ( $provider instanceof X_VlcShares_Plugins_ResolverInterface ) {
         	
         	// location param come in a plugin encoded way
         	$location = $provider->resolveLocation($location);
         
         	$codecCond = array();
         	
         	$this->helpers()->stream()->setLocation($location);
         	
         	if ( $this->helpers()->stream()->getVideoStreamsNumber() ) {
         		$codecCond[] = $this->helpers()->stream()->getVideoCodecName();
         	}
         	
         	
         	if ( $this->helpers()->stream()->getVideoStreamsNumber() ) {
         		$codecCond[] = $this->helpers()->stream()->getAudioCodecName();
         	}
         
         	$codecCond = implode('+', $codecCond);
         	if ( $codecCond == '') $codecCond = null;
         	
         }
         
         $deviceCond = $this->helpers()->devices()->getDeviceType();
         
         $profiles = Application_Model_ProfilesMapper::i()->fetchByConds($codecCond, $deviceCond, $providerClass);
         */
         // i try to mark current selected profile based on $this->getId() param
         // in $profileLabel i get the name of the current profile
         $currentLabel = false;
         $profileId = $controller->getRequest()->getParam($this->getId(), false);
         if ($profileId !== false) {
             $_profile = new Application_Model_Profile();
             Application_Model_ProfilesMapper::i()->find($profileId, $_profile);
             if ($_profile->getId() != null) {
                 $currentLabel = $_profile->getLabel();
             }
         }
         $defaultId = $this->helpers()->devices()->getDefaultDeviceIdProfile();
         $profile = new Application_Model_Profile();
         Application_Model_ProfilesMapper::i()->find($defaultId, $profile);
         $profiles = array($profile);
         $extraIds = $this->helpers()->devices()->getDevice()->getExtra('alt-profiles');
         //X_Debug::i("Profiles: ".$extraIds);
         if ($extraIds && is_array($extraIds) && count($extraIds)) {
             foreach ($extraIds as $id) {
                 if ($defaultId == $id) {
                     continue;
                 }
                 $profile = new Application_Model_Profile();
                 Application_Model_ProfilesMapper::i()->find($id, $profile);
                 if ($profile->getId()) {
                     $profiles[] = $profile;
                 }
             }
         }
         $return = new X_Page_ItemList_PItem();
         /*
         $item = new X_Page_Item_PItem($this->getId().'-auto', X_Env::_('p_profiles_selection_auto'));
         $item->setType(X_Page_Item_PItem::TYPE_ELEMENT)
         	->setLink(array(
         			'action'	=>	'mode',
         			$this->getId() => null, // unset this plugin selection
         			'pid'		=>	null
         		), 'default', false)
         	->setHighlight($currentLabel === false);
         $return->append($item);
         */
         if (count($profiles)) {
             X_Debug::e("No valid profiles for this device: i need at least a profile");
         }
         // the best is the first
         foreach ($profiles as $profile) {
             /* @var $profile Application_Model_Profile */
             X_Debug::i("Valid profile: [{$profile->getId()}] {$profile->getLabel()}");
             $item = new X_Page_Item_PItem($this->getId() . '-' . $profile->getId(), $profile->getLabel() . ($profile->getId() == $defaultId ? " [" . X_Env::_('p_profiles_selection_auto') . "]" : ''));
             $item->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setLink(array('action' => 'mode', 'pid' => null, $this->getId() => $profile->getId()), 'default', false)->setHighlight($currentLabel == $profile->getLabel() || !$currentLabel && $profile->getId() == $defaultId);
             $return->append($item);
         }
         // general profiles are in the bottom of array
         return $return;
     } catch (Exception $e) {
         X_Debug::f("Problem while getting provider obj: {$e->getMessage()}");
         throw $e;
     }
 }
 public function streamAction()
 {
     $request = $this->getRequest();
     X_VlcShares_Plugins::broker()->gen_preProviderSelection($this);
     $provider = $request->getParam('p', false);
     if ($provider === false || !X_VlcShares_Plugins::broker()->isRegistered($provider)) {
         throw new Exception("Invalid provider");
     }
     $location = X_Env::decode($request->getParam('l', ''));
     $providerObj = X_VlcShares_Plugins::broker()->getPlugins($provider);
     // if provider is a resolver, i can use new streamer api
     if (X_VlcShares_Plugins::helpers()->streamer()->isEnabled() && $providerObj instanceof X_VlcShares_Plugins_ResolverInterface) {
         $url = $providerObj->resolveLocation($location);
         X_Debug::i("Resolved location: {{$url}}");
         // check if url is valid (resolver give null or false on error)
         if (!$url) {
             X_Debug::e("Invalid location: {$location}");
             throw new Exception("Stream location is invalid: {$url}");
         }
         $engine = X_VlcShares_Plugins::helpers()->streamer()->find($url);
         X_Debug::i("Streamer engine found: {{$engine->getId()}}");
         // automatically set the url as source param in the engine
         $engine->setSource($url);
         // NEW APIS
         // each arg is stored as in a LIFO stack. If i put top priority as first,
         // low priority args could override it. So i use an inverse priority insertion
         // register low priority args
         X_VlcShares_Plugins::broker()->preRegisterStreamerArgs($engine, $url, $provider, $location, $this);
         // register normal priority args
         X_VlcShares_Plugins::broker()->registerStreamerArgs($engine, $url, $provider, $location, $this);
         // register top priority args
         X_VlcShares_Plugins::broker()->postRegisterStreamerArgs($engine, $url, $provider, $location, $this);
         X_VlcShares_Plugins::broker()->preStartStreamer($engine, $url, $provider, $location, $this);
         $results = X_VlcShares_Plugins::broker()->canStartStreamer($engine, $url, $provider, $location, $this);
         $started = false;
         if (is_null($results) || !in_array(false, $results)) {
             X_Debug::i("Starting streamer {{$engine->getId()}}: {$engine}");
             $started = true;
             X_Streamer::i()->start($engine);
         } else {
             $pluginId = array_search(false, $results, true);
             X_Debug::f("Plugin {{$pluginId}} prevented streamer from starting...");
             //throw new Exception("Plugin {{$pluginId}} prevented streamer from starting");
         }
         X_VlcShares_Plugins::broker()->postStartStreamer($started, $engine, $url, $provider, $location, $this);
     } else {
         // otherwise i'm forced to fallback to old api
         //{{{ THIS CODE BLOCK WILL IS DEPRECATED AND WILL BE REMOVED IN 0.5.6 or 0.6
         //TODO remove in 0.5.6 or 0.6
         // each arg is stored as in a LIFO stack. If i put top priority as first,
         // low priority args could override it. So i use an inverse priority insertion
         // register low priority args
         X_VlcShares_Plugins::broker()->preRegisterVlcArgs($this->vlc, $provider, $location, $this);
         // register normal priority args
         X_VlcShares_Plugins::broker()->registerVlcArgs($this->vlc, $provider, $location, $this);
         // register top priority args
         X_VlcShares_Plugins::broker()->postRegisterVlcArgs($this->vlc, $provider, $location, $this);
         X_VlcShares_Plugins::broker()->preSpawnVlc($this->vlc, $provider, $location, $this);
         $this->vlc->spawn();
         X_VlcShares_Plugins::broker()->postSpawnVlc($this->vlc, $provider, $location, $this);
         try {
             $engine = X_VlcShares_Plugins::helpers()->streamer()->get('vlc');
         } catch (Exception $e) {
             X_Debug::w('No vlc streamer available');
             $engine = new X_Streamer_Engine_Vlc($this->vlc);
         }
         $url = $this->vlc->getArg('source');
         //}}}
     }
     $pageItems = new X_Page_ItemList_PItem();
     // i can't add here the go to play button
     // because i don't know the output type
     // i need to leave this to the plugins, too
     // i hope that an output manager plugin
     // will be always enabled
     // top links
     $pageItems->merge(X_VlcShares_Plugins::broker()->preGetStreamItems($engine, $url, $provider, $location, $this));
     // normal links
     $pageItems->merge(X_VlcShares_Plugins::broker()->getStreamItems($engine, $url, $provider, $location, $this));
     // bottom links
     $pageItems->merge(X_VlcShares_Plugins::broker()->postGetStreamItems($engine, $url, $provider, $location, $this));
     // trigger for page creation
     X_VlcShares_Plugins::broker()->gen_afterPageBuild($pageItems, $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);
 }
 /**
  * Show an wiimc compatible error page in plx format
  */
 function gen_beforePageBuild(Zend_Controller_Action $controller)
 {
     //if ( !((bool) $this->config('forced.enabled', false)) && !$this->helpers()->devices()->isWiimc() ) return;
     if (!$this->isDefaultRenderer()) {
         return;
     }
     $controllerName = $controller->getRequest()->getControllerName();
     $actionName = $controller->getRequest()->getControllerName();
     if ("{$controllerName}/{$actionName}" != "error/error") {
         return;
     }
     X_Debug::i("Plugin triggered");
     try {
         $cachePlugin = X_VlcShares_Plugins::broker()->getPlugins('cache');
         if (method_exists($cachePlugin, 'setDoNotCache')) {
             $cachePlugin->setDoNotCache();
         }
     } catch (Exception $e) {
     }
     // setting request as dispatched prevent action execution
     $controller->getRequest()->setDispatched(true);
     /* @var $urlHelper Zend_Controller_Action_Helper_Url */
     $urlHelper = $controller->getHelper('url');
     $errors = $controller->getRequest()->getParam('error_handler');
     $view = new stdClass();
     switch ($errors->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
             // 404 error -- controller or action not found
             //$this->getResponse()->setHttpResponseCode(404);
             $view->message = 'Page not found';
             break;
         default:
             // application error
             //$this->getResponse()->setHttpResponseCode(500);
             $view->message = 'Application error';
             break;
     }
     X_Debug::f($view->message . ": " . $errors->exception->getMessage());
     X_Debug::f($errors->exception->getTraceAsString());
     $view->exception = $errors->exception;
     $plx = new X_Plx(X_Env::_('p_wiimcplxrenderer_plxtitle_error_error'), X_Env::_('p_wiimcplxrenderer_plxdescription_error_error'));
     $plx->addItem(new X_Plx_Item(X_Env::_('p_wiimcplxrenderer_plxerror_title', $view->message), X_Env::completeUrl($urlHelper->url())));
     $plx->addItem(new X_Plx_Item(X_Env::_('p_wiimcplxrenderer_plxerror_message', $errors->exception->getMessage()), X_Env::completeUrl($urlHelper->url())));
     $plx->addItem(new X_Plx_Item(X_Env::_('p_wiimcplxrenderer_plxerror_stacktrace_separator'), X_Env::completeUrl($urlHelper->url())));
     $stacktrace = explode("\n", $errors->exception->getTraceAsString());
     foreach ($stacktrace as $i => $trace) {
         $plx->addItem(new X_Plx_Item(X_Env::_('p_wiimcplxrenderer_plxerror_trace', $i, $trace), X_Env::completeUrl($urlHelper->url())));
     }
     $plx->addItem(new X_Plx_Item(X_Env::_('p_wiimcplxrenderer_plxerror_request_separator'), X_Env::completeUrl($urlHelper->url())));
     $params = $errors->request->getParams();
     foreach ($params as $key => $value) {
         $plx->addItem(new X_Plx_Item(X_Env::_('p_wiimcplxrenderer_plxerror_param', $key, $value), X_Env::completeUrl($urlHelper->url())));
     }
     $this->_render($plx, $controller);
     $controller->getResponse()->sendResponse();
     // the execution will stop here!
     // or zf will send in header code 500 and wiimc will not parse the response
     exit;
 }
 public function installPlugin($source, $isUrl = false)
 {
     X_Debug::i("Installing plugin from {{$source}}: isUrl = {{$isUrl}}");
     if ($isUrl) {
         // perform a download in a temp file
         $http = new Zend_Http_Client($source, array('headers' => array('User-Agent' => "vlc-shares/" . X_VlcShares::VERSION . " plugininstaller/" . X_VlcShares::VERSION)));
         $http->setStream(true);
         $source = $http->request()->getStreamName();
     }
     try {
         // unzip and manifest parse
         $egg = X_Egg::factory($source, APPLICATION_PATH . '/../', APPLICATION_PATH . '/../data/plugin/tmp/', true);
         $pluginKey = $egg->getKey();
         // first we must check if key already exists in the db
         $plugin = new Application_Model_Plugin();
         Application_Model_PluginsMapper::i()->fetchByKey($pluginKey, $plugin);
         if ($plugin->getId() !== null) {
             throw new Exception(X_Env::_('plugin_err_installerror_keyexists') . ": {$pluginKey}");
         }
         // time to check if plugin support this vlc-shares version
         $vFrom = $egg->getCompatibilityFrom();
         $vTo = $egg->getCompatibilityTo();
         if (version_compare(X_VlcShares::VERSION_CLEAN, $vFrom, '<') || $vTo !== null && version_compare(X_VlcShares::VERSION_CLEAN, $vTo, '>=')) {
             throw new Exception(X_Env::_('plugin_err_installerror_unsupported') . ": {$vFrom} - {$vTo}");
         }
         // copy the files: first check if some file exists...
         $toBeCopied = array();
         foreach ($egg->getFiles() as $file) {
             /* @var $file X_Egg_File */
             if (!$file->getProperty(X_Egg_File::P_REPLACE, false) && file_exists($file->getDestination())) {
                 throw new Exception(X_Env::_('plugin_err_installerror_fileexists') . ": {$file->getDestination()}");
             }
             if (!file_exists($file->getSource())) {
                 if (!$file->getProperty(X_Egg_File::P_IGNOREIFNOTEXISTS, false)) {
                     throw new Exception(X_Env::_('plugin_err_installerror_sourcenotexists') . ": {$file->getSource()}");
                 }
                 // ignore this item if P_IGNOREIFNOTEXISTS is true and file not exists
                 continue;
             }
             $toBeCopied[] = array('src' => $file->getSource(), 'dest' => $file->getDestination(), 'resource' => $file);
         }
         // before copy act, i must be sure to be able to revert changes
         $plugin = new Application_Model_Plugin();
         $plugin->setLabel($egg->getLabel())->setKey($pluginKey)->setDescription($egg->getDescription())->setFile($egg->getFile())->setClass($egg->getClass())->setType(Application_Model_Plugin::USER)->setVersion($egg->getVersion());
         Application_Model_PluginsMapper::i()->save($plugin);
         // so i must copy uninstall information inside a uninstall dir in data
         $dest = APPLICATION_PATH . '/../data/plugin/_uninstall/' . $pluginKey;
         // i have to create the directory
         if (!mkdir($dest, 0777, true)) {
             throw new Exception(X_Env::_('plugin_err_installerror_uninstalldircreation') . ": {$dest}");
         }
         if (!copy($egg->getManifestFile(), "{$dest}/manifest.xml")) {
             throw new Exception(X_Env::_('plugin_err_installerror_uninstallmanifestcopy') . ": " . $egg->getManifestFile() . " -> {$dest}/manifest.xml");
         }
         $uninstallSql = $egg->getUninstallSQL();
         if ($uninstallSql !== null && file_exists($uninstallSql)) {
             if (!copy($uninstallSql, "{$dest}/uninstall.sql")) {
                 throw new Exception(X_Env::_('plugin_err_installerror_uninstallsqlcopy') . ": {$dest}");
             }
         }
         // ... then copy
         foreach ($toBeCopied as $copyInfo) {
             $copied = false;
             if (!file_exists(dirname($copyInfo['dest']))) {
                 @mkdir(dirname($copyInfo['dest']), 0777, true);
             }
             if (!copy($copyInfo['src'], $copyInfo['dest'])) {
                 $this->_helper->flashMessenger(array('text' => X_Env::_('plugin_err_installerror_copyerror') . ": <br/>" . $copyInfo['src'] . '<br/>' . $copyInfo['dest'], 'type' => 'error'));
             } else {
                 X_Debug::i("File copied {{$copyInfo['dest']}}");
                 $copied = true;
             }
             /* @var $xeggFile X_Egg_File */
             $xeggFile = $copyInfo['resource'];
             if ($copied) {
                 // check permission
                 $permission = $xeggFile->getProperty(X_Egg_File::P_PERMISSIONS, false);
                 if ($permission !== false) {
                     if (!chmod($copyInfo['dest'], octdec($permission))) {
                         X_Debug::e("Chmod {{$permission}} failed for file {{$copyInfo['dest']}}");
                     } else {
                         X_Debug::i("Permissions set to {{$permission}} for file {{$copyInfo['dest']}} as required");
                     }
                 }
             } else {
                 if ($xeggFile->getProperty(X_Egg_File::P_HALTONCOPYERROR, false)) {
                     X_Debug::f("File not copied {{$copyInfo['dest']}} and flagged as HaltOnCopyError");
                     break;
                 }
             }
         }
         // change database
         $installSql = $egg->getInstallSQL();
         if ($installSql !== null && file_exists($installSql)) {
             try {
                 $dataSql = file_get_contents($installSql);
                 if (trim($dataSql) !== '') {
                     $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
                     $db = $bootstrap->getResource('db');
                     $db->getConnection()->exec($dataSql);
                 }
             } catch (Exception $e) {
                 X_Debug::e("DB Error while installind: {$e->getMessage()}");
                 $this->_helper->flashMessenger(X_Env::_('plugin_err_installerror_sqlerror') . ": {$e->getMessage()}");
                 //throw $e;
             }
         }
         // process acl fragment
         $aclHelper = X_VlcShares_Plugins::helpers()->acl();
         // new classes
         $accounts = Application_Model_AuthAccountsMapper::i()->fetchAll();
         foreach ($egg->getAclClasses() as $aclClass) {
             /* @var $aclClass X_Egg_AclClass */
             $res = $aclHelper->addClass($aclClass->getName(), $aclClass->getProperty(X_Egg_AclClass::P_DESCRIPTION, ''));
             if (!$res) {
                 $this->_helper->flashMessenger(array('text' => X_Env::_('plugin_err_installerror_aclclass', $aclClass->getName()), 'type' => 'warning'));
                 continue;
             }
             $extends = $aclClass->getExtends();
             if (count($extends)) {
                 foreach ($accounts as $account) {
                     /* @var $account Application_Model_AuthAccount */
                     foreach ($extends as $baseClass) {
                         if (in_array($baseClass, $aclHelper->getPermissions($account->getUsername()))) {
                             $aclHelper->grantPermission($account->getUsername(), $aclClass->getName());
                         }
                     }
                 }
             }
         }
         //new resources
         foreach ($egg->getAclResources() as $resource) {
             /* @var $resource X_Egg_AclResource */
             $aclHelper->addResource($resource->getKey(), $resource->getClass(), $egg->getKey(), false);
         }
         $egg->cleanTmp();
         unlink($source);
         return true;
     } catch (Exception $e) {
         if ($egg !== null) {
             $egg->cleanTmp();
         }
         // delete the uploaded file
         unlink($source);
         //$this->_helper->flashMessenger(array('text' => X_Env::_('plugin_err_installerror').": ".$e->getMessage(), 'type' => 'error'));
         //return false;
         throw $e;
     }
 }
 /**
  * Show the list of valid streams
  * @param string $provider
  * @param string $location
  * @param string $pid
  * @param Zend_Controller_Action $controller
  * @return X_Page_ItemList_PItem
  */
 public function getSelectionItems($provider, $location, $pid, Zend_Controller_Action $controller)
 {
     // we want to expose items only if pid is this plugin
     if ($this->getId() != $pid) {
         return;
     }
     X_Debug::i('Plugin triggered');
     $urlHelper = $controller->getHelper('url');
     // i try to mark current selected sub based on $this->getId() param
     // in $currentSub i get the name of the current profile
     $currentStream = $controller->getRequest()->getParam($this->getId(), false);
     $return = new X_Page_ItemList_PItem();
     try {
         /* @var $realdebridHelper X_VlcShares_Plugins_Helper_RealDebrid */
         $realdebridHelper = $this->helpers('realdebrid');
         // check if a valid location has been setted
         if (!$realdebridHelper->isValid()) {
             X_Debug::i("Try to force location retrieval");
             $providerObj = X_VlcShares_Plugins::broker()->getPlugins($provider);
             if ($providerObj instanceof X_VlcShares_Plugins_ResolverInterface) {
                 $providerObj->resolveLocation($location);
             } elseif (method_exists($providerObj, 'resolveLocation')) {
                 // try to check if resolveLocation is there, even if not the interface
                 $providerObj->resolveLocation($location);
             } else {
                 X_Debug::e("Provider can't be called for location resolving");
                 return;
             }
         }
         $links = $realdebridHelper->getUrls();
         X_Debug::i('Plugin triggered. Location could be provided by RealDebrid');
         // if $pid == ID:refresh, only force refresh the link
         if ($controller->getRequest()->getParam("{$this->getId()}:refresh", false) != false) {
             $realdebridHelper->cleanCurrentCacheEntry();
             $item = new X_Page_Item_PItem($this->getId(), X_Env::_('p_realdebrid_refreshdone'));
             $item->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setLink(array('action' => 'mode', "{$this->getId()}:refresh" => null, 'pid' => null), 'default', false);
             $return->append($item);
         } else {
             foreach ($links as $i => $streamlink) {
                 $linkPart = explode('/', $streamlink);
                 $label = urldecode(array_pop($linkPart));
                 $item = new X_Page_Item_PItem($this->getId() . "-{$i}", X_Env::_('p_realdebrid_streamoption', $label, $streamlink));
                 $item->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setLink(array('action' => 'mode', $this->getId() => $i == 0 ? null : $i, 'pid' => null), 'default', false)->setHighlight($currentStream == $i);
                 $return->append($item);
             }
         }
     } catch (Exception $e) {
         X_Debug::f("Location is not provided by RealDebrid, but i'm inside the stream type selection O_o");
     }
     return $return;
 }
 /**
  * Change the url of directplay link to add seeked value
  * @see X_VlcShares_Plugins_Abstract::filterModeItems()
  */
 public function filterModeItems(X_Page_Item_PItem $item, $provider, Zend_Controller_Action $controller)
 {
     if ($item->getKey() == 'core-directwatch' && $item->isUrl()) {
         $ssValue = $controller->getRequest()->getParam($this->getId(), 0);
         if ($ssValue > 0) {
             // need to change the value
             $link = $item->getLink();
             /* @var $hosterHelper X_VlcShares_Plugins_Helper_HosterSSWrapper */
             $hosterHelper = $this->helpers()->hoster();
             /* @var $hoster X_VlcShares_Plugins_Helper_HostInterface */
             $hoster = $hosterHelper->getLastPositiveMatch();
             /* @var $ssHelper X_VlcShares_Plugins_Helper_StreamSeeker */
             $ssHelper = $this->helpers('streamseeker');
             if ($ssHelper->isSeekableHoster($hoster)) {
                 $newLink = $ssHelper->getSeekedUrl($link, $ssValue, $hoster);
                 X_Debug::i("Changing link to {$newLink}");
                 $item->setLink($newLink);
             } else {
                 X_Debug::f("A seekable hoster reported as unseekable on last check: " . get_class($hoster));
             }
         }
     }
 }
 function __call($funcName, $funcParams)
 {
     if (method_exists('X_VlcShares_Plugins_Abstract', $funcName) && !in_array($funcName, $this->backlistedFunctions)) {
         $toBeCalled = array();
         foreach ($this->plugins as $pluginId => $pluginObj) {
             /* @var $pluginObj X_VlcShares_Plugins_Abstract */
             $priority = $pluginObj->getPriority($funcName);
             if ($priority !== -1) {
                 $toBeCalled[$priority][$pluginId] = $pluginObj;
             }
         }
         $returnedVal = null;
         ksort($toBeCalled);
         foreach ($toBeCalled as $priorityStack) {
             foreach ($priorityStack as $pluginId => $pluginObj) {
                 /* @var $pluginObj X_VlcShares_Plugins_Abstract */
                 //X_Debug::i("Calling ".get_class($pluginObj)."::$funcName"); // for problem, uncomment this
                 $return = call_user_func_array(array($pluginObj, $funcName), $funcParams);
                 if ($return !== null) {
                     //$returnedVal[$pluginId] = $return;
                     if ($return instanceof X_Page_ItemList) {
                         if ($returnedVal == null) {
                             $returnedVal = $return;
                         } else {
                             $returnedVal->merge($return);
                         }
                     } else {
                         if ($returnedVal == null) {
                             $returnedVal = array($pluginId => $return);
                         } elseif (is_array($returnedVal)) {
                             $returnedVal[$pluginId] = $return;
                         }
                     }
                 }
             }
         }
         return $returnedVal;
     } else {
         X_Debug::f("Invalid trigger: {$funcName}");
         throw new Exception('Invalid trigger');
     }
 }