示例#1
0
 /**
  * add video
  * @param string $url
  * @return string error message or array( $videoTitle, $videoPageId, $videoProvider )
  */
 public function addVideo($url)
 {
     global $wgIsGhostVideo;
     wfProfileIn(__METHOD__);
     if (!$this->wg->User->isAllowed('videoupload')) {
         wfProfileOut(__METHOD__);
         return wfMessage('videos-error-admin-only')->plain();
     }
     if (empty($url)) {
         wfProfileOut(__METHOD__);
         return wfMessage('videos-error-no-video-url')->text();
     }
     $vHelper = new VideoHandlerHelper();
     # @TODO Commenting out to fix MAIN-4436 -- Should be fixed correctly when content team is back
     #		if ( !$vHelper->isVideoProviderSupported( $url ) ) {
     #			wfProfileOut( __METHOD__ );
     #			return wfMessage( 'videos-error-provider-not-supported' )->parse();
     #		}
     try {
         // is it a WikiLink?
         $title = Title::newFromText($url, NS_FILE);
         if (!$title || !WikiaFileHelper::isFileTypeVideo($title)) {
             $title = Title::newFromText(str_replace(array('[[', ']]'), array('', ''), $url), NS_FILE);
         }
         if (!$title || !WikiaFileHelper::isFileTypeVideo($title)) {
             $file = $this->getVideoFileByUrl($url);
             if ($file) {
                 $title = $file->getTitle();
             }
         }
         if ($title && WikiaFileHelper::isFileTypeVideo($title)) {
             $videoTitle = $title;
             $videoPageId = $title->getArticleId();
             $videoProvider = '';
             wfRunHooks('AddPremiumVideo', array($title));
         } else {
             if (empty($this->wg->allowNonPremiumVideos)) {
                 wfProfileOut(__METHOD__);
                 return wfMessage('videohandler-non-premium')->parse();
             }
             list($videoTitle, $videoPageId, $videoProvider) = $this->addVideoVideoHandlers($url);
             $file = RepoGroup::singleton()->findFile($videoTitle);
         }
         if (!$file instanceof File) {
             WikiaLogger::instance()->error('\\VideoHandlerHelper->adDefaultVideoDescription() - File is empty', ['exception' => new Exception(), 'url' => $url, 'title' => $title, 'videoTitle' => $videoTitle, 'videoPageId' => $videoPageId, 'videoProvider' => $videoProvider, 'wgIsGhostVideo' => $wgIsGhostVideo]);
             wfProfileOut(__METHOD__);
             return wfMessage('videos-something-went-wrong')->parse();
         } else {
             // Add a default description if available and one doesn't already exist
             $vHelper->addDefaultVideoDescription($file);
         }
     } catch (Exception $e) {
         wfProfileOut(__METHOD__);
         return $e->getMessage();
     }
     wfProfileOut(__METHOD__);
     return array($videoTitle, $videoPageId, $videoProvider);
 }
示例#2
0
 public function execute()
 {
     $this->test = $this->hasOption('test');
     $this->verbose = $this->hasOption('verbose');
     $title = $this->getOption('title', '');
     echo "Checking " . F::app()->wg->Server . "\n";
     $stats = ['checked' => 0, 'ok' => 0, 'failed' => 0, 'fail_action' => [], 'error' => 0];
     if ($this->test) {
         echo "== TEST MODE ==\n";
     }
     $this->debug("(debugging output enabled)\n");
     $startTime = time();
     if ($title) {
         $videos = [$title];
     } else {
         $videos = VideoInfoHelper::getLocalVideoTitles();
         $this->debug("Found " . count($videos) . " video(s)\n");
     }
     $fix = $this->test ? false : true;
     $helper = new VideoHandlerHelper();
     foreach ($videos as $title) {
         $stats['checked']++;
         $status = $helper->fsckVideoThumbnail($title, $fix);
         if ($status->isGood()) {
             $result = $status->value;
             if ($result['check'] == 'ok') {
                 $stats['ok']++;
                 $this->debug("File '{$title}' ... ok\n");
             } else {
                 $stats['failed']++;
                 if (empty($stats['fail_action'][$result['action']])) {
                     $stats['fail_action'][$result['action']] = 0;
                 }
                 $stats['fail_action'][$result['action']]++;
                 echo "File '{$title}' ... failed\n";
                 echo "\tACTION: " . $result['action'] . "\n";
             }
         } else {
             echo "File '{$title}' ... ERROR\n";
             $stats['error']++;
             foreach ($status->errors as $err) {
                 echo "\tERR: " . $err['message'] . "\n";
             }
         }
     }
     printf("Checked %5d video(s)\n", $stats['checked']);
     printf("\t%5d ok\n", $stats['ok']);
     printf("\t%5d failed\n", $stats['failed']);
     foreach ($stats['fail_action'] as $action => $count) {
         printf("\t\t( %4d %s )\n", $count, $action);
     }
     printf("\t%5d error(s)\n", $stats['error']);
     $delta = F::app()->wg->lang->formatTimePeriod(time() - $startTime);
     echo "Finished after {$delta}\n";
 }
 /**
  * Get the video details (things like videoId, provider, description, regional restrictions, etc)
  * for video from the local wiki.
  *
  * @param array $videos A list of video titles
  * @return array
  */
 public function getVideoDetailFromLocalWiki(array $videos)
 {
     $videoDetails = [];
     $helper = new \VideoHandlerHelper();
     foreach ($videos as $video) {
         $details = $helper->getVideoDetail($video, self::$videoOptions);
         if (!empty($details)) {
             $videoDetails[] = $details;
         }
     }
     return $videoDetails;
 }
 /**
  * This task is run when a video is uploaded but the provider does not have a
  * thumbnail for us to use. This gets triggered the first time a thumbnail
  * cannot be found, and is queued up again at longer intervals until we either
  * get a thumbnail from the provider, or exhaust all of our attempts.
  * @param $title
  * @param $delayIndex
  * @param $provider
  * @param $videoId
  * @return FileRepoStatus
  */
 public function retryThumbUpload($title, $delayIndex, $provider, $videoId)
 {
     global $IP, $wgCityId;
     /** @var Title $title */
     $file = WikiaFileHelper::getVideoFileFromTitle($title);
     if (empty($file)) {
         $msg = "File not found on wiki";
         if ($title instanceof Title) {
             $title = $title->getText();
         }
         $this->log("error", $delayIndex, $title, $provider, ["errorMsg" => $msg]);
         return Status::newFatal($msg);
     }
     $delayIndex++;
     $this->log("start", $delayIndex, $title->getText(), $provider);
     // IVA requires extra steps to update their thumbnail, use the script we have for that
     if ($provider == self::IVA) {
         $cmd = sprintf("SERVER_ID={$wgCityId} php {$IP}/maintenance/wikia/VideoHandlers/updateOoyalaThumbnail.php --videoId={$videoId} --delayIndex={$delayIndex}");
         $response = wfShellExec($cmd, $exitStatus);
         if ($exitStatus == 0) {
             $msg = "Video thumbnail uploaded successfully";
             $status = Status::newGood($msg);
         } else {
             $msg = "Error uploading video thumbnail: {$response}";
             $status = Status::newFatal($msg);
         }
     } else {
         $helper = new VideoHandlerHelper();
         $status = $helper->resetVideoThumb($file, null, $delayIndex);
     }
     if ($status->isGood()) {
         // A good status doesn't necessarily mean we updated the actual thumbnail. A good status is returned for
         // successfully uploading the default thumb as well. Actually check the img sha to see if the thumb changed
         if ($file->getSha1() != self::DEFAULT_THUMB_SHA) {
             $this->log("success", $delayIndex, $title->getText(), $provider, ['thumbnail' => $file->getThumbUrl()]);
         }
     } else {
         $this->log("error", $delayIndex, $title->getText(), $provider, ['errorMsg' => $status->getMessage()]);
     }
     return $status;
 }
/**
 * Update thumbnail in the wiki
 *
 * @param string $videoTitle - video title on the wiki
 * @param string $thumbnailUrl
 * @param integer $delayIndex
 *
 * @global integer $failed
 * @global boolean $dryRun
 * @global string $msg
 *
 * @return boolean
 */
function updateThumbnailWiki($videoTitle, $thumbnailUrl, $delayIndex)
{
    global $failed, $dryRun, $msg;
    $title = $videoTitle;
    $file = WikiaFileHelper::getVideoFileFromTitle($title);
    if (empty($file)) {
        $failed++;
        print "{$msg}...FAILED (Error: File not found in the wiki. Title: {$videoTitle}).\n";
        return false;
    }
    $helper = new VideoHandlerHelper();
    if (!$dryRun) {
        $status = $helper->resetVideoThumb($file, $thumbnailUrl, $delayIndex);
        if (!$status->isGood()) {
            $failed++;
            print "{$msg}...FAILED (Error: Cannot reset video thumbnail in the wiki. Title: {$videoTitle}).\n";
            return false;
        }
    }
    return true;
}
示例#6
0
 /**
  * add premium video
  * @param integer $userId
  * @return boolean
  */
 public function addPremiumVideo($userId)
 {
     wfProfileIn(__METHOD__);
     $this->addedAt = wfTimestamp(TS_MW);
     if (!empty($userId)) {
         $this->addedBy = $userId;
     }
     $affected = $this->addToDatabase();
     // create file page when adding premium video to wiki
     $videoHandlerHelper = new VideoHandlerHelper();
     $status = $videoHandlerHelper->addCategoryVideos($this->videoTitle, $this->addedBy);
     wfProfileOut(__METHOD__);
     return $affected;
 }
 /**
  * Correctly formats response as expected by VET, and inflates video data on each result.
  *
  * @param array $searchResponse
  * @return array
  */
 protected function postProcessSearchResponse(array $searchResponse)
 {
     $config = $this->getConfig();
     $data = [];
     $start = $config->getStart();
     $pos = $start;
     $videoOptions = ['thumbWidth' => $this->getWidth(), 'thumbHeight' => $this->getHeight(), 'getThumbnail' => true, 'thumbOptions' => ['forceSize' => 'small']];
     // Determine the source for the search
     $isLocalSearch = $this->getSearchType() === 'local';
     $helper = new VideoHandlerHelper();
     foreach ($searchResponse['items'] as $singleVideoData) {
         if (empty($singleVideoData['title'])) {
             continue;
         }
         // Get data about this video from the video wiki
         if ($isLocalSearch) {
             $videosDetail = $helper->getVideoDetail($singleVideoData, $videoOptions);
         } else {
             $videosDetail = $helper->getVideoDetailFromWiki(F::app()->wg->WikiaVideoRepoDBName, $singleVideoData['title'], $videoOptions);
         }
         $trimTitle = $this->getTrimTitle();
         if (!empty($trimTitle)) {
             $videosDetail['fileTitle'] = mb_substr($singleVideoData['title'], 0, $trimTitle);
         }
         $singleVideoData['pos'] = $pos++;
         $data[] = $videosDetail;
     }
     return ['totalItemCount' => $searchResponse['total'], 'nextStartFrom' => $start + $config->getLimit(), 'items' => $data];
 }
 /**
  * Call 'VideoHandlerHelper::getVideoDetail' on the video wiki for each of a list of video titles.  Returns a list
  * of video details for each title passed
  *
  * @param array $videos A list of video titles
  * @return array
  */
 public function getVideoDetailFromVideoWiki($videos)
 {
     $videoDetails = [];
     if (!empty($videos)) {
         $helper = new \VideoHandlerHelper();
         $videoDetails = $helper->getVideoDetailFromWiki($this->wg->WikiaVideoRepoDBName, $videos, self::$videoOptions);
     }
     return $videoDetails;
 }
 /**
  * Prepare the string used for the article content of the file page. This includes
  * the category string string and description. eg:
  *
  * [[Category:Phantasy Star Nova]][[Category:IGN]][[Category:IGN games]][[Category:Games]][[Category:Videos]]
  *  ==Description==
  * Check out the character creator mode as well as the battle system in this PlayStation Vita exclusive.
  *
  * @return string
  */
 public function prepareBodyString()
 {
     /** @var ApiWrapper $apiWrapper */
     $apiWrapper = new static::$API_WRAPPER($this->metaData['videoId'], $this->metaData);
     $videoHandlerHelper = new VideoHandlerHelper();
     $body = $this->prepareCategoriesString();
     $body .= $videoHandlerHelper->addDescriptionHeader($apiWrapper->getDescription());
     return $body;
 }
 /**
  * Search for related video titles
  * @param Title|string $title - Either a Title object or title text
  * @param bool $test - Operate in test mode.  Allows commandline scripts to implement --test
  * @param bool $verbose - Whether to output more debugging information
  * @return array - A list of suggested videos
  */
 public function suggestionSearch($title, $test = false, $verbose = false)
 {
     wfProfileIn(__METHOD__);
     // Accept either a title string or title object here
     $titleObj = is_object($title) ? $title : Title::newFromText($title, NS_FILE);
     $articleId = $titleObj->getArticleID();
     if (!$test) {
         wfSetWikiaPageProp(WPP_LVS_SUGGEST_DATE, $articleId, time());
     }
     // flag for kept video
     $pageStatus = $this->getPageStatus($articleId);
     $isKeptVideo = $this->isStatusKeep($pageStatus);
     // get videos that have been suggested (kept videos)
     $historicalSuggestions = array_flip($this->getHistoricalSuggestions($articleId));
     // get current suggestions
     $suggestTitles = array();
     $suggest = wfGetWikiaPageProp(WPP_LVS_SUGGEST, $articleId);
     $validSuggest = [];
     if (!empty($suggest)) {
         if ($verbose) {
             echo "\tExamining the " . count($suggest) . " current match(es)\n";
         }
         foreach ($suggest as $video) {
             // Do some data integrity checking; clean up for VID-1446
             if (!array_key_exists('title', $video)) {
                 continue;
             }
             if ($isKeptVideo && array_key_exists($video['title'], $historicalSuggestions)) {
                 if ($verbose) {
                     echo "\t\t[FILTER] Match was already suggested in the past: '" . $video['title'] . "'\n";
                 }
                 continue;
             }
             $suggestTitles[$video['title']] = 1;
             $validSuggest[] = $video;
         }
         // See if we cleaned up any data
         if (!$test && count($validSuggest) != count($suggest)) {
             // We call wfSetWikiaPageProp below, but only if we get new suggestions.  Write out here
             // to make sure we get the cleaned version written when necessary.
             wfSetWikiaPageProp(WPP_LVS_SUGGEST, $articleId, $validSuggest);
         }
     }
     $readableTitle = $titleObj->getText();
     $params = array('title' => $readableTitle);
     /* Comment this out until the minseconds/maxseconds params are handled correctly by
     		   the searchVidoesByTitle method (MAIN-1276)
     		$file = wfFindFile( $titleObj );
     		if ( !empty( $file ) ) {
     			$serializedMetadata = $file->getMetadata();
     			if ( !empty( $serializedMetadata ) ) {
     				$metadata = unserialize( $serializedMetadata );
     				if ( !empty( $metadata['duration'] ) ) {
     					$duration = $metadata['duration'];
     					$params['minseconds'] = $duration - min( [ $duration, self::DURATION_DELTA ] );
     					$params['maxseconds'] = $duration + min( [ $duration, self::DURATION_DELTA ] );
     				}
     			}
     		}
     		*/
     // get search results
     $videoRows = $this->app->sendRequest('WikiaSearchController', 'searchVideosByTitle', $params)->getData();
     if ($verbose) {
         echo "\tSearch found " . count($videoRows) . " potential new match(es)\n";
     }
     $videos = array();
     $count = 0;
     $isNew = false;
     $titleTokenized = $this->getNormalizedTokens($readableTitle);
     // Reuse code from VideoHandlerHelper
     $helper = new VideoHandlerHelper();
     foreach ($videoRows as $videoInfo) {
         $rowTitle = preg_replace('/^File:/', '', $videoInfo['title']);
         $videoRowTitleTokenized = $this->getNormalizedTokens($rowTitle);
         $similarity = $this->getJaccard()->similarity($titleTokenized, $videoRowTitleTokenized);
         if ($similarity < self::MIN_JACCARD_SIMILARITY) {
             if ($verbose) {
                 echo "\t\t[FILTER] Below Jaccard similarity threshold ({$similarity} < " . self::MIN_JACCARD_SIMILARITY . "): '{$rowTitle}'\n";
             }
             continue;
         }
         $videoTitle = preg_replace('/.+File:/', '', urldecode($videoInfo['url']));
         // skip if the video has already been suggested (from kept videos)
         if ($isKeptVideo) {
             if (array_key_exists($videoTitle, $historicalSuggestions)) {
                 if ($verbose) {
                     echo "\t\t[FILTER] New suggestion was suggested previously: '{$videoTitle}'\n";
                 }
                 continue;
             } else {
                 $isNew = true;
             }
         }
         // skip if the video exists in the current suggestions
         if (array_key_exists($videoTitle, $suggestTitles)) {
             if ($verbose) {
                 echo "\t\t[FILTER] New suggestion is already suggested: '{$videoTitle}'\n";
             }
             continue;
         } else {
             $isNew = true;
         }
         // get video detail
         $videoDetail = $helper->getVideoDetailFromWiki($this->wg->WikiaVideoRepoDBName, $videoInfo['title'], $this->defaultVideoOptions);
         // Go to the next suggestion if we can't get any details for this one
         if (empty($videoDetail)) {
             if ($verbose) {
                 echo "\t\t[FILTER] Can't find video detail for '{$videoTitle}'\n";
             }
             continue;
         }
         $videos[] = $videoDetail;
         $count++;
         if ($count >= self::NUM_SUGGESTIONS) {
             break;
         }
     }
     // combine current suggestions and new suggestions
     $videos = array_slice(array_merge($videos, $validSuggest), 0, self::NUM_SUGGESTIONS);
     // If we're just testing don't set any page props
     if (!$test) {
         // Cache these suggestions
         if (empty($videos)) {
             wfSetWikiaPageProp(WPP_LVS_EMPTY_SUGGEST, $articleId, 1);
         } else {
             wfDeleteWikiaPageProp(WPP_LVS_EMPTY_SUGGEST, $articleId);
             wfSetWikiaPageProp(WPP_LVS_SUGGEST, $articleId, $videos);
             // set page status
             if (!$this->isStatusSwap($pageStatus) && !$this->isStatusForever($pageStatus) && $isNew) {
                 $this->setPageStatusNew($articleId);
             }
         }
     }
     wfProfileOut(__METHOD__);
     // The first video in the array is the top choice.
     return $videos;
 }
示例#11
0
 public function execute()
 {
     $this->test = $this->hasOption('test');
     $this->verbose = $this->hasOption('verbose');
     $this->opt = $this->getOption('opt');
     $this->startDate = $this->getOption('start');
     $this->endDate = $this->getOption('end');
     $this->provider = $this->getOption('provider');
     if (empty($this->opt) || !in_array($this->opt, self::$opts)) {
         die("Error: invalid option. Please enter 'reupload' or 'data'.\n");
     }
     if ($this->opt == 'reupload' && (empty($this->startDate) || empty($this->endDate))) {
         die("Error: Reuploading image requires start date and end date.\n");
     }
     $app = F::app();
     echo "Wiki: {$app->wg->CityId} ({$app->wg->DBname})\n";
     if ($this->test) {
         echo "== TEST MODE ==\n";
     }
     $startTime = time();
     $cnt = 0;
     $success = 0;
     $failed = 0;
     $affected = 0;
     if ($this->opt == 'reupload') {
         $videos = $this->getVideos();
     } else {
         $videos = VideoInfoHelper::getLocalVideoTitles();
     }
     $total = count($videos);
     $helper = new VideoHandlerHelper();
     foreach ($videos as $title) {
         $cnt++;
         $this->debug("Video [{$cnt} of {$total}]: {$title} ");
         $file = WikiaFileHelper::getVideoFileFromTitle($title);
         // check if the file exists
         if (empty($file)) {
             echo " ... FAILED (File not found)\n";
             $failed++;
             continue;
         }
         // check for test mode
         if ($this->test) {
             $this->debug("... DONE\n");
             $success++;
             continue;
         }
         if ($this->opt == 'reupload') {
             if ($this->provider == 'screenplay') {
                 $thumbUrl = ScreenplayApiWrapper::getThumbnailUrlFromAsset($file->getVideoId());
                 if (empty($thumbUrl)) {
                     echo " ... FAILED (Thumbnail URL not found)\n";
                     $failed++;
                     continue;
                 }
             } else {
                 $thumbUrl = null;
             }
             $status = $helper->resetVideoThumb($file, $thumbUrl);
         } else {
             if ($this->opt == 'data') {
                 if (file_exists($file->getLocalRefPath())) {
                     $status = $helper->updateThumbnailData($file);
                 } else {
                     $status = Status::newFatal('Path not found');
                 }
             } else {
                 $status = Status::newGood();
             }
         }
         if ($status->isGood()) {
             if ($this->opt == 'data') {
                 $changed = $status->value;
             } else {
                 $changed = 1;
             }
             $this->debug("... DONE ({$changed} affected).\n");
             $success++;
             if ($changed > 0) {
                 $affected++;
             }
         } else {
             $errorMsg = array();
             foreach ($status->errors as $err) {
                 $errorMsg[] = $err['message'];
             }
             $this->debug("... FAILED (" . implode(', ', $errorMsg) . ")\n");
             $failed++;
         }
     }
     $diff = $app->wg->lang->formatTimePeriod(time() - $startTime);
     echo "Wiki {$app->wg->CityId} ({$app->wg->DBname}): Total: {$total}, Success: {$success} ({$affected} affected), Failed: {$failed}. Finished after {$diff}\n";
 }
示例#12
0
 function insertFinalVideo()
 {
     global $wgRequest, $wgContLang;
     $id = $wgRequest->getVal('id');
     $provider = $wgRequest->getVal('provider');
     $name = urldecode($wgRequest->getVal('name'));
     $embed_code = '';
     if ($provider == 'FILE') {
         // no need to upload, local reference
         $title = $oTitle = Title::newFromText($name, NS_FILE);
         if (empty($oTitle)) {
             header('X-screen-type: error');
             return wfMessage('vet-name-incorrect')->plain();
         }
         wfRunHooks('AddPremiumVideo', array($title));
     } else {
         // needs to upload
         // sanitize name and init title objects
         $name = VideoFileUploader::sanitizeTitle($name);
         if ($name == '') {
             header('X-screen-type: error');
             return wfMessage('vet-warn3')->plain();
         }
         $nameFile = VideoFileUploader::sanitizeTitle($name);
         $titleFile = VideoFileUploader::getUniqueTitle($nameFile);
         if (empty($titleFile)) {
             header('X-screen-type: error');
             return wfMessage('vet-name-incorrect')->plain();
         }
         // by definition, WikiaFileHelper::useVideoHandlersExtForEmbed() == true
         $nameSanitized = $titleFile->getBaseText();
         $title = $titleFile;
         $extra = 0;
         $metadata = array();
         while ('' != $wgRequest->getVal('metadata' . $extra)) {
             $metadata[] = $wgRequest->getVal('metadata' . $extra);
             $extra++;
         }
         $parts = explode('/', $provider);
         $provider = $parts[1];
         $oTitle = null;
         $status = $this->uploadVideoAsFile($provider, $id, $nameSanitized, $oTitle);
         if (!$status->ok) {
             header('X-screen-type: error');
             return wfMessage('wva-thumbnail-upload-failed')->plain();
         }
     }
     $description = trim(urldecode($wgRequest->getVal('description')));
     // Set the video descriptions
     $vHelper = new VideoHandlerHelper();
     $vHelper->setVideoDescription($oTitle, $description);
     $message = wfMessage('vet-single-success')->plain();
     $ns_file = $wgContLang->getFormattedNsText($title->getNamespace());
     $caption = $wgRequest->getVal('caption');
     $width = $wgRequest->getVal('width');
     $width = empty($width) ? 335 : $width;
     $layout = $wgRequest->getVal('layout');
     header('X-screen-type: summary');
     $tag = $ns_file . ":" . $oTitle->getText();
     // all videos added via VET will be shown as thumbnails / "framed"
     $tag .= "|thumb";
     if (!empty($layout)) {
         $tag .= "|{$layout}";
     }
     if ($width != '') {
         $tag .= "|{$width} px";
     }
     if ($caption != '') {
         $tag .= "|" . $caption;
     }
     $tag = "[[{$tag}]]";
     $button_message = wfMessage('vet-return')->plain();
     // Adding a video from article view page
     $editFromViewMode = $wgRequest->getVal('placeholder');
     if ($editFromViewMode) {
         Wikia::setVar('EditFromViewMode', true);
         $article_title = $wgRequest->getVal('article');
         $ns = $wgRequest->getVal('ns');
         $box = $wgRequest->getVal('box');
         $article_title_obj = Title::newFromText($article_title, $ns);
         $article_obj = new Article($article_title_obj);
         $text = $article_obj->getContent();
         // match [[File:Placeholder|video]]
         $placeholder = MediaPlaceholderMatch($text, $box, true);
         $success = false;
         if ($placeholder) {
             $placeholder_tag = $placeholder[0];
             $file = wfFindFile($title);
             $embed_code = $file->transform(array('width' => $width))->toHtml();
             $params = array('alt' => $title->getText(), 'title' => $title->getText(), 'img-class' => 'thumbimage', 'align' => $layout, 'outerWidth' => $width, 'file' => $file, 'url' => $file->getUrl(), 'html' => $embed_code);
             $embed_code = F::app()->renderView('ThumbnailController', 'articleBlock', $params);
             // Make output match what's in a saved article
             if ($layout == 'center') {
                 $embed_code = '<div class="center">' . $embed_code . '</div>';
             }
             $summary = wfMessage('vet-added-from-placeholder')->plain();
             $text = substr_replace($text, $tag, $placeholder[1], strlen($placeholder_tag));
             $button_message = wfMessage('vet-placeholder-return')->plain();
             $success = $article_obj->doEdit($text, $summary);
         }
         if (!$success) {
             header('X-screen-type: error');
             return wfMessage('vet-insert-error')->plain();
         }
     }
     $tmpl = new EasyTemplate(dirname(__FILE__) . '/templates/');
     $tmpl->set_vars(array('tag' => $tag, 'message' => $message, 'code' => $embed_code, 'button_message' => $button_message));
     return $tmpl->render('summary');
 }
 /**
  * Get video data
  * @param string $title
  * @param string $altThumbTitle
  * @param string $displayTitle
  * @param string $description
  * @param array $thumbOptions
  * @return array
  */
 public function getVideoData($title, $altThumbTitle = '', $displayTitle = '', $description = '', $thumbOptions = array())
 {
     wfProfileIn(__METHOD__);
     $video = array();
     /** @var Title $title A string $title will get converted to an object here */
     $file = WikiaFileHelper::getVideoFileFromTitle($title);
     if (!empty($file)) {
         $videoTitle = $title->getText();
         if (empty($displayTitle)) {
             $displayTitle = $videoTitle;
         }
         // get thumbnail
         $thumb = $file->transform(array('width' => self::THUMBNAIL_WIDTH, 'height' => self::THUMBNAIL_HEIGHT));
         $videoThumb = $thumb->toHtml($thumbOptions);
         $thumbUrl = $thumb->getUrl();
         $largeThumb = $file->transform(array('width' => self::MAX_THUMBNAIL_WIDTH, 'height' => self::MAX_THUMBNAIL_HEIGHT));
         $largeThumbUrl = $largeThumb->getUrl();
         // replace original thumbnail with the new one
         $altThumbName = '';
         $altThumbKey = '';
         if (!empty($altThumbTitle)) {
             $imageData = $this->getImageData($altThumbTitle);
             if (!empty($imageData)) {
                 $videoThumb = str_replace($thumbUrl, $imageData['thumbUrl'], $videoThumb);
                 $largeThumbUrl = $imageData['largeThumbUrl'];
                 $altThumbName = $imageData['imageTitle'];
                 $altThumbKey = $imageData['imageKey'];
                 // TODO: Saipetch will fix this :)
                 $thumbUrl = $imageData['thumbUrl'];
             }
         }
         // get description
         if (empty($description)) {
             $videoHandlerHelper = new VideoHandlerHelper();
             $description = $videoHandlerHelper->getVideoDescription($file);
         }
         $video = array('videoTitle' => $videoTitle, 'videoKey' => $title->getDBkey(), 'videoThumb' => $videoThumb, 'largeThumbUrl' => $largeThumbUrl, 'altThumbName' => $altThumbName, 'altThumbKey' => $altThumbKey, 'displayTitle' => $displayTitle, 'description' => $description, 'thumbUrl' => $thumbUrl);
     }
     wfProfileOut(__METHOD__);
     return $video;
 }
 /**
  * get list of videos
  * @param string $sort [recent/popular/trend]
  * @param integer $page
  * @param array $providers
  * @param string $category
  * @param array $options
  * @return array $videos
  */
 public function getVideos($sort, $page, $providers = [], $category = '', $options = [])
 {
     wfProfileIn(__METHOD__);
     if ($sort == 'premium') {
         $sort = 'recent';
         $filter = 'premium';
     } else {
         $filter = 'all';
     }
     if ($this->app->checkSkin('wikiamobile')) {
         $limit = self::VIDEOS_PER_PAGE_MOBILE;
         $providers = $this->wg->WikiaMobileSupportedVideos;
         $thumbOptions = ['useTemplate' => true, 'fluid' => true, 'forceSize' => 'small', 'img-class' => 'media', 'dataParams' => true];
     } else {
         $limit = self::VIDEOS_PER_PAGE;
         $providers = empty($providers) ? [] : explode(',', $providers);
         $thumbOptions = ['fluid' => true, 'showViews' => true, 'fixedHeight' => self::THUMBNAIL_HEIGHT, 'hidePlayButton' => true];
     }
     // get video list
     $mediaService = new MediaQueryService();
     $videoList = $mediaService->getVideoList($sort, $filter, $limit, $page, $providers, $category);
     $videoOptions = ['thumbWidth' => self::THUMBNAIL_WIDTH, 'thumbHeight' => self::THUMBNAIL_HEIGHT, 'postedInArticles' => self::POSTED_IN_ARTICLES, 'thumbOptions' => $thumbOptions, 'getThumbnail' => array_key_exists('getThumbnail', $options) ? $options['getThumbnail'] : true];
     // get video detail
     $videos = [];
     $helper = new VideoHandlerHelper();
     foreach ($videoList as $videoInfo) {
         $videoDetail = $helper->getVideoDetail($videoInfo, $videoOptions);
         if (!empty($videoDetail)) {
             $byUserMsg = WikiaFileHelper::getByUserMsg($videoDetail['userName'], $videoDetail['timestamp']);
             $viewTotal = wfMessage('videohandler-video-views', $this->wg->Lang->formatNum($videoDetail['viewsTotal']))->text();
             $videos[] = ['title' => $videoDetail['fileTitle'], 'fileKey' => $videoDetail['title'], 'fileUrl' => $videoDetail['fileUrl'], 'thumbnail' => $videoDetail['thumbnail'], 'timestamp' => wfTimeFormatAgo($videoDetail['timestamp'], false), 'updated' => $videoDetail['timestamp'], 'viewTotal' => $viewTotal, 'byUserMsg' => $byUserMsg, 'truncatedList' => $videoDetail['truncatedList'], 'duration' => $videoDetail['duration'], 'thumbUrl' => $videoDetail['thumbUrl'], 'embedUrl' => $videoDetail['embedUrl']];
         }
     }
     wfProfileOut(__METHOD__);
     return $videos;
 }
 /**
  * Get list of videos (controller that provides access to MediaQueryService::getVideoList method)
  * @requestParam string sort [recent/popular/trend]
  * @requestParam integer limit (maximum = 100)
  * @requestParam integer page
  * @requestParam string|array providers - Only videos hosted by these providers will be returned. Default: all providers.
  * @requestParam string|array category - Only videos tagged with these categories will be returned. Default: any categories.
  * @requestParam integer width - the width of the thumbnail to return
  * @requestParam integer height - the height of the thumbnail to return
  * @requestParam integer detail [0/1] - check for getting video detail
  * @responseParam array
  *   [array('title'=>value, 'provider'=>value, 'addedAt'=>value,'addedBy'=>value, 'duration'=>value, 'viewsTotal'=>value)]
  */
 public function getVideoList()
 {
     wfProfileIn(__METHOD__);
     $params = $this->getVideoListParams();
     // Key to cache the data under in memcache
     $cacheKey = $this->getVideoListCacheKey($params);
     $cacheOptions = ['cacheTTL' => \WikiaResponse::CACHE_STANDARD, 'negativeCacheTTL' => 0];
     // Retrieve the result and if not null, cache it
     $videoList = \WikiaDataAccess::cacheWithOptions($cacheKey, function () use($params) {
         $mediaService = new \MediaQueryService();
         $videoList = $mediaService->getVideoList($params['sort'], $params['filter'], $params['limit'], $params['page'], $params['providers'], $params['category']);
         // get video detail
         if (!empty($params['detail'])) {
             $videoOptions = ['thumbWidth' => $params['width'], 'thumbHeight' => $params['height']];
             $helper = new \VideoHandlerHelper();
             foreach ($videoList as &$videoInfo) {
                 $videoDetail = $helper->getVideoDetail($videoInfo, $videoOptions);
                 if (!empty($videoDetail)) {
                     $videoInfo = array_merge($videoInfo, $videoDetail);
                 }
             }
             unset($videoInfo);
         }
         return $videoList;
     }, $cacheOptions);
     $this->response->setVal('videos', $videoList);
     $this->response->setCacheValidity(\WikiaResponse::CACHE_STANDARD);
     wfProfileOut(__METHOD__);
 }
 /**
  * Modify the description of a video
  * @requestParam string title
  * @requestParam string description
  * @responseParam string status [success/fail]
  * @responseParam string errMsg
  */
 public function editDescription()
 {
     $title = urldecode($this->request->getVal('title'));
     $title = Title::newFromText($title, NS_FILE);
     $description = urldecode($this->request->getVal('description'));
     $vHelper = new VideoHandlerHelper();
     $status = $vHelper->setVideoDescription($title, $description);
     if ($status) {
         $this->status = 'success';
     } else {
         $this->status = 'fail';
         $this->errMsg = wfMessage('vet-description-save-error')->text();
     }
 }