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); }
/** * (non-PHPdoc) * @see X_PageParser_Parser::parse() */ public function parse($string) { switch ($this->mode) { case self::MODE_TITLES: return $this->parseTitles($string); case self::MODE_EPISODES: return $this->parseEpisodes($string); case self::MODE_LINKS: return $this->parseLinks($string); case self::MODE_NEXTPAGE: return $this->parseNextPage($string); default: throw new Exception("Invalid mode: {" . $this->mode . "}"); } // dead code // first, find the thumb url: $match = array(); $thumb = false; preg_match(self::PATTERN_THUMBNAIL, $string, $match); // avoid relative thumbnails if (count($match) > 0 && X_Env::startWith($match['image'], 'http://')) { $thumb = $match['image']; X_Debug::i("Thumbnail found: {$thumb}"); } /* @var $hosterHelper X_VlcShares_Plugins_Helper_Hoster */ $hosterHelper = X_VlcShares_Plugins::helpers()->hoster(); $subparser = X_PageParser_Parser_HosterLinks::factory($hosterHelper, X_PageParser_Parser_Preg::factory(self::PATTERN_LINKS, X_PageParser_Parser_Preg::PREG_MATCH_ALL, PREG_SET_ORDER)); $links = $subparser->parse($string); X_Debug::i("Valid hosters link found: " . count($links)); // clean results and reformat them $cleanedLinks = array(); foreach ($links as $link) { $cLink = array(); $cLink['hosterId'] = $link['hoster']->getId(); $cLink['videoId'] = $link['hoster']->getResourceId($link['url']); $cLink['label'] = strip_tags($link['label']); $cLink['link'] = "{$cLink['hosterId']}:{$cLink['videoId']}"; $cLink['thumbnail'] = $thumb; $cleanedLinks[] = $cLink; } return $cleanedLinks; }
/** * Search in $dirPath for sub valid for $filename * @param string $dirPath * @param string $filename */ public function getFSTracks($dirPath, $filename) { $validTracks = explode('|', $this->config('file.extensions', 'mp3|wav|mpa|mp2a|mpga|wma|ogg|aac|ac3')); X_Debug::i("Check for subs in {$dirPath} for {$filename} (valid: {$this->config('file.extensions', 'mp3|wav|mpa|mp2a|mpga|wma|ogg|aac|ac3')})"); $dir = new DirectoryIterator($dirPath); $tracksFound = array(); foreach ($dir as $entry) { if ($entry->isFile()) { // se e' un file sub valido if (array_search(pathinfo($entry->getFilename(), PATHINFO_EXTENSION), $validTracks) !== false) { // stessa parte iniziale if (X_Env::startWith($entry->getFilename(), $filename)) { X_Debug::i("{$entry} is valid"); $trackName = substr($entry->getFilename(), strlen($filename)); $tracksFound[$validTracks] = array('language' => trim(pathinfo($trackName, PATHINFO_FILENAME), '.'), 'format' => pathinfo($trackName, PATHINFO_EXTENSION)); } } } } return $tracksFound; }
/** * Call a $menusContainer method following $nodeDefinitions and the current $location provided * * @param X_Page_ItemList_PItem $items * @param string $location * @param array $nodesDefinitions * @param object $menusContainer * @return X_Page_ItemList_PItem * @throws Exception */ static function menuProxy(X_Page_ItemList_PItem $items, $location = '', $nodesDefinitions = array(), $menusContainer) { if (!is_object($menusContainer)) { throw new Exception(sprintf("\$menuContainer must be an object, %s given", gettype($menusContainer))); } X_Debug::i("Searching node handler for: {$location}"); foreach ($nodesDefinitions as $nodeSign => $handler) { @(list($matchType, $matchValue) = @explode(':', $nodeSign, 2)); $validHandler = false; $method = false; $params = array($items); $matches = array(); switch ($matchType) { case 'exact': $validHandler = $matchValue == $location; $method = $handler['function']; $params = array_merge($params, $handler['params']); break; case 'regex': $validHandler = preg_match($matchValue, $location, $matches) > 0; $method = $handler['function']; // optimization: continue only if $validHandler if ($validHandler) { foreach ($handler['params'] as $placeholder) { // if placehoster start with $ char, it's a placehoster from regex if (X_Env::startWith($placeholder, "\$")) { // remove the $ char from the beginning of $placehoster $placeholder = substr($placeholder, 1); $params[] = array_key_exists($placeholder, $matches) ? $matches[$placeholder] : null; } else { $params[] = $placeholder; } } } break; } // stop loop on first validHandler found if ($validHandler) { X_Debug::i(sprintf("Matching NodeSign: %s", $nodeSign)); break; } } if (!$validHandler) { throw new Exception("Provider can't handle this node location: {$location}"); } if (!method_exists($menusContainer, $method)) { throw new Exception(sprintf("Invalid node handler: %s::%s() => %s", get_class($menusContainer), $method, htmlentities($nodeSign))); } $reflectionMethod = new ReflectionMethod($menusContainer, $method); if (!$reflectionMethod->isPublic()) { throw new Exception(sprintf("Menu method must be public: ", get_class($menusContainer), $method)); } X_Debug::i(sprintf("Calling menu function {%s::%s(%s)}", get_class($menusContainer), $method, print_r($params, true))); // $items is always the first params item (index 0) call_user_func_array(array($menusContainer, $method), $params); return $items; }
/** * 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)); } }
function restoreAction() { ignore_user_abort(); /* @var $request Zend_Controller_Request_Http */ $request = $this->getRequest(); if ($request->isPost()) { $file = $request->getPost('file', false); if ($file === false || !X_Env::startWith(realpath(APPLICATION_PATH . "/../data/backupper/{$file}"), realpath(APPLICATION_PATH . "/../data/backupper/")) || !file_exists(APPLICATION_PATH . "/../data/backupper/{$file}")) { $this->_helper->flashMessenger(array('text' => X_Env::_('p_backupper_err_invalidrestorefile'), 'type' => 'warning')); $this->_helper->redirector('index', 'backupper'); } try { /* @var $backuppedData Zend_Config_Xml */ $backuppedData = new Zend_Config_Xml(APPLICATION_PATH . "/../data/backupper/{$file}"); $decryptFunction = $backuppedData->metadata->get('decrypt', false); if ($decryptFunction !== false) { if (function_exists($decryptFunction)) { $arrayBackuppedData = $backuppedData->toArray(); $arrayBackuppedData['plugins'] = array_map($decryptFunction, $arrayBackuppedData['plugins']); } else { throw new Exception("Unknown decryption function: {$decryptFunction}"); } $backuppedData = new Zend_Config($arrayBackuppedData); } } catch (Exception $e) { X_Debug::e("Error while restoring: {$e->getMessage()}"); $this->_helper->flashMessenger(array('text' => X_Env::_('p_backupper_err_malformedrestorefile'), 'type' => 'error')); $this->_helper->redirector('index', 'backupper'); } //die('<pre>'.var_export($backuppedData->toArray(), true).'</pre>'); $components = $request->getPost('components', array()); if (count($components)) { $plugins = X_VlcShares_Plugins::broker()->getPlugins(); $items = array(); foreach ($plugins as $pId => $plugin) { if (array_key_exists($pId, $components) && (bool) $components[$pId]) { if ($plugin instanceof X_VlcShares_Plugins_BackuppableInterface) { //$toBackup[$pId] = $plugin; try { $data = $backuppedData->plugins->{$pId}; if (!is_object($data) || !method_exists($data, 'toArray')) { $data = array(); } else { $data = $data->toArray(); } $returned = $plugin->restoreItems($data); X_Debug::i("Plugins {$pId} restored"); if ($returned) { $this->_helper->flashMessenger(array('text' => $returned, 'type' => 'info')); } else { $this->_helper->flashMessenger(array('text' => X_Env::_('p_backupper_restore_done_plugin') . ": {$pId}", 'type' => 'info')); } } catch (Exception $e) { X_Debug::e("Error restoring {$pId}: {$e->getMessage()}"); $this->_helper->flashMessenger(array('text' => X_Env::_('p_backupper_err_pluginnotrestored') . ": {$pId}, {$e->getMessage()}", 'type' => 'error')); } } } } $this->_helper->flashMessenger(array('text' => X_Env::_('p_backupper_restore_done'), 'type' => 'info')); } else { $this->_helper->flashMessenger(array('text' => X_Env::_('p_backupper_restore_norestoreactionneeded'), 'type' => 'warning')); } } $this->_helper->redirector('index', 'backupper'); }
/** * 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; } }
/** * 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); } $client = new Zend_Http_Client(sprintf(self::SOURCE_URL, $url), array('headers' => array('User-Agent' => "vlc-shares/" . X_VlcShares::VERSION . " own3d/" . X_VlcShares_Plugins_Own3d::VERSION))); $xml = $client->request()->getBody(); $dom = simplexml_load_string($xml); $thumbnail = trim((string) $dom->player[0]->thumb[0]); $title = trim((string) $dom->channels[0]->channel[0]['name']); $description = trim((string) $dom->channels[0]->channel[0]['description']); $pageUrl = trim((string) $dom->channels[0]->channel[0]['ownerLink']); $item = null; $streams = array(); $other_i = 0; foreach ($dom->channels[0]->channel[0]->clip[0]->item as $item) { // check base and convert cdn url $cdnType = X_Env::startWith((string) $item['base'], '${cdn') ? substr((string) $item['base'], 5, 1) : "o_" . $other_i++; foreach ($item->stream as $stream) { $label = (string) $stream['label']; $name = (string) $stream['name']; // remove the part before the ? if any if (strpos($name, '?') !== false) { $name = substr($name, strpos($name, '?') + 1); } $url = $this->getEngineUrl((string) $item['base'], $name, $pageUrl); $sKey = "{$cdnType}_{$label}"; $streams[$sKey] = $url; } } X_Debug::i(print_r($streams, true)); return array('title' => $title, 'description' => $description, 'thumbnail' => $thumbnail, 'streams' => $streams, 'length' => 0); }
protected function decodePid($pid) { /* my @keys = @{ read_keys()->{pid} }; my @data = split /~/, $encrypted_pid; return $encrypted_pid if $data[1] eq ''; */ $splitted = preg_split('/~/', $pid); if (count($splitted) == 1) { if (X_Env::startWith($splitted[0], "NO_MORE_RELEASES_PLEASE_")) { return substr($splitted[0], strlen("NO_MORE_RELEASES_PLEASE_")); } else { return $splitted[0]; } } /* my $cipher = Crypt::Rijndael->new(pack("H*", $data[1])); my $tmp = $cipher->decrypt(pack("H*", $data[0])); */ $tmp = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, @pack("H*", $splitted[1]), pack("H*", $splitted[0]), MCRYPT_MODE_ECB); foreach (self::$KEYS_PID as $key) { /* my $cipher = Crypt::Rijndael->new(pack("H*", $key)); my $unencrypted_pid = $cipher->decrypt($tmp); */ $unencrypted_pid = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, pack("H*", $key), $tmp, MCRYPT_MODE_ECB); // if ($unencrypted_pid =~ /[0-9A-Za-z_-]{32}/) { if (preg_match('/[0-9A-Za-z_-]{32}/', $unencrypted_pid)) { if (X_Env::startWith($unencrypted_pid, "NO_MORE_RELEASES_PLEASE_")) { return substr($unencrypted_pid, strlen("NO_MORE_RELEASES_PLEASE_")); } else { return $unencrypted_pid; } } } if (X_Env::startWith($pid, "NO_MORE_RELEASES_PLEASE_")) { return substr($pid, strlen("NO_MORE_RELEASES_PLEASE_")); } else { return $pid; } }
public function gen_afterPageBuild(X_Page_ItemList_PItem $list, Zend_Controller_Action $controller) { // force Rendering win over everythings /*if ( !$this->_forceRendering ) { if ( !((bool) $this->config('forced.enabled', false)) && !$this->helpers()->devices()->isWiimc() ) return; } */ // new renderer interface if (!$this->isDefaultRenderer()) { return; } X_Debug::i("Plugin triggered"); $request = $controller->getRequest(); $enhanced = $this->helpers()->devices()->isWiimcEnhanced() && $this->config('support.enhanced', true); $plx = new X_Plx(X_Env::_('p_wiimcplxrenderer_plxtitle_' . $request->getControllerName() . '_' . $request->getActionName()), X_Env::_('p_wiimcplxrenderer_plxdescription_' . $request->getControllerName() . '_' . $request->getActionName())); // wiimc plus custom tags if ($enhanced) { $plx->setWiimcplus_generator_name('vlc-shares'); // uses the __call api $plx->setWiimcplus_generator_version(X_VlcShares::VERSION_CLEAN); // uses the __call api if ($request->getControllerName() == 'index' && $request->getActionName() == 'collections') { $plx->setWiimcplus_assert_mainmenu('true'); // uses the __call api } // show the current time as custom playlist header tag if the page is controls/control or browse/stream if ($request->getControllerName() == 'controls' && $request->getActionName() == 'control' || $request->getControllerName() == 'browse' && $request->getActionName() == 'stream') { $vlc = X_Vlc::getLastInstance(); if ($vlc) { // check to be sure that vlc is running right now $currentTime = X_Env::formatTime($vlc->getCurrentTime()); $totalTime = X_Env::formatTime($vlc->getTotalTime()); $plx->setWiimcplus_current_time("{$currentTime}/{$totalTime}"); // uses the __call api } } elseif ($request->getControllerName() == 'browse' && $request->getActionName() == 'selection') { $plx->setWiimcplus_assert_nohistory('true'); // uses the __call api } } foreach ($list->getItems() as $i => $item) { /* @var $item X_Page_Item_PItem */ $plxItemName = ($item->isHighlight() ? '-) ' : '') . $item->getLabel(); $plxItemWiimcplusIcon = null; switch ($item->getType()) { case X_Page_Item_PItem::TYPE_CONTAINER: $plxItemType = X_Plx_Item::TYPE_PLAYLIST; $plxItemWiimcplusIcon = 'folder'; break; case X_Page_Item_PItem::TYPE_ELEMENT: $plxItemType = X_Plx_Item::TYPE_PLAYLIST; if ($request->getControllerName() == 'browse' && $request->getActionName() == 'share') { $plxItemWiimcplusIcon = 'file'; } break; case X_Page_Item_PItem::TYPE_REQUEST: $plxItemType = X_Plx_Item::TYPE_SEARCH; break; case X_Page_Item_PItem::TYPE_PLAYABLE: $plxItemType = X_Plx_Item::TYPE_VIDEO; break; default: $plxItemType = $item->getType(); } /* @var $urlHelper Zend_Controller_Action_Helper_Url */ $urlHelper = $controller->getHelper('url'); $plxItemUrl = $item->isUrl() ? $item->getLink() : X_Env::completeUrl($urlHelper->url($item->getLink(), $item->getRoute(), $item->isReset())); $plxItem = new X_Plx_Item($plxItemName, $plxItemUrl, $plxItemType); if ($item->getThumbnail() != null) { if (X_Env::startWith($item->getThumbnail(), 'http') || X_Env::startWith($item->getThumbnail(), 'https')) { $plxItem->setThumb($item->getThumbnail()); } else { $plxItem->setThumb(X_Env::completeUrl($item->getThumbnail())); } } if ($enhanced) { if ($plxItemWiimcplusIcon !== null) { $plxItem->setWiimcplus_icon($plxItemWiimcplusIcon); } if ($item->getKey() == 'core-separator') { $plxItem->setWiimcplus_assert_separator('true'); } if ($item->getKey() == 'core-directwatch') { $plxItem->setWiimcplus_assert_directwatch('true'); if ($item->getCustom('subtitle') != null) { $plxItem->setWiimcplus_subtitle($item->getCustom('subtitle')); } } if ($item->getKey() == 'core-play') { $plxItem->setWiimcplus_assert_startvlc('true'); } } $plx->addItem($plxItem); } $this->_render($plx, $controller); }
/** * 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]; } list($fileId, $fileName) = @explode('/', $url); if (!$fileId || !$fileName) { //throw new X_Exception_Hoster_InvalidId("Invalid id {{$id}}"); //TODO 0.5.5+ only X_Debug::e("Invalid id {{$url}}"); throw new Exception("Invalid id {{$url}}", self::E_ID_INVALID); } // use the api $http = new Zend_Http_Client(sprintf(self::API_URL_HTTP, 'checkfiles', "files={$fileId}&filenames={$fileName}")); $this->prepareHttpClient($http); $text = $http->request()->getBody(); // check for api error response if (X_Env::startWith($text, 'ERROR:')) { // error found, get error message $matches = array(); if (!preg_match('/^ERROR: (?P<error>.*)$/m', $text, $matches)) { // can't find the error msg. who cares... X_Debug::e("Invalid id {{$url}}"); throw new Exception("Invalid id {{$url}}", self::E_ID_INVALID); } else { X_Debug::e("Invalid id {{$url}}: {$matches['error']}"); throw new Exception("Invalid id {{$url}}: {$matches['error']}", self::E_ID_INVALID); } } // normal reponse "fileid,filename,size,serverid,status,shorthost,md5\n" list(, , $size, , $status, , ) = explode(',', $text, 7); // md5 + garbage switch ($status) { case '1': // file OK, continue break; case '0': // file not found X_Debug::e("Invalid id {{$url}}: file not found"); throw new Exception("Invalid id {{$url}}: file not found", self::E_ID_INVALID); case '3': // server down X_Debug::e("Resource unavailable {{$url}}: server is down"); throw new Exception("Resource unavailable {{$url}}: server is down", 101); // 101 = resource not available in 0.5.5 // 101 = resource not available in 0.5.5 case '4': // illegal X_Debug::e("Invalid id {{$url}}: illegal resource"); throw new Exception("Invalid id {{$url}}: illegal resource", 102); // 101 = resource illegal in 0.5.5 // 101 = resource illegal in 0.5.5 default: // unknown status code X_Debug::e("Invalid id {{$url}}: unknown status code {{$status}}"); throw new Exception("Invalid id {{$url}}: unknown status code {{$status}}", 999998); // 999998 = plugin obsolete in 0.5.5 } $infos = array('title' => $fileName, 'size' => $size, 'description' => '', 'length' => 0); // add in cache $this->info_cache[$url] = $infos; return $infos; }
private function getLinkHosterUrl($linkId) { try { /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache'); $response = $cacheHelper->retrieveItem("raiclick::{$linkId}"); 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"); } // first get the playlist url from the page $page = X_PageParser_Page::getPage(sprintf(self::URL_PLAYABLE, $linkId), new X_PageParser_Parser_Preg('/videoURL = \\"(?P<url>.*?)\\"/', X_PageParser_Parser_Preg::PREG_MATCH)); $this->preparePageLoader($page); $parsed = $page->getParsed(); $url = $parsed['url']; $hosterLocation = false; if ($url) { // check if url schema is mms if (X_Env::startWith($url, 'mms://')) { $hosterLocation = $url; } else { // the get the video url from the playlist $page = X_PageParser_Page::getPage($url, new X_PageParser_Parser_Preg('/HREF="(?P<url>.*?)\\"/', X_PageParser_Parser_Preg::PREG_MATCH)); $this->preparePageLoader($page); $parsed = $page->getParsed(); $hosterLocation = $parsed['url']; } } X_Debug::i("Hoster location resolved: {$hosterLocation}"); try { /* @var $cacheHelper X_VlcShares_Plugins_Helper_Cache */ $cacheHelper = X_VlcShares_Plugins::helpers()->helper('cache'); $cacheHelper->storeItem("raiclick::{$linkId}", $hosterLocation, 15); // store for the next 15 min X_Debug::i("Value stored in cache for 15 min: {key = raiclick::{$linkId}, value = {$hosterLocation}}"); } catch (Exception $e) { // no cache plugin, next time i have to repeat the request } return $hosterLocation; }
/** * Add megavideo id to jdownloader download queue * @param string $provider * @param string $location * @param string $pid * @param Zend_Controller_Action $controller * @return X_Page_ItemList_PItem */ public function getSelectionItems($provider, $location, $pid, Zend_Controller_Action $controller) { // we want to expose items only if pid is this plugin if ($this->getId() != $pid) { return; } X_Debug::i('Plugin triggered'); $action = $controller->getRequest()->getParam("{$this->getId()}:action", ''); /* @var $jdownloader X_VlcShares_Plugins_Helper_JDownloader */ $jdownloader = $this->helpers('jdownloader'); // IF action = 'start, stop or pause' // execute the action and return confirm, then exit if ($action != '') { try { if ($action == "start") { $jdownloader->sendRawCommand(X_VlcShares_Plugins_Helper_JDownloader::CMD_ACTION_START); $link = new X_Page_Item_PItem($this->getId() . '-started', X_Env::_('p_jdownloader_selection_started')); $link->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setLink(array('action' => 'share', 'pid' => null, "{$this->getId()}:action" => null), 'default', false); return new X_Page_ItemList_PItem(array($link)); } if ($action == "pause") { $jdownloader->sendRawCommand(X_VlcShares_Plugins_Helper_JDownloader::CMD_ACTION_PAUSE); $link = new X_Page_Item_PItem($this->getId() . '-started', X_Env::_('p_jdownloader_selection_paused')); $link->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setLink(array('action' => 'share', 'pid' => null, "{$this->getId()}:action" => null), 'default', false); return new X_Page_ItemList_PItem(array($link)); } if ($action == "stop") { $jdownloader->sendRawCommand(X_VlcShares_Plugins_Helper_JDownloader::CMD_ACTION_STOP); $link = new X_Page_Item_PItem($this->getId() . '-started', X_Env::_('p_jdownloader_selection_stopped')); $link->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setLink(array('action' => 'share', 'pid' => null, "{$this->getId()}:action" => null), 'default', false); return new X_Page_ItemList_PItem(array($link)); } } catch (Exception $e) { // connection problems or timeout $link = new X_Page_Item_PItem($this->getId() . '-error', X_Env::_('p_jdownloader_selection_error_network')); $link->setDescription($e->getMessage()); $link->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setLink(array('action' => 'share', 'pid' => null, "{$this->getId()}:action" => null), 'default', false); return new X_Page_ItemList_PItem(array($link)); } } else { // else only confirm the addict /* @var $megavideo X_VlcShares_Plugins_Helper_Megavideo */ $megavideo = $this->helpers('megavideo'); try { $megavideo->getServer(); } catch (Exception $e) { // not loaded location yet X_Debug::i("Force location loading"); $providerObj = X_VlcShares_Plugins::broker()->getPlugins($provider); if ($providerObj instanceof X_VlcShares_Plugins_ResolverInterface) { $providerObj->resolveLocation($location); } } $url = null; try { $url = "http://www.megavideo.com/?v=" . $megavideo->getId(); } catch (Exception $e) { // TODO please, rewrite this piece of code // it's really a shame // let's try to get the url from the hoster try { switch ($provider) { // special cases case 'onlinelibrary': // hoster/id is stored inside db $exploded = explode('/', $location); $exploded = array_pop($exploded); $video = new Application_Model_Video(); Application_Model_VideosMapper::i()->find($exploded, $video); $hoster = $video->getHoster(); $videoId = $video->getIdVideo(); break; default: // we try to get information by location decoding // many plugins use a /-divided location with last param in the format of HOSTER:VIDEOID $exploded = explode('/', $location); $exploded = array_pop($exploded); $exploded = explode(':', $exploded, 2); @(list($hoster, $videoId) = $exploded); break; } // lets search a valid hoster $url = $this->helpers()->hoster()->getHoster($hoster)->getHosterUrl($videoId); } catch (Exception $e) { // simply: provider isn't compatible // trying direct download $pObj = X_VlcShares_Plugins::broker()->getPlugins($provider); if ($pObj instanceof X_VlcShares_Plugins_ResolverInterface) { $url = $pObj->resolveLocation($location); if (!X_Env::startWith($url, "http://") && !X_Env::startWith($url, "https://")) { // not valid, revert changes $url = null; } } } } try { if ($url === null) { throw new Exception(); } X_Debug::i("Appending {{$url}} to the queue"); $jdownloader->addLink($url); $link = new X_Page_Item_PItem($this->getId() . '-added', X_Env::_('p_jdownloader_selection_added')); } catch (Zend_Http_Client_Adapter_Exception $e) { // connection problems or timeout $link = new X_Page_Item_PItem($this->getId() . '-error', X_Env::_('p_jdownloader_selection_error_network')); $link->setDescription($e->getMessage()); } catch (Exception $e) { // wrapper/other error X_Debug::e("Trying to add a new download to JDowloader, but location isn't a megavideo url or there is an error"); $link = new X_Page_Item_PItem($this->getId() . '-error', X_Env::_('p_jdownloader_selection_error_invalid')); $link->setDescription($e->getMessage()); } $link->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setLink(array('action' => 'mode', $this->getId() => null, 'pid' => null), 'default', false); return new X_Page_ItemList_PItem(array($link)); } }
private function _fetchVideos(X_Page_ItemList_PItem $items, $type, $letter, $thread) { X_Debug::i("Fetching videos for {$type}/{$letter}/{$thread}"); if ($type == self::TYPE_SERIES_PERGENRE || $type == self::TYPE_SERIES_PERLETTER) { return $this->_fetchVideosAPI($items, $type, $letter, $thread); } $baseUrl = $this->config('base.url', self::BASE_URL); // threads for movies have / -> : conversion $_thread = str_replace(':', '/', $thread); $baseUrl .= "{$type}/{$_thread}"; $htmlString = $this->_loadPage($baseUrl, true); // XPATH doesn't work well. Maybe for kanji inside the page, so i use regex $cleaned = stristr(strstr($htmlString, 'Episodes:'), '</table>', true); $regexp = "<a\\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\\/a>"; if (preg_match_all("/{$regexp}/siU", $cleaned, $matches, PREG_SET_ORDER)) { //X_Debug::i(var_export($matches, true)); foreach ($matches as $match) { // $match[2] = link address // $match[3] = link text $label = $match[3]; if ($label == '') { $label = X_Env::_('p_animeftw_nonamevideo'); } $href = $match[2]; // href format: http://www.animeftw.tv/videos/baccano/ep-3 if (X_Env::startWith($href, $this->config('base.url', self::BASE_URL))) { $href = substr($href, strlen($this->config('base.url', self::BASE_URL))); } // href format: videos/baccano/ep-3 @(list(, , $epName) = explode('/', trim($href, '/'))); // works even without the $epName $href = $epName; //$found = true; X_Debug::i("Valid link found: {$href}"); $item = new X_Page_Item_PItem($this->getId() . "-{$label}", $label); $item->setIcon('/images/icons/folder_32.png')->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setCustom(__CLASS__ . ':location', "{$type}/{$letter}/{$thread}/{$href}")->setLink(array('action' => 'mode', 'l' => X_Env::encode("{$type}/{$letter}/{$thread}/{$href}")), 'default', false); if (APPLICATION_ENV == 'development') { $item->setDescription("{$type}/{$letter}/{$thread}/{$href}"); } $items->append($item); } } }
/** * Add button -watch youtube stream directly- * * @param string $provider * @param string $location * @param Zend_Controller_Action $controller */ public function preGetModeItems($provider, $location, Zend_Controller_Action $controller) { if ($provider != $this->getId()) { return; } X_Debug::i("Plugin triggered"); // i have to remove default sub provider // and install the newer one in getModeItems X_VlcShares_Plugins::broker()->unregisterPluginClass('X_VlcShares_Plugins_FileSubs'); $url = $this->resolveLocation($location); if ($url) { // i have to check for rtsp videos, wiimc can't handle them if (X_Env::startWith($url, 'rtsp') && $this->helpers()->devices()->isWiimc()) { return; } $link = new X_Page_Item_PItem('core-directwatch', X_Env::_('p_youtube_watchdirectly')); $link->setIcon('/images/icons/play.png')->setType(X_Page_Item_PItem::TYPE_PLAYABLE)->setLink($url); // add tag wiimcplus_subtitle for subtitle in direct watching if ($this->config('closedcaption.enabled', true)) { /* @var $request Zend_Controller_Request_Http */ $request = $controller->getRequest(); $sub = false; $lc = $request->getParam($this->getId() . ':sub', false); if ($lc !== false) { @(list(, , , $videoId) = explode('/', $location)); $sub = array('controller' => 'youtube', 'action' => 'convert', 'v' => $videoId, 'l' => $lc, 'f' => 'file.srt'); } /* @var $urlHelper Zend_Controller_Action_Helper_Url */ $urlHelper = $controller->getHelper('url'); if ($sub !== false) { $link->setCustom('subtitle', X_Env::completeUrl($urlHelper->url($sub, 'default', true))); X_Debug::i("CC-XML to SRT Url: " . X_Env::completeUrl($urlHelper->url($sub, 'default', true))); } } @(list(, , , $videoId) = explode('/', $location)); $link2 = new X_Page_Item_PItem('core-directwatch', "Watch throught WIIMC"); $link2->setIcon('/images/icons/play.png')->setType(X_Page_Item_PItem::TYPE_PLAYABLE)->setLink("http://www.youtube.com/watch?v={$videoId}"); return new X_Page_ItemList_PItem(array($link, $link2)); } else { // if there is no link, i have to remove start-vlc button // and replace it with a Warning button X_Debug::i('Setting priority to filterModeItems'); $this->setPriority('filterModeItems', 99); $link = new X_Page_Item_PItem('youtube-warning', X_Env::_('p_youtube_invalidyoutube')); $link->setIcon('/images/msg_error.png')->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setLink(array('controller' => 'browse', 'action' => 'share', 'p' => $this->getId(), 'l' => X_Env::encode($this->getParentLocation($location))), 'default', true); return new X_Page_ItemList_PItem(array($link)); } }
private function _fetchGroupLastAnime(X_Page_ItemList_PItem $items, $resourceType, $pageN = 1) { $page = X_PageParser_Page::getPage(sprintf(self::URL_ANIME_INDEX_NEW, $pageN), X_PageParser_Parser_Preg::factory(self::PATTERN_MOVIESLAST, X_PageParser_Parser_Preg::PREG_MATCH_ALL, PREG_SET_ORDER)); $this->preparePageLoader($page); $parsed = $page->getParsed(); if ($pageN > 1) { // append "back" as first $prevPage = $pageN - 1; $items->append(X_VlcShares_Plugins_Utils::getPreviousPage("{$resourceType}/{$prevPage}", $prevPage)); } // $parsed format = array(array('image', 'category', 'id', 'label'),..) foreach ($parsed as $pItem) { $thumb = $pItem['image']; // fix for relative path: if (X_Env::startWith($thumb, '../')) { $thumb = self::URL_ANIME_INDEX_NEW . $thumb; } $group = $pItem['category']; $label = trim($pItem['label']); $id = $pItem['id']; X_Debug::i("Parsed item: " . var_export(array($id, $group, $label, $thumb), true)); $item = new X_Page_Item_PItem($this->getId() . "-{$resourceType}-{$group}-{$id}", $label); $item->setIcon('/images/icons/folder_32.png')->setType(X_Page_Item_PItem::TYPE_CONTAINER)->setCustom(__CLASS__ . ':location', "{$resourceType}/{$pageN}/{$group}/{$id}")->setDescription(APPLICATION_ENV == 'development' ? "{$resourceType}/{$pageN}/{$group}/{$id}" : null)->setThumbnail($thumb)->setLink(array('l' => X_Env::encode("{$resourceType}/{$pageN}/{$group}/{$id}")), 'default', false); $items->append($item); } if (count($page->getParsed(X_PageParser_Parser_Preg::factory(self::PATTERN_MOVIESLAST_NEXTPAGE, X_PageParser_Parser_Preg::PREG_MATCH)))) { // append "next" as last $nextPage = $pageN + 1; $items->append(X_VlcShares_Plugins_Utils::getNextPage("{$resourceType}/{$nextPage}", $nextPage)); } }
function svideoAction() { /* @var $request Zend_Controller_Request_Http */ $request = $this->getRequest(); if (!$request->isPost()) { $this->_helper->flashMessenger(array('text' => X_Env::_('p_youtube_save_invalidrequest'), 'type' => 'error')); $this->_helper->redirector('index', 'youtube'); } try { $form = new Application_Form_YoutubeVideo(); } catch (Exception $e) { $this->_helper->flashMessenger(array('text' => X_Env::_('p_youtube_save_formerror') . ": {$e->getMessage()}", 'type' => 'error')); $this->_helper->redirector('index', 'youtube'); } $post = $request->getPost(); X_Debug::i("Post = '" . var_export($post, true) . "'"); $valid = $form->isValid($post); if ($valid != true) { $this->_helper->flashMessenger(array('text' => X_Env::_('p_youtube_save_invaliddata'), 'type' => 'error')); //$this->_helper->flashMessenger(array('text' => '<pre>'.var_export($form, true).'</pre>', 'type' => 'error')); foreach ($form->getErrorMessages() as $error) { $this->_helper->flashMessenger(array('text' => $error, 'type' => 'error')); } $this->_helper->redirector('index', 'youtube'); } try { $idYoutube = $form->getValue('idYoutube'); if (X_Env::startWith($idYoutube, 'http')) { $start = strpos($idYoutube, 'v='); $end = strpos($idYoutube, '&', $start); if ($end !== false) { $idYoutube = substr($idYoutube, $start + 2, $end - $start - 2); } else { $idYoutube = substr($idYoutube, $start + 2); } X_Debug::i("Found ID: {$idYoutube}"); } $idCategory = $form->getValue('idCategory'); // check if $accountName is a valid account and if it has a thumbnail image /* @var $helper X_VlcShares_Plugins_Helper_Youtube */ $helper = X_VlcShares_Plugins::helpers('youtube'); $videoEntry = $helper->getVideo($idYoutube); $thumb = $videoEntry->getVideoThumbnails(); $thumb = @$thumb[0]['url']; $thumb = str_replace('default', '0', $thumb); $video = new Application_Model_YoutubeVideo(); $video->setLabel($videoEntry->getVideoTitle())->setDescription($videoEntry->getVideoDescription())->setIdYoutube($idYoutube)->setIdCategory($idCategory)->setThumbnail($thumb); Application_Model_YoutubeVideosMapper::i()->save($video); $this->_helper->flashMessenger(array('text' => X_Env::_('p_youtube_save_completed_video'), 'type' => 'info')); $this->_helper->redirector('category', 'youtube', 'default', array('idCategory' => $idCategory)); } catch (Zend_Gdata_App_HttpException $e) { $this->_helper->flashMessenger(array('text' => X_Env::_('p_youtube_save_err_invalidvideo'), 'type' => 'error')); $this->_helper->redirector('index', 'youtube'); } catch (Exception $e) { $this->_helper->flashMessenger(array('text' => X_Env::_('p_youtube_save_err_dberror') . ": {$e->getMessage()}", 'type' => 'error')); $this->_helper->redirector('index', 'youtube'); } }
/** * @see X_VlcShares_Plugins_ResolverInterface::getParentLocation * @param $location */ function getParentLocation($location = null) { if ($location == null || $location == '') { return false; } if ($location == self::INDEX_BLEACH || $location == self::INDEX_ONEPIECE || $location == self::INDEX_NARUTO) { return null; // no parent for category index. Fallback to normal index } else { if (X_Env::startWith($location, '?page=')) { // ok, we are inside a category $location = substr($location, strlen('?page=')); if (X_Env::startWith($location, self::INDEX_BLEACH)) { return self::INDEX_BLEACH; } elseif (X_Env::startWith($location, self::INDEX_BLEACH)) { return self::INDEX_NARUTO; } elseif (X_Env::startWith($location, self::INDEX_ONEPIECE) || X_Env::startWith($location, 'strm_one_piece')) { // i need to use double condition because in the page i have an inconsitence return self::INDEX_ONEPIECE; } else { return false; } } else { return false; } } }