function gen_beforePageBuild(Zend_Controller_Action $controller) { $moduleName = $controller->getRequest()->getModuleName(); $controllerName = $controller->getRequest()->getControllerName(); $actionName = $controller->getRequest()->getActionName(); $providerName = $controller->getRequest()->getParam('p', false); // check permission class if ($controllerName == 'browse' && $actionName == 'share') { // check provider too only if controller == browse $resourceKey = "{$moduleName}/{$controllerName}/{$actionName}" . ($providerName !== false ? "/{$providerName}" : ''); } else { $resourceKey = "{$moduleName}/{$controllerName}/{$actionName}"; } // TODO: // replace this with an ACL call: // if ( !$acl->canUse($resource, $currentStatus) ) if (array_search("{$moduleName}/{$controllerName}/{$actionName}", $this->_whiteList) === false) { if (!$this->isLoggedIn()) { X_Debug::i("Login required and user not logged in"); if ($this->helpers()->devices()->isVlc()) { X_Debug::i("Look like it's this vlc: {$_SERVER['REMOTE_ADDR']}"); if (gethostbyname($_SERVER['REMOTE_ADDR']) == '::1' || gethostbyname($_SERVER['REMOTE_ADDR']) == '127.0.0.1') { X_Debug::i("Skipping auth, it should be the local vlc"); return; } } elseif ($this->helpers()->devices()->isWiimc() && $this->helpers()->devices()->isWiimcBeforeVersion('1.1.6')) { // wiimc <= 1.1.5 send 2 different user-agent string // for browsing mode and video mode // so i have care about this // TODO remove this when 1.1.5 an older will be deprecated // anyway i take care only of vanilla wiimc based on ios58. custom version // not supported $useragent = "{$_SERVER['HTTP_USER_AGENT']} (IOS58)"; // try to add " (ISO58)" to the useragent and check again if (Application_Model_AuthSessionsMapper::i()->fetchByIpUserAgent($_SERVER['REMOTE_ADDR'], $useragent)) { X_Debug::i("Workaround for WIIMC user-agent-incongruence"); return; } } elseif ($this->helpers()->acl()->canUseAnonymously($resourceKey)) { X_Debug::i("Resource can be used anonymously"); return; } X_Debug::w("Auth required, redirecting to login"); $controller->getRequest()->setControllerName("auth")->setActionName('index')->setDispatched(false); } elseif ($this->config('acl.enabled', false)) { X_Debug::i("ACL enabled, checking resource {{$resourceKey}}"); $username = $this->getCurrentUser(true); if (!$this->helpers()->acl()->canUse($username, $resourceKey)) { X_Debug::w("Forbidden, can't access resource"); $controller->getRequest()->setControllerName("auth")->setActionName('forbidden')->setDispatched(false); } else { X_Debug::i("Access granted"); } } else { X_Debug::i("ACL disabled"); } } else { X_Debug::i("Whitelisted resource"); } }
public function parse($string) { $parsed = array(); switch ($this->function) { case self::PREG_MATCH: if (@preg_match($this->pattern, $string, $parsed, $this->flags) === false) { X_Debug::w("Invalid pattern (" . preg_last_error() . "): {$this->pattern}"); $parsed = array(); } break; case self::PREG_MATCH_ALL: if (@preg_match_all($this->pattern, $string, $parsed, $this->flags) === false) { X_Debug::w("Invalid pattern (" . preg_last_error() . "): {$this->pattern}"); $parsed = array(); } break; case self::PREG_SPLIT: $parsed = @preg_split($this->pattern, $string, null, $this->flags); if ($parsed === false) { X_Debug::w("Invalid pattern (" . preg_last_error() . "): {$this->pattern}"); $parsed = array(); } break; default: X_Debug::e("Invalid function code provided: {$this->function}"); } return $parsed; }
/** * Execute vlcwrapper initialization on the first request */ private function lazyInit() { if ($this->_initialized === false) { $options = $this->options; $adapterConf = $options->get('adapter', new Zend_Config(array())); $adapter = $adapterConf->get('name', "X_Vlc_Adapter_" . (X_Env::isWindows() ? 'Windows' : 'Linux')); X_Debug::i("Adapter: {$adapter}"); $this->adapter = new $adapter($options); $commanderConf = $options->get('commander', new Zend_Config(array())); $commander = $commanderConf->get('name', ''); $commanderPath = $commanderConf->get('path', ''); if ($commanderPath != '' && file_exists($commanderPath)) { X_Debug::i("Including commanderPath: {$commanderPath}"); include_once $commanderPath; } if (class_exists($commander, true) && array_key_exists('X_Vlc_Commander', class_parents($commander))) { X_Debug::i("Commander: {$commander}"); $commander = new $commander($options); $this->adapter->setCommander($commander); } else { X_Debug::w("Commander: no selection"); } $this->_conf_vlcArgs = $options->get('args', "{%source%} --play-and-exit --sout=\"#{%profile%}:{%output%}\" --sout-keep {%subtitles%} {%audio%} {%filters%}"); $this->_conf_vlcPath = $options->get('path', "vlc"); $this->_initialized = true; } }
function spawn($threadId) { $http = new Zend_Http_Client($this->url, array('timeout' => 3, 'keepalive' => false)); $i = 20; do { if ($i-- < 0) { throw new Exception("To many hash generation failed"); } $salt = rand(1, 1000); $key = time(); $privKey = rand(100000, 999999); $hash = md5("{$salt}{$privKey}{$key}"); } while (!$this->storeRequestKey($hash, $privKey)); $http->setParameterPost('hash', $hash)->setParameterPost('key', $key)->setParameterPost('salt', $salt)->setParameterPost('thread', $threadId); try { $body = $http->request(Zend_Http_Client::POST)->getBody(); $response = @Zend_Json::decode($body); if ($response) { return @$response['success']; } } catch (Exception $e) { // timeout // don't know, assume true X_Debug::w("Request timeout"); return true; } }
protected function processProperties($properties = array()) { if (!is_array($properties)) { X_Debug::e("Properties is not an array"); return; } foreach ($properties as $key => $value) { $properties_ignored = true; // prot-type is valid if (isset(self::$validProperties[$key])) { // check value $validValues = self::$validProperties[$key]; @(list($typeValidValues, $validValues) = @explode(':', $validValues, 2)); // typeValidValues = boolean / regex / set / ... switch ($typeValidValues) { case 'boolean': $checkValues = array('true', 'false', '0', '1'); if (array_search($value, $checkValues)) { // cast to type $value = (bool) $value; $properties_ignored = false; } else { $properties_ignored = "invalid property value {{$value}}, not boolean"; } break; case 'set': $checkValues = explode('|', $validValues); if (array_search($value, $checkValues)) { $properties_ignored = false; } else { $properties_ignored = "invalid property value {{$value}}, not in valid set"; } break; case 'regex': if (preg_match($validValues, $value)) { $properties_ignored = false; } else { $properties_ignored = "invalid property value {{$value}}, format not valid"; } break; } } else { $properties_ignored = "invalid property"; } if ($properties_ignored !== false) { X_Debug::w("Property {{$key}} of acl-resource {{$this->getKey()}} ignored: " . $properties_ignored !== true ? $properties_ignored : 'unknown reason'); } else { X_Debug::i("Valid property for acl-resource {{$this->getKey()}}: {$key} => {{$value}}"); $this->properties[$key] = $value; } } }
/** * Sorts items: * if provider is FileSystem uses a folder/file sort * else alphabetical one * @param array &$items array of X_Page_Item_PItem * @param string $provider id of the plugin the handle the request * @param Zend_Controller_Action $controller */ public function orderShareItems(&$items, $provider, Zend_Controller_Action $controller) { X_Debug::i('Plugin triggered'); try { $plugin = X_VlcShares_Plugins::broker()->getPlugins($provider); // TODO check for problem if i always use sortFolderBased if (true || is_a($plugin, 'X_VlcShares_Plugins_FileSystem')) { X_Debug::i('Sort sortFolderBased'); usort($items, array(__CLASS__, 'sortFolderBased')); } else { X_Debug::i('Sort generic'); usort($items, array(__CLASS__, 'sortAlphabetically')); } } catch (Exception $e) { X_Debug::w("Problem while sorting: {$e->getMessage()}"); } }
/** * get a playable resource url * from an $url (or a resource id if $isId = true) * @param string $url the hoster page or resource ID * @param boolean $isId * @return string a playable url */ function getPlayable($url, $isId = true) { if (!$isId) { $url = $this->getResourceId($url); } // $url is an id now for sure /* @var $youtubeHelper X_VlcShares_Plugins_Helper_Youtube */ $youtubeHelper = X_VlcShares_Plugins::helpers()->helper('youtube'); /* @var $youtubePlugin X_VlcShares_Plugins_Youtube */ $youtubePlugin = X_VlcShares_Plugins::broker()->getPlugins('youtube'); X_Debug::i("Youtube ID: {$url}"); // THIS CODE HAVE TO BE MOVED IN YOUTUBE HELPER // FIXME $formats = $youtubeHelper->getFormatsNOAPI($url); $returned = null; $qualityPriority = explode('|', $youtubePlugin->config('quality.priority', '5|34|18|35')); foreach ($qualityPriority as $quality) { if (array_key_exists($quality, $formats)) { $returned = $formats[$quality]; X_Debug::i('Video format selected: ' . $quality); break; } } if ($returned === null) { // for valid video id but video with restrictions // alternatives formats can't be fetched by youtube page. // i have to fallback to standard api url $apiVideo = $youtubeHelper->getVideo($url); foreach ($apiVideo->mediaGroup->content as $content) { if ($content->type === "video/3gpp") { $returned = $content->url; X_Debug::w('Content restricted video, fallback to api url:' . $returned); break; } } if ($returned === null) { $returned = false; } } if ($returned !== false && $returned !== null) { // valid return return $returned; } throw new Exception("Invalid video", self::E_ID_INVALID); }
public function addTranslation($key) { $moduleName = $key . '.' . $this->lang; // i have to check $moduleName to be sure that the file is inside the languages/ directory if (file_exists(realpath(APPLICATION_PATH . "/../languages/{$moduleName}"))) { $translate = new Zend_Translate('ini', realpath(APPLICATION_PATH . "/../languages/{$moduleName}")); } elseif ($this->lang != 'en_GB.ini' && file_exists(realpath(APPLICATION_PATH . "/../languages/{$key}.en_GB.ini"))) { // fallback to english translation X_Debug::w("Language file not found: {$moduleName}. Falling back to english translation"); $translate = new Zend_Translate('ini', realpath(APPLICATION_PATH . "/../languages/{$key}.en_GB.ini")); } else { X_Debug::w("Language file not found: {$moduleName}"); return false; } // time to append translator to the global instance X_Env::initTranslator($translate); return true; }
/** * Return true if $item is an hidden file or system file (check configs) * @param X_Page_Item_PItem $item * @param string $provider * @param Zend_Controller_Action $controller * @return boolean|null true or null if file is ok, false otherwise (will be filtered out) */ public function filterShareItems(X_Page_Item_PItem $item, $provider, Zend_Controller_Action $controller) { try { $plugin = X_VlcShares_Plugins::broker()->getPlugins($provider); if (is_a($plugin, 'X_VlcShares_Plugins_FileSystem') && $plugin instanceof X_VlcShares_Plugins_ResolverInterface) { // i use instanceof ResolverInterface // so i have code suggestions // X_VlcShares_Plugins_FileSystem register a custom param in item // for location lookup $location = $plugin->resolveLocation($item->getCustom('X_VlcShares_Plugins_FileSystem:location')); // i must check for $location !== false as a fallback for no custom param case if ($location !== false && file_exists($location)) { // i have a location to check for hidden files: if ($this->_checkEntry($location) === false) { X_Debug::i("Plugin triggered, item filtered: {$location}"); return false; } } //X_Debug::i('Plugin triggered'); } } catch (Exception $e) { X_Debug::w("Problem while filtering: {$e->getMessage()}"); } }
public function getPositions($location, $sourceFile) { $positions = array(); try { /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers('cache'); $positions = $cacheHelper->retrieveItem("streamseeker::{$location}"); if ($positions) { $positions = @unserialize($positions); } X_Debug::i("Using positions values stored in cache about {$location}"); // return stored values return $positions; } catch (Exception $e) { // no cache plugin or no positions cached X_Debug::i("No FLV info in cache about {$location}"); } // dump 9kb of the file to analyze it $tmpFile = tempnam(sys_get_temp_dir(), 'fia'); $sampleSize = intval($this->options->get('samplesize', 100)) * 1000; X_Debug::i("Downloading {$sampleSize} bytes in {$tmpFile} from {$sourceFile}"); $src = fopen($sourceFile, 'r'); $dest = fopen($tmpFile, 'w'); $copied = stream_copy_to_stream($src, $dest, $sampleSize); fclose($src); fclose($dest); X_Debug::i("{$copied} bytes downloaded"); try { $flvinfo = new X_FLVInfo(); $fileInfo = $flvinfo->getInfo($tmpFile, true, true); if ($fileInfo->signature) { $keyframes = @$fileInfo->rawMeta[1]['keyframes']; $times = $keyframes->times; $filepositions = $keyframes->filepositions; $lastAdd = 0; //$firstKey = 0; $minDelta = intval($this->options->get('mindelta', 5)) * 60; // mindelta is in minutes // time to parse and filter the response // filter using a minDelta function foreach ($times as $key => $seconds) { /* if ( $key == 0 ) { $firstKey = $filepositions[$key]; continue; }*/ if ($seconds - $lastAdd > $minDelta) { // new step //$positions["{$filepositions[$key]},{$firstKey}"] = X_Env::formatTime(intval($seconds)); $positions[$filepositions[$key]] = X_Env::formatTime(intval($seconds)); $lastAdd = intval($seconds); } } X_Debug::i("Valid position found in flv file: " . count($positions)); // parse done, store try { /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers('cache'); $cacheHelper->storeItem("streamseeker::{$location}", serialize($positions), $this->options->get('cachevalidity', 10)); } catch (Exception $e) { X_Debug::e("Cache is disabled. This is really bad for streamseeker"); } } else { X_Debug::w("Wrong signature. Can't analyze"); } } catch (Exception $e) { X_Debug::e("FLVInfo throws an error: {$e->getMessage()}"); } return $positions; }
protected function _fetch() { if ($this->_location == null) { X_Debug::w('Trying to fetch a megavideo location without a location'); throw new Exception('Trying to fetch a megavideo location without a location'); } if ($this->_fetched === false) { $this->_fetched = new X_Megavideo($this->_location); $this->_cachedSearch[$this->_location] = $this->_fetched; } }
/** * get an array with standard information about the playable * @param string $url the hoster page or resource ID * @param boolean $isId * @return array format: * array( * 'title' => TITLE * 'description' => DESCRIPTION * 'length' => LENGTH * ... * ) */ function getPlayableInfos($url, $isId = true) { if (!$isId) { $url = $this->getResourceId($url); } // use cached values if (array_key_exists($url, $this->info_cache)) { return $this->info_cache[$url]; } // use the api $http = new Zend_Http_Client("http://www.sockshare.com/embed/" . $url, array('headers' => array('User-Agent' => "vlc-shares/" . X_VlcShares::VERSION . " sockshare/" . X_VlcShares_Plugins_SockShare::VERSION))); $xml = $http->request()->getBody(); if (preg_match('/<div class\\=\\"message t_0\\">This file doesn\'t exist, or has been removed\\.<\\/div>/', $xml)) { X_Debug::e("Invalid ID {{$url}} or file removed"); throw new Exception("Invalid ID {{$url}}", self::E_ID_INVALID); } $matches = array(); if (!preg_match('/<strong>(?P<title>[^<]+)<\\/strong>/', $xml, $matches)) { $title = X_Env::_('p_sockshare_title_not_setted'); X_Debug::w("Title not found"); } else { $title = $matches['title']; } $description = ''; if (!preg_match('/<input type\\=\\"hidden\\" value\\=\\"(?P<hash>[^\\"]+)\\" name\\=\\"(?P<arg>[^\\"]+)\\">/', $xml, $matches)) { X_Debug::w("Couldn't find hash for file {{$url}}"); throw new Exception("Couldn't find hash for file {{$url}}", self::E_ID_INVALID); } $hash = $matches['hash']; $arg = $matches['arg']; // To turn cookie stickiness on, set a Cookie Jar $http->setCookieJar(); // First request: log in and start a session $http->setUri("http://www.sockshare.com/embed/" . $url); $http->setParameterPost($arg, $hash); $http->setParameterPost('confirm', 'Close Ad and Watch as Free User'); $http->request('POST'); $xml = $http->request()->getBody(); $matches = array(); if (!preg_match('/<img src="(?P<thumbnail>.+?)" name="bg" style=".+?" id="bg"\\/>/', $xml, $matches)) { X_Debug::w("No thumbnail found"); $thumbnail = ''; } else { $thumbnail = $matches['thumbnail']; } X_Debug::i("Thumbnail found {{$thumbnail}}"); $matches = array(); if (!preg_match("/playlist: '(?P<playlist>[^']+)'/", $xml, $matches)) { $playlist = ''; X_Debug::w("Couldn't find playlist for file " . $url . "!"); throw new Exception("Couldn't find playlist for file {{$url}}", self::E_ID_INVALID); } $playlist = $matches['playlist']; $http->setUri("http://www.sockshare.com" . $playlist); $http->request('GET'); $xml = $http->request()->getBody(); $matches = array(); if (!preg_match('/<media:content url\\=\\"(?P<video>[^\\"]+)\\" type\\=\\"video\\/x-flv\\" duration\\=\\"(?P<length>[^\\"]+)\\" \\/>/', $xml, $matches)) { X_Debug::w("Couldn't find video link for file " . $url . "!"); throw new Exception("Couldn't find video link for file {{$url}}", self::E_ID_INVALID); } $length = $matches['length']; $video = $matches['video']; $infos = array('title' => $title, 'description' => $description, 'length' => $length, 'thumbnail' => $thumbnail, 'url' => $video); // add in cache $this->info_cache[$url] = $infos; return $infos; }
public function removeResource($key) { $resource = new Application_Model_AclResource(); Application_Model_AclResourcesMapper::i()->find($key, $resource); if (!$resource->isNew()) { try { Application_Model_AclResourcesMapper::i()->delete($resource); X_Debug::i("Resource removed {{$key}}"); $this->resetCached(); return true; } catch (Exception $e) { X_Debug::e("Error removing resource: {$e->getMessage()}"); return false; } } else { X_Debug::w("Resource doesn't exists {{$key}}}"); return true; } }
/** * */ public function getInfo($infos = null) { // uso per fare il parsing if (is_null($infos)) { $infos = $this->_send(''); } /** <root> <volume>256</volume> <length>234</length> <time>12</time> <state>playing</state> <position>5</position> <fullscreen></fullscreen> <random>0</random> <loop>0</loop> <repeat>0</repeat> <information> <category name="Diffusione 0"> <info name="Tipo">Video</info> <info name="Codifica">XVID</info> <info name="Risoluzione">720x576</info> <info name="Risoluzione video">720x576</info> <info name="Immagini al secondo">25</info> </category> <category name="Diffusione 1"> <info name="Tipo">Audio</info> <info name="Codifica">mpga</info> <info name="Canali">Mono</info> <info name="Campionamento">48000 Hz</info> <info name="Bitrate">80 kb/s</info> </category> <meta-information> <title><![CDATA[/media/Windows/video.avi]]></title> <artist><![CDATA[]]></artist> <genre><![CDATA[]]></genre> <copyright><![CDATA[]]></copyright> <album><![CDATA[]]></album> <track><![CDATA[]]></track> <description><![CDATA[]]></description> <rating><![CDATA[]]></rating> <date><![CDATA[]]></date> <url><![CDATA[]]></url> <language><![CDATA[]]></language> <now_playing><![CDATA[]]></now_playing> <publisher><![CDATA[]]></publisher> <encoded_by><![CDATA[]]></encoded_by> <art_url><![CDATA[]]></art_url> <track_id><![CDATA[]]></track_id> </meta-information> </information> <stats> <readbytes>1498004</readbytes> <inputbitrate>0,107826</inputbitrate> <demuxreadbytes>1335729</demuxreadbytes> <demuxbitrate>0,139785</demuxbitrate> <decodedvideo>166</decodedvideo> <displayedpictures>467</displayedpictures> <lostpictures>27</lostpictures> <decodedaudio>528</decodedaudio> <playedabuffers>528</playedabuffers> <lostabuffers>3</lostabuffers> <sentpackets>0</sentpackets> <sentbytes>0</sentbytes> <sendbitrate>0,000000</sendbitrate> </stats> </root> */ $rInfos = array(); try { $dom = new Zend_Dom_Query($infos); // lunghezza $results = $dom->queryXpath('/root/length'); if (count($results) > 0) { $rInfos['length'] = $results->current()->nodeValue; } // posizione ora $results = $dom->queryXpath('/root/time'); if (count($results) > 0) { $rInfos['time'] = $results->current()->nodeValue; } // posizione name if ($this->options->version == '1.1.x') { $results = $dom->queryXpath('/root/information/meta-information/title'); if (count($results) > 0) { $rInfos['name'] = $results->current()->nodeValue; } } elseif ($this->options->version == '2.x') { $results = $dom->queryXpath('/root/information/category[@name="meta"]/info[@name="filename"]'); if (count($results) > 0) { $rInfos['name'] = $results->current()->nodeValue; } } /* l'aggiungo in 0.5 forse // posizione ora $results = $dom->queryXpath('/root/information/category'); if ( count($results) > 0 ) { $rInfos['streams'] = array(); //$rInfos['length'] = $results[0]->nodeValue; foreach ( $results as $category ) { $stream = array(); //$stream $rInfos['streams'][] = $stream; } } */ } catch (Exception $e) { X_Debug::w("Catch exception: {$e->getMessage()}"); } return $rInfos; }
/** * Disable layout and viewRenderer * @param Zend_Controller_Action $controller */ private function _disableRendering(Zend_Controller_Action $controller) { try { $controller->getHelper('viewRenderer')->setNoRender(true); // disableLayout must be called at the end // i don't know if layout is enabled // and maybe an exception is raised if // i call e disableLayout without layout active $controller->getHelper('layout')->disableLayout(); } catch (Exception $e) { X_Debug::w("Unable to disable viewRenderer or Layout: {$e->getMessage()}"); } }
private function _initConfigsForm($configs, $posts = null) { if ($this->configForm === null) { $this->configForm = new Application_Form_Configs($configs); $this->configForm->setAction($this->_helper->url('save', 'configs')); $languages = array(); foreach (new DirectoryIterator(APPLICATION_PATH . "/../languages/") as $entry) { if ($entry->isFile() && pathinfo($entry->getFilename(), PATHINFO_EXTENSION) == 'ini') { if (count(explode('.', $entry->getFilename())) == 2) { $languages[$entry->getFilename()] = $entry->getFilename(); } } } try { $this->configForm->general_languageFile->setMultiOptions($languages); } catch (Exception $e) { X_Debug::w("No language settings? O_o"); } try { $this->configForm->general_debug_level->setMultiOptions(array('-1' => '-1: ' . X_Env::_('config_debug_level_optforced'), '0' => '0: ' . X_Env::_('config_debug_level_optfatal'), '1' => '1: ' . X_Env::_('config_debug_level_opterror'), '2' => '2: ' . X_Env::_('config_debug_level_optwarning'), '3' => '3: ' . X_Env::_('config_debug_level_optinfo'))); } catch (Exception $e) { X_Debug::w("No debug level settings? O_o"); } try { $this->configForm->vlc_version->setMultiOptions(array('1.1.x' => '<= 1.1.x', '2.x' => '2.x')); } catch (Exception $e) { X_Debug::w("No vlc version setting? O_o"); } try { $_guis = X_VlcShares_Plugins::broker()->getPlugins(); $guis = array(); foreach ($_guis as $gui) { if ($gui instanceof X_VlcShares_Plugins_RendererInterface) { $guis[get_class($gui)] = "{$gui->getName()} - {$gui->getDescription()}"; } } $this->configForm->helpers_devices_gui->setMultiOptions($guis); } catch (Exception $e) { X_Debug::w("No gui settings"); } try { $_profiles = Application_Model_ProfilesMapper::i()->fetchAll(); foreach ($_profiles as $profile) { $profiles[$profile->getId()] = "{$profile->getId()} - {$profile->getLabel()}"; } $this->configForm->helpers_devices_profile->setMultiOptions($profiles); } catch (Exception $e) { X_Debug::w("No gui settings"); } } if ($posts !== null && is_array($posts)) { $this->configForm->isValid($posts); } return $this->configForm; }
/** * Convert form password to password element * @param string $section * @param string $namespace * @param unknown_type $key * @param Zend_Form_Element $element * @param Zend_Form $form * @param Zend_Controller_Action $controller */ public function prepareConfigElement($section, $namespace, $key, Zend_Form_Element $element, Zend_Form $form, Zend_Controller_Action $controller) { // nothing to do if this isn't the right section if ($namespace != $this->getId()) { return; } switch ($key) { // i have to convert it to a password element case 'plugins_rapidshare_premium_password': $password = $form->createElement('password', 'plugins_rapidshare_premium_password', array('label' => $element->getLabel(), 'description' => $element->getDescription(), 'renderPassword' => true)); $form->plugins_rapidshare_premium_password = $password; break; } // remove cookie if somethings has value if (!$form->isErrors() && !is_null($element->getValue()) && ($key = 'plugins_rapidshare_premium_password')) { // clean cookies try { X_Debug::i("Cleaning up cookies in cache"); /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache'); try { $cacheHelper->retrieveItem("rapidshare::cookie"); // set expire date to now! $cacheHelper->storeItem("rapidshare::cookie", '', 0); } catch (Exception $e) { // nothing to do } try { $cacheHelper->retrieveItem("rapidshare::lastreloginflag"); // set expire date to now! $cacheHelper->storeItem("realdebrid::lastreloginflag", '', 0); } catch (Exception $e) { // nothing to do } } catch (Exception $e) { X_Debug::w("Cache plugin disabled? O_o"); } } }
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 _getRealId($fakeId, $t) { try { /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache'); $response = $cacheHelper->retrieveItem("icefilms::{$t},{$fakeId}"); X_Debug::i("Valid cache entry found: {$response}"); return $response; } catch (Exception $e) { // no cache plugin or no entry in cache, it's the same X_Debug::i("Cache disabled or no valid entry found"); } // hover check $m = rand(100, 300) * -1; // time check $s = rand(5, 50); $http = new Zend_Http_Client("http://www.icefilms.info/membersonly/components/com_iceplayer/video.php?h=374&w=631&vid={$t}&img=", array('maxredirects' => $this->config('request.maxredirects', 10), 'timeout' => $this->config('request.timeout', 25))); // first request, set the cookies $htmlString = $http->setCookieJar(true)->request()->getBody(); //$captchaPattern = '/name\=captcha value\=([^\>]+)/'; //$secretPattern = '/name\=secret value\=([^\>]+)/'; $secretPattern = '/f\\.lastChild\\.value=\\"([^\']+)\\",a/'; //$iqsPattern = '/name\=iqs value\=([^\>]+)/'; $sec = array(); if (preg_match($secretPattern, $htmlString, $sec)) { if (count($sec)) { $sec = $sec[1]; } else { X_Debug::w("Secret string not found"); $sec = ''; } } else { X_Debug::e("Secret pattern failed {{$secretPattern}}"); $sec = ''; } $http->setUri('http://www.icefilms.info/membersonly/components/com_iceplayer/video.phpAjaxResp.php'); $http->setHeaders(array('User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1', 'Content-type:application/x-www-form-urlencoded', 'Origin: http://www.icefilms.info', "Referer: http://www.icefilms.info/membersonly/components/com_iceplayer/video.php?h=374&w=631&vid={$t}&img=")); $http->setMethod(Zend_Http_Client::POST)->setParameterPost('id', $fakeId)->setParameterPost('s', $s)->setParameterPost('iqs', '')->setParameterPost('url', '')->setParameterPost('m', $m)->setParameterPost('cap', '')->setParameterPost('sec', $sec)->setParameterPost('t', $t); //X_Debug::i("Cookies: ".$http->getCookieJar()->getAllCookies(Zend_Http_CookieJar::COOKIE_STRING_CONCAT)); $response = $http->request()->getBody(); //X_Debug::i("Request: ".$http->getLastRequest()); //X_Debug::i("Response: ".$http->getLastResponse()->getBody()); X_Debug::i("Raw: {$response}"); $response = trim(urldecode(substr($response, strlen('/membersonly/components/com_iceplayer/GMorBMlet.php?url='))), '&'); X_Debug::i("Filtered: {$response}"); try { /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache'); $cacheHelper->storeItem("icefilms::{$t},{$fakeId}", $response, 15); // store for the next 15 min X_Debug::i("Value stored in cache for 15 min: {key = icefilms::{$t},{$fakeId}, value = {$response}}"); } catch (Exception $e) { // no cache plugin, next time i have to repeat the request } return $response; }
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; }
protected function _initExtraPlugins() { $this->bootstrap('debug'); $this->bootstrap('db'); $this->bootstrap('plugins'); $this->bootstrap('frontController'); $this->bootstrap('view'); $this->bootstrap('configs'); $configs = $this->getResource('configs'); /* if ($configs instanceof Zend_Config ) { isset($configs->general->) } */ // only add them if in development env if (APPLICATION_ENV != 'development') { return; } $extraPlugins = trim($configs->general->get('extraPlugins', '')); if ($extraPlugins == '') { return; } $extraPlugins = explode(',', $extraPlugins); if (!count($extraPlugins)) { return; } $extraPlugins = array_map('trim', $extraPlugins); X_Debug::i("Extra plugins whitelist: " . implode(', ', $extraPlugins)); // check for extra plugins path $extraPluginsPath = APPLICATION_PATH . '/../../plugins'; if (!file_exists($extraPluginsPath)) { X_Debug::w("Extra plugins path not found"); return; } $displayError = ini_get('display_errors'); $displayStartup = ini_get('display_startup_errors'); $errorReporting = ini_get('error_reporting'); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); ini_set('error_reporting', 'E_ALL'); restore_error_handler(); restore_exception_handler(); //$prevHanlder = set_error_handler('myErrorHandler', E_ALL | E_STRICT); // scan /extra/plugins/$directory/ for dev_bootstrap.php file // and execute it. $directory = new DirectoryIterator($extraPluginsPath); foreach ($directory as $entry) { /* @var $entry DirectoryIterator */ // it doesn't allow dotted directories (. and ..) and file/symlink if ($entry->isDot() || !$entry->isDir()) { continue; } // not in white list if (array_search($entry->getFilename(), $extraPlugins) === false) { continue; } // skip this directory if a plugin with the same id is already registered if (X_VlcShares_Plugins::broker()->isRegistered($entry->getFilename())) { continue; } $bootstrapFile = $entry->getRealPath() . '/dev_bootstrap.php'; if (file_exists($bootstrapFile)) { // delegate everything to dev_bootstrap.php include_once $bootstrapFile; include $extraPluginsPath . '/bootstrap.php'; } } ini_set('display_errors', $displayError); ini_set('display_startup_errors', $displayStartup); ini_set('error_reporting', $errorReporting); }
/** * Remove vlc-play button if location is invalid * @param X_Page_Item_PItem $item, * @param string $provider * @param Zend_Controller_Action $controller */ public function filterModeItems(X_Page_Item_PItem $item, $provider, Zend_Controller_Action $controller) { if ($item->getKey() == 'core-play') { X_Debug::i('plugin triggered'); X_Debug::w('core-play flagged as invalid because the link is invalid'); return false; } }
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; }
/** * @see X_VlcShares_Plugins_ResolverInterface::resolveLocation * @param string $location * @return string real address of a resource */ function resolveLocation($location = null) { if ($location == '' || $location == null) { return false; } if (array_key_exists($location, $this->cachedLocation)) { return $this->cachedLocation[$location]; } X_Debug::i("Requested location: {$location}"); $split = $location != '' ? @explode('/', $location, 5) : array(); @(list($sortType, $subType, $page, $thread, $linkTypeId) = $split); @(list($videoType, $videoId) = @explode(':', $linkTypeId, 2)); //@list($letter, $thread, $href) = explode('/', $location, 3); X_Debug::i("SortType: {$sortType}, SubType: {$subType}, Page: {$page}, Thread: {$thread}, VType: {$videoType}, VID: {$videoId}"); if ($videoType == null || $videoId == null) { $this->cachedLocation[$location] = false; return false; } $return = false; switch ($videoType) { case self::TYPE_MEGAVIDEO: try { /* @var $megavideoHelper X_VlcShares_Plugins_Helper_Megavideo */ $megavideoHelper = $this->helpers('megavideo'); // fetch megavideo ?d= links @(list($mvType, $mvId) = @explode('=', $videoId)); if ($mvType == 'd') { // convert megaupload->megavideo id in megavideo id $http = new Zend_Http_Client("http://www.megavideo.com/?d={$mvId}"); $response = $http->request(); $body = $response->getBody(); $matches = array(); if (preg_match('/flashvars\\.v \\= \\"([^\\"]*)\\";/', $body, $matches)) { $videoId = $matches[1]; } else { // conversion failed break; } } elseif ($mvType == 'v') { $videoId = $mvId; } X_Debug::i("Megavideo ID: {$videoId}"); if ($megavideoHelper->setLocation($videoId)->getServer()) { $return = $megavideoHelper->getUrl(); } } catch (Exception $e) { X_Debug::e("Megavideo helper isn't installed or enabled: {$e->getMessage()}"); } break; case self::TYPE_YOUTUBE: try { /* @var $youtubeHelper X_VlcShares_Plugins_Helper_Youtube */ $youtubeHelper = $this->helpers('youtube'); /* @var $youtubePlugin X_VlcShares_Plugins_Youtube */ $youtubePlugin = X_VlcShares_Plugins::broker()->getPlugins('youtube'); X_Debug::i("Youtube ID: {$videoId}"); // THIS CODE HAVE TO BE MOVED IN YOUTUBE HELPER // FIXME $formats = $youtubeHelper->getFormatsNOAPI($videoId); $returned = null; $qualityPriority = explode('|', $youtubePlugin->config('quality.priority', '5|34|18|35')); foreach ($qualityPriority as $quality) { if (array_key_exists($quality, $formats)) { $returned = $formats[$quality]; X_Debug::i('Video format selected: ' . $quality); break; } } if ($returned === null) { // for valid video id but video with restrictions // alternatives formats can't be fetched by youtube page. // i have to fallback to standard api url $apiVideo = $youtubeHelper->getVideo($videoId); foreach ($apiVideo->mediaGroup->content as $content) { if ($content->type === "video/3gpp") { $returned = $content->url; X_Debug::w('Content restricted video, fallback to api url:' . $returned); break; } } if ($returned === null) { $returned = false; } } $return = $returned; } catch (Exception $e) { X_Debug::e("Youtube helper isn't installed or enabled: {$e->getMessage()}"); } break; default: X_Debug::i("Using new hoster api"); try { $hoster = $this->helpers()->hoster()->getHoster($videoType); $return = $hoster->getPlayable($videoId); } catch (Exception $e) { X_Debug::e("Hoster api hasn't a valid handler for {{$videoType}:{$videoId}}: {$e->getMessage()}"); $return = false; } } $this->cachedLocation[$location] = $return; return $return; }
public function resolveLocation($location = null) { if ($location == null || $location == false || $location == '') { return false; } if (array_key_exists($location, $this->cachedLocation) && array_key_exists('url', $this->cachedLocation[$location])) { return $this->cachedLocation[$location]['url']; } else { $exploded = $location != '' ? explode('/', $location) : array(null, null, null, null); @(list($mode, $submode, $page, $id) = $exploded); // prepare cache info $toBeCached = array(); if (array_key_exists($location, $this->cachedLocation)) { $toBeCached = $this->cachedLocation[$location]; } /* @var $helper X_VlcShares_Plugins_Helper_Youtube */ $helper = $this->helpers('youtube'); /* @var $foundVideo Zend_Gdata_YouTube_VideoEntry */ $foundVideo = false; try { switch ($mode) { case self::MODE_ACCOUNTS: case self::A_ACTIVITIES: case self::A_FAVORITES: case self::A_PLAYLISTS: case self::A_SUBSCRIPTIONS: case self::A_UPLOADED: if ($id !== null) { // the youtube video url is inside the id //$foundVideo = $helper->getVideo($id); $foundVideo = $id; } break; case self::MODE_LIBRARY: if ($id !== null) { $video = new Application_Model_YoutubeVideo(); Application_Model_YoutubeVideosMapper::i()->find($id, $video); if ($video->getId() != null) { //$foundVideo = $helper->getVideo($video->getIdYoutube()); $foundVideo = $video->getIdYoutube(); } } break; } } catch (Exception $e) { // WTF: video query is invalid!!! X_Debug::e('Error in video query: ' . $e->getMessage()); return false; } //X_Debug::i("Video debug info: ". print_r($helper->getVideo($foundVideo), true)); if ($foundVideo !== false && $foundVideo !== null) { //$content = $foundVideo->getMediaGroup()->getContent(); //print_r($foundVideo); //$content = $content[0]; /* @var $content Zend_Gdata_YouTube_Extension_MediaContent */ $formats = $helper->getFormatsNOAPI($foundVideo); $returned = null; $qualityPriority = explode('|', $this->config('quality.priority', '5|34|18|35')); foreach ($qualityPriority as $quality) { if (array_key_exists($quality, $formats)) { $returned = $formats[$quality]; X_Debug::i('Video format selected: ' . $quality); break; } } if ($returned === null) { // for valid video id but video with restrictions // alternatives formats can't be fetched by youtube page. // i have to fallback to standard api url X_Debug::i("Getting video url from standard api"); $apiVideo = $helper->getVideo($foundVideo); foreach ($apiVideo->mediaGroup->content as $content) { if ($content->type === "video/3gpp") { $returned = $content->url; X_Debug::w('Content restricted video, fallback to api url:' . $returned); break; } } if ($returned === null) { X_Debug::e("No video link found in api too"); $returned = false; } } $toBeCached['url'] = $returned; $this->cachedLocation[$location] = $toBeCached; return $returned; } } }
private function _action_seek(X_Vlc $vlc, $param) { $time = (int) $param * 60; $totalTime = $vlc->getTotalTime(); if ($time >= 0 && $time <= $totalTime) { $vlc->seek($time); } else { X_Debug::w("Time value out of range: {$time} vs {$totalTime}"); } }
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 addAction() { $csrf = new Zend_Form_Element_Hash('csrf', array('salt' => __CLASS__)); $validCheck = $csrf->isValid($this->getRequest()->getParam('csrf', false)); $csrf->initCsrfToken(); $hash = $csrf->getHash(); $return = array('success' => true, 'api' => array('resolver' => $this->_helper->url->url(array('controller' => 'bookmarklets', 'action' => 'resolver', 'csrf' => $hash)), 'adder' => $this->_helper->url->url(array('controller' => 'bookmarklets', 'action' => 'add', 'csrf' => $hash)), 'bookmark' => $this->_helper->url->url(array('controller' => 'bookmarklets', 'action' => 'bookmark', 'csrf' => $hash))), 'links' => array()); if ($validCheck) { $links = $this->getRequest()->getParam("links", array()); $category = $this->getRequest()->getParam("category", false); $added = 0; $ignored = 0; $total = count($links); if ($category) { $hosterHelper = X_VlcShares_Plugins::helpers()->hoster(); foreach ($links as $link) { $href = isset($link['href']) ? $link['href'] : false; $title = isset($link['title']) ? $link['title'] : false; $description = isset($link['description']) ? $link['description'] : false; $thumbnail = isset($link['thumbnail']) ? $link['thumbnail'] : false; if (!$href || !$title) { $ignored++; continue; } try { $hoster = $hosterHelper->findHoster($href); $id = $hoster->getResourceId($href); $video = new Application_Model_Video(); $video->setHoster($hoster->getId())->setIdVideo($id)->setTitle($title)->setCategory($category); if ($thumbnail) { $video->setThumbnail($thumbnail); } if ($description) { $video->setDescription($description); } try { Application_Model_VideosMapper::i()->save($video); $added++; } catch (Exception $e) { $ignored++; } } catch (Exception $e) { X_Debug::w("No hoster found: {{$e->getMessage()}}"); $ignored++; } } $return['links'] = array('total' => $total, 'ignored' => $ignored, 'added' => $added); } else { X_Debug::e("No category selected"); $return['success'] = false; } } else { X_Debug::e("Invalid CSRF"); $return['success'] = false; } $this->_helper->json($return, true, false); }
/** * get an array with standard information about the playable * @param string $url the hoster page or resource ID * @param boolean $isId * @return array format: * array( * 'title' => TITLE * 'description' => DESCRIPTION * 'length' => LENGTH * ... * ) */ function getPlayableInfos($url, $isId = true) { if (!$isId) { $url = $this->getResourceId($url); } // use cached values if (array_key_exists($url, $this->info_cache)) { return $this->info_cache[$url]; } // use the api $http = new Zend_Http_Client("http://www.youporn.com/watch/" . $url, array('headers' => array('User-Agent' => $this->hide ? 'User-Agent: vlc-shares/' . X_VlcShares::VERSION . ' youporn/' . X_VlcShares_Plugins_YouPorn::VERSION : 'User-Agent: Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20101019 Firefox/4.0.1'))); $http->setParameterPost('user_choice', 'Enter'); //$http->setCookieJar(true); X_Debug::i("Fetching {http://www.youporn.com/watch/{$url}}"); $datas = $http->request(Zend_Http_Client::POST)->getBody(); //$referer = str_replace(':80', '', $http->getUri(true)); $match = array(); $pattern = '%<a href="(?P<download>(http://videos.*?))"%i'; if (preg_match_all($pattern, $datas, $match, PREG_SET_ORDER) < 1) { X_Debug::e("Can't find the download url for videoid {$url}"); throw new Exception("Invalid ID {{$url}}", self::E_ID_INVALID); } X_Debug::i("Valid download urls: " . print_r($match, true)); $downloadUrl = @html_entity_decode(@$match[$this->quality]['download']); if (!$downloadUrl) { X_Debug::i("Invalid quality index: {{$this->quality}}. Using the first one"); $downloadUrl = @html_entity_decode(@$match[0]['download']); if (!$downloadUrl) { X_Debug::i("No qualities available at all"); throw new Exception("Invalid quality index: {0}", self::E_ID_INVALID); } } $match = array(); if (preg_match('/<title>(?P<title>.*?) - Free P**n Videos - YouPorn<\\/title>/i', $datas, $match)) { $title = $match['title']; } else { X_Debug::w("No title found"); $title = ''; } $match = array(); if (preg_match('/<meta name="description" content="(?P<description>[^\\"]*)" \\/>/i', $datas, $match)) { $description = $match['description']; } else { X_Debug::w("No description found"); $description = ''; } $idT1 = substr($url, 0, 2); $idT2 = substr($url, 2, 2); //$cookies = $http->getCookieJar()->getAllCookies(Zend_Http_CookieJar::COOKIE_STRING_CONCAT); $infos = array('title' => $title, 'description' => $description, 'length' => 0, 'thumbnail' => "http://ss-1.youporn.com/screenshot/{$idT1}/{$idT2}/screenshot/{$url}_extra_large.jpg", 'url' => $downloadUrl); // add in cache $this->info_cache[$url] = $infos; return $infos; }
public function cleanCurrentCacheEntry() { if ($this->lastUrl == null) { X_Debug::e("No location available"); } try { /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache'); $cacheHelper->storeItem("realdebrid::{$this->lastUrl}", '', 0); } catch (Exception $e) { X_Debug::w("Cache disabled, clean is useless"); } }