/**
  * Get data for each gallery item
  * @param array $item Data about the media item
  * @param int $index Where the item shows up in the gallery
  * @return array|null
  */
 protected function getMediaData(array $item, $index)
 {
     $file = wfFindFile($item['title']);
     if (!$file instanceof File) {
         WikiaLogger::instance()->error('File with title: ' . $item['title'] . 'doesn\'t exist', ['class' => __CLASS__]);
         return null;
     }
     $dimension = MediaGalleryHelper::getImageWidth($this->itemCount, $index);
     $thumbUrl = WikiaFileHelper::getSquaredThumbnailUrl($file, $dimension);
     $dimensions = ['width' => $dimension, 'height' => $dimension];
     $thumb = $file->transform($dimensions);
     if (!$thumb instanceof ThumbnailImage) {
         WikiaLogger::instance()->error('ThumbnailImage from title: ' . $item['title'] . ' couldn\'t be created.', ['thumbClass' => get_class($thumb)]);
         return null;
     }
     $thumb->setUrl($thumbUrl);
     $thumbnail = $this->app->renderView('ThumbnailController', 'gallery', ['thumb' => $thumb]);
     $caption = '';
     if (!empty($item['caption'])) {
         // parse any wikitext in caption. Logic borrowed from WikiaMobileMediaService::renderMediaGroup.
         $parser = $this->getParser();
         $caption = $parser->internalParse($item['caption']);
         $parser->replaceLinkHolders($caption);
         $caption = $parser->killMarkers($caption);
     }
     $title = $file->getTitle();
     return ['thumbUrl' => $thumbUrl, 'thumbHtml' => $thumbnail, 'caption' => $caption, 'linkHref' => $file->getTitle()->getLinkURL(), 'title' => $title->getText(), 'dbKey' => $title->getDBKey()];
 }
 public function getVideoData($titleText, $thumbnailWidth, $videoWidth = self::DEFAULT_OASIS_VIDEO_WIDTH, $autoplay = true, $useMaster = false, $cityShort = 'life', $videoHeight = '', $useJWPlayer = true, $inAjaxResponse = false)
 {
     wfProfileIn(__METHOD__);
     $data = array();
     $title = Title::newFromText($titleText, NS_FILE);
     $file = wfFindFile($title);
     if (!WikiaFileHelper::isVideoFile($file)) {
         $data['error'] = wfMsg('related-videos-error-no-video-title');
     } else {
         $meta = unserialize($file->getMetadata());
         $trans = $file->transform(array('width' => $thumbnailWidth, 'height' => -1));
         $thumb = array('width' => $trans->width, 'height' => $trans->height, 'thumb' => $trans->url);
         $data['external'] = 0;
         // false means it is not set. Meaningful values: 0 and 1.
         $data['id'] = $titleText;
         $data['fullUrl'] = $title->getFullURL();
         $data['prefixedUrl'] = $title->getPrefixedURL();
         $data['description'] = $file->getDescription();
         $data['duration'] = $meta['duration'];
         $data['embedCode'] = null;
         $data['embedJSON'] = null;
         $data['provider'] = $file->minor_mime;
         $data['thumbnailData'] = $thumb;
         $data['title'] = $file->getTitle()->getText();
         $data['timestamp'] = $file->getTimestamp();
         $data['uniqueId'] = $file->getVideoUniqueId();
     }
     $data['owner'] = '';
     $data['ownerUrl'] = '';
     wfProfileOut(__METHOD__);
     return $data;
 }
Beispiel #3
0
 public function getDuplicates()
 {
     wfProfileIn(__METHOD__);
     $img = $this->getDisplayedFile();
     $handler = $img->getHandler();
     if ($handler instanceof VideoHandler && $handler->isBroken()) {
         wfProfileOut(__METHOD__);
         return $this->dupes = array();
     } else {
         $dupes = parent::getDuplicates();
         $finalDupes = array();
         foreach ($dupes as $dupe) {
             if (WikiaFileHelper::isFileTypeVideo($dupe) && $dupe instanceof WikiaLocalFile) {
                 if ($dupe->getProviderName() != $img->getProviderName()) {
                     continue;
                 }
                 if ($dupe->getVideoId() != $img->getVideoId()) {
                     continue;
                 }
                 $finalDupes[] = $dupe;
             }
         }
         wfProfileOut(__METHOD__);
         return $finalDupes;
     }
 }
 /**
  * This method pulls the data needed for a VideoInfo object from an existing file when the data does not exist
  * in the video_info table.  This is used in the case where video_info data wasn't created when the video uploaded.
  * @param File $file - The file object to get video info for
  * @param boolean $premiumOnly - If true will exit immediately if $file is a local file
  * @return array|null - An array of data suitable for passing to the VideoInfo constructor
  */
 public function getVideoDataFromFile($file, $premiumOnly = false)
 {
     wfProfileIn(__METHOD__);
     $video = null;
     if ($file instanceof File && $file->exists() && WikiaFileHelper::isFileTypeVideo($file)) {
         if (!($premiumOnly && $file->isLocal())) {
             $fileMetadata = $file->getMetadata();
             $userId = $file->getUser('id');
             $addedAt = $file->getTimestamp() ? $file->getTimestamp() : wfTimestamp(TS_MW);
             $duration = 0;
             $hdfile = 0;
             $videoId = '';
             if ($fileMetadata) {
                 $fileMetadata = unserialize($fileMetadata);
                 if (array_key_exists('duration', $fileMetadata)) {
                     $duration = $fileMetadata['duration'];
                 }
                 if (array_key_exists('hd', $fileMetadata)) {
                     $hdfile = $fileMetadata['hd'] ? 1 : 0;
                 }
                 if (array_key_exists('videoId', $fileMetadata)) {
                     $videoId = $fileMetadata['videoId'];
                 }
             }
             $premium = $file->isLocal() ? 0 : 1;
             $video = array('videoTitle' => $file->getName(), 'videoId' => $videoId, 'provider' => $file->minor_mime, 'addedAt' => $addedAt, 'addedBy' => $userId, 'duration' => $duration, 'premium' => $premium, 'hdfile' => $hdfile);
         }
     }
     wfProfileOut(__METHOD__);
     return $video;
 }
Beispiel #5
0
 protected function getVideoDuplicate($provider, $videoId)
 {
     $duplicates = WikiaFileHelper::getDuplicateVideos($provider, $videoId);
     if (count($duplicates) > 0) {
         return wfFindFile($duplicates[0]['video_title']);
     }
     return null;
 }
 protected static function invalidateCacheWikiTotalImages($file, $reupload)
 {
     $title = $file->getTitle();
     if ($title instanceof Title && !WikiaFileHelper::isVideoFile($file) && !$reupload) {
         $wikiService = new WikiService();
         $wikiService->invalidateCacheTotalImages();
     }
 }
 /**
  * @dataProvider durationDataProvider
  */
 public function testDuration($sec, $expResult)
 {
     // setup
     $this->setUpMock();
     // test
     $responseData = WikiaFileHelper::formatDuration($sec);
     $this->assertEquals($expResult, $responseData);
 }
 /**
  * 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);
 }
 private function executeVideo()
 {
     $wikiaFilename = WikiaFileHelper::getWikiaFilename($this->mParams['url']);
     if ($wikiaFilename) {
         return $this->executeWikiaVideo($wikiaFilename);
     } else {
         return $this->execute3rdPartyVideo($this->mParams['url']);
     }
 }
Beispiel #10
0
 /**
  * @desc returns image url for given image title
  *
  * @param string $title
  *
  * @return string url or '' if image doesn't exist
  */
 public function resolveImageUrl($title)
 {
     if ($title) {
         $file = \WikiaFileHelper::getFileFromTitle($title);
         if ($file) {
             return $file->getUrl();
         }
     }
     return '';
 }
 public function execute()
 {
     $this->verbose = $this->hasOption("verbose");
     $this->dryRun = $this->hasOption("dryRun");
     $this->limit = $this->getOption("limit", self::BATCH_SIZE);
     $titles = $this->getScreenplayTitles();
     $ooyalaAsset = new OoyalaAsset();
     if ($this->dryRun) {
         echo "Dry run...\n";
     }
     foreach ($titles as $title) {
         $videoFile = WikiaFileHelper::getVideoFileFromTitle($title);
         if (empty($videoFile)) {
             $this->log("Skipping video '{$title}' -- couldn't find video file");
             $this->skippedVideos++;
             continue;
         }
         $ooyalaData = $this->prepForOoyala($videoFile);
         if ($this->dryRun) {
             echo "Ready to migrate video " . $videoFile->getName() . " to Ooyala with the following data:\n";
             print_r($ooyalaData);
             $success = true;
             $videoId = "TestID";
         } else {
             // $videoId gets set in addRemoteAsset()
             $success = $ooyalaAsset->addRemoteAsset($ooyalaData, $videoId);
         }
         if (!$success) {
             $this->log("Error uploading video {$ooyalaData['assetTitle']} onto Ooyala. Skipping update locally");
             $this->skippedVideos++;
             continue;
         }
         $localData = $this->prepForLocal($videoFile, $ooyalaData, $videoId);
         if ($this->dryRun) {
             echo "Ready to update video " . $videoFile->getName() . " locally with the following new metadata\n";
             print_r(unserialize($localData));
         } else {
             $this->updateVideoLocally($videoFile, $localData, $videoId);
         }
         $this->migratedVideos++;
     }
     $this->printSummary();
 }
 /**
  * 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;
}
 /**
  * Load RelatedVideos NS article data (try to use cache layer)
  */
 protected function load($master = false)
 {
     wfProfileIn(__METHOD__);
     if (!$master) {
         $this->mData = F::app()->wg->memc->get($this->mMemcacheKey);
     }
     if (empty($this->mData)) {
         $article = Article::newFromID($this->mId);
         // check existence
         if (empty($article)) {
             wfDebug(__METHOD__ . ": RelatedVideos NS article doesn't exist\n");
             wfProfileOut(__METHOD__);
             return;
         }
         $lists = array();
         $lists[self::BLACKLIST_MARKER] = array();
         $lists[self::WHITELIST_MARKER] = array();
         $dbr = wfGetDB(DB_SLAVE);
         $res = $dbr->select(array('imagelinks'), array('il_to'), ' il_from = ' . $this->mId, __METHOD__);
         if (empty($res)) {
             return;
         }
         while ($row = $res->fetchObject($res)) {
             $sTitle = $row->il_to;
             $oTitle = Title::newFromText($sTitle, NS_VIDEO);
             if (is_object($oTitle) && WikiaFileHelper::isTitleVideo($oTitle)) {
                 $lists[self::WHITELIST_MARKER][] = $this->createEntry($sTitle);
             }
         }
         $this->mData = array('lists' => $lists);
         wfDebug(__METHOD__ . ": loaded from scratch\n");
         // store it in memcache
         F::app()->wg->memc->set($this->mMemcacheKey, $this->mData, self::CACHE_TTL);
     } else {
         wfDebug(__METHOD__ . ": loaded from memcache\n");
     }
     $this->mExists = true;
     wfProfileOut(__METHOD__);
     return;
 }
 /**
  * change title tag for Video Page and Image Page
  * @author Jacek Jursza
  * @param ImagePage $imgPage
  * @param $html
  * @return bool
  */
 function onImagePageAfterImageLinks($imgPage, $html)
 {
     $file = $imgPage->getDisplayedFile();
     /* @var $file LocalRepo */
     $title = $imgPage->getTitle();
     /* @var $title Title */
     $newTitle = '';
     if (!empty($file) && !empty($title)) {
         if (WikiaFileHelper::isFileTypeVideo($file)) {
             $newTitle = wfMsg('seotweaks-video') . ' - ' . $title->getBaseText();
         } else {
             // It's not Video so lets check if it is Image
             if ($file instanceof LocalFile && $file->getHandler() instanceof BitmapHandler) {
                 $newTitle = wfMsg('seotweaks-image') . ' - ' . $title->getBaseText();
             }
         }
         if (!empty($newTitle)) {
             $this->wg->out->setPageTitle($newTitle);
         }
     }
     return true;
 }
 /**
  * add video
  * @param string $url
  * @return string error message or array( $videoTitle, $videoPageId, $videoProvider )
  */
 public function addVideo($url)
 {
     $this->wf->ProfileIn(__METHOD__);
     if (empty($url)) {
         $this->wf->ProfileOut(__METHOD__);
         return $this->wf->Msg('videos-error-no-video-url');
     }
     try {
         if (WikiaFileHelper::isVideoStoredAsFile()) {
             // is it a WikiLink?
             $title = Title::newFromText($url);
             if (!$title || !WikiaFileHelper::isTitleVideo($title)) {
                 $title = Title::newFromText(str_replace(array('[[', ']]'), array('', ''), $url));
             }
             if (!$title || !WikiaFileHelper::isTitleVideo($title)) {
                 if (($pos = strpos($url, 'Video:')) !== false) {
                     $title = Title::newFromText(substr($url, $pos));
                 } elseif (($pos = strpos($url, 'File:')) !== false) {
                     $title = Title::newFromText(substr($url, $pos));
                 }
             }
             if ($title && WikiaFileHelper::isTitleVideo($title)) {
                 $videoTitle = $title;
                 $videoPageId = $title->getArticleId();
                 $videoProvider = '';
                 wfRunHooks('AddPremiumVideo', array($title));
             } else {
                 list($videoTitle, $videoPageId, $videoProvider) = $this->addVideoVideoHandlers($url);
             }
         } else {
             throw new Exception($this->wf->Msg('videos-error-old-type-video'));
         }
     } catch (Exception $e) {
         $this->wf->ProfileOut(__METHOD__);
         return $e->getMessage();
     }
     $this->wf->ProfileOut(__METHOD__);
     return array($videoTitle, $videoPageId, $videoProvider);
 }
 public function execute()
 {
     global $wgUser, $wgTitle;
     $wgUser = User::newFromName('Wikia');
     $wgUser->load();
     //get list of pages from how-to category
     $aReturn = ApiService::call(array('action' => 'query', 'list' => 'categorymembers', 'cmtitle' => 'Category:How-to', 'cmnamespace' => '120'));
     //perform update foreach page from category
     foreach ($aReturn['query']['categorymembers'] as $cm) {
         $oWebinarTitle = Title::newFromText($cm['title']);
         $wgTitle = $oWebinarTitle;
         $oWebinarArticle = new Article($oWebinarTitle);
         echo "Webinar page: " . $oWebinarTitle->getText() . "\n";
         //get video link
         $content = $oWebinarArticle->getContent();
         //preq match
         $matches = $this->matchFile($content);
         if (!empty($matches)) {
             //remove params
             $aFileTitWithParams = explode('|', $matches[1]);
             //get file title
             $oFilePageTitle = Title::newFromText($aFileTitWithParams[0], NS_FILE);
             echo "video file title: " . $oFilePageTitle->getText() . "\n";
             if (WikiaFileHelper::isFileTypeVideo($oFilePageTitle)) {
                 //to test
                 echo "=----------- IS VIDEO \n";
                 //prepare new content without link to video file
                 $newFileContent = str_replace($matches[0], '', $content);
                 //article obj
                 $oFileArticle = new Article($oFilePageTitle);
                 //set new contnet without file link at the begining
                 $oFileArticle->doEdit($newFileContent, 'Moving How-to webinars to video file pages');
                 //set redirect
                 $oWebinarArticle->doEdit("#redirect[[" . $oFilePageTitle->getPrefixedDBkey() . "]]", 'Setting redirect - conent was moveed to video file page');
             }
         }
     }
 }
 /**
  * Clear total videos by category cache when video categories are added via the Category Select extension,
  * after checking if it was associated with one of the categories filtered in Special Videos.
  * @param $title
  * @param $categories
  * @return true
  */
 public static function onCategorySelectSave($title, $categories)
 {
     if ($title instanceof Title && WikiaFileHelper::isFileTypeVideo($title)) {
         VideoInfoHooksHelper::clearCategories($title);
     }
     return true;
 }
 public function doSubmit()
 {
     global $wgOut, $wgRequest, $wgUser;
     $replaced = false;
     if ('' == $wgRequest->getVal('wpWikiaVideoAddName')) {
         if ('' != $wgRequest->getVal('wpWikiaVideoAddPrefilled')) {
             $this->mName = $wgRequest->getVal('wpWikiaVideoAddPrefilled');
             $replaced = true;
         } else {
             $this->mName = '';
         }
     } else {
         $this->mName = $wgRequest->getVal('wpWikiaVideoAddName');
     }
     '' != $wgRequest->getVal('wpWikiaVideoAddUrl') ? $this->mUrl = $wgRequest->getVal('wpWikiaVideoAddUrl') : ($this->mUrl = '');
     if ('' != $this->mName && '' != $this->mUrl) {
         $this->mName = ucfirst($this->mName);
         // sanitize all video titles
         $this->mName = VideoFileUploader::sanitizeTitle($this->mName);
         $title = Title::makeTitleSafe(NS_VIDEO, $this->mName);
         if ($title instanceof Title) {
             $permErrors = $title->getUserPermissionsErrors('edit', $wgUser);
             $permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser);
             $permErrorsCreate = $title->exists() ? array() : $title->getUserPermissionsErrors('create', $wgUser);
             if ($permErrors || $permErrorsUpload || $permErrorsCreate) {
                 header('X-screen-type: error');
                 $wgOut->addWikiMsg('wva-protected');
                 return;
             }
             if (WikiaFileHelper::useVideoHandlersExtForEmbed()) {
                 $res = null;
                 try {
                     $res = VideoFileUploader::URLtoTitle($this->mUrl, $this->mName);
                 } catch (Exception $e) {
                 }
                 if (!$res) {
                     $wgOut->addHTML(wfMsg('wva-failure'));
                     return;
                 }
             }
             if (WikiaFileHelper::useWikiaVideoExtForEmbed()) {
                 $video = new VideoPage($title);
                 $video->parseUrl($this->mUrl);
                 $video->setName($this->mName);
                 $video->save();
             }
             $sk = RequestContext::getMain()->getSkin();
             $link_back = $sk->makeKnownLinkObj($title);
             if ($replaced) {
                 $wgOut->addHTML(wfMsg('wva-success-replaced', $link_back));
             } else {
                 $wgOut->addHTML(wfMsg('wva-success', $link_back));
             }
         } else {
             //bad title returned
             $wgOut->addHTML(wfMsg('wva-failure'));
         }
     } else {
         //one of two params blank
         $wgOut->addHTML(wfMsg('wva-failure'));
     }
 }
 /**
  * Returns pre-formatted social sharing urls and codes
  * @requestParam string fileTitle
  * @requestParam string articleTitle	(optional)
  * @responseParam string url - raw url that is automically determined.  This is determined to be either article url or file page url.
  * @responseParam string articleUrl - url to article page
  * @responseParam string fileUrl - url to file page
  * @responseParam string networks - contains id(facebook, twitter, etc) and urls of external social networks
  */
 public function getShareCodes()
 {
     $fileTitle = urldecode($this->request->getVal('fileTitle', ''));
     $file = wfFindFile($fileTitle);
     $shareUrl = '';
     $articleUrl = '';
     $articleNS = '';
     $articleTitleText = '';
     $fileUrl = '';
     $thumbUrl = '';
     $networks = array();
     if (!empty($file)) {
         $fileTitleObj = Title::newFromText($fileTitle, NS_FILE);
         $fileTitle = $fileTitleObj->getText();
         $articleTitle = $this->request->getVal('articleTitle');
         $articleTitleObj = Title::newFromText($articleTitle);
         if (!empty($articleTitleObj) && $articleTitleObj->exists()) {
             $fileParam = wfUrlencode($fileTitleObj->getDBKey());
             $articleUrl = $articleTitleObj->getFullURL("file={$fileParam}");
             $articleNS = $articleTitleObj->getNamespace();
             $articleTitleText = $articleTitleObj->getText();
         }
         // check if the file is added to the wiki
         if (WikiaFileHelper::isAdded($file)) {
             $fileUrl = $fileTitleObj->getFullURL();
         } else {
             $fileUrl = WikiaFileHelper::getFullUrlPremiumVideo($fileTitleObj->getDBkey());
         }
         // determine share url
         $sharingNamespaces = array(NS_MAIN, NS_CATEGORY);
         $shareUrl = !empty($articleUrl) && in_array($articleNS, $sharingNamespaces) ? $articleUrl : $fileUrl;
         $thumb = $file->transform(array('width' => 300, 'height' => 250));
         $thumbUrl = $thumb->getUrl();
         if (WikiaFileHelper::isFileTypeVideo($file)) {
             $msgSuffix = '-video';
         } else {
             $msgSuffix = '';
         }
         $msgArticleTitle = empty($articleUrl) ? $fileTitle : $articleTitleText;
         $linkDescription = wfMessage('lightbox-share-description' . $msgSuffix, $msgArticleTitle, $this->wg->Sitename)->text();
         $shareNetworks = SocialSharingService::getInstance()->getNetworks(array('facebook', 'twitter', 'stumbleupon', 'reddit', 'plusone'));
         foreach ($shareNetworks as $network) {
             $networks[] = array('id' => $network->getId(), 'url' => $network->getUrl($shareUrl, $linkDescription));
         }
     }
     $this->shareUrl = $shareUrl;
     $this->articleUrl = $articleUrl;
     $this->fileUrl = $fileUrl;
     $this->networks = $networks;
     $this->fileTitle = $fileTitle;
     $this->imageUrl = $thumbUrl;
     // set cache control to 1 day
     $this->response->setCacheValidity(WikiaResponse::CACHE_STANDARD);
 }
 public function doSubmit()
 {
     global $wgOut;
     $errors = array();
     $replaced = false;
     $this->mUrl = $this->getRequest()->getVal('wpWikiaVideoAddUrl', '');
     $this->mName = $this->getRequest()->getVal('wpWikiaVideoAddName', '');
     if ($this->mName == '') {
         $this->mName = $this->getRequest()->getVal('name', '');
         if ($this->mName != '') {
             $replaced = true;
         }
     }
     if ($this->mUrl == '') {
         $errors['videoUrl'] = wfMessage('wva-failure')->text();
         $this->showForm($errors);
         return;
     } else {
         if ($this->mName == '') {
             $videoService = new VideoService();
             $retval = $videoService->addVideo($this->mUrl);
             if (is_array($retval)) {
                 list($title, $videoPageId, $videoProvider) = $retval;
             } else {
                 $errors['videoUrl'] = $retval;
                 $this->showForm($errors);
                 return;
             }
         } else {
             $this->mName = ucfirst($this->mName);
             // sanitize all video titles
             $this->mName = VideoFileUploader::sanitizeTitle($this->mName);
             $title = Title::makeTitleSafe(NS_FILE, $this->mName);
             if ($title instanceof Title) {
                 $permErrors = $title->getUserPermissionsErrors('edit', $this->getUser());
                 $permErrorsUpload = $title->getUserPermissionsErrors('upload', $this->getUser());
                 $permErrorsCreate = $title->exists() ? array() : $title->getUserPermissionsErrors('create', $this->getUser());
                 if ($permErrors || $permErrorsUpload || $permErrorsCreate) {
                     header('X-screen-type: error');
                     $wgOut->addWikiMsg('wva-protected');
                     return;
                 }
                 if (empty(F::app()->wg->allowNonPremiumVideos)) {
                     $errors['videoUrl'] = wfMessage('videohandler-non-premium')->parse();
                     $this->showForm($errors);
                     return;
                 }
                 if (WikiaFileHelper::useVideoHandlersExtForEmbed()) {
                     $res = null;
                     try {
                         $res = VideoFileUploader::URLtoTitle($this->mUrl, $this->mName);
                     } catch (Exception $e) {
                     }
                     if (!$res) {
                         $errors['videoUrl'] = wfMessage('wva-failure')->text();
                         $this->showForm($errors);
                         return;
                     }
                 }
             } else {
                 //bad title returned
                 $errors['name'] = wfMessage('wva-failure')->text();
                 $this->showForm($errors);
                 return;
             }
         }
     }
     if ($replaced) {
         $successMsgKey = 'wva-success-replaced';
     } else {
         $successMsgKey = 'wva-success';
     }
     $query = array("sort" => "recent", "msg" => $successMsgKey, "msgTitle" => urlencode($title));
     $wgOut->redirect(SpecialPage::getTitleFor("Videos")->getLocalUrl($query));
 }
Beispiel #22
0
 /**
  * Numbers given by Exif user agents are often magical, that is they
  * should be replaced by a detailed explanation depending on their
  * value which most of the time are plain integers. This function
  * formats Exif (and other metadata) values into human readable form.
  *
  * @param $tags Array: the Exif data to format ( as returned by
  *                    Exif::getFilteredData() or BitmapMetadataHandler )
  * @return array
  */
 public static function getFormattedData($tags)
 {
     global $wgLang;
     $resolutionunit = !isset($tags['ResolutionUnit']) || $tags['ResolutionUnit'] == 2 ? 2 : 3;
     unset($tags['ResolutionUnit']);
     foreach ($tags as $tag => &$vals) {
         // This seems ugly to wrap non-array's in an array just to unwrap again,
         // especially when most of the time it is not an array
         if (!is_array($tags[$tag])) {
             $vals = array($vals);
         }
         // _type is a special value to say what array type
         if (isset($tags[$tag]['_type'])) {
             $type = $tags[$tag]['_type'];
             unset($vals['_type']);
         } else {
             $type = 'ul';
             // default unordered list.
         }
         //This is done differently as the tag is an array.
         if ($tag == 'GPSTimeStamp' && count($vals) === 3) {
             //hour min sec array
             $h = explode('/', $vals[0]);
             $m = explode('/', $vals[1]);
             $s = explode('/', $vals[2]);
             // this should already be validated
             // when loaded from file, but it could
             // come from a foreign repo, so be
             // paranoid.
             if (!isset($h[1]) || !isset($m[1]) || !isset($s[1]) || $h[1] == 0 || $m[1] == 0 || $s[1] == 0) {
                 continue;
             }
             $tags[$tag] = intval($h[0] / $h[1]) . ':' . str_pad(intval($m[0] / $m[1]), 2, '0', STR_PAD_LEFT) . ':' . str_pad(intval($s[0] / $s[1]), 2, '0', STR_PAD_LEFT);
             $time = wfTimestamp(TS_MW, '1971:01:01 ' . $tags[$tag]);
             // the 1971:01:01 is just a placeholder, and not shown to user.
             if ($time && intval($time) > 0) {
                 $tags[$tag] = $wgLang->time($time);
             }
             continue;
         }
         // The contact info is a multi-valued field
         // instead of the other props which are single
         // valued (mostly) so handle as a special case.
         if ($tag === 'Contact') {
             $vals = self::collapseContactInfo($vals);
             continue;
         }
         foreach ($vals as &$val) {
             switch ($tag) {
                 case 'Compression':
                     switch ($val) {
                         case 1:
                         case 2:
                         case 3:
                         case 4:
                         case 5:
                         case 6:
                         case 7:
                         case 8:
                         case 32773:
                         case 32946:
                         case 34712:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'PhotometricInterpretation':
                     switch ($val) {
                         case 2:
                         case 6:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'Orientation':
                     switch ($val) {
                         case 1:
                         case 2:
                         case 3:
                         case 4:
                         case 5:
                         case 6:
                         case 7:
                         case 8:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'PlanarConfiguration':
                     switch ($val) {
                         case 1:
                         case 2:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                     // TODO: YCbCrSubSampling
                 // TODO: YCbCrSubSampling
                 case 'YCbCrPositioning':
                     switch ($val) {
                         case 1:
                         case 2:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'XResolution':
                 case 'YResolution':
                     switch ($resolutionunit) {
                         case 2:
                             $val = self::msg('XYResolution', 'i', self::formatNum($val));
                             break;
                         case 3:
                             $val = self::msg('XYResolution', 'c', self::formatNum($val));
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                     // TODO: YCbCrCoefficients  #p27 (see annex E)
                 // TODO: YCbCrCoefficients  #p27 (see annex E)
                 case 'ExifVersion':
                 case 'FlashpixVersion':
                     $val = "{$val}" / 100;
                     break;
                 case 'ColorSpace':
                     switch ($val) {
                         case 1:
                         case 65535:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'ComponentsConfiguration':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                         case 3:
                         case 4:
                         case 5:
                         case 6:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'DateTime':
                 case 'DateTimeOriginal':
                 case 'DateTimeDigitized':
                 case 'DateTimeReleased':
                 case 'DateTimeExpires':
                 case 'GPSDateStamp':
                 case 'dc-date':
                 case 'DateTimeMetadata':
                     if ($val == '0000:00:00 00:00:00' || $val == '    :  :     :  :  ') {
                         $val = wfMsg('exif-unknowndate');
                     } elseif (preg_match('/^(?:\\d{4}):(?:\\d\\d):(?:\\d\\d) (?:\\d\\d):(?:\\d\\d):(?:\\d\\d)$/D', $val)) {
                         // Full date.
                         $time = wfTimestamp(TS_MW, $val);
                         if ($time && intval($time) > 0) {
                             $val = $wgLang->timeanddate($time);
                         }
                     } elseif (preg_match('/^(?:\\d{4}):(?:\\d\\d):(?:\\d\\d) (?:\\d\\d):(?:\\d\\d)$/D', $val)) {
                         // No second field. Still format the same
                         // since timeanddate doesn't include seconds anyways,
                         // but second still available in api
                         $time = wfTimestamp(TS_MW, $val . ':00');
                         if ($time && intval($time) > 0) {
                             $val = $wgLang->timeanddate($time);
                         }
                     } elseif (preg_match('/^(?:\\d{4}):(?:\\d\\d):(?:\\d\\d)$/D', $val)) {
                         // If only the date but not the time is filled in.
                         $time = wfTimestamp(TS_MW, substr($val, 0, 4) . substr($val, 5, 2) . substr($val, 8, 2) . '000000');
                         if ($time && intval($time) > 0) {
                             $val = $wgLang->date($time);
                         }
                     }
                     // else it will just output $val without formatting it.
                     break;
                     /** Wikia change start */
                 /** Wikia change start */
                 case 'duration':
                     $val = WikiaFileHelper::formatDuration($val);
                     break;
                 case 'published':
                     global $wgContLang;
                     $val = $wgContLang->date($val);
                     break;
                     /** Wikia change end */
                 /** Wikia change end */
                 case 'ExposureProgram':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                         case 3:
                         case 4:
                         case 5:
                         case 6:
                         case 7:
                         case 8:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'SubjectDistance':
                     $val = self::msg($tag, '', self::formatNum($val));
                     break;
                 case 'MeteringMode':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                         case 3:
                         case 4:
                         case 5:
                         case 6:
                         case 7:
                         case 255:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'LightSource':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                         case 3:
                         case 4:
                         case 9:
                         case 10:
                         case 11:
                         case 12:
                         case 13:
                         case 14:
                         case 15:
                         case 17:
                         case 18:
                         case 19:
                         case 20:
                         case 21:
                         case 22:
                         case 23:
                         case 24:
                         case 255:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'Flash':
                     $flashDecode = array('fired' => $val & bindec('00000001'), 'return' => ($val & bindec('00000110')) >> 1, 'mode' => ($val & bindec('00011000')) >> 3, 'function' => ($val & bindec('00100000')) >> 5, 'redeye' => ($val & bindec('01000000')) >> 6);
                     # We do not need to handle unknown values since all are used.
                     foreach ($flashDecode as $subTag => $subValue) {
                         # We do not need any message for zeroed values.
                         if ($subTag != 'fired' && $subValue == 0) {
                             continue;
                         }
                         $fullTag = $tag . '-' . $subTag;
                         $flashMsgs[] = self::msg($fullTag, $subValue);
                     }
                     $val = $wgLang->commaList($flashMsgs);
                     break;
                 case 'FocalPlaneResolutionUnit':
                     switch ($val) {
                         case 2:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'SensingMethod':
                     switch ($val) {
                         case 1:
                         case 2:
                         case 3:
                         case 4:
                         case 5:
                         case 7:
                         case 8:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'FileSource':
                     switch ($val) {
                         case 3:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'SceneType':
                     switch ($val) {
                         case 1:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'CustomRendered':
                     switch ($val) {
                         case 0:
                         case 1:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'ExposureMode':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'WhiteBalance':
                     switch ($val) {
                         case 0:
                         case 1:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'SceneCaptureType':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                         case 3:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'GainControl':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                         case 3:
                         case 4:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'Contrast':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'Saturation':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'Sharpness':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'SubjectDistanceRange':
                     switch ($val) {
                         case 0:
                         case 1:
                         case 2:
                         case 3:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                     //The GPS...Ref values are kept for compatibility, probably won't be reached.
                 //The GPS...Ref values are kept for compatibility, probably won't be reached.
                 case 'GPSLatitudeRef':
                 case 'GPSDestLatitudeRef':
                     switch ($val) {
                         case 'N':
                         case 'S':
                             $val = self::msg('GPSLatitude', $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'GPSLongitudeRef':
                 case 'GPSDestLongitudeRef':
                     switch ($val) {
                         case 'E':
                         case 'W':
                             $val = self::msg('GPSLongitude', $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'GPSAltitude':
                     if ($val < 0) {
                         $val = self::msg('GPSAltitude', 'below-sealevel', self::formatNum(-$val, 3));
                     } else {
                         $val = self::msg('GPSAltitude', 'above-sealevel', self::formatNum($val, 3));
                     }
                     break;
                 case 'GPSStatus':
                     switch ($val) {
                         case 'A':
                         case 'V':
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'GPSMeasureMode':
                     switch ($val) {
                         case 2:
                         case 3:
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'GPSTrackRef':
                 case 'GPSImgDirectionRef':
                 case 'GPSDestBearingRef':
                     switch ($val) {
                         case 'T':
                         case 'M':
                             $val = self::msg('GPSDirection', $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'GPSLatitude':
                 case 'GPSDestLatitude':
                     $val = self::formatCoords($val, 'latitude');
                     break;
                 case 'GPSLongitude':
                 case 'GPSDestLongitude':
                     $val = self::formatCoords($val, 'longitude');
                     break;
                 case 'GPSSpeedRef':
                     switch ($val) {
                         case 'K':
                         case 'M':
                         case 'N':
                             $val = self::msg('GPSSpeed', $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'GPSDestDistanceRef':
                     switch ($val) {
                         case 'K':
                         case 'M':
                         case 'N':
                             $val = self::msg('GPSDestDistance', $val);
                             break;
                         default:
                             /* If not recognized, display as is. */
                             break;
                     }
                     break;
                 case 'GPSDOP':
                     // See http://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
                     if ($val <= 2) {
                         $val = self::msg($tag, 'excellent', self::formatNum($val));
                     } elseif ($val <= 5) {
                         $val = self::msg($tag, 'good', self::formatNum($val));
                     } elseif ($val <= 10) {
                         $val = self::msg($tag, 'moderate', self::formatNum($val));
                     } elseif ($val <= 20) {
                         $val = self::msg($tag, 'fair', self::formatNum($val));
                     } else {
                         $val = self::msg($tag, 'poor', self::formatNum($val));
                     }
                     break;
                     // This is not in the Exif standard, just a special
                     // case for our purposes which enables wikis to wikify
                     // the make, model and software name to link to their articles.
                 // This is not in the Exif standard, just a special
                 // case for our purposes which enables wikis to wikify
                 // the make, model and software name to link to their articles.
                 case 'Make':
                 case 'Model':
                     $val = self::msg($tag, '', $val);
                     break;
                 case 'Software':
                     if (is_array($val)) {
                         //if its a software, version array.
                         $val = wfMsg('exif-software-version-value', $val[0], $val[1]);
                     } else {
                         $val = self::msg($tag, '', $val);
                     }
                     break;
                 case 'ExposureTime':
                     // Show the pretty fraction as well as decimal version
                     $val = wfMsg('exif-exposuretime-format', self::formatFraction($val), self::formatNum($val));
                     break;
                 case 'ISOSpeedRatings':
                     // If its = 65535 that means its at the
                     // limit of the size of Exif::short and
                     // is really higher.
                     if ($val == '65535') {
                         $val = self::msg($tag, 'overflow');
                     } else {
                         $val = self::formatNum($val);
                     }
                     break;
                 case 'FNumber':
                     $val = wfMsg('exif-fnumber-format', self::formatNum($val));
                     break;
                 case 'FocalLength':
                 case 'FocalLengthIn35mmFilm':
                     $val = wfMsg('exif-focallength-format', self::formatNum($val));
                     break;
                 case 'MaxApertureValue':
                     if (strpos($val, '/') !== false) {
                         // need to expand this earlier to calculate fNumber
                         list($n, $d) = explode('/', $val);
                         if (is_numeric($n) && is_numeric($d)) {
                             $val = $n / $d;
                         }
                     }
                     if (is_numeric($val)) {
                         $fNumber = pow(2, $val / 2);
                         if ($fNumber !== false) {
                             $val = wfMsg('exif-maxaperturevalue-value', self::formatNum($val), self::formatNum($fNumber, 2));
                         }
                     }
                     break;
                 case 'iimCategory':
                     switch (strtolower($val)) {
                         // See pg 29 of IPTC photo
                         // metadata standard.
                         case 'ace':
                         case 'clj':
                         case 'dis':
                         case 'fin':
                         case 'edu':
                         case 'evn':
                         case 'hth':
                         case 'hum':
                         case 'lab':
                         case 'lif':
                         case 'pol':
                         case 'rel':
                         case 'sci':
                         case 'soi':
                         case 'spo':
                         case 'war':
                         case 'wea':
                             $val = self::msg('iimcategory', $val);
                     }
                     break;
                 case 'SubjectNewsCode':
                     // Essentially like iimCategory.
                     // 8 (numeric) digit hierarchical
                     // classification. We decode the
                     // first 2 digits, which provide
                     // a broad category.
                     $val = self::convertNewsCode($val);
                     break;
                 case 'Urgency':
                     // 1-8 with 1 being highest, 5 normal
                     // 0 is reserved, and 9 is 'user-defined'.
                     $urgency = '';
                     if ($val == 0 || $val == 9) {
                         $urgency = 'other';
                     } elseif ($val < 5 && $val > 1) {
                         $urgency = 'high';
                     } elseif ($val == 5) {
                         $urgency = 'normal';
                     } elseif ($val <= 8 && $val > 5) {
                         $urgency = 'low';
                     }
                     if ($urgency !== '') {
                         $val = self::msg('urgency', $urgency, $val);
                     }
                     break;
                     // Things that have a unit of pixels.
                 // Things that have a unit of pixels.
                 case 'OriginalImageHeight':
                 case 'OriginalImageWidth':
                 case 'PixelXDimension':
                 case 'PixelYDimension':
                 case 'ImageWidth':
                 case 'ImageLength':
                     $val = self::formatNum($val) . ' ' . wfMsg('unit-pixel');
                     break;
                     // Do not transform fields with pure text.
                     // For some languages the formatNum()
                     // conversion results to wrong output like
                     // foo,bar@example,com or foo٫bar@example٫com.
                     // Also some 'numeric' things like Scene codes
                     // are included here as we really don't want
                     // commas inserted.
                 // Do not transform fields with pure text.
                 // For some languages the formatNum()
                 // conversion results to wrong output like
                 // foo,bar@example,com or foo٫bar@example٫com.
                 // Also some 'numeric' things like Scene codes
                 // are included here as we really don't want
                 // commas inserted.
                 case 'ImageDescription':
                 case 'Artist':
                 case 'Copyright':
                 case 'RelatedSoundFile':
                 case 'ImageUniqueID':
                 case 'SpectralSensitivity':
                 case 'GPSSatellites':
                 case 'GPSVersionID':
                 case 'GPSMapDatum':
                 case 'Keywords':
                 case 'WorldRegionDest':
                 case 'CountryDest':
                 case 'CountryCodeDest':
                 case 'ProvinceOrStateDest':
                 case 'CityDest':
                 case 'SublocationDest':
                 case 'WorldRegionCreated':
                 case 'CountryCreated':
                 case 'CountryCodeCreated':
                 case 'ProvinceOrStateCreated':
                 case 'CityCreated':
                 case 'SublocationCreated':
                 case 'ObjectName':
                 case 'SpecialInstructions':
                 case 'Headline':
                 case 'Credit':
                 case 'Source':
                 case 'EditStatus':
                 case 'FixtureIdentifier':
                 case 'LocationDest':
                 case 'LocationDestCode':
                 case 'Writer':
                 case 'JPEGFileComment':
                 case 'iimSupplementalCategory':
                 case 'OriginalTransmissionRef':
                 case 'Identifier':
                 case 'dc-contributor':
                 case 'dc-coverage':
                 case 'dc-publisher':
                 case 'dc-relation':
                 case 'dc-rights':
                 case 'dc-source':
                 case 'dc-type':
                 case 'Lens':
                 case 'SerialNumber':
                 case 'CameraOwnerName':
                 case 'Label':
                 case 'Nickname':
                 case 'RightsCertificate':
                 case 'CopyrightOwner':
                 case 'UsageTerms':
                 case 'WebStatement':
                 case 'OriginalDocumentID':
                 case 'LicenseUrl':
                 case 'MorePermissionsUrl':
                 case 'AttributionUrl':
                 case 'PreferredAttributionName':
                 case 'PNGFileComment':
                 case 'Disclaimer':
                 case 'ContentWarning':
                 case 'GIFFileComment':
                 case 'SceneCode':
                 case 'IntellectualGenre':
                 case 'Event':
                 case 'OrginisationInImage':
                 case 'PersonInImage':
                     $val = htmlspecialchars($val);
                     break;
                 case 'ObjectCycle':
                     switch ($val) {
                         case 'a':
                         case 'p':
                         case 'b':
                             $val = self::msg($tag, $val);
                             break;
                         default:
                             $val = htmlspecialchars($val);
                             break;
                     }
                     break;
                 case 'Copyrighted':
                     switch ($val) {
                         case 'True':
                         case 'False':
                             $val = self::msg($tag, $val);
                             break;
                     }
                     break;
                 case 'Rating':
                     if ($val == '-1') {
                         $val = self::msg($tag, 'rejected');
                     } else {
                         $val = self::formatNum($val);
                     }
                     break;
                 case 'LanguageCode':
                     $lang = $wgLang->getLanguageName(strtolower($val));
                     if ($lang) {
                         $val = htmlspecialchars($lang);
                     } else {
                         $val = htmlspecialchars($val);
                     }
                     break;
                 default:
                     $val = self::formatNum($val);
                     break;
             }
         }
         // End formatting values, start flattening arrays.
         $vals = self::flattenArray($vals, $type);
     }
     return $tags;
 }
Beispiel #23
0
echo "MUT is *{$mut}*\n";
// 1. count number of articles in content namespace
$queryArticleCnt = "SELECT COUNT(*) AS cnt FROM page WHERE page_namespace IN ( " . implode(",", $wgContentNamespaces) . ")";
$rows = $dbw->query($queryArticleCnt);
$row = $dbw->fetchObject($rows);
$totalArticleCnt = $row->cnt;
echo "Total articles in content namespaces: " . $totalArticleCnt . " \n";
// 2. count number of local videos in articles
$queryLocalVideo = "SELECT COUNT(*) AS cnt\r\n \t\t    FROM imagelinks il LEFT JOIN image i ON il.il_to = i.img_name\r\n \t\t    WHERE i.img_major_mime = 'video' ";
$rows = $dbw->query($queryLocalVideo);
$row = $dbw->fetchObject($rows);
$localVideoCnt = $row->cnt;
echo "Local video cnt in articles: " . $localVideoCnt . " \n";
// 3. count number of videos from video wiki
$queryRepositoryVideo = "SELECT il.*, i.img_major_mime\r\n\t\t\t FROM imagelinks il LEFT JOIN image i ON il.il_to = i.img_name\r\n\t\t\t WHERE i.img_major_mime IS NULL ";
$rows = $dbw->query($queryRepositoryVideo);
$aAllFiles = array();
while ($file = $dbw->fetchObject($rows)) {
    $aAllFiles[] = $file->il_to;
}
$repositoryVideoCnt = 0;
if (count($aAllFiles) > 0) {
    foreach ($aAllFiles as $fileName) {
        $oTitle = Title::newFromText($fileName, NS_FILE);
        $oFile = wfFindFile($oTitle);
        if (!empty($oFile) && WikiaFileHelper::isFileTypeVideo($oFile)) {
            $repositoryVideoCnt++;
        }
    }
}
echo "Repo video cnt in articles: " . $repositoryVideoCnt . "\n";
 public static function onImageBeforeProduceHTML(&$dummy, Title &$title, &$file, &$frameParams, &$handlerParams, &$time, &$res)
 {
     global $wgArticleAsJson;
     wfProfileIn(__METHOD__);
     if ($wgArticleAsJson) {
         $linkHref = '';
         if (isset($frameParams['link-title']) && $frameParams['link-title'] instanceof Title) {
             $linkHref = $frameParams['link-title']->getLocalURL();
         } else {
             if (!empty($frameParams['link-url'])) {
                 $linkHref = $frameParams['link-url'];
             }
         }
         $details = WikiaFileHelper::getMediaDetail($title, self::$mediaDetailConfig);
         //information for mobile skins how they should display small icons
         $details['context'] = self::isIconImage($handlerParams) ? self::MEDIA_CONTEXT_ICON : self::MEDIA_CONTEXT_ARTICLE_IMAGE;
         self::$media[] = self::createMediaObject($details, $title->getText(), $frameParams['caption'], $linkHref);
         self::addUserObj($details);
         $res = self::createMarker($details['width'], $details['height']);
         wfProfileOut(__METHOD__);
         return false;
     }
     wfProfileOut(__METHOD__);
     return true;
 }
 protected function getFromFile($title)
 {
     $file = wfFindFile($title);
     if ($file instanceof LocalFile) {
         //media type: photo, video
         if (WikiaFileHelper::isFileTypeVideo($file)) {
             /* @var VideoHandler $handler */
             $handler = VideoHandler::getHandler($file->getMimeType());
             $typeInfo = explode('/', $file->getMimeType());
             $metadata = $handler ? $handler->getVideoMetadata(true) : null;
             return ['type' => static::VIDEO_TYPE, 'provider' => isset($typeInfo[1]) ? $typeInfo[1] : static::UNKNOWN_PROVIDER, 'metadata' => ['title' => isset($metadata['title']) ? $metadata['title'] : '', 'description' => isset($metadata['description']) ? $metadata['description'] : '', 'duration' => isset($metadata['duration']) ? (int) $metadata['duration'] : 0]];
         } else {
             return ['type' => static::IMAGE_TYPE];
         }
     }
     return [];
 }
Beispiel #26
0
 /**
  * Test for whether the current file page represents a video
  * @return bool - true if the file is a video, false if not
  */
 protected function isVideo()
 {
     $file = $this->getDisplayedFile();
     return WikiaFileHelper::isVideoFile($file);
 }
 public function renderMediaGroup()
 {
     $this->wf->profileIn(__METHOD__);
     $items = $this->request->getVal('items', array());
     $first = null;
     $wikiText = '';
     $result = '';
     $params = array();
     //separate linked items from normal ones and select the first one
     //which will be rendered in the page
     foreach ($items as $item) {
         /**
          * @var $file File
          */
         $file = $this->wf->FindFile($item['title']);
         if ($file instanceof File) {
             if (!empty($item['link'])) {
                 //build wikitext for linked images to render separately
                 $wikiText .= '[[' . $item['title']->getPrefixedDBkey() . '|link=' . $item['link'];
                 if ($item['caption']) {
                     $wikiText .= "|{$item['caption']}";
                 }
                 $wikiText .= "]]\n";
             } else {
                 if (empty($first)) {
                     $first = array('data' => $item, 'file' => $file);
                 }
                 //prepare data for media collection
                 $info = array('name' => $item['title']->getText(), 'full' => $this->wf->ReplaceImageServer($file->getFullUrl(), $file->getTimestamp()));
                 if (WikiaFileHelper::isFileTypeVideo($file)) {
                     $info['type'] = 'video';
                 }
                 if (!empty($item['caption'])) {
                     $info['capt'] = $item['caption'];
                 }
                 $params[] = $info;
             }
         }
     }
     if (!empty($first) && !empty($params)) {
         $file = $first['file'];
         $origWidth = $file->getWidth();
         $origHeight = $file->getHeight();
         //only one non-linked media left
         if (count($params) == 1) {
             $item = $first['data'];
             //build wikitext for a normal thumb
             $groupWikiText = '[[' . $item['title']->getPrefixedDBkey() . '|thumb|' . min($origWidth, self::THUMB_WIDTH) . 'px';
             if ($item['caption']) {
                 $groupWikiText .= "|{$item['caption']}";
             }
             $groupWikiText .= "]]\n";
             $wikiText = "{$groupWikiText}{$wikiText}";
         } else {
             //many left, proceed preparing and rendering the media group
             $size = self::calculateMediaSize($origWidth, $origHeight);
             $thumb = $file->transform($size);
             $attribs = array('src' => $this->wf->ReplaceImageServer($thumb->getUrl(), $file->getTimestamp()), 'width' => $size['width'], 'height' => $size['height']);
             $result = $this->render(self::GROUP, $attribs, $params, array(), false, Xml::element('img', $attribs, '', true), null, $this->wf->MsgForContent('wikiamobile-media-group-footer', count($params)));
         }
     }
     //if there's any raw wikitext left to parse
     //then do it now
     if (!empty($wikiText)) {
         $origVal = $this->wg->WikiaMobileDisableMediaGrouping;
         //avoid wikitext recursion
         $this->wg->WikiaMobileDisableMediaGrouping = true;
         $tmpParser = new Parser();
         $result .= $tmpParser->parse($wikiText, $this->wg->Title, new ParserOptions())->getText();
         //restoring to previous value
         $this->wg->WikiaMobileDisableMediaGrouping = $origVal;
     }
     $this->response->setBody($result);
     $this->wf->profileOut(__METHOD__);
 }
 /**
  * Checks if a the video already exists on Wikia. If so, and reupload is on, save the name of that
  * video in $this->oldName. This will be used later in the ingestion process.
  * @throws FeedIngesterSkippedException
  */
 public function checkVideoExistsOnWikia()
 {
     $duplicates = WikiaFileHelper::findVideoDuplicates($this->videoData['provider'], $this->videoData['videoId'], static::$REMOTE_ASSET);
     if (count($duplicates) > 0) {
         $oldName = $duplicates[0]['img_name'];
         if (!$this->reupload) {
             $msg = "Skipping {$oldName} (Id: {$this->videoData['videoId']}, {$this->videoData['provider']}) - ";
             $msg .= "video already exists on Wikia and reupload is disabled.\n";
             throw new FeedIngesterSkippedException($msg);
         }
         $this->oldName = $oldName;
         echo "Video already exists, using it's old name: {$this->oldName}\n";
     } else {
         $this->oldName = null;
     }
 }
/**
 * Compare new metadata with the one from file
 * @param array $video
 * @param string $msg
 * @param array $newMeta
 * @return boolean
 */
function compareMetadataFile($video, $msg, $newMeta)
{
    // find duplicate videos from wiki
    $duplicates = WikiaFileHelper::getDuplicateVideos('ooyala', $video['embed_code'], 2);
    if (empty($duplicates)) {
        echo "\n\tNOTE: {$msg} ... File not found in DB\n";
        return false;
    } else {
        if (count($duplicates) > 1) {
            $dupes = array();
            foreach ($duplicates as $dup) {
                $dupes[] = $dup['video_title'];
            }
            echo "\n\tNOTE: {$msg} ... (Found " . count($duplicates) . " duplicates: " . implode(',', $dupes) . ")\n";
            return false;
        }
    }
    // get file object
    $title = $duplicates[0]['video_title'];
    $file = WikiaFileHelper::getVideoFileFromTitle($title);
    if (empty($file)) {
        echo "\n\tNOTE: {$msg} ... File not found\n";
        return false;
    }
    $fileMeta = unserialize($file->getMetadata());
    foreach ($fileMeta as $key => &$value) {
        if ($key == 'ageRequired') {
            $fileMeta['age_required'] = $value;
            unset($fileMeta['ageRequired']);
        } else {
            if ($key == 'language') {
                $fileMeta['lang'] = $value;
                unset($fileMeta['language']);
            } else {
                if ($key == 'published') {
                    $value = date('Y-m-d', $value);
                } else {
                    $keyLc = strtolower($key);
                    if ($key != $keyLc) {
                        $fileMeta[$keyLc] = $value;
                        unset($fileMeta[$key]);
                    }
                }
            }
        }
    }
    echo "\n\tCompare to File:\n";
    compareMetadata($fileMeta, $newMeta);
    return true;
}
 /**
  * Render slider preview
  *
  * @author Jakub Kurcek
  */
 public static function renderSliderPreview($slider)
 {
     global $wgTitle, $wgParser;
     wfProfileIn(__METHOD__);
     // use global instance of parser (RT #44689 / RT #44712)
     $parserOptions = new ParserOptions();
     wfDebug(__METHOD__ . "\n" . print_r($slider, true));
     // render slider images
     foreach ($slider['images'] as &$image) {
         $imageTitle = Title::newFromText($image['name'], NS_FILE);
         $image['pageTitle'] = '';
         $img = wfFindFile($imageTitle);
         if (is_object($img) && $imageTitle->getNamespace() == NS_FILE) {
             // render thumbnail
             $is = new ImageServing(null, self::STRICT_IMG_WIDTH_PREV, array('w' => self::STRICT_IMG_WIDTH_PREV, 'h' => self::STRICT_IMG_HEIGHT_PREV));
             $image['thumbnailBg'] = $is->getUrl($image['name'], $img->getWidth(), $img->getHeight());
         } elseif (is_object($imageTitle)) {
             $image['pageTitle'] = $imageTitle->getText();
         }
         $image['isFileTypeVideo'] = WikiaFileHelper::isFileTypeVideo($img);
         //need to use parse() - see RT#44270
         $image['caption'] = $wgParser->parse($image['caption'], $wgTitle, $parserOptions)->getText();
         // remove <p> tags from parser caption
         if (preg_match('/^<p>(.*)\\n?<\\/p>\\n?$/sU', $image['caption'], $m)) {
             $image['caption'] = $m[1];
         }
     }
     wfDebug(__METHOD__ . '::after' . "\n" . print_r($slider, true));
     // render gallery HTML preview
     $template = new EasyTemplate(dirname(__FILE__) . '/templates');
     $template->set_vars(array('height' => self::STRICT_IMG_HEIGHT_PREV, 'slider' => $slider, 'width' => self::STRICT_IMG_WIDTH_PREV));
     $html = $template->render('sliderPreview');
     wfProfileOut(__METHOD__);
     return $html;
 }