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;
 }
 public function wakeup(X_Threads_Thread_Info $thread)
 {
     try {
         $this->resume($thread);
     } catch (Exception $e) {
         X_Debug::e("Wake up failed");
     }
 }
 static function registerVlcLocation(X_VlcShares_Plugins_ResolverInterface $plugin, X_Vlc $vlc, $location)
 {
     $location = $plugin->resolveLocation($location);
     if ($location !== null) {
         $vlc->registerArg('source', "\"{$location}\"");
     } else {
         X_Debug::e("No source o_O");
     }
 }
 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;
         }
     }
 }
Beispiel #5
0
 public function __construct(X_Vlc $vlcInstance = null)
 {
     if (is_null($vlcInstance)) {
         $vlcInstance = X_Vlc::getLastInstance();
         // OMG OMG no
     }
     if (is_null($vlcInstance)) {
         // check again
         X_Debug::e("Streamer engine VLC without a vlc instance available");
         throw new Exception("No X_Vlc instance available");
     }
     $this->vlc = $vlcInstance;
 }
 /**
  * get the resource ID for the hoster
  * from an $url
  * @param string $url the hoster page
  * @return string the resource id
  */
 function getResourceId($url)
 {
     $matches = array();
     if (preg_match(self::PATTERN, $url, $matches)) {
         if ($matches['ID'] != '') {
             return $matches['ID'];
         }
         X_Debug::e("No id found in {{$url}}", self::E_ID_NOTFOUND);
         throw new Exception("No id found in {{$url}}");
     } else {
         X_Debug::e("Regex failed");
         throw new Exception("Regex failed", self::E_URL_INVALID);
     }
 }
 public function parse($string)
 {
     $parsed = array();
     if ($this->namespace) {
         $parsed = simplexml_load_string($string, "SimpleXMLElement", 0, $this->namespace);
     } else {
         $parsed = simplexml_load_string($string);
     }
     if ($parsed === false) {
         X_Debug::e("simplexml_load_string return error: invalid string");
         $parsed = array();
     }
     return $parsed;
 }
 /**
  * Retrieve news from plugins
  * @param Zend_Controller_Action $this
  * @return X_Page_ItemList_News
  */
 public function getIndexNews(Zend_Controller_Action $controller)
 {
     try {
         $view = $controller->getHelper('viewRenderer');
         $view->view->headScript()->appendFile('http://www.google.com/jsapi');
         $view->view->headScript()->appendFile($view->view->baseUrl("/js/widgetdevnews/script.js"));
         $view->view->headLink()->appendStylesheet($view->view->baseUrl('/css/widgetdevnews/style.css'));
         $text = (include dirname(__FILE__) . '/WidgetDevNews.commits.phtml');
         $item = new X_Page_Item_News($this->getId(), '');
         $item->setTab(X_Env::_('p_widgetdevnews_commits_tab'))->setContent($text);
         return new X_Page_ItemList_News(array($item));
     } catch (Exception $e) {
         X_Debug::e('No view O_o');
     }
 }
 /**
  * (non-PHPdoc)
  * @see X_PageParser_Parser::parse()
  */
 public function parse($string)
 {
     $matches = array();
     if (!preg_match(self::PATTERN_MAIN, $string, $matches)) {
         X_Debug::e('Main pattern failed');
         return array();
     }
     $string = $matches['main'];
     $string = str_replace(array('\\n', '\\u003c', '\\u003e'), array('', '<', '>'), $string);
     $string = stripslashes($string);
     //X_Debug::i("Decoded string: {$string}");
     $matches = array();
     if (!preg_match_all(self::PATTERN_ITEMS, $string, $matches, PREG_SET_ORDER)) {
         X_Debug::e('Items pattern failed: {' . preg_last_error() . '}');
         return array();
     }
     return $matches;
 }
 protected function dispatchRequest(Zend_Controller_Request_Http $request, X_Page_ItemList_PItem $items, Zend_Controller_Action $controller)
 {
     /* @var $view Zend_Controller_Action_Helper_ViewRenderer */
     $view = $controller->getHelper('viewRenderer');
     /* @var $layout Zend_Layout_Controller_Action_Helper_Layout */
     $layout = $controller->getHelper('layout');
     try {
         $view->setNoRender(true);
         $layout->disableLayout();
     } catch (Exception $e) {
         X_Debug::e("Layout or View not enabled: " . $e->getMessage());
     }
     $result = array();
     $actionName = $request->getActionName();
     $controllerName = $request->getControllerName();
     $result['controller'] = $controllerName;
     $result['action'] = $actionName;
     $result['success'] = true;
     $result['items'] = array();
     /* @var $urlHelper Zend_Controller_Action_Helper_Url */
     $urlHelper = $controller->getHelper('url');
     $skipMethod = array('getCustom', 'getLinkParam', 'getLinkAction', 'getLinkController');
     foreach ($items->getItems() as $itemId => $item) {
         /* @var $item X_Page_Item_PItem */
         $aItem = array();
         $methods = get_class_methods(get_class($item));
         foreach ($methods as $method) {
             if (array_search($method, $skipMethod) !== false) {
                 continue;
             }
             if ($method == "getIcon") {
                 $aItem['icon'] = $request->getBaseUrl() . $item->getIcon();
             } elseif (X_Env::startWith($method, 'get')) {
                 $aItem[lcfirst(substr($method, 3))] = $item->{$method}();
             } elseif (X_Env::startWith($method, 'is')) {
                 $aItem[lcfirst(substr($method, 2))] = $item->{$method}();
             }
         }
         $result['items'][] = $aItem;
     }
     /* @var $jsonHelper Zend_Controller_Action_Helper_Json */
     $jsonHelper = $controller->getHelper('Json');
     $jsonHelper->direct($result, true, false);
 }
 /**
  * Store plugin config and set priorities if in configs
  * @param array|Zend_Config $configs
  */
 public function setConfigs($configs)
 {
     if ($configs instanceof Zend_Config) {
         $this->configs = $configs;
     } elseif (is_array($configs)) {
         $this->configs = new Zend_Config($configs);
     } else {
         X_Debug::e('Unknown plugin configs: ' + var_export($configs, true));
         throw new Exception('Unknown configs');
     }
     if ($this->configs->priorities) {
         foreach ($this->configs->priorities->toArray() as $triggerName => $priority) {
             $this->setPriority($triggerName, $priority);
         }
     }
     if ($this->configs->id) {
         $this->id = $this->configs->id;
     }
 }
 /**
  * @see X_VlcShares_Plugins_ResolverInterface::getLocation()
  */
 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}");
     list($hoster, $id) = explode(':', $location, 2);
     try {
         $return = $this->helpers()->hoster()->getHoster($hoster)->getPlayable($id, true);
     } catch (Exception $e) {
         X_Debug::e("Own3dLive hoster error: {$e->getMessage()}");
         $return = false;
     }
     $this->cachedLocation[$location] = $return;
     return $return;
 }
 public function videoAction()
 {
     $id = $this->getRequest()->getParam("id", false);
     if (!$id) {
         throw new Exception(X_Env::_("p_veoh_invalid_id"));
     }
     // this algorithm is taken from jdownload veoh hoster plugin
     $http1 = new Zend_Http_Client();
     $http1->setCookieJar(true);
     $http1->setUri("http://www.veoh.com/watch/{$id}");
     $response1 = $http1->request()->getBody();
     $fbsettingPattern = '/FB\\.init\\(\\"(?P<fbsetting>[^\\"]+)\\"/';
     $fbsetting = array();
     if (!preg_match($fbsettingPattern, $response1, $fbsetting)) {
         X_Debug::e("Can't get FBSetting. Regex failed");
         throw new Exception("Can't get FBSetting");
     }
     $fbsetting = $fbsetting['fbsetting'];
     $http2 = new Zend_Http_Client();
     $http2->setUri("http://www.veoh.com/static/swf/webplayer/VWPBeacon.swf?port=50246&version=1.2.2.1112");
     $response2 = $http2->request();
     $http1->setUri("http://www.veoh.com/rest/v2/execute.xml?apiKey=" . base64_decode(X_VlcShares_Plugins_Veoh::APIKEY) . "&method=veoh.video.findByPermalink&permalink=" . $id . "&");
     $response1 = $http1->request()->getBody();
     $fHashPath = array();
     if (!preg_match('/fullHashPath\\=\\"(?P<fHashPath>[^\\"]+)\\"/', $response1, $fHashPath)) {
         X_Debug::e("Can't get fHashPath. Regex failed");
         throw new Exception("Can't get fHashPath");
     }
     $fHashPath = $fHashPath['fHashPath'];
     $fHashToken = array();
     if (!preg_match('/fullHashPathToken\\=\\"(?P<fHashToken>[^\\"]+)\\"/', $response1, $fHashToken)) {
         X_Debug::e("Can't get fHashToken. Regex failed");
         throw new Exception("Can't get fHashToken");
     }
     $fHashToken = $fHashToken['fHashToken'];
     // TODO check if correct
     $fHashToken = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, pack('H*', base64_decode(X_VlcShares_Plugins_Veoh::SKEY)), base64_decode($fHashToken), MCRYPT_MODE_CBC, pack('H*', base64_decode(X_VlcShares_Plugins_Veoh::IV)));
     //$fHashToken = trim($fHashToken);
     if (!preg_match('/(?P<fHashToken>[a-z0-9A-z]+)/', $fHashToken, $fHashToken)) {
         throw new Exception("Decryption failed");
     }
     $fHashToken = $fHashToken['fHashToken'];
     if ($fHashPath == null || $fHashToken == null) {
         throw new Exception("Hoster failure");
     }
     X_Debug::i("HashPath: {$fHashPath}, HashToken: {$fHashToken}");
     $http1->getCookieJar()->addCookie(new Zend_Http_Cookie("fbsetting_{$fbsetting}", "%7B%22connectState%22%3A2%2C%22oneLineStorySetting%22%3A3%2C%22shortStorySetting%22%3A3%2C%22inFacebook%22%3Afalse%7D", "http://www.veoh.com"));
     $http1->getCookieJar()->addCookie(new Zend_Http_Cookie("base_domain_{$fbsetting}", "veoh.com", "http://www.veoh.com"));
     $cookies = $http1->getCookieJar()->getAllCookies(Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
     $opts = array('http' => array('header' => array("Referer: http://www.veoh.com/static/swf/qlipso/production/MediaPlayer.swf?version=2.0.0.011311.5", "x-flash-version: 10,1,53,64", "Cookie: {$cookies}"), 'content' => $fHashPath . $fHashToken));
     $context = stream_context_create($opts);
     X_Debug::i("Video url: {$fHashPath}{$fHashToken}");
     // 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/flv");
     @readfile("{$fHashPath}{$fHashToken}", false, $context);
 }
 /**
  * Retrieve statistic from plugins
  * @param Zend_Controller_Action $this
  * @return array The format of the array should be:
  * 		array(
  * 			array(
  * 				'title' => ITEM TITLE,
  * 				'label' => ITEM LABEL,
  * 				'stats' => array(INFO, INFO, INFO),
  * 				'provider' => array('controller', 'index', array()) // if provider is setted, stats key is ignored 
  * 			), ...
  * 		)
  */
 public function getIndexMessages(Zend_Controller_Action $controller)
 {
     X_Debug::i('Plugin triggered');
     $type = 'warning';
     $showError = true;
     try {
         $backupDir = new DirectoryIterator(APPLICATION_PATH . "/../data/backupper/");
         foreach ($backupDir as $entry) {
             if ($entry->isFile() && pathinfo($entry->getFilename(), PATHINFO_EXTENSION) == 'xml' && X_Env::startWith($entry->getFilename(), 'backup_')) {
                 $showError = false;
                 break;
             }
         }
     } catch (Exception $e) {
         X_Debug::e("Error while parsing backupper data directory: {$e->getMessage()}");
     }
     $showError = $showError && $this->config('alert.enabled', true);
     if ($showError) {
         $urlHelper = $controller->getHelper('url');
         /* @var $urlHelper Zend_Controller_Action_Helper_Url */
         $removeAlertLink = $urlHelper->url(array('controller' => 'backupper', 'action' => 'alert', 'status' => 'off'));
         $mess = new X_Page_Item_Message($this->getId(), X_Env::_('p_backupper_warningmessage_nobackup') . " <a href=\"{$removeAlertLink}\">" . X_Env::_('p_backupper_warningmessage_nobackupremove') . '</a>');
         $mess->setType($type);
         return new X_Page_ItemList_Message(array($mess));
     }
 }
 /**
  * This hook can be used to add normal priority args in vlc stack
  * 
  * @param X_Vlc $vlc vlc wrapper object
  * @param string $provider id of the plugin that should handle request
  * @param string $location to stream
  * @param Zend_Controller_Action $controller the controller who handle the request
  */
 public function registerVlcArgs(X_Vlc $vlc, $provider, $location, Zend_Controller_Action $controller)
 {
     X_Debug::i('Plugin triggered');
     $profileId = $controller->getRequest()->getParam($this->getId(), false);
     if ($profileId !== false) {
         $profile = new Application_Model_Profile();
         Application_Model_ProfilesMapper::i()->find($profileId, $profile);
     } else {
         // if no params is provided, i will try to
         // get the best profile for this condition
         $profile = $this->getBest($location, $this->helpers()->devices()->getDeviceType(), $provider);
     }
     if ($profile->getArg() !== null) {
         $vlc->registerArg('profile', $profile->getArg());
         if ($this->config('store.session', true)) {
             // store the link in session for future use
             try {
                 /* @var $cache X_VlcShares_Plugins_Helper_Cache */
                 $cache = $this->helpers()->helper('cache');
                 $cache->storeItem('profile::lastvlclink', $profile->getLink(), 240);
             } catch (Exception $e) {
                 // nothing to store or no place to store to
             }
         }
     } else {
         X_Debug::e("No profile arg for vlc");
     }
 }
 /**
  * Execute the action
  * 
  * @param X_Streamer_Engine $vlc
  * @param string $pid
  * @param string $action
  * @param Zend_Controller_Action $controller the controller who handle the request
  */
 public function execute(X_Streamer_Engine $engine, $pid, $action, Zend_Controller_Action $controller)
 {
     // the trigger isn't for this plugin
     if ($this->getId() != $pid) {
         return;
     }
     X_Debug::i("Plugin triggered for action {$action}");
     $param = $controller->getRequest()->getParam('param', null);
     if (method_exists($this, "_action_{$action}")) {
         $method = "_action_{$action}";
         if ($action === 'stop') {
             $this->{$method}($engine, $param);
         } else {
             if ($engine instanceof X_Streamer_Engine_Vlc) {
                 $this->{$method}($engine->getVlcWrapper(), $param);
             }
         }
     } else {
         X_Debug::e("Invalid action {$action}");
     }
 }
 /**
  * This hook can be used to add low priority args in vlc stack
  * 
  * @param X_Vlc $vlc vlc wrapper object
  * @param string $provider id of the plugin that should handle request
  * @param string $location to stream
  * @param Zend_Controller_Action $controller the controller who handle the request
  */
 public function preRegisterVlcArgs(X_Vlc $vlc, $provider, $location, Zend_Controller_Action $controller)
 {
     // this plugin inject params only if this is the provider
     if ($provider != $this->getId()) {
         return;
     }
     // i need to register source as first, because subtitles plugin use source
     // for create subfile
     X_Debug::i('Plugin triggered');
     $dLocation = $this->resolveLocation($location);
     if ($location !== null) {
         // TODO adapt to newer api when ready
         $vlc->registerArg('source', "\"{$dLocation}\"");
     } else {
         X_Debug::e("No source o_O");
         return;
     }
     // Now, it's time to check for sub parameter
     $request = $controller->getRequest();
     $sub = $request->getParam($this->getId() . ':sub', false);
     if ($sub !== false) {
         $sub = X_Env::decode($sub);
         /* @var $helper X_VlcShares_Plugins_Helper_Youtube */
         $helper = $this->helpers('youtube');
         list(, , , $videoId) = explode('/', $location);
         $sub = $helper->getSubtitleNOAPI($videoId, $sub);
         $urlHelper = $controller->getHelper('url');
         $subFile = X_Env::completeUrl($urlHelper->url($sub['srt_url'], 'default', true));
         $vlc->registerArg('subtitles', "--sub-file=\"{$subFile}\"");
     }
 }
 /**
  * @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}");
     @(list($letter, $thread, $href) = explode('/', $location, 3));
     X_Debug::i("Letter: {$letter}, Thread: {$thread}, Ep: {$href}");
     if ($href == null || $thread == null) {
         $this->cachedLocation[$location] = false;
         return false;
     }
     @(list($epId, $epName) = explode(':', $href, 2));
     // i have to fetch the streaming page :(
     $baseUrl = $this->config('base.url', 'http://www.jigoku.it/anime-streaming/');
     $baseUrl .= "{$thread}/{$epId}/{$epName}";
     $htmlString = $this->_loadPage($baseUrl, true);
     $dom = new Zend_Dom_Query($htmlString);
     $results = $dom->queryXpath('//object[@id="oplayer"]//param[@name="movie"]/attribute::value');
     X_Debug::i("Videos found: " . $results->count());
     $return = false;
     if ($results->count()) {
         $current = $results->current();
         $linkUrl = $current->nodeValue;
         X_Debug::i("Link url: {{$linkUrl}}");
         if (strpos($linkUrl, 'megavideo') !== false) {
             @(list(, $megavideoID) = explode('/v/', $linkUrl, 2));
             X_Debug::i("Megavideo ID: {$megavideoID}");
             try {
                 $return = $this->helpers()->hoster()->findHoster($linkUrl)->getPlayable($megavideoID, true);
             } catch (Exception $e) {
                 X_Debug::e($e->getMessage());
             }
         } elseif ($linkUrl == "/js/mediaplayer/player.swf") {
             // direct link, nice
             X_Debug::i("Direct link mode");
             $navCurrent = $current->parentNode->nextSibling;
             while ($navCurrent != null) {
                 /* @var $navCurrent DOMElement */
                 //  no text nodes or comments
                 if ($navCurrent instanceof DOMElement) {
                     if ((string) $navCurrent->nodeName == "param") {
                         if ($navCurrent->hasAttribute('name') && $navCurrent->getAttribute("name") == "flashvars") {
                             $flashvars = $navCurrent->getAttribute("value");
                             $parsed = array();
                             parse_str($flashvars, $parsed);
                             X_Debug::i("Parsed string: " . var_export($parsed, true));
                             $return = $parsed['file'];
                             break;
                         }
                     }
                 }
                 $navCurrent = $navCurrent->nextSibling;
             }
         }
     }
     $this->cachedLocation[$location] = $return;
     return $return;
 }
 /**
  * Fetch info about location
  */
 private function fetch()
 {
     // if $this->_location should be fetched
     // $this->_fetched === false is true
     // else all datas are in $this->_fetched (array)
     if ($this->_fetched === false) {
         if (!$this->options->enabled || !file_exists($this->options->path)) {
             X_Debug::e("Helper disabled ({$this->options->enabled}) or wrong path ({$this->options->path})");
             $ffmpegOutput = array();
         } else {
             $ffmpegOutput = $this->_invoke();
         }
         //$dom = new Zend_Dom_Query($xmlString);
         $fetched = array('source' => $this->_location, 'videos' => array(), 'audios' => array(), 'subs' => array());
         //X_Debug::i(var_export($ffmpegOutput, true));
         foreach ($ffmpegOutput as $line) {
             $line = trim($line);
             if ($line == '') {
                 continue;
             }
             // jump away from empty line
             // we are looking for line like this:
             // Stream #0.0(jpn): Video: h264, yuv420p, 1280x720, PAR 1:1 DAR 16:9, 23.98 tbr, 1k tbn, 47.95 tbc
             // Stream #0.1(jpn): Audio: aac, 48000 Hz, stereo, s16
             // Stream #0.2(ita): Subtitle: 0x0000
             // Stream #0.3: Attachment: 0x0000   <--- MKV Menu
             // OR DIFFERENT VERSION:
             //Stream #0:0: Video: h264 (High) (H264 / 0x34363248), yuv420p, 640x480 [SAR 1:1 DAR 4:3], 23.98 fps, 23.98 tbr, 1k tbn, 47.95 tbc (default)
             //Stream #0:1(eng): Audio: vorbis, 48000 Hz, stereo, s16 (default)
             //Stream #0:2(jpn): Audio: vorbis, 48000 Hz, mono, s16
             //Stream #0:3(eng): Subtitle: ssa (default)
             //if ( !X_Env::startWith($line, 'Stream #0') ) continue;
             $matches = array();
             $pattern = '/Stream #(?P<mainid>\\d+)(.|:)(?P<subid>\\d+)(?P<lang>(\\(\\w+\\))?): (?P<type>\\w+): (?P<codec>[^,\\s]+)(?P<extra>.*)/';
             if (!preg_match($pattern, $line, $matches)) {
                 continue;
             }
             X_Debug::i("Checking line: {$line}");
             $language = @$matches['lang'];
             $streamID = $matches['subid'];
             $streamType = $matches['type'];
             $streamFormat = $matches['codec'];
             $streamMore = $matches['extra'];
             // it's the line we are looking for
             // time to split
             //list(, $streamID, $streamType, $streamFormat, $streamMore ) = explode(' ', $line, 5);
             /*
             X_Debug::i("StreamID (raw): $streamID");
             X_Debug::i("StreamType (raw): $streamType");
             X_Debug::i("StreamFormat (raw): $streamFormat");
             X_Debug::i("StreamMore (raw): $streamMore");
             */
             // in 0 -> Stream
             // in 1 -> #0.StreamID(language):    <--- language is present only in mkv files. For avi, no (language)
             // in 2 -> StreamType:  <---- Video|Audio|Subtitle|Attachment
             // in 3 -> StreamFormat, blablabla   <--- for audio and video
             //    OR
             // in 3 -> StreamFormat   <---- for subtitle and attachment
             switch ($streamType) {
                 case 'Video':
                     $streamType = 'videos';
                     break;
                 case 'Audio':
                     $streamType = 'audios';
                     break;
                 case 'Subtitle':
                     $streamType = 'subs';
                     break;
                 default:
                     $streamType = false;
             }
             if (!$streamType) {
                 continue;
             }
             // check for Annotation or unknown type of stream
             // time to get the real streamID
             //
             //@list($streamID, $language) = explode('(', trim($streamID, '):'), 2);
             // in $streamID there is : #0.1
             // discard the first piece
             //list( , $streamID) = explode('.', ltrim($streamID,'#'), 2);
             $infoStream = array();
             if ($streamType == 'subs') {
                 // i don't need format decoding for subs
                 $infoStream['format'] = trim($streamFormat);
                 $infoStream['language'] = $language;
             } else {
                 $infoStream = array('codecType' => X_VlcShares_Plugins_Helper_StreaminfoInterface::AVCODEC_UNKNOWN, 'codecName' => X_VlcShares_Plugins_Helper_StreaminfoInterface::AVCODEC_UNKNOWN);
                 foreach ($this->formatTests as $key => $test) {
                     $valid = false;
                     if ($test[0] == $streamFormat) {
                         $valid = true;
                         if (count($test) > 1 && !X_Env::startWith(trim($streamMore), $test[1])) {
                             $valid = false;
                         }
                     }
                     if ($valid) {
                         $infoStream = array('codecType' => $key, 'codecName' => $key);
                         break;
                     }
                 }
             }
             $infoStream['ID'] = $streamID;
             // language if available
             if ($language) {
                 $infoStream['language'] = $language;
             }
             //$fetched[$streamType][$streamID] = $infoStream;
             // no index as key for use with vlc --sub-track
             X_Debug::i("Stream type {{$streamType}} found: " . print_r($infoStream, true));
             $fetched[$streamType][] = $infoStream;
         }
         //X_Debug::i(var_export($fetched, true));
         // I use lazy init for info
         // and I insert results in cache
         $this->_fetched = $fetched;
     }
 }
 public function bookmarkAction()
 {
     $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))));
     if ($validCheck) {
         $url = $this->getRequest()->getParam("url", false);
         $title = strip_tags($this->getRequest()->getParam("title", false));
         $description = strip_tags($this->getRequest()->getParam("description", false));
         $thumbnail = $this->getRequest()->getParam("thumbnail", false);
         $ua = $this->getRequest()->getParam("ua", false);
         $cookies = $this->getRequest()->getParam("cookies", false);
         if ($url && $title) {
             $model = new Application_Model_Bookmark();
             $model->setUrl($url);
             $model->setTitle($title);
             if ($thumbnail) {
                 $model->setThumbnail($thumbnail);
             }
             if ($description) {
                 $model->setDescription($description);
             }
             if ($ua) {
                 $model->setUa($ua);
             }
             if ($cookies) {
                 $model->setCookies($cookies);
             }
             try {
                 Application_Model_BookmarksMapper::i()->save($model);
             } catch (Exception $e) {
                 X_Debug::e("DB Error: {$e->getMessage()}");
                 $return['success'] = false;
             }
         } else {
             X_Debug::e("Missing data");
             $return['success'] = false;
         }
     } else {
         X_Debug::e("Invalid CSRF");
         $return['success'] = false;
     }
     $this->_helper->json($return, true, false);
 }
Beispiel #21
0
 function cleanTmp()
 {
     // remove temp file
     if ($this->_cleanFlag && $this->getBasePath() !== null) {
         try {
             //$this->_cleanDir(new DirectoryIterator($this->getBasePath()));
             $this->_rrmdir($this->getBasePath());
         } catch (Exception $e) {
             X_Debug::e('Directory cleanup error: ' . $e->getMessage());
         }
     }
 }
 /**
  * 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.veetle.com/index.php/channel/ajaxInfo/" . $url, array('headers' => array('User-Agent' => "vlc-shares/" . X_VlcShares::VERSION . " veetle/" . X_VlcShares_Plugins_Veetle::VERSION)));
     $datas = $http->request()->getBody();
     $json = Zend_Json::decode($datas);
     if (@$json['success'] != 1) {
         throw new Exception("Invalid ID {{$url}}", self::E_ID_INVALID);
     }
     $json = Zend_Json::decode($json['payload']);
     if (!isset($json['flashEnabled']) || !$json['flashEnabled']) {
         X_Debug::e("Selected channel is not flash enabled {{$url}}");
         throw new Exception("Invalid ID {{$url}}. Channel is not flash enabled", self::E_ID_INVALID);
     }
     $infos = array('title' => @$json['title'], 'description' => @$json['description'], 'length' => 0, 'thumbnail' => @$json['logo']['lg']);
     // add in cache
     $this->info_cache[$url] = $infos;
     return $infos;
 }
 public function getLinkParams($linkId)
 {
     $channelParams = false;
     try {
         /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */
         $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache');
         $channelParams = unserialize($cacheHelper->retrieveItem("weebtv::{$linkId}"));
         X_Debug::i("Valid cache entry found: " . print_r($channelParams, true));
     } 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");
     }
     if (!$channelParams) {
         // get the cid from the page
         X_Debug::i("Fetching channel params for: {{$linkId}}");
         $page = X_PageParser_Page::getPage(sprintf(self::URL_CHANNEL, $linkId), new X_PageParser_Parser_Preg('%<param name="movie" value="(?P<swf>.+?)" />.*?<param name="flashvars" value="&cid=(?P<cid>.+?)" />%s', X_PageParser_Parser_Preg::PREG_MATCH));
         $this->preparePageLoader($page);
         $_channelParams = $page->getParsed();
         $channelParams = array();
         // clean params from useless keys
         foreach ($_channelParams as $key => $value) {
             if ($key == 'cid' || $key == 'swf') {
                 $channelParams[$key] = $value;
             }
         }
         X_Debug::i("Params: " . print_r($channelParams, true));
         unset($page);
     }
     $cid = @$channelParams['cid'];
     $swfUrl = @$channelParams['swf'];
     if (!$cid) {
         X_Debug::e("Cid not found for channel {{$linkId}}");
         throw new Exception("Cid not found for channel {{$linkId}}");
     }
     // store in cache if possible
     try {
         /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */
         $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache');
         $cacheHelper->storeItem("weebtv::{$linkId}", serialize($channelParams), 60);
         // store for the next 15 min
         X_Debug::i("Value stored in cache for 60 min: {key = weebtv::{$linkId}}");
     } catch (Exception $e) {
         // no cache plugin, next time i have to repeat the request
     }
     // first get the playlist url from the page
     $authEnabled = $this->config('auth.enabled', false);
     $username = rawurlencode($this->config('auth.username', ''));
     $password = rawurlencode($this->config('auth.password', ''));
     $authString = '';
     if ($authEnabled) {
         $authString = "&username={$username}&userpassword={$password}";
     }
     // without encode
     $username = $this->config('auth.username', '');
     $password = $this->config('auth.password', '');
     $http = new Zend_Http_Client(self::URL_PARAMS . $authString, array('headers' => array('User-Agent' => 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11')));
     $http->setParameterPost('firstConnect', '1');
     $http->setParameterPost('watchTime', '0');
     $http->setParameterPost('cid', $cid);
     $http->setParameterPost('ip', 'NaN');
     if ($authEnabled) {
         $http->setParameterPost('username', $username);
         $http->setParameterPost('password', $password);
     }
     $str = $http->request('POST')->getBody();
     $params = array();
     parse_str($str, $params);
     $rtmpParams = array();
     $check = array('ticket' => 73, 'rtmp' => 10, 'time' => 16, 'playPath' => 11);
     foreach ($check as $label => $key) {
         if (isset($params[$key])) {
             $rtmpParams[$label] = $params[$key];
         }
     }
     X_Debug::i("Fetched stream params for channel {{$linkId}}: " . print_r($rtmpParams, true));
     $ticket = $rtmpParams['ticket'];
     if ($authEnabled) {
         $ticket .= ";{$username};{$password}";
     }
     $hosterLocation = X_RtmpDumpWeebTv::buildUri(array('rtmp' => $rtmpParams['rtmp'] . '/' . $rtmpParams['playPath'], 'swfUrl' => rawurldecode($swfUrl), 'weeb' => $ticket, 'live' => '1'));
     X_Debug::i("Hoster location resolved: {$hosterLocation}");
     return $hosterLocation;
 }
 public function stop()
 {
     if (!$this->isStreaming()) {
         return;
     }
     $thread = X_Threads_Manager::instance()->getThreadInfo(self::THREAD_ID);
     $infos = $thread->getInfo();
     if (isset($infos['message_params']) && isset($infos['message_params']['streamerId'])) {
         $engineId = $infos['message_params']['streamerId'];
         $engine = X_VlcShares_Plugins::helpers()->streamer()->get($engineId);
         //$engine = new $engineClass();
         if ($engine instanceof X_Streamer_StopperEngine) {
             $engine->doStop($infos);
         }
     } else {
         X_Debug::e("Invalid streamer");
     }
     X_Threads_Manager::instance()->halt($thread);
 }
 public function clearLastCheck()
 {
     X_Debug::i("Resetting last check");
     $c = new Application_Model_Config();
     Application_Model_ConfigsMapper::i()->fetchByKey($this->getId() . '.autocheck.last', $c);
     if ($c->getId()) {
         $c->setValue('');
         try {
             Application_Model_ConfigsMapper::i()->save($c);
         } catch (Exception $e) {
             X_Debug::e("Error while storing last check time in db");
         }
     }
     @unlink(APPLICATION_PATH . '/../data/updatenotifier/lastcheck.txt');
 }
 function alertAction()
 {
     $status = $this->getRequest()->getParam('status', false);
     $config = new Application_Model_Config();
     Application_Model_ConfigsMapper::i()->fetchByKey("backupper.alert.enabled", $config);
     if ($config->getId() == null) {
         // i need to add a new config, yeah!
         $config->setKey('backupper.alert.enabled')->setValue(1)->setDefault(1)->setSection('plugins')->setType(Application_Model_Config::TYPE_BOOLEAN);
     }
     switch ($status) {
         case 'on':
             $config->setValue(1);
             break;
         case 'off':
             $config->setValue(0);
             break;
         default:
             $this->_helper->flashMessenger(array('text' => X_Env::_('p_backupper_err_unknownstatus'), 'type' => 'error'));
             $this->_helper->redirector('index', 'backupper');
             break;
     }
     try {
         Application_Model_ConfigsMapper::i()->save($config);
         $this->_helper->flashMessenger(array('text' => X_Env::_('p_backupper_alertstatuschanged'), 'type' => 'info'));
     } catch (Exception $e) {
         X_Debug::e('Unable to store alert.enabled status: ' . $e->getMessage());
         $this->_helper->flashMessenger(array('text' => X_Env::_('p_backupper_err_dberror') . ": {$e->getMessage()}", 'type' => 'error'));
     }
     $this->_helper->redirector('index', 'backupper');
 }
 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 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");
     }
 }
 /**
  * This hook can be used to add low priority args in vlc stack
  * 
  * @param X_Vlc $vlc vlc wrapper object
  * @param string $provider id of the plugin that should handle request
  * @param string $location to stream
  * @param Zend_Controller_Action $controller the controller who handle the request
  */
 public function preRegisterVlcArgs(X_Vlc $vlc, $provider, $location, Zend_Controller_Action $controller)
 {
     // this plugin inject params only if this is the provider
     if ($provider != $this->getId()) {
         return;
     }
     // i need to register source as first, because subtitles plugin use source
     // for create subfile
     X_Debug::i('Plugin triggered');
     $location = $this->resolveLocation($location);
     if ($location !== null) {
         // TODO adapt to newer api when ready
         $vlc->registerArg('source', "\"{$location}\"");
     } else {
         X_Debug::e("No source o_O");
     }
 }
 /**
  * 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;
 }