/**
  * Get category/video list
  * @param unknown_type $provider
  * @param unknown_type $location
  * @param Zend_Controller_Action $controller
  */
 public function getShareItems($provider, $location, Zend_Controller_Action $controller)
 {
     // this plugin add items only if it is the provider
     if ($provider != $this->getId()) {
         return;
     }
     X_Debug::i("Plugin triggered");
     // try to disable SortItems plugin, so link are listed as in html page
     X_VlcShares_Plugins::broker()->unregisterPluginClass('X_VlcShares_Plugins_SortItems');
     $urlHelper = $controller->getHelper('url');
     $items = new X_Page_ItemList_PItem();
     if ($location != '' && array_key_exists((int) $location, $this->seasons)) {
         // episodes list
         $url = $this->seasons[(int) $location];
         $html = $this->_loadPage($url);
         $dom = new Zend_Dom_Query($html);
         $results = $dom->queryXpath('//div[@id="randomVideos"]//div[@class="randomTab"]//a[@class="previewDescriptionTitle"]');
         $resultsImages = $dom->queryXpath('//div[@id="randomVideos"]//div[@class="randomTab"]//img[1]/attribute::src');
         for ($i = 0; $i < $results->count(); $i++, $results->next()) {
             $node = $results->current();
             $href = $node->getAttribute('href');
             $label = $node->nodeValue;
             $id = explode('id=', $href, 2);
             $id = @$id[1];
             $thumb = null;
             try {
                 if ($resultsImages->valid()) {
                     $thumb = $resultsImages->current()->nodeValue;
                     $resultsImages->next();
                 }
             } catch (Exception $e) {
                 $thumb = null;
             }
             $item = new X_Page_Item_PItem($this->getId() . '-' . $label, $label);
             $item->setIcon('/images/icons/file_32.png')->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setCustom(__CLASS__ . ':location', $id)->setLink(array('action' => 'mode', 'l' => X_Env::encode($id)), 'default', false);
             if ($thumb !== null) {
                 $item->setThumbnail($thumb);
             }
             $items->append($item);
         }
     } else {
         foreach ($this->seasons as $key => $seasons) {
             $item = new X_Page_Item_PItem($this->getId() . '-' . $key, X_Env::_('p_allsp_season_n') . ": {$key}");
             $item->setIcon('/images/icons/folder_32.png')->setType(X_Page_Item_PItem::TYPE_CONTAINER)->setCustom(__CLASS__ . ':location', $key)->setLink(array('action' => 'share', 'l' => X_Env::encode($key)), 'default', false);
             $items->append($item);
         }
     }
     return $items;
 }
 protected function libraryMenu(X_Page_ItemList_PItem $items, $submode = false)
 {
     X_Debug::i("Submode requested: " . print_r($submode, true));
     // disabling cache plugin
     try {
         $cachePlugin = X_VlcShares_Plugins::broker()->getPlugins('cache');
         if (method_exists($cachePlugin, 'setDoNotCache')) {
             $cachePlugin->setDoNotCache();
         }
     } catch (Exception $e) {
         // cache plugin not registered, no problem
     }
     if ($submode === false || $submode == null) {
         // load all categories in the library
         $categories = Application_Model_YoutubeCategoriesMapper::i()->fetchAll();
         foreach ($categories as $category) {
             /* @var $category Application_Model_YoutubeCategory */
             $item = new X_Page_Item_PItem('youtube-category-' . $category->getId(), $category->getLabel());
             $item->setThumbnail($category->getThumbnail())->setIcon('/images/youtube/icons/category.png')->setCustom(__CLASS__ . ':location', self::MODE_LIBRARY . "/" . $category->getId())->setLink(array('l' => X_Env::encode(self::MODE_LIBRARY . "/" . $category->getId())), 'default', false)->setGenerator(__CLASS__);
             $items->append($item);
         }
     } else {
         // load all video inside a category categories
         /* @var $category Application_Model_YoutubeCategory */
         $category = new Application_Model_YoutubeCategory();
         Application_Model_YoutubeCategoriesMapper::i()->find($submode, $category);
         X_Debug::i('Category found: ' . print_r($category, true));
         if ($category->getId() != null && $category->getId() == $submode) {
             $videos = Application_Model_YoutubeVideosMapper::i()->fetchByCategory($category->getId());
             foreach ($videos as $video) {
                 /* @var $video Application_Model_YoutubeVideo */
                 $item = new X_Page_Item_PItem('youtube-library-' . $video->getId(), $video->getLabel());
                 $item->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setIcon('/images/youtube/icons/video.png')->setDescription($video->getDescription())->setThumbnail($video->getThumbnail())->setCustom(__CLASS__ . ':location', self::MODE_LIBRARY . "/" . $category->getId() . "/0/" . $video->getId())->setLink(array('action' => 'mode', 'l' => X_Env::encode(self::MODE_LIBRARY . "/" . $category->getId() . "/0/" . $video->getId())), 'default', false)->setGenerator(__CLASS__);
                 $items->append($item);
             }
         }
     }
 }
 /**
  * Fetch videos in $category and $itemPage
  */
 protected function fetchVideos(X_Page_ItemList_PItem $items, $catPage, $category, $itemPage)
 {
     // FIXME we shouldn't use paginator. We could use db for pagination
     // it's faster
     $videos = Application_Model_VideosMapper::i()->fetchByCategory($category);
     $totalPageCount = $this->helpers()->paginator()->getPages($videos);
     if ($this->helpers()->paginator()->hasPrevious($videos, $itemPage)) {
         $item = new X_Page_Item_PItem($this->getId() . '-previousvidpage', X_Env::_("p_onlinelibrary_previouspage", $itemPage - 1, $totalPageCount));
         $item->setType(X_Page_Item_PItem::TYPE_CONTAINER)->setCustom(__CLASS__ . ':location', "{$catPage}/" . X_Env::encode($category) . "/" . ($itemPage - 1))->setLink(array('l' => X_Env::encode("{$catPage}/" . X_Env::encode($category) . "/" . ($itemPage - 1))), 'default', false);
         $items->append($item);
     }
     foreach ($this->helpers()->paginator()->getPage($videos, $itemPage) as $video) {
         /* @var $video Application_Model_Video */
         $item = new X_Page_Item_PItem($this->getId() . '-' . $video->getId(), $video->getTitle() . " [" . ucfirst($video->getHoster() . "]"));
         $item->setIcon("/images/icons/hosters/{$video->getHoster()}.png")->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setCustom(__CLASS__ . ':location', "{$catPage}/" . X_Env::encode($category) . "/{$itemPage}/" . $video->getId())->setLink(array('action' => 'mode', 'l' => X_Env::encode("{$catPage}/" . X_Env::encode($category) . "/{$itemPage}/" . $video->getId())), 'default', false);
         if (trim($video->getDescription()) != '') {
             $item->setDescription(trim($video->getDescription()));
         }
         if (trim($video->getThumbnail()) != '') {
             $item->setThumbnail(trim($video->getThumbnail()));
         }
         $items->append($item);
     }
     if ($this->helpers()->paginator()->hasNext($videos, $itemPage)) {
         $item = new X_Page_Item_PItem($this->getId() . '-previousvidpage', X_Env::_("p_onlinelibrary_nextpage", $itemPage + 1, $totalPageCount));
         $item->setType(X_Page_Item_PItem::TYPE_CONTAINER)->setCustom(__CLASS__ . ':location', "{$catPage}/" . X_Env::encode($category) . "/" . ($itemPage + 1))->setLink(array('l' => X_Env::encode("{$catPage}/" . X_Env::encode($category) . "/" . ($itemPage + 1))), 'default', false);
         $items->append($item);
     }
 }
 /**
  * Check the item in the collection should be filtered out
  * If return is false, the item will be discarded at 100%
  * If return is true, isn't sure that the item will be added
  * 'cause another plugin can prevent this
  * 
  * Plugins who check per-item acl or blacklist should hook here
  * 
  * @param X_Page_Item_PItem $item
  * @param string $provider
  * @param Zend_Controller_Action $controller
  * @return boolean true if item is ok, false if item should be discarded
  */
 public function filterShareItems(X_Page_Item_PItem $item, $provider, Zend_Controller_Action $controller)
 {
     $providerClass = X_VlcShares_Plugins::broker()->getPluginClass($provider);
     $providerObj = X_VlcShares_Plugins::broker()->getPlugins($provider);
     if (is_a($providerObj, 'X_VlcShares_Plugins_FileSystem')) {
         if ($item->getType() == X_Page_Item_PItem::TYPE_ELEMENT) {
             $itemLocation = $item->getCustom('X_VlcShares_Plugins_FileSystem:location');
             /* @var $urlHelper Zend_Controller_Action_Helper_Url */
             $urlHelper = $controller->getHelper('url');
             $path = $providerObj->resolveLocation($itemLocation);
             $thumb = new Application_Model_FsThumb();
             Application_Model_FsThumbsMapper::i()->fetchByPath($path, $thumb);
             if ($thumb->isNew()) {
                 $thumbUrl = X_Env::completeUrl($urlHelper->direct('thumb', 'fsthumbs', 'default', array('l' => X_Env::encode($itemLocation), 't' => 'dummy.jpg')));
             } else {
                 $thumbUrl = X_Env::completeUrl(Zend_Controller_Front::getInstance()->getBaseUrl() . $thumb->getUrl());
             }
             //$item->setDescription($itemLocation);
             $item->setThumbnail($thumbUrl);
         }
     }
     return true;
 }
 /**
  * Fill a list of resource by type, group and page
  * @param X_Page_ItemList_PItem $items an empty list
  * @param string $resourceType the resource type selected
  * @param string $resourceGroup the resource group selected
  * @param int $page number of the page 
  * @return X_Page_ItemList_PItem the list filled
  */
 private function _fetchResources(X_Page_ItemList_PItem $items, $resourceType, $resourceGroup, $page = 1)
 {
     X_Debug::i("Fetching resources for {$resourceType}/{$resourceGroup}/{$page}");
     // if resourceGroup == new, query and url are specials
     if ($resourceGroup == 'new') {
         switch ($resourceType) {
             case self::TYPE_MOVIES:
                 $url = self::URL_MOVIES_INDEX_NEW;
                 $xpathQuery = '//div[@id="maincontent"]//div[@class="galleryitem"]';
                 break;
             case self::TYPE_ANIME:
                 $url = self::URL_ANIME_INDEX_NEW;
                 $xpathQuery = '//div[@id="sidebar"]//div[@id="text-5"]//tr[11]//td';
                 break;
             case self::TYPE_TVSHOWS:
                 $url = self::URL_TVSHOWS_INDEX_NEW;
                 $xpathQuery = '//div[@id="sidebar"]//div[@id="text-5"]//tr[position()=1 or position()=4 or position()=5]//td//a/parent::node()';
                 break;
         }
     } else {
         switch ($resourceType) {
             case self::TYPE_MOVIES:
                 $url = sprintf(self::URL_MOVIES_INDEX_AZ, $resourceGroup);
                 $xpathQuery = '//div[@id="maincontent"]//p/*/a[1][node()][text()]';
                 $hasThumbnail = false;
                 $hasDescription = false;
                 break;
             case self::TYPE_ANIME:
                 $url = self::URL_ANIME_INDEX_AZ;
                 $xpathQuery = '//div[@id="maincontent"]//p/*/a[1][node()][text()]';
                 break;
             case self::TYPE_TVSHOWS:
                 $url = self::URL_TVSHOWS_INDEX_AZ;
                 $xpathQuery = '//div[@id="maincontent"]//p/*/a[1][node()][text()]';
                 break;
         }
     }
     // fetch the page from filmstream (url is different for each $resourceType)
     $htmlString = $this->_loadPage($url);
     // load the readed page inside a DOM object, so we can user XPath for traversal
     $dom = new Zend_Dom_Query($htmlString);
     // execute the query
     $result = $dom->queryXpath($xpathQuery);
     if ($result->valid()) {
         X_Debug::i("Resources found: " . $result->count());
         $perPage = $this->config('items.perpage', 50);
         // before to slice the results, we must check if a -next-page- is needed
         $nextNeeded = $result->count() > $page * $perPage ? true : false;
         $matches = array();
         $i = 1;
         while ($result->valid()) {
             if ($i > ($page - 1) * $perPage && $i < $page * $perPage) {
                 $currentRes = $result->current();
                 if ($resourceGroup == 'new') {
                     $IdNode = $currentRes->firstChild;
                     while ($IdNode instanceof DOMText && $IdNode != null) {
                         $IdNode = $IdNode->nextSibling;
                     }
                     // anime, tvshow, subbed are on the side bar, and $currentRes has 1 child only
                     if ($currentRes->childNodes->length == 1) {
                         $labelNode = $IdNode;
                     } else {
                         $labelNode = $IdNode->nextSibling;
                     }
                     if (is_object($labelNode) && trim($labelNode->nodeValue) == '') {
                         $labelNode = $labelNode->parentNode;
                     }
                     $resourceId = str_replace('/', ':', substr($IdNode->getAttribute('href'), strlen(self::URL_BASE), -1));
                     // i've done everthing. If all doesn't work, just skip this entry
                     if ($resourceId == "") {
                         $i++;
                         $result->next();
                         continue;
                     }
                     $resourceLabel = trim(@$labelNode->nodeValue);
                     if ($resourceLabel == '') {
                         $resourceLabel = $currentRes->nodeValue;
                     }
                     $resourceDescription = null;
                     $resourceThumbnail = $IdNode->firstChild != null && !$IdNode->firstChild instanceof DOMText ? $IdNode->firstChild->getAttribute('src') : null;
                 } else {
                     $resourceId = str_replace('/', ':', substr($currentRes->getAttribute('href'), strlen(self::URL_BASE), -1));
                     $resourceLabel = trim($currentRes->nodeValue);
                     $resourceDescription = null;
                     $resourceThumbnail = null;
                 }
                 $matches[] = array($resourceId, $resourceLabel, $resourceDescription, $resourceThumbnail);
             }
             $i++;
             $result->next();
         }
         if ($page > 1) {
             // we need the "previus-page" link
             $item = new X_Page_Item_PItem($this->getId() . "-previouspage", X_Env::_("p_filmstream_page_previous", $page - 1));
             $item->setType(X_Page_Item_PItem::TYPE_CONTAINER)->setCustom(__CLASS__ . ':location', "{$resourceType}/{$resourceGroup}/" . ($page - 1))->setLink(array('l' => X_Env::encode("{$resourceType}/{$resourceGroup}/" . ($page - 1))), 'default', false);
             $items->append($item);
         }
         foreach ($matches as $resource) {
             @(list($resourceId, $resourceLabel, $resourceDescription, $resourceThumbnail) = $resource);
             $item = new X_Page_Item_PItem($this->getId() . "-{$resourceType}-{$resourceGroup}-{$page}-{$resourceId}", $resourceLabel);
             $item->setIcon('/images/icons/folder_32.png')->setType(X_Page_Item_PItem::TYPE_CONTAINER)->setCustom(__CLASS__ . ':location', "{$resourceType}/{$resourceGroup}/{$page}/{$resourceId}")->setLink(array('l' => X_Env::encode("{$resourceType}/{$resourceGroup}/{$page}/{$resourceId}")), 'default', false);
             if ($resourceDescription != null) {
                 $item->setDescription($resourceDescription);
             } elseif (APPLICATION_ENV == 'development') {
                 $item->setDescription("{$resourceType}/{$resourceGroup}/{$page}/{$resourceId}");
             }
             if ($resourceThumbnail != null) {
                 $item->setThumbnail($resourceThumbnail);
             }
             $items->append($item);
         }
         if ($nextNeeded) {
             // we need the "previus-page" link
             $item = new X_Page_Item_PItem($this->getId() . "-nextpage", X_Env::_("p_filmstream_page_next", $page + 1));
             $item->setType(X_Page_Item_PItem::TYPE_CONTAINER)->setCustom(__CLASS__ . ':location', "{$resourceType}/{$resourceGroup}/" . ($page + 1))->setLink(array('l' => X_Env::encode("{$resourceType}/{$resourceGroup}/" . ($page + 1))), 'default', false);
             $items->append($item);
         }
     } else {
         X_Debug::e("Query failed {{$xpathQuery}}");
     }
 }
 public function menuLinks(X_Page_ItemList_PItem $items, $type, $filter, $title, $season, $episode, $pageN = 1)
 {
     $pageN = X_VlcShares_Plugins_Utils::isset_or($pageN, 1);
     if ($type == 'documentaries') {
         $page = X_PageParser_Page::getPage(sprintf(self::URL_INDEX_LINKS_DOCUMENTARIES, $type, $title, $pageN), new X_PageParser_Parser_TvLinks(X_PageParser_Parser_TvLinks::MODE_LINKS, $type, $filter, $title, $season, $episode, $pageN));
     } else {
         $page = X_PageParser_Page::getPage(sprintf(self::URL_INDEX_LINKS, $type, $title, $season, $episode, $pageN), new X_PageParser_Parser_TvLinks(X_PageParser_Parser_TvLinks::MODE_LINKS, $type, $filter, $title, $season, $episode, $pageN));
     }
     $this->preparePageLoader($page);
     $parsed = $page->getParsed();
     if ($pageN > 1) {
         // add -previous-page-
         $previousPage = $pageN - 1;
         $items->append(X_VlcShares_Plugins_Utils::getPreviousPage("{$type}/{$filter}/{$title}/{$season}/{$episode}/{$previousPage}", $previousPage));
     }
     foreach ($parsed as $match) {
         $id = $match['id'];
         $hoster = $match['hoster'];
         $label = X_Env::_('p_tvlinks_watchon', ucfirst($hoster));
         $thumbnail = array_key_exists('thumbnail', $match) ? $match['thumbnail'] : null;
         $item = new X_Page_Item_PItem($this->getId() . "-{$type}-{$filter}-{$title}-{$season}-{$episode}-{$id}", $label);
         if (file_exists(APPLICATION_PATH . '/../public/images/icons/hosters/' . $hoster . '.png')) {
             $item->setIcon("/images/icons/hosters/{$hoster}.png");
         } else {
             if (X_VlcShares::VERSION == "0.5.4") {
                 $item->setIcon("/images/icons/file_32.png");
             } else {
                 // icons exists only in vlc-shares > 0.5.4
                 $item->setIcon("/images/icons/unknown-hoster.png");
             }
         }
         $item->setType(X_Page_Item_PItem::TYPE_ELEMENT)->setCustom(__CLASS__ . ':location', "{$type}/{$filter}/{$title}/{$season}/{$episode}/{$pageN}/{$id}")->setDescription(APPLICATION_ENV == 'development' ? "{$type}/{$filter}/{$title}/{$season}/{$episode}/{$pageN}/{$id}" : null)->setLink(array('action' => 'mode', 'l' => X_Env::encode("{$type}/{$filter}/{$title}/{$season}/{$episode}/{$pageN}/{$id}")), 'default', false);
         if ($thumbnail) {
             $item->setThumbnail($thumbnail);
         }
         $items->append($item);
     }
     if ($page->getParsed(new X_PageParser_Parser_TvLinks(X_PageParser_Parser_TvLinks::MODE_NEXTPAGE, $type, $filter, $title, $season, $episode, $pageN))) {
         $nextPage = $pageN + 1;
         $items->append(X_VlcShares_Plugins_Utils::getNextPage("{$type}/{$filter}/{$title}/{$season}/{$episode}/{$nextPage}", $nextPage));
     }
 }