private function _getFilePath($currentTheme, $pathToTemplate, $fallBackDirectory, $debugEnabled)
 {
     $environmentDetector = tubepress_impl_patterns_sl_ServiceLocator::getEnvironmentDetector();
     $userContentDirectory = $environmentDetector->getUserContentDirectory();
     /**
      * First try to load the template from system themes.
      */
     $filePath = TUBEPRESS_ROOT . "/src/main/resources/default-themes/{$currentTheme}/{$pathToTemplate}";
     if (is_readable($filePath)) {
         if ($debugEnabled) {
             $this->_logger->debug("Found {$pathToTemplate} first try at {$filePath}");
         }
         return $filePath;
     }
     if ($debugEnabled) {
         $this->_logger->debug("Didn't find {$pathToTemplate} at {$filePath}. Trying user theme directory next.");
     }
     /**
      * Next try to load the template from the user's theme directory.
      */
     $filePath = "{$userContentDirectory}/themes/{$currentTheme}/{$pathToTemplate}";
     if (is_readable($filePath)) {
         if ($debugEnabled) {
             $this->_logger->debug("Found {$pathToTemplate} in user's theme directory at {$filePath}");
         }
         return $filePath;
     }
     if ($debugEnabled) {
         $this->_logger->debug("Didn't find {$pathToTemplate} in system or user's theme directories. Falling back to {$fallBackDirectory}");
     }
     /**
      * Finally, load the template from the fallback directory.
      */
     return "{$fallBackDirectory}/{$pathToTemplate}";
 }
 protected function getStatusCodeToHtmlMap()
 {
     $executionContext = tubepress_impl_patterns_sl_ServiceLocator::getExecutionContext();
     $player = tubepress_impl_patterns_sl_ServiceLocator::getPlayerHtmlGenerator();
     $provider = tubepress_impl_patterns_sl_ServiceLocator::getVideoCollector();
     $qss = tubepress_impl_patterns_sl_ServiceLocator::getHttpRequestParameterService();
     $isDebugEnabled = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     if ($isDebugEnabled) {
         $this->_logger->debug('Handling incoming request. First parsing shortcode.');
     }
     $nvpMap = $qss->getAllParams();
     $videoId = $qss->getParamValue(tubepress_spi_const_http_ParamName::VIDEO);
     if ($isDebugEnabled) {
         $this->_logger->debug('Requested video is ' . $videoId);
     }
     $executionContext->setCustomOptions($nvpMap);
     if ($executionContext->get(tubepress_api_const_options_names_Embedded::LAZYPLAY)) {
         $executionContext->set(tubepress_api_const_options_names_Embedded::AUTOPLAY, true);
     }
     if ($isDebugEnabled) {
         $this->_logger->debug('Now asking video collector for video ' . $videoId);
     }
     /* grab the video! */
     $video = $provider->collectSingleVideo($videoId);
     if ($video === null) {
         return array(404 => "Video {$videoId} not found");
     }
     if ($isDebugEnabled) {
         $this->_logger->debug('Video collector found video ' . $videoId . '. Sending it to browser');
     }
     $toReturn = array('title' => $video->getAttribute(tubepress_api_video_Video::ATTRIBUTE_TITLE), 'html' => $player->getHtml($video));
     return array(200 => json_encode($toReturn));
 }
 private function _getSingleVideoHtml($videoId)
 {
     $eventDispatcher = tubepress_impl_patterns_sl_ServiceLocator::getEventDispatcher();
     $provider = tubepress_impl_patterns_sl_ServiceLocator::getVideoCollector();
     $themeHandler = tubepress_impl_patterns_sl_ServiceLocator::getThemeHandler();
     $template = $themeHandler->getTemplateInstance('single_video.tpl.php', TUBEPRESS_ROOT . '/src/main/resources/default-themes/default');
     /* grab the video from the provider */
     if ($this->_logger->isHandling(ehough_epilog_Logger::DEBUG)) {
         $this->_logger->debug(sprintf('Asking provider for video with ID %s', $videoId));
     }
     $video = $provider->collectSingleVideo($videoId);
     if ($video === null) {
         return sprintf('Video %s not found', $videoId);
         //>(translatable)<
     }
     if ($eventDispatcher->hasListeners(tubepress_api_const_event_EventNames::TEMPLATE_SINGLE_VIDEO)) {
         $event = new tubepress_spi_event_EventBase($template, array('video' => $video));
         $eventDispatcher->dispatch(tubepress_api_const_event_EventNames::TEMPLATE_SINGLE_VIDEO, $event);
         $template = $event->getSubject();
     }
     $html = $template->toString();
     if ($eventDispatcher->hasListeners(tubepress_api_const_event_EventNames::HTML_SINGLE_VIDEO)) {
         $event = new tubepress_spi_event_EventBase($html);
         $eventDispatcher->dispatch(tubepress_api_const_event_EventNames::HTML_SINGLE_VIDEO, $event);
         $html = $event->getSubject();
     }
     return $html;
 }
 /**
  * Determines if this response needs to be decoded.
  *
  * @param ehough_shortstop_api_HttpResponse $response The HTTP response.
  *
  * @return boolean True if this response should be decoded. False otherwise.
  */
 public final function needsToBeDecoded(ehough_shortstop_api_HttpResponse $response)
 {
     $entity = $response->getEntity();
     $isDebugEnabled = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     if ($entity === null) {
         if ($isDebugEnabled) {
             $this->_logger->debug('Response contains no entity');
         }
         return false;
     }
     $content = $entity->getContent();
     if ($content == '' || $content == null) {
         if ($isDebugEnabled) {
             $this->_logger->debug('Response entity contains no content');
         }
         return false;
     }
     $expectedHeaderName = $this->getHeaderName();
     $actualHeaderValue = $response->getHeaderValue($expectedHeaderName);
     if ($actualHeaderValue === null) {
         if ($isDebugEnabled) {
             $this->_logger->debug(sprintf('Response does not contain %s header. No need to decode.', $expectedHeaderName));
         }
         return false;
     }
     if ($isDebugEnabled) {
         $this->_logger->debug(sprintf('Response contains %s header. Will attempt decode.', $expectedHeaderName));
     }
     return true;
 }
 private function _getFromCache($url, tubepress_spi_context_ExecutionContext $context, $isDebugEnabled)
 {
     /**
      * @var $cache ehough_stash_interfaces_PoolInterface
      */
     $cache = tubepress_impl_patterns_sl_ServiceLocator::getCacheService();
     if ($isDebugEnabled) {
         $this->_logger->debug(sprintf('First asking cache for <a href="%s">URL</a>', $url));
     }
     $cacheKey = $this->_urlToCacheKey($url);
     $result = $cache->getItem($cacheKey);
     if ($result && !$result->isMiss()) {
         if ($isDebugEnabled) {
             $this->_logger->debug(sprintf('Cache has <a href="%s">URL</a>. Sweet.', $url));
         }
     } else {
         if ($isDebugEnabled) {
             $this->_logger->debug(sprintf('Cache does not have <a href="%s">URL</a>. We\'ll have to get it from the network.', $url));
         }
         $data = $this->_getFromNetwork($url);
         $storedSuccessfully = $result->set($data, $context->get(tubepress_api_const_options_names_Cache::CACHE_LIFETIME_SECONDS));
         if (!$storedSuccessfully) {
             if ($isDebugEnabled) {
                 $this->_logger->debug('Unable to store data to cache');
             }
             return $data;
         }
     }
     return $result->get();
 }
 /**
  * @return string The HTML for this shortcode handler.
  */
 public final function getHtml()
 {
     $qss = tubepress_impl_patterns_sl_ServiceLocator::getHttpRequestParameterService();
     $execContext = tubepress_impl_patterns_sl_ServiceLocator::getExecutionContext();
     $rawSearchTerms = $qss->getParamValue(tubepress_spi_const_http_ParamName::SEARCH_TERMS);
     $hasSearchTerms = $rawSearchTerms != '';
     $shouldLog = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     /* if the user isn't searching, don't display anything */
     if (!$hasSearchTerms) {
         if ($shouldLog) {
             $this->_logger->debug('User doesn\'t appear to be searching. Will not display anything.');
         }
         return '';
     }
     if ($shouldLog) {
         $this->_logger->debug('User is searching. We\'ll handle this.');
     }
     /* who are we searching? */
     switch ($execContext->get(tubepress_api_const_options_names_InteractiveSearch::SEARCH_PROVIDER)) {
         case 'vimeo':
             $execContext->set(tubepress_api_const_options_names_Output::GALLERY_SOURCE, tubepress_addons_vimeo_api_const_options_values_GallerySourceValue::VIMEO_SEARCH);
             $execContext->set(tubepress_addons_vimeo_api_const_options_names_GallerySource::VIMEO_SEARCH_VALUE, $rawSearchTerms);
             break;
         default:
             $execContext->set(tubepress_api_const_options_names_Output::GALLERY_SOURCE, tubepress_addons_youtube_api_const_options_values_GallerySourceValue::YOUTUBE_SEARCH);
             $execContext->set(tubepress_addons_youtube_api_const_options_names_GallerySource::YOUTUBE_TAG_VALUE, $rawSearchTerms);
             break;
     }
     /* display the results as a thumb gallery */
     return $this->_thumbGalleryShortcodeHandler->getHtml();
 }
 private function _logRequest(ehough_shortstop_api_HttpRequest $request)
 {
     $headerArray = $request->getAllHeaders();
     $this->_logger->debug(sprintf('Here are the ' . count($headerArray) . ' headers in the request for %s', $request));
     foreach ($headerArray as $name => $value) {
         $this->_logger->debug("<!--suppress HtmlPresentationalElement --><tt>{$name}: {$value}</tt>");
     }
 }
 public function onResponse(ehough_tickertape_GenericEvent $event)
 {
     if (!$this->_logger->isHandling(ehough_epilog_Logger::DEBUG)) {
         return;
     }
     $response = $event->getSubject();
     $request = $event->getArgument('request');
     $this->_logger->debug(sprintf('The raw result for %s is in the HTML source for this page <span style="display:none">%s</span>', $request, htmlspecialchars(var_export($response, true))));
 }
示例#9
0
 /**
  * Determines whether or not this transport is available on the system.
  *
  * @return bool True if this transport is available on the system. False otherwise.
  */
 public function isAvailable()
 {
     if (!function_exists('http_request')) {
         if ($this->_logger->isHandling(ehough_epilog_Logger::DEBUG)) {
             $this->_logger->debug('http_request() does not exist');
         }
         return false;
     }
     return true;
 }
 /**
  * @return string The HTML for this shortcode handler.
  */
 public final function getHtml()
 {
     $execContext = tubepress_impl_patterns_sl_ServiceLocator::getExecutionContext();
     $galleryId = $execContext->get(tubepress_api_const_options_names_Advanced::GALLERY_ID);
     $shouldLog = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     if ($galleryId == '') {
         $galleryId = mt_rand();
         $result = $execContext->set(tubepress_api_const_options_names_Advanced::GALLERY_ID, $galleryId);
         if ($result !== true) {
             return false;
         }
     }
     if ($shouldLog) {
         $this->_logger->debug(sprintf('Starting to build thumbnail gallery %s', $galleryId));
     }
     $provider = tubepress_impl_patterns_sl_ServiceLocator::getVideoCollector();
     $eventDispatcher = tubepress_impl_patterns_sl_ServiceLocator::getEventDispatcher();
     $themeHandler = tubepress_impl_patterns_sl_ServiceLocator::getThemeHandler();
     $ms = tubepress_impl_patterns_sl_ServiceLocator::getMessageService();
     $qss = tubepress_impl_patterns_sl_ServiceLocator::getHttpRequestParameterService();
     $template = $themeHandler->getTemplateInstance('gallery.tpl.php', TUBEPRESS_ROOT . '/src/main/resources/default-themes/default');
     $page = $qss->getParamValueAsInt(tubepress_spi_const_http_ParamName::PAGE, 1);
     /* first grab the videos */
     if ($shouldLog) {
         $this->_logger->debug('Asking provider for videos');
     }
     $feedResult = $provider->collectVideoGalleryPage();
     $numVideos = sizeof($feedResult->getVideos());
     if ($shouldLog) {
         $this->_logger->debug(sprintf('Provider has delivered %d videos', $numVideos));
     }
     if ($numVideos == 0) {
         return $ms->_('No matching videos');
         //>(translatable)<
     }
     /* send the template through the listeners */
     if ($eventDispatcher->hasListeners(tubepress_api_const_event_EventNames::TEMPLATE_THUMBNAIL_GALLERY)) {
         $event = new tubepress_spi_event_EventBase($template, array('page' => $page, 'videoGalleryPage' => $feedResult));
         $eventDispatcher->dispatch(tubepress_api_const_event_EventNames::TEMPLATE_THUMBNAIL_GALLERY, $event);
         $template = $event->getSubject();
     }
     $html = $template->toString();
     /* send gallery HTML through the listeners */
     if ($eventDispatcher->hasListeners(tubepress_api_const_event_EventNames::HTML_THUMBNAIL_GALLERY)) {
         $event = new tubepress_spi_event_EventBase($html, array('page' => $page, 'videoGalleryPage' => $feedResult));
         $eventDispatcher->dispatch(tubepress_api_const_event_EventNames::HTML_THUMBNAIL_GALLERY, $event);
         $html = $event->getSubject();
     }
     /* we're done. tie up */
     if ($shouldLog) {
         $this->_logger->debug(sprintf('Done assembling gallery %d', $galleryId));
     }
     return $html;
 }
 /**
  * Execute a unit of processing work to be performed.
  *
  * This Command may either complete the required processing and return true,
  * or delegate remaining processing to the next Command in a Chain containing
  * this Command by returning false.
  *
  * @param ehough_chaingang_api_Context $context The Context to be processed by this Command.
  *
  * @return boolean True if the processing of this Context has been completed, or false if the
  *                 processing of this Context should be delegated to a subsequent Command
  *                 in an enclosing Chain.
  */
 public function execute(ehough_chaingang_api_Context $context)
 {
     $response = $context->get('response');
     $encoding = $response->getHeaderValue(ehough_shortstop_api_HttpResponse::HTTP_HEADER_TRANSFER_ENCODING);
     if (strcasecmp($encoding, 'chunked') !== 0) {
         if ($this->_logger->isHandling(ehough_epilog_Logger::DEBUG)) {
             $this->_logger->debug('Response is not encoded with Chunked-Transfer');
         }
         return false;
     }
     /** @noinspection PhpUndefinedMethodInspection */
     $decoded = self::_decode($response->getEntity()->getContent());
     $context->put('response', $decoded);
     return true;
 }
 private function _readConfig()
 {
     $envDetector = tubepress_impl_patterns_sl_ServiceLocator::getEnvironmentDetector();
     $userContentDirectory = $envDetector->getUserContentDirectory();
     $configFileLocation = $userContentDirectory . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'boot.json';
     if (!is_file($configFileLocation) || !is_readable($configFileLocation)) {
         if ($this->_shouldLog) {
             $this->_logger->debug(sprintf('No readable config file at %s', $configFileLocation));
         }
         return;
     }
     if ($this->_shouldLog) {
         $this->_logger->debug(sprintf('Attempting to read boot config from %s', $configFileLocation));
     }
     $contents = file_get_contents($configFileLocation);
     if ($contents === false) {
         if ($this->_shouldLog) {
             $this->_logger->warn(sprintf('Failed to read file contents of %s', $configFileLocation));
         }
         return;
     }
     $decoded = @json_decode($contents, true);
     if ($decoded === false || !is_array($decoded)) {
         if ($this->_shouldLog) {
             $this->_logger->warn(sprintf('Failed to parse %s', $configFileLocation));
         }
     }
     if ($this->_shouldLog) {
         $this->_logger->debug(sprintf('Successfully read boot config from %s', $configFileLocation));
     }
     $this->_bootConfig = $decoded;
 }
 /**
  * Handles the detection of a custom options
  *
  * @param array                            $match         The array shortcode matches
  *
  * @return array The name value pair array.
  */
 private function _buildNameValuePairArray($match)
 {
     $toReturn = array();
     $eventDispatcher = tubepress_impl_patterns_sl_ServiceLocator::getEventDispatcher();
     $value = null;
     foreach ($match as $m) {
         if (!empty($m[1])) {
             $name = $m[1];
             $value = $m[2];
         } elseif (!empty($m[3])) {
             $name = $m[3];
             $value = $m[4];
         } elseif (!empty($m[5])) {
             $name = $m[5];
             $value = $m[6];
         }
         if (!isset($name) || !isset($value)) {
             continue;
         }
         if ($this->_shouldLog) {
             $this->_logger->debug(sprintf('Name-value pair detected: %s = "%s" (unfiltered)', $name, $value));
         }
         $event = new tubepress_spi_event_EventBase($value, array('optionName' => $name));
         $eventDispatcher->dispatch(tubepress_api_const_event_EventNames::OPTIONS_NVP_READFROMEXTERNAL, $event);
         $filtered = $event->getSubject();
         if ($this->_shouldLog) {
             $this->_logger->debug(sprintf('Name-value pair detected: %s = "%s" (filtered)', $name, $filtered));
         }
         $toReturn[$name] = $filtered;
     }
     return $toReturn;
 }
 private function _13_recordFinishTime()
 {
     if (!$this->_shouldLog) {
         return;
     }
     $now = microtime(true);
     $this->_logger->debug(sprintf('Boot completed in %f milliseconds', ($now - $this->_startTime) * 1000.0));
 }
 /**
  * Sets compression headers.
  *
  * @param ehough_shortstop_api_HttpRequest $request The request to modify.
  *
  * @return void
  */
 private function _setDefaultHeadersCompression(ehough_shortstop_api_HttpRequest $request)
 {
     if ($this->_isDebugEnabled) {
         $this->_logger->debug('Determining if HTTP compression is available...');
     }
     $header = $this->_httpContentDecoder->getAcceptEncodingHeaderValue();
     if ($header !== null) {
         if ($this->_isDebugEnabled) {
             $this->_logger->debug('HTTP decompression is available.');
         }
         $request->setHeader(ehough_shortstop_api_HttpRequest::HTTP_HEADER_ACCEPT_ENCODING, $header);
     } else {
         if ($this->_isDebugEnabled) {
             $this->_logger->debug('HTTP decompression is NOT available.');
         }
     }
 }
 public function onResponse(ehough_tickertape_GenericEvent $event)
 {
     $isDebugEnabled = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     $response = $event->getSubject();
     if ($this->_responseDecoder->needsToBeDecoded($response)) {
         if ($isDebugEnabled) {
             $this->_logger->debug(sprintf('Response is %s-Encoded. Attempting decode.', $this->_name));
         }
         $this->_responseDecoder->decode($response);
         if ($isDebugEnabled) {
             $this->_logger->debug(sprintf('Successfully decoded %s-Encoded response.', $this->_name));
         }
     } else {
         if ($isDebugEnabled) {
             $this->_logger->debug(sprintf('Response is not %s-Encoded.', $this->_name));
         }
     }
 }
 /**
  * @return string The HTML for this shortcode handler.
  */
 public final function getHtml()
 {
     $qss = tubepress_impl_patterns_sl_ServiceLocator::getHttpRequestParameterService();
     $execContext = tubepress_impl_patterns_sl_ServiceLocator::getExecutionContext();
     $videoId = $qss->getParamValue(tubepress_spi_const_http_ParamName::VIDEO);
     $shouldLog = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     if ($shouldLog) {
         $this->_logger->debug(sprintf('Building single video with ID %s', $videoId));
     }
     $result = $execContext->set(tubepress_api_const_options_names_Output::VIDEO, $videoId);
     if ($result !== true) {
         if ($shouldLog) {
             $this->_logger->debug('Could not verify video ID.');
         }
         return false;
     }
     /* display the results as a thumb gallery */
     return $this->_singleVideoShortcodeHandler->getHtml();
 }
示例#18
0
 /**
  * Perform optional tear down after handling a request.
  *
  * @return void
  */
 protected function tearDown()
 {
     if ($this->_logger->isHandling(ehough_epilog_Logger::DEBUG)) {
         $this->_logger->debug('Closing cURL');
     }
     if (isset($this->_handle)) {
         curl_close($this->_handle);
         unset($this->_handle);
     }
 }
 public function onVideoGalleryPage(tubepress_api_event_EventInterface $event)
 {
     $totalResults = $event->getSubject()->getTotalResultCount();
     $context = tubepress_impl_patterns_sl_ServiceLocator::getExecutionContext();
     $limit = $context->get(tubepress_api_const_options_names_Feed::RESULT_COUNT_CAP);
     $firstCut = $limit == 0 ? $totalResults : min($limit, $totalResults);
     $secondCut = min($firstCut, self::_calculateRealMax($context, $firstCut));
     $videos = $event->getSubject()->getVideos();
     $resultCount = count($videos);
     $shouldLog = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     if ($shouldLog) {
         $this->_logger->debug(sprintf('Effective total result count (taking into account user-defined limit) is %d video(s)', $secondCut));
     }
     if ($resultCount > $secondCut) {
         if ($shouldLog) {
             $this->_logger->debug(sprintf('Result has %d video(s), limit is %d. So we\'re chopping it down.', $resultCount, $secondCut));
         }
         $event->getSubject()->setVideos(array_splice($videos, 0, $secondCut - $resultCount));
     }
     $event->getSubject()->setTotalResultCount($secondCut);
 }
 private function _prependVideo($id, tubepress_api_event_EventInterface $event, $shouldLog)
 {
     $videos = $event->getSubject()->getVideos();
     /* see if the array already has it */
     if (self::_videoArrayAlreadyHasVideo($videos, $id)) {
         $videos = self::_moveVideoUpFront($videos, $id);
         $event->getSubject()->setVideos($videos);
         return;
     }
     try {
         $provider = tubepress_impl_patterns_sl_ServiceLocator::getVideoCollector();
         $video = $provider->collectSingleVideo($id);
         array_unshift($videos, $video);
     } catch (Exception $e) {
         if ($shouldLog) {
             $this->_logger->debug(sprintf('Could not prepend video %s to the gallery: %s', $id, $e->getMessage()));
         }
     }
     /* modify the feed result */
     $event->getSubject()->setVideos($videos);
 }
 /**
  * Sets the value of an option
  *
  * @param string $optionName  The name of the option
  * @param mixed  $optionValue The option value
  *
  * @return mixed True if the option was set normally, otherwise a string error message.
  */
 public final function set($optionName, $optionValue)
 {
     $eventDispatcherService = tubepress_impl_patterns_sl_ServiceLocator::getEventDispatcher();
     $optionValidatorService = tubepress_impl_patterns_sl_ServiceLocator::getOptionValidator();
     /** First run it through the filters. */
     /** Run it through the filters. */
     $event = new tubepress_spi_event_EventBase($optionValue, array('optionName' => $optionName));
     $eventDispatcherService->dispatch(tubepress_api_const_event_EventNames::OPTIONS_NVP_PREVALIDATIONSET, $event);
     $filteredValue = $event->getSubject();
     if ($optionValidatorService->isValid($optionName, $filteredValue)) {
         if ($this->_logger->isHandling(ehough_epilog_Logger::DEBUG)) {
             $this->_logger->debug(sprintf('Accepted valid value: %s = %s', $optionName, $this->_normalizeForStringOutput($filteredValue)));
         }
         $this->_customOptions[$optionName] = $filteredValue;
         return true;
     }
     $problemMessage = $optionValidatorService->getProblemMessage($optionName, $filteredValue);
     if ($this->_logger->isHandling(ehough_epilog_Logger::DEBUG)) {
         $this->_logger->warn(sprintf('Ignoring invalid value for "%s" (%s)', $optionName, $problemMessage));
     }
     return $problemMessage;
 }
 public function onVideoGalleryPage(tubepress_api_event_EventInterface $event)
 {
     $context = tubepress_impl_patterns_sl_ServiceLocator::getExecutionContext();
     $perPageSortOrder = $context->get(tubepress_api_const_options_names_Feed::PER_PAGE_SORT);
     $feedSortOrder = $context->get(tubepress_api_const_options_names_Feed::ORDER_BY);
     $shouldLog = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     /** No sort requested? */
     if ($perPageSortOrder === tubepress_api_const_options_values_PerPageSortValue::NONE) {
         if ($shouldLog) {
             $this->_logger->debug('Requested per-page sort order is "none". Not applying per-page sorting.');
         }
         return;
     }
     /** Grab a handle to the videos. */
     $videos = $event->getSubject()->getVideos();
     if ($perPageSortOrder === tubepress_api_const_options_values_PerPageSortValue::RANDOM) {
         if ($shouldLog) {
             $this->_logger->debug('Shuffling videos');
         }
         shuffle($videos);
     } else {
         /** Determine the sort method name. */
         $sortCallback = '_' . $perPageSortOrder . '_compare';
         /** If we have a sorter, use it. */
         if (method_exists($this, $sortCallback)) {
             if ($shouldLog) {
                 $this->_logger->debug(sprintf('Now sorting %s videos on page (%s)', count($videos), $perPageSortOrder));
             }
             uasort($videos, array($this, $sortCallback));
         } else {
             if ($shouldLog) {
                 $this->_logger->debug(sprintf('No sort available for this page (%s)', $perPageSortOrder));
             }
         }
     }
     $videos = array_values($videos);
     /** Modify the feed result. */
     $event->getSubject()->setVideos($videos);
 }
示例#23
0
 /**
  * Determines whether or not this transport is available on the system.
  *
  * @return bool True if this transport is available on the system. False otherwise.
  */
 public function isAvailable()
 {
     $isDebugging = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     if (!function_exists('fopen')) {
         if ($isDebugging) {
             $this->_logger->debug('fopen() does not exist');
         }
         return false;
     }
     if (function_exists('ini_get') && ini_get('allow_url_fopen') != true) {
         if ($isDebugging) {
             $this->_logger->debug('allow_url_fopen is set to false');
         }
         return false;
     }
     return true;
 }
 private function _createDomDocument($feed)
 {
     if ($this->_logger->isHandling(ehough_epilog_Logger::DEBUG)) {
         $this->_logger->debug('Attempting to load XML from YouTube');
     }
     if (!class_exists('DOMDocument')) {
         throw new RuntimeException('DOMDocument class not found');
     }
     $doc = new DOMDocument();
     if ($doc->loadXML($feed) === false) {
         throw new RuntimeException('Could not parse XML from YouTube');
     }
     if ($this->_logger->isHandling(ehough_epilog_Logger::DEBUG)) {
         $this->_logger->debug('Successfully loaded XML from YouTube');
     }
     $this->_domDocument = $doc;
 }
 private function _includeFile($file, tubepress_spi_addon_Addon $addon)
 {
     if ($this->_shouldLog) {
         $this->_logger->debug(sprintf('Now including file %s for add-on %s', $file, $addon->getName()));
     }
     if (!is_file($file) || !is_readable($file)) {
         $this->_logWarning(sprintf('%s is not a readable file', $file));
         return;
     }
     try {
         /** @noinspection PhpIncludeInspection */
         include $file;
     } catch (Exception $e) {
         $this->_logWarning(sprintf('Failed to include %s: %s', $file, $e->getMessage()));
     }
     if ($this->_shouldLog) {
         $this->_logger->debug(sprintf('Done including file %s for add-on %s', $file, $addon->getName()));
     }
 }
 private function _feedToVideoArray($feed)
 {
     $toReturn = array();
     $total = $this->countVideosInFeed($feed);
     $isDebugEnabled = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     if ($isDebugEnabled) {
         $this->_logger->debug(sprintf('Now attempting to build %d video(s) from raw feed', $total));
     }
     for ($index = 0; $index < $total; $index++) {
         if (!$this->canWorkWithVideoAtIndex($index)) {
             if ($isDebugEnabled) {
                 $this->_logger->debug(sprintf('Skipping video at index %d', $index));
             }
             continue;
         }
         /*
          * Let's build a video!
          */
         $video = new tubepress_api_video_Video();
         /*
          * Every video needs to have a provider.
          */
         $video->setAttribute(tubepress_api_video_Video::ATTRIBUTE_PROVIDER_NAME, $this->getName());
         /*
          * Let add-ons build the rest of the video.
          */
         $event = new tubepress_spi_event_EventBase($video);
         $event->setArgument('zeroBasedFeedIndex', $index);
         $event->setArgument('rawFeed', $feed);
         /*
          * Let subclasses add to the event.
          */
         $this->onBeforeFiringVideoConstructionEvent($event);
         $video = $this->_fireEventAndGetSubject(tubepress_api_const_event_EventNames::VIDEO_CONSTRUCTION, $event);
         array_push($toReturn, $video);
     }
     $this->onFeedAnalysisComplete($feed);
     if ($isDebugEnabled) {
         $this->_logger->debug(sprintf('Built %d video(s) from raw feed', sizeof($toReturn)));
     }
     return $toReturn;
 }
 private function _tryToBuildAddonFromFile(SplFileInfo $infoFile)
 {
     $manifestFilePath = realpath("{$infoFile}");
     $infoFileContents = @json_decode(file_get_contents($manifestFilePath), true);
     $shouldLog = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
     if ($infoFileContents === null || $infoFileContents === false || empty($infoFileContents)) {
         if ($shouldLog) {
             $this->_logger->debug('Could not parse add-on manifest file at ' . $manifestFilePath);
         }
         return null;
     }
     try {
         return $this->_constructAddonFromArray($infoFileContents, $manifestFilePath);
     } catch (Exception $e) {
         if ($shouldLog) {
             $this->_logger->warn('Caught exception when parsing info file at ' . $infoFile->getRealpath() . ': ' . $e->getMessage());
         }
         return null;
     }
 }
 private function _registerPsr0ClassPath(tubepress_spi_addon_Addon $addon, ehough_pulsar_ComposerClassLoader $classLoader)
 {
     $classPaths = $addon->getPsr0ClassPathRoots();
     if (count($classPaths) === 0) {
         return;
     }
     if ($this->_shouldLog) {
         $this->_logger->debug(sprintf('Add-on %s has %d PSR-0 path(s) for the classloader', $addon->getName(), count($classPaths)));
     }
     foreach ($classPaths as $prefix => $path) {
         if ($this->_shouldLog) {
             $this->_logger->debug(sprintf('Add-on %s registered %s => %s as a PSR-0 classpath', $addon->getName(), $prefix, $path));
         }
         if ($prefix) {
             $classLoader->registerPrefix($prefix, $path);
             $classLoader->registerNamespace($prefix, $path);
         } else {
             $classLoader->registerNamespaceFallback($path);
             $classLoader->registerPrefixFallback($path);
         }
     }
 }
 /**
  * @param string $path The contents of the cache file.
  *
  * @return object The hydrated object, or null if there was a problem.
  */
 protected function hydrate($path)
 {
     if (!is_file($path) || !is_readable($path)) {
         if ($this->_shouldLog) {
             $this->_logger->debug(sprintf('IOC container cache file is not a readable file: %s', $path));
         }
         return false;
     }
     if (!class_exists('TubePressServiceContainer')) {
         include $path;
     }
     if (!class_exists('TubePressServiceContainer')) {
         if ($this->_shouldLog) {
             $this->_logger->debug(sprintf('Could not read cached service container', $path));
         }
         return false;
     }
     if ($this->_shouldLog) {
         $this->_logger->debug(sprintf('Loaded cached container. Now attempting to instantiate', $path));
     }
     /** @noinspection PhpUndefinedClassInspection */
     return new TubePressServiceContainer();
 }
 private function _killCacheIfNeeded(ehough_epilog_Logger $logger, $shouldLog)
 {
     $bootConfigService = tubepress_impl_patterns_sl_ServiceLocator::getBootHelperConfigService();
     $shouldKillCache = $bootConfigService->isCacheKillerTurnedOn();
     if (!$shouldKillCache) {
         return;
     }
     $elementName = $this->getBootCacheConfigElementName();
     $filePath = $bootConfigService->getAbsolutePathToCacheFileForElement($elementName);
     if (!file_exists($filePath)) {
         return;
     }
     if ($shouldLog) {
         $logger->debug(sprintf('Attempting to delete cache file for %s at %s', $elementName, $filePath));
     }
     $result = @unlink($filePath);
     if (!$shouldLog) {
         return;
     }
     if ($result === true) {
         $logger->debug(sprintf('Successfully deleted cache file for %s at %s', $elementName, $filePath));
     } else {
         $logger->warn(sprintf('Could not delete cache file for %s at %s. Please delete it manually.', $elementName, $filePath));
     }
 }