/**
  * Get the embed code for the given title from the video wiki, rather than the local wiki.  This is
  * useful when a video of the same name from youtube (or other non-premium provider) exists on the local wiki
  * and we want to show the equivalent video from the video wiki.  See also getEmbedCode in this controller.
  *
  * @requestParam string fileTitle The title of the video to find the embed code for
  * @requestParam int width The desired width of video playback to return with the embed code
  * @requestParam boolean autoplay Whether the video should play immediately on page load
  * @responseParam string videoId A unique identifier for the video title given
  * @responseParam string asset A URL for the video
  * @responseParam string embedCode The HTML to embed on the page to play the video given by fileTitle
  */
 public function getPremiumEmbedCode()
 {
     // Pass through all the same parameters
     $params = array('controller' => __CLASS__, 'method' => 'getEmbedCode', 'fileTitle' => $this->getVal('fileTitle', ''), 'width' => $this->getVal('width', ''), 'autoplay' => $this->getVal('autoplay', false));
     // Call out to the getEmbedCode method in the context of the Video Wiki (WikiaVideoRepoDBName)
     $response = ApiService::foreignCall(F::app()->wg->WikiaVideoRepoDBName, $params, ApiService::WIKIA, true);
     // Map the foreign call response back to our response
     foreach ($response as $key => $val) {
         $this->setVal($key, $val);
     }
 }
 public static function getImageOriginalUrl($wikiId, $pageId)
 {
     $app = F::app();
     $app->wf->ProfileIn(__METHOD__);
     $dbname = WikiFactory::IDtoDB($wikiId);
     $title = GlobalTitle::newFromId($pageId, $wikiId);
     $param = array('action' => 'query', 'prop' => 'imageinfo', 'iiprop' => 'url', 'titles' => $title->getPrefixedText());
     $response = ApiService::foreignCall($dbname, $param);
     $app->wf->ProfileOut(__METHOD__);
     return array('src' => $imageSrc, 'page' => $imagePage);
 }
 public static function getImageOriginalUrl($wikiId, $pageId)
 {
     wfProfileIn(__METHOD__);
     $dbname = WikiFactory::IDtoDB($wikiId);
     $title = GlobalTitle::newFromId($pageId, $wikiId);
     $param = array('action' => 'query', 'prop' => 'imageinfo', 'iiprop' => 'url', 'titles' => $title->getPrefixedText());
     $imagePage = $title->getFullUrl();
     $response = ApiService::foreignCall($dbname, $param, ApiService::API, true);
     if (!empty($response['query']['pages'])) {
         $imagePageData = array_shift($response['query']['pages']);
         $imageInfo = array_shift($imagePageData['imageinfo']);
         $imageSrc = empty($imageInfo['url']) ? '' : $imageInfo['url'];
     } else {
         $imageSrc = '';
     }
     wfProfileOut(__METHOD__);
     return array('src' => $imageSrc, 'page' => $imagePage);
 }
 /**
  * add video to other wikis
  * @param string $videoUrl
  * @param array $wikis
  * @return array|false $result
  */
 public function addVideoAcrossWikis($videoUrl, $wikis)
 {
     wfProfileIn(__METHOD__);
     $params = array('controller' => 'VideosController', 'method' => 'addVideo', 'url' => $videoUrl);
     $result = false;
     foreach ($wikis as $wikiId => $wiki) {
         $result[$wikiId] = true;
         if (!empty($wiki['d'])) {
             $response = ApiService::foreignCall($wiki['d'], $params, ApiService::WIKIA, true);
             if (!empty($response['error'])) {
                 Wikia::log(__METHOD__, false, "Error: Cannot add video to wiki {$wikiId} ({$response['error']})", true, true);
                 $result[$wikiId] = false;
             }
         }
     }
     wfProfileOut(__METHOD__);
     return $result;
 }
 /**
  * Returns given blog post data
  *
  * @param string $dbname database name
  * @param string $title page title
  * @param boolean $getSnippet include blog post snippet in the data
  * @return mixed blog post data
  */
 private function getBlogPostData($dbname, $title, $getSnippet = false)
 {
     wfProfileIn(__METHOD__);
     wfDebug(__METHOD__ . ": '{$title}' ({$dbname})\n");
     $cityId = WikiFactory::DBtoID($dbname);
     // get blog info
     $data = ApiService::foreignCall($dbname, array('action' => 'query', 'prop' => 'revisions', 'titles' => $title, 'rvprop' => 'timestamp|user|content'));
     $blogPostData = reset($data['query']['pages']);
     $revisionData = array_shift($blogPostData['revisions']);
     // page ID
     $pageId = intval($blogPostData['pageid']);
     // parse blog post wikitext and get summary
     if ($getSnippet === true) {
         $data = ApiService::foreignCall($dbname, array('action' => 'parse', 'text' => $revisionData['*'], 'title' => $title));
         $snippet = $this->getSnippet($data['parse']['text']['*']);
     }
     // generate full URL to blog post
     $blogPostTitle = F::build('GlobalTitle', array($pageId, $cityId), 'newFromId');
     if (empty($blogPostTitle)) {
         wfProfileOut(__METHOD__);
         return false;
     }
     $blogPostUrl = $blogPostTitle->getFullURL();
     // get blog post title
     $title = end(explode('/', $blogPostTitle->getText(), 2));
     // get creator real name
     $creator = F::build('User', array($revisionData['user']), 'newFromName');
     if (!empty($creator)) {
         $creatorName = $creator->getRealName();
         if ($creatorName == '') {
             $creatorName = $creator->getName();
         }
     } else {
         $creatorName = $revisionData['user'];
     }
     // get creator user page URL
     $blogCreatorPageTitle = F::build('GlobalTitle', array($revisionData['user'], NS_USER, $cityId), 'newFromText');
     // get 220x140 image
     $imageData = ApiService::foreignCall($dbname, array('action' => 'imagecrop', 'imgId' => $pageId, 'imgSize' => 220, 'imgHeight' => 140));
     // data
     $res = array('pageId' => $pageId, 'cityId' => $cityId, 'wikiname' => WikiFactory::getVarValueByName('wgSitename', $cityId), 'wikiUrl' => 'http://' . parse_url($blogPostUrl, PHP_URL_HOST), 'title' => $title, 'url' => $blogPostUrl, 'created' => $revisionData['timestamp'], 'creator' => $creatorName, 'creatorUrl' => $blogCreatorPageTitle->getFullURL(), 'snippet' => !empty($snippet) ? $snippet : false, 'image' => $imageData['image']['imagecrop']);
     wfProfileOut(__METHOD__);
     return $res;
 }
 /**
  * Get video list from Video wiki
  *
  * @return array
  */
 public function addVideosFromVideoWiki()
 {
     $params = ['controller' => 'VideoHandler', 'method' => 'getVideoList', 'sort' => $this->sort, 'limit' => $this->getPaddedVideoLimit(), 'category' => $this->categories];
     $response = \ApiService::foreignCall($this->wg->WikiaVideoRepoDBName, $params, \ApiService::WIKIA);
     $videosWithDetails = $this->getVideoDetailFromVideoWiki($this->getVideoTitles($response['videos']));
     foreach ($videosWithDetails as $video) {
         if ($this->atVideoLimit()) {
             break;
         }
         $this->addVideo($video);
     }
 }
 /**
  * @desc Returns data from API based on parameters
  *
  * @param array $params more documentation: http://en.wikipedia.org/w/api.php
  *
  * @return mixed
  */
 private function getApiData($params)
 {
     $dbName = $this->getCommunityDbName();
     $data = ApiService::foreignCall($dbName, $params);
     return $data;
 }
 /**
  * @param array $topArticles - output from getTopArticles
  * @return array of article details. Format:
  * [
  *   'type' => self::RECOMMENDATION_TYPE,
  *   'title' => $articleDetails['title'],
  *   'url' => $response['basepath'] . $articleDetails['url'],
  *   'description' => $articleDetails['abstract'],
  *   'media' => [
  *     'url' => $articleDetails['thumbnail']
  *   ],
  *   'source' => self::RECOMMENDATION_ENGINE
  * ]
  */
 protected function getArticlesInfo($topArticles)
 {
     wfProfileIn(__METHOD__);
     $out = [];
     foreach ($topArticles as $topArticleInfo) {
         $articleId = $topArticleInfo['articleId'];
         $wikiId = $topArticleInfo['wikiId'];
         $params = ['controller' => 'ArticlesApiController', 'method' => 'getDetails', 'ids' => $articleId, 'width' => 400, 'height' => 225];
         $wikiData = \WikiFactory::getWikiByID($wikiId);
         $response = \ApiService::foreignCall($wikiData->city_dbname, $params, \ApiService::WIKIA);
         if (!empty($response['items'][$articleId])) {
             $articleDetails = $response['items'][$articleId];
             $media = ['thumbUrl' => $articleDetails['thumbnail'], 'originalWidth' => !empty($articleDetails['original_dimensions']['width']) ? (int) $articleDetails['original_dimensions']['width'] : null, 'originalHeight' => !empty($articleDetails['original_dimensions']['height']) ? (int) $articleDetails['original_dimensions']['height'] : null];
             $out[] = ['type' => self::RECOMMENDATION_TYPE, 'title' => $wikiData->city_title . ' - ' . $articleDetails['title'], 'url' => $response['basepath'] . $articleDetails['url'], 'description' => $articleDetails['abstract'], 'media' => $media, 'source' => self::RECOMMENDATION_ENGINE];
         }
     }
     wfProfileOut(__METHOD__);
     return $out;
 }
 protected function findIdForUrls($urls, $source = null)
 {
     $data = [];
     if (!empty($urls)) {
         foreach ($urls as $item) {
             $url = $item['url'];
             $result = GlobalTitle::explodeURL($url);
             $wikia_id = $result['wikiId'];
             $articleName = $result['articleName'];
             if (!(empty($wikia_id) || empty($articleName))) {
                 $res = ApiService::foreignCall(WikiFactory::IDtoDB($wikia_id), ['action' => 'query', 'titles' => $articleName, 'indexpageids', 'format' => 'json']);
                 if (!empty($res['query']['pages'])) {
                     $pages = array_keys($res['query']['pages']);
                     $page_id = array_shift($pages);
                     $newItem = $item;
                     $newItem['wikia_id'] = $wikia_id;
                     $newItem['page_id'] = $page_id;
                     $newItem['source'] = $source;
                     $data[] = $newItem;
                 }
             }
         }
     }
     return $data;
 }
 /**
  * Same as 'VideoHandlerHelper::getVideoDetail' but retrieves information from an external wiki
  * Typically used to get premium video info from video.wikia.com when on another wiki.
  * @param string $dbName - The DB name of the wiki that should be used to find video details
  * @param array|string $title - The list of title of the video to get details for
  * @param array $videoOptions
  *   [ array( 'thumbWidth' => int, 'thumbHeight' => int, 'postedInArticles' => int, 'getThumbnail' => bool, 'thumbOptions' => array ) ]
  * @return array - As associative array of video information
  */
 public function getVideoDetailFromWiki($dbName, $title, $videoOptions)
 {
     wfProfileIn(__METHOD__);
     $params = ['controller' => 'VideoHandler', 'method' => 'getVideoDetail', 'fileTitle' => $title, 'videoOptions' => $videoOptions];
     $response = ApiService::foreignCall($dbName, $params, ApiService::WIKIA);
     $videoDetail = empty($response['detail']) ? [] : $response['detail'];
     wfProfileOut(__METHOD__);
     return $videoDetail;
 }
 /**
  * Add more detail for global articles to the current $data by making HTTP requests to the other wiki URLs
  * @param array $data
  * @return array
  */
 public function addGlobalSummary($data)
 {
     return $this->addSummary($data, function ($dbName, $articleIds) {
         $ids = array();
         $result = array();
         foreach ($articleIds as $id) {
             $memcKey = $this->getMemcKeyGlobalSummary($dbName, $id);
             $summary = $this->wg->Memc->get($memcKey);
             if (is_array($summary)) {
                 $result['summary'][$id] = $summary;
             } else {
                 $ids[] = $id;
             }
         }
         if (!empty($ids)) {
             $params = array('controller' => 'ArticleSummaryController', 'method' => 'blurb', 'ids' => implode(',', $ids));
             $response = ApiService::foreignCall($dbName, $params, ApiService::WIKIA);
             if (!empty($response['summary'])) {
                 foreach ($response['summary'] as $id => $info) {
                     if (!array_key_exists('error', $info)) {
                         $result['summary'][$id] = $info;
                         $memcKey = $this->getMemcKeyGlobalSummary($dbName, $id);
                         $this->wg->Memc->set($memcKey, $info, 60 * 60);
                     }
                 }
             }
         }
         return $result;
     });
 }
 /**
  * swap video
  * @requestParam string videoTitle
  * @requestParam string newTitle
  * @requestParam integer currentPage
  * @responseParam string result [ok/error]
  * @responseParam string msg - result message
  * @responseParam string html
  * @responseParam integer totalVideos - total videos with suggestions
  * @responseParam string redirect - redirect url
  */
 public function swapVideo()
 {
     $videoTitle = $this->request->getVal('videoTitle', '');
     $newTitle = $this->request->getVal('newTitle', '');
     $currentPage = $this->getVal('currentPage', 1);
     $sort = 'recent';
     // set default value for response params
     $this->setDefaultParams();
     // validate action
     $validAction = $this->sendRequest('LicensedVideoSwapSpecial', 'validateAction', array('videoTitle' => $videoTitle));
     $msg = $validAction->getVal('msg', '');
     if (!empty($msg)) {
         $this->result = 'error';
         $this->msg = $msg;
         return;
     }
     $file = WikiaFileHelper::getVideoFileFromTitle($videoTitle);
     // check if file exists
     if (empty($file)) {
         $this->html = '';
         $this->result = 'error';
         $this->msg = wfMessage('videohandler-error-video-no-exist')->text();
         return;
     }
     $helper = new LicensedVideoSwapHelper();
     // check if the file is swapped
     $articleId = $file->getTitle()->getArticleID();
     if ($helper->isSwapped($articleId)) {
         $this->result = 'error';
         $this->msg = wfMessage('lvs-error-already-swapped')->text();
         return;
     }
     // check if the file is premium
     if (!$file->isLocal()) {
         $this->result = 'error';
         $this->msg = wfMessage('lvs-error-permission')->text();
         return;
     }
     // set swap status
     $helper->setPageStatusInfo($articleId);
     // check if the new file exists
     $params = array('controller' => 'VideoHandlerController', 'method' => 'fileExists', 'fileTitle' => $newTitle);
     $response = ApiService::foreignCall($this->wg->WikiaVideoRepoDBName, $params, ApiService::WIKIA);
     if (empty($response['fileExists'])) {
         $helper->deletePageStatusInfo($articleId);
         $this->result = 'error';
         $this->msg = wfMessage('videohandler-error-video-no-exist')->text();
         return;
     }
     // remove local video
     $removeVideo = $this->sendRequest('VideoHandlerController', 'removeVideo', array('title' => $file->getName()));
     $result = $removeVideo->getVal('result', '');
     if ($result != 'ok') {
         $helper->deletePageStatusInfo($articleId);
         $this->result = 'error';
         $this->msg = $removeVideo->getVal('msg', '');
         return;
     }
     $isSameTitle = $videoTitle->getDBKey() == $newTitle;
     $swapValue['newTitle'] = $newTitle;
     // force to get new file for same title
     $newFile = WikiaFileHelper::getVideoFileFromTitle($newTitle, $isSameTitle);
     // check if new file exists
     if (empty($newFile)) {
         $helper->deletePageStatusInfo($articleId);
         $this->result = 'error';
         $this->msg = wfMessage('videohandler-error-video-no-exist')->text();
         return;
     }
     // add premium video
     wfRunHooks('AddPremiumVideo', array($newFile->getTitle()));
     $title = Title::newFromText($videoTitle->getDBKey(), NS_FILE);
     if (!$isSameTitle) {
         // add redirect url
         $status = $helper->addRedirectLink($title, $newFile->getTitle());
         if (!$status->isGood()) {
             $helper->deletePageStatusInfo($articleId);
             $this->result = 'error';
             $this->msg = $status->getMessage();
             return;
         }
         // set swap status
         $helper->setPageStatusSwap($title->getArticleID(), $articleId);
         $helper->setPageStatusInfoSwap($title->getArticleID(), $swapValue);
     } else {
         // set swap status
         $helper->setPageStatusSwapExact($title->getArticleID(), $articleId);
         $helper->setPageStatusInfoSwapExact($title->getArticleID(), $swapValue);
     }
     // remove old page status
     $helper->deletePageStatus($articleId);
     $helper->deletePageStatusInfo($articleId);
     // move suggestion data to new article
     $helper->moveSuggestionData($articleId, $title->getArticleID());
     // add to log
     $reason = wfMessage('lvs-log-summary', $file->getTitle()->getText(), $newFile->getTitle()->getText())->text();
     $helper->addLog($file->getTitle(), wfMessage('lvs-log-description')->text(), $reason);
     // clear cache for total videos
     $helper->invalidateCacheTotalVideos();
     // clear cache for total new videos
     $helper->invalidateCacheTotalNewVideos();
     // get video list
     $useMaster = true;
     $videoList = $helper->getRegularVideoList($sort, $currentPage, $useMaster);
     // get total videos with suggestions
     $this->totalVideos = $helper->getUnswappedVideoTotal($useMaster);
     if (empty($videoList)) {
         $this->redirect = $helper->getRedirectUrl($currentPage, $sort);
     } else {
         $this->html = $this->app->renderView('LicensedVideoSwapSpecial', 'row', array('videoList' => $videoList));
         $this->html .= $helper->getPagination($this->totalVideos, $currentPage, $sort);
     }
     $undoOptions = array('class' => 'undo', 'href' => '#', 'data-video-title' => $videoTitle->getDBKey(), 'data-new-title' => $newTitle->getDBKey());
     $undo = Xml::element('a', $undoOptions, wfMessage('lvs-undo-swap')->text());
     $this->msg = wfMessage('lvs-swap-video-success')->rawParams($undo)->parse();
 }
 /**
  * This method calls out to the wiki given by $wikiId to get revision data, since
  * this data cannot be gathered locally if $wikiId != $wgCityId
  *
  * @param int $revId
  * @param int $wikiId
  *
  * @return bool
  */
 public function loadDataFromRevIdOnWiki($revId, $wikiId, $useMasterDB = false)
 {
     $dbName = WikiFactory::IDtoDB($wikiId);
     $params = ['controller' => 'WallNotifications', 'method' => 'getEntityData', 'revId' => $revId, 'useMasterDB' => $useMasterDB];
     $response = ApiService::foreignCall($dbName, $params, ApiService::WIKIA);
     if (!empty($response['status']) && $response['status'] == 'ok') {
         $this->parentTitleDbKey = $response['parentTitleDbKey'];
         $this->msgText = $response['msgText'];
         $this->threadTitleFull = $response['threadTitleFull'];
         $this->data = $response['data'];
         return true;
     }
     return false;
 }
 function uploadSingleImage($imageId, $destinationName, $targetWikiId, $sourceWikiId)
 {
     global $IP, $wgWikiaLocalSettingsPath;
     $retval = "";
     $dbname = WikiFactory::IDtoDB($sourceWikiId);
     $imageTitle = F::build('GlobalTitle', array($imageId, $sourceWikiId), 'newFromId');
     $sourceImageUrl = null;
     if ($imageTitle instanceof GlobalTitle) {
         $param = array('action' => 'query', 'titles' => $imageTitle->getPrefixedText(), 'prop' => 'imageinfo', 'iiprop' => 'url');
         $response = ApiService::foreignCall($dbname, $param);
         if (!empty($response["query"]["pages"][$imageId]) && !empty($response["query"]["pages"][$imageId]["imageinfo"][0]["url"])) {
             $sourceImageUrl = wfReplaceImageServer($response["query"]["pages"][$imageId]["imageinfo"][0]["url"]);
         }
     }
     if (empty($sourceImageUrl)) {
         $this->log('Apparently the image is unaccessible');
         return array('status' => 1);
     }
     $city_url = WikiFactory::getVarValueByName("wgServer", $targetWikiId);
     if (empty($city_url)) {
         $this->log('Apparently the server is not available via WikiFactory');
         return array('status' => 1);
     }
     $dbname = WikiFactory::IDtoDB($sourceWikiId);
     $destinationName = $this->getNameWithWiki($destinationName, $dbname);
     $sCommand = "SERVER_ID={$targetWikiId} php {$IP}/maintenance/wikia/ImageReview/PromoteImage/upload.php";
     $sCommand .= " --originalimageurl=" . escapeshellarg($sourceImageUrl);
     $sCommand .= " --destimagename=" . escapeshellarg($destinationName);
     $sCommand .= " --userid=" . escapeshellarg($this->mUser);
     $sCommand .= " --wikiid=" . escapeshellarg($sourceWikiId);
     $sCommand .= " --conf {$wgWikiaLocalSettingsPath}";
     $output = wfShellExec($sCommand, $retval);
     if ($retval) {
         $this->log('Upload error! (' . $city_url . '). Error code returned: ' . $retval . ' Error was: ' . $output);
     } else {
         $this->log('Upload successful: ' . $output);
     }
     $output = json_decode($output);
     return array('status' => $retval, 'name' => $output->name, 'id' => $output->id);
 }