private function sassProcessing()
 {
     global $IP, $wgSassExecutable, $wgDevelEnvironment;
     wfProfileIn(__METHOD__);
     $tempDir = sys_get_temp_dir();
     //replace \ to / is needed because escapeshellcmd() replace \ into spaces (?!!)
     $tempOutFile = str_replace('\\', '/', tempnam($tempDir, 'Sass'));
     $tempDir = str_replace('\\', '/', $tempDir);
     $params = urldecode(http_build_query($this->mParams, '', ' '));
     $cmd = "{$wgSassExecutable} {$IP}/{$this->mOid} {$tempOutFile} --cache-location {$tempDir}/sass -r {$IP}/extensions/wikia/SASS/wikia_sass.rb {$params}";
     $escapedCmd = escapeshellcmd($cmd) . " 2>&1";
     $sassResult = shell_exec($escapedCmd);
     if ($sassResult != '') {
         Wikia::log(__METHOD__, false, "commandline error: " . $sassResult . " -- Full commandline was: {$escapedCmd}", true);
         Wikia::log(__METHOD__, false, "Full commandline was: {$escapedCmd}", true);
         Wikia::log(__METHOD__, false, AssetsManager::getRequestDetails(), true);
         if (file_exists($tempOutFile)) {
             unlink($tempOutFile);
         }
         if (!empty($wgDevelEnvironment)) {
             $exceptionMsg = "Problem with SASS processing: {$sassResult}";
         } else {
             $exceptionMsg = 'Problem with SASS processing. Check the PHP error log for more info.';
         }
         throw new Exception("/* {$exceptionMsg} */");
     }
     $this->mContent = file_get_contents($tempOutFile);
     unlink($tempOutFile);
     wfProfileOut(__METHOD__);
 }
示例#2
0
function fnForumIndexProtector(Title &$title, User &$user, $action, &$result)
{
    if ($user->isLoggedIn()) {
        #this doesnt apply to logged in users, bail, but keep going
        return true;
    }
    if ($action != 'edit' && $action != 'create') {
        #only kill editing actions (what else can anons even do?), bail, but keep going
        return true;
    }
    #this only applies to Forum:Index and Forum_talk:Index
    #check pagename
    if ($title->getText() != 'Index') {
        #wrong pagename, bail, but keep going
        return true;
    }
    $ns = $title->getNamespace();
    #check namespace(s)
    if ($ns == NS_FORUM || $ns == NS_FORUM_TALK) {
        #bingo bango, its a match!
        $result = array('protectedpagetext');
        Wikia::log(__METHOD__, __LINE__, "anon trying to edit forum:index, killing request");
        #bail, and stop the request
        return false;
    }
    return true;
}
 /**
  * @desc Related pages are lazy-loaded on article pages for mobile, oasis and monobook. However, there are extensions
  * dependent on this method where related pages module isn't lazy-loaded such as: FilePage (FilePageController.class.php)
  */
 public function section()
 {
     global $wgTitle, $wgContentNamespaces, $wgRequest, $wgMemc;
     // request params
     $altTitle = $this->request->getVal('altTitle', null);
     $relatedPages = RelatedPages::getInstance();
     $anyNs = $this->request->getVal('anyNS', false);
     $title = empty($altTitle) ? $wgTitle : $altTitle;
     $articleid = $title->getArticleId();
     if (!$anyNs) {
         $ignoreNS = !empty($wgTitle) && in_array($wgTitle->getNamespace(), $wgContentNamespaces);
     } else {
         $ignoreNS = false;
     }
     $this->skipRendering = Wikia::isMainPage() || $ignoreNS || count($relatedPages->getCategories($articleid)) == 0 || $wgRequest->getVal('action', 'view') != 'view' || $relatedPages->isRendered();
     if (!$this->skipRendering) {
         $mKey = wfMemcKey('mOasisRelatedPages', $articleid, self::MEMC_KEY_VER);
         $this->pages = $wgMemc->get($mKey);
         $this->srcAttrName = $this->app->checkSkin('monobook') ? 'src' : 'data-src';
         if (empty($this->pages)) {
             $this->pages = $relatedPages->get($articleid);
             if (count($this->pages) > 0) {
                 $wgMemc->set($mKey, $this->pages, 3 * 3600);
             } else {
                 $this->skipRendering = true;
             }
         }
     }
     $this->mobileSkin = false;
     $this->relatedPagesHeading = wfMessage('wikiarelatedpages-heading')->plain();
 }
示例#4
0
 /**
  * @param $sql string
  * @return true|false|resource
  *
  * For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
  * For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
  */
 protected function doQuery($sql)
 {
     $this->installErrorHandler();
     if ($this->bufferResults()) {
         $ret = mysql_query($sql, $this->mConn);
     } else {
         $ret = mysql_unbuffered_query($sql, $this->mConn);
     }
     $phpError = $this->restoreErrorHandler();
     if ($ret === false) {
         global $wgDBname;
         $error = $this->lastError();
         if (!$error) {
             $error = $phpError;
         }
         $err_num = $this->lastErrno();
         error_log(sprintf("SQL (%s): %d: %s", $wgDBname, $err_num, $error));
         error_log("SQL: invalid query: {$sql}");
         # Wikia change - begin
         switch ($err_num) {
             case 1213:
                 /* deadlock*/
                 error_log("MOLI: deadlock: {$error} ");
                 Wikia::debugBacktrace("MOLI: Deadlock:");
                 break;
             case 2006:
                 /* server has gone away */
                 error_log("MOLI: gone away: {$error} ");
                 Wikia::debugBacktrace("MOLI: gone away:");
                 break;
         }
         # Wikia change - end
     }
     return $ret;
 }
 public function __construct(WebRequest $request)
 {
     parent::__construct($request);
     global $IP;
     if (strpos($this->mOid, '..') !== false) {
         throw new Exception('File path must not contain \'..\'.');
     }
     if (endsWith($this->mOid, '.js', false)) {
         $this->mContentType = AssetsManager::TYPE_JS;
     } else {
         if (endsWith($this->mOid, '.css', false)) {
             $this->mContentType = AssetsManager::TYPE_CSS;
         } else {
             throw new Exception('Requested file must be .css or .js.');
         }
     }
     $filePath = $IP . '/' . $this->mOid;
     if (file_exists($filePath)) {
         $this->mContent = file_get_contents($filePath);
     } else {
         $requestDetails = AssetsManager::getRequestDetails();
         Wikia::log(__METHOD__, false, "file '{$filePath}' doesn't exist ({$requestDetails})", true);
         throw new Exception('File does not exist');
     }
 }
 public function index()
 {
     $this->messages = $this->getVal('messages');
     // loading assets in Monobook that would normally load in oasis
     if ($this->app->checkSkin('monobook')) {
         $this->response->addAsset('skins/shared/styles/sprite.scss');
         $this->response->addAsset('extensions/wikia/Forum/css/monobook/RelatedForumMonobook.scss');
     }
     $title = $this->getContext()->getTitle();
     $topicTitle = Title::newFromText($title->getPrefixedText(), NS_WIKIA_FORUM_TOPIC_BOARD);
     // common data
     $this->sectionHeading = wfMessage('forum-related-discussion-heading', $title->getText())->escaped();
     $this->newPostButton = wfMessage('forum-related-discussion-new-post-button')->escaped();
     $this->newPostUrl = $topicTitle->getFullUrl('openEditor=1');
     $this->newPostTooltip = wfMessage('forum-related-discussion-new-post-tooltip', $title->getText())->escaped();
     $this->blankImgUrl = wfBlankImgUrl();
     $this->seeMoreUrl = $topicTitle->getFullUrl();
     $this->seeMoreText = wfMessage('forum-related-discussion-see-more')->escaped();
     // TODO: move classes to template when Venus will be live on all wikis
     $this->venusBtnClasses = '';
     if ($this->app->checkSkin('venus')) {
         $this->venusBtnClasses = 'wikia-button secondary';
         Wikia::addAssetsToOutput('related_forum_discussion_css');
     }
 }
 /**
  * Blocks view source page & make it so that users cannot create/edit
  * pages that are on the takedown list.
  *
  * @param EditPage $editPage edit page instance
  * @return bool show edit page form?
  */
 public static function onAlternateEdit(EditPage $editPage)
 {
     $wg = F::app()->wg;
     $wf = F::app()->wf;
     $title = $editPage->getTitle();
     // Block view-source on the certain pages.
     if ($title->exists()) {
         // Look at the page-props to see if this page is blocked.
         if (!$wg->user->isAllowed('editlyricfind')) {
             // some users (staff/admin) will be allowed to edit these to prevent vandalism/spam issues.
             $removedProp = $wf->GetWikiaPageProp(WPP_LYRICFIND_MARKED_FOR_REMOVAL, $title->getArticleID());
             if (!empty($removedProp)) {
                 $wg->Out->addHTML(Wikia::errorbox(wfMessage('lyricfind-editpage-blocked')));
                 $blockEdit = true;
             }
         }
     } else {
         // Page is being created. Prevent this if page is prohibited by LyricFind.
         $blockEdit = LyricFindTrackingService::isPageBlockedViaApi($amgId = "", $gracenoteId = "", $title->getText());
         if ($blockEdit) {
             $wg->Out->addHTML(Wikia::errorbox(wfMessage('lyricfind-creation-blocked')));
         }
     }
     return !$blockEdit;
 }
 /**
  * execute -- main entry point to api method
  *
  * use secret hash for checking if api is called by proper engine
  *
  * @access public
  *
  * @return api result
  */
 public function execute()
 {
     global $wgTheSchwartzSecretToken, $wgCityId, $wgServer, $wgExtensionMessagesFiles;
     $params = $this->extractRequestParams();
     $status = 0;
     if (isset($params["token"]) && $params["token"] === $wgTheSchwartzSecretToken) {
         /**
          * get creator from param
          */
         $founder = User::newFromId($params["user_id"]);
         $founder->load();
         /**
          * get city_founding_user from city_list
          */
         if (!$founder) {
             $wiki = WikiFactory::getWikiByID($wgCityId);
             $founder = User::newFromId($wiki->city_founding_user);
         }
         Wikia::log(__METHOD__, "user", $founder->getName());
         if ($founder && $founder->isEmailConfirmed()) {
             if ($founder->sendMail(wfMsg("autocreatewiki-reminder-subject"), wfMsg("autocreatewiki-reminder-body", array($founder->getName(), $wgServer)), null, null, "AutoCreateWikiReminder", wfMsg("autocreatewiki-reminder-body-HTML", array($founder->getName(), $wgServer)))) {
                 $status = 1;
             }
         }
     } else {
         $this->dieUsageMsg(array("sessionfailure"));
     }
     $result = array("status" => $status);
     $this->getResult()->setIndexedTagName($result, 'status');
     $this->getResult()->addValue(null, $this->getModuleName(), $result);
 }
 public function index()
 {
     wfProfileIn(__METHOD__);
     Wikia::addAssetsToOutput('recent_wiki_activity_scss');
     Wikia::addAssetsToOutput('recent_wiki_activity_js');
     $this->changeList = WikiaDataAccess::cache(wfMemcKey(self::$memcKey), 0, function () {
         global $wgContentNamespaces, $wgLang;
         $maxElements = 4;
         $includeNamespaces = implode('|', $wgContentNamespaces);
         $parameters = array('type' => 'widget', 'maxElements' => $maxElements, 'flags' => array('shortlist'), 'uselang' => $wgLang->getCode(), 'includeNamespaces' => $includeNamespaces);
         $feedProxy = new ActivityFeedAPIProxy($includeNamespaces, $this->userName);
         $feedProvider = new DataFeedProvider($feedProxy, 1, $parameters);
         $feedData = $feedProvider->get($maxElements);
         foreach ($feedData['results'] as &$result) {
             if (!empty($result['articleComment'])) {
                 $title = Title::newFromText($result['title'], $result['ns']);
                 if ($title instanceof Title) {
                     $result['url'] = $title->getLocalURL();
                 }
             }
         }
         return $feedData['results'];
     });
     wfProfileOut(__METHOD__);
 }
示例#10
0
 /**
  * Send a packet to SFlow daemon
  *
  * @param $app_name
  * @param $op_name
  * @param string $attributes
  * @param int $status
  * @param string $status_descr
  * @param int $req_bytes
  * @param int $resp_bytes
  * @param int $uS
  */
 private static function app_operation($app_name, $op_name, $attributes = "", $status = 0, $status_descr = "", $req_bytes = 0, $resp_bytes = 0, $uS = 0)
 {
     global $wgSFlowHost, $wgSFlowPort, $wgSFlowSampling;
     // sampling handling
     $sampling_rate = $wgSFlowSampling;
     if ($sampling_rate > 1) {
         if (mt_rand(1, $sampling_rate) != 1) {
             return;
         }
     }
     wfProfileIn(__METHOD__);
     try {
         $sock = fsockopen("udp://" . $wgSFlowHost, $wgSFlowPort, $errno, $errstr);
         if (!$sock) {
             wfProfileOut(__METHOD__);
             return;
         }
         $data = ["flow_sample" => ["app_name" => $app_name, "sampling_rate" => $sampling_rate, "app_operation" => ["operation" => $op_name, "attributes" => $attributes, "status_descr" => $status_descr, "status" => $status, "req_bytes" => $req_bytes, "resp_bytes" => $resp_bytes, "uS" => $uS]]];
         $payload = json_encode($data);
         wfDebug(sprintf("%s: sending '%s'\n", __METHOD__, $payload));
         fwrite($sock, $payload);
         fclose($sock);
     } catch (\Exception $e) {
         \Wikia::log(__METHOD__, 'send', $e->getMessage(), true);
         \Wikia::logBacktrace(__METHOD__);
     }
     wfProfileOut(__METHOD__);
 }
示例#11
0
 public static function onWFAfterErrorDetection($cv_id, $city_id, $cv_name, $cv_value, &$return, &$error)
 {
     if (self::isWikiaBarConfig($city_id, $cv_name)) {
         /* @var $validator WikiaBarMessageDataValidator */
         $validator = F::build('WikiaBarMessageDataValidator');
         /* @var $model WikiaBarModel */
         $model = F::build('WikiaBarModel');
         $errorCount = 0;
         $errors = array();
         if (is_array($cv_value)) {
             foreach ($cv_value as $vertical => $languages) {
                 foreach ($languages as $language => $content) {
                     $validator->clearErrors();
                     $model->parseBarConfigurationMessage(trim($content), $validator);
                     $messageErrorCount = $validator->getErrorCount();
                     if ($messageErrorCount) {
                         $errorMessages = $validator->getErrors();
                         foreach ($errorMessages as &$errorMessage) {
                             $errorMessage = Wikia::errormsg('vertical: ' . $vertical . ', language: ' . $language . ' : ' . $errorMessage);
                         }
                         $errors = array_merge($errors, $errorMessages);
                         $errorCount += $messageErrorCount;
                     }
                 }
             }
         }
         if ($errorCount) {
             $error = $errorCount;
             $return = trim(implode("<br/>", $errors));
         }
     }
     return true;
 }
示例#12
0
 function execute()
 {
     $this->app->setSkinTemplateObj($this);
     $response = $this->app->sendRequest(Wikia::getVar('OasisEntryControllerName', 'Oasis'), 'index', null, false);
     $response->sendHeaders();
     $response->render();
 }
示例#13
0
 /**
  * @param $sql string
  * @return resource
  */
 protected function doQuery($sql)
 {
     $this->installErrorHandler();
     if ($this->bufferResults()) {
         $ret = mysql_query($sql, $this->mConn);
     } else {
         $ret = mysql_unbuffered_query($sql, $this->mConn);
     }
     $phpError = $this->restoreErrorHandler();
     if ($ret === false) {
         global $wgDBname;
         $error = $this->lastError();
         if (!$error) {
             $error = $phpError;
         }
         $err_num = $this->lastErrno();
         error_log(sprintf("SQL (%s): %d: %s", $wgDBname, $err_num, $error));
         error_log("SQL: invalid query: {$sql}");
         if ($err_num == 1213) {
             /* deadlock*/
             error_log("MOLI: deadlock: {$error} ");
             Wikia::debugBacktrace("MOLI: Deadlock:");
         }
     }
     return $ret;
 }
示例#14
0
 static function updateBacklinkText()
 {
     wfProfileIn(__METHOD__);
     $dbr = wfGetDb(DB_MASTER);
     $rowCount = count(self::$backlinkRows);
     if ($rowCount == 0) {
         wfProfileOut(__METHOD__);
         return true;
     }
     $deleteSql = 'DELETE FROM `' . self::TABLE_NAME . '` WHERE source_page_id IN (' . implode(', ', self::$sourceArticleIds) . ');';
     $insertSql = "INSERT IGNORE INTO `" . self::TABLE_NAME . "` (`source_page_id`, `target_page_id`, `backlink_text`, `count` ) VALUES ";
     $rowCounter = 0;
     foreach (self::$backlinkRows as $signature => $count) {
         // $signature is incomplete sql value set "(1234,1234,'foo', "
         $insertSql .= $signature . "{$count})";
         $insertSql .= ++$rowCounter == $rowCount ? ';' : ', ';
     }
     try {
         $dbr->begin();
         $dbr->query($deleteSql, __METHOD__);
         $dbr->query($insertSql, __METHOD__);
         $dbr->commit(__METHOD__);
     } catch (Exception $e) {
         $dbr->rollback();
         Wikia::Log(__METHOD__, 'Transaction', $e);
     }
     wfProfileOut(__METHOD__);
     return true;
 }
 public function executeIndex($params)
 {
     $page_owner = User::newFromName($this->wg->Title->getText());
     if (!is_object($page_owner) || $page_owner->getId() == 0) {
         // do not show module if page owner does not exist or is an anonymous user
         return false;
     }
     // add CSS for this module
     $this->wg->Out->addStyle(AssetsManager::getInstance()->getSassCommonURL("skins/oasis/css/modules/FollowedPages.scss"));
     $showDeletedPages = isset($params['showDeletedPages']) ? (bool) $params['showDeletedPages'] : true;
     // get 6 followed pages
     $watchlist = FollowModel::getWatchList($page_owner->getId(), 0, 6, null, $showDeletedPages);
     $data = array();
     // weird.  why is this an array of one element?
     foreach ($watchlist as $unused_id => $item) {
         $pagelist = $item['data'];
         foreach ($pagelist as $page) {
             $data[] = $page;
         }
     }
     // only display  your own page
     if ($page_owner->getId() == $this->wg->User->getId()) {
         $this->follow_all_link = Wikia::specialPageLink('Following', 'oasis-wikiafollowedpages-special-seeall', 'more');
     }
     $this->data = $data;
     $this->max_followed_pages = min(self::MAX_FOLLOWED_PAGES, count($this->data));
 }
 public static function onArticleSaveComplete($article, $user, $revision, $status)
 {
     wfProfileIn(__METHOD__);
     $insertedImages = Wikia::getVar('imageInserts');
     $imageDeletes = Wikia::getVar('imageDeletes');
     $changedImages = $imageDeletes;
     foreach ($insertedImages as $img) {
         $changedImages[$img['il_to']] = true;
     }
     $sendTrackEvent = false;
     foreach ($changedImages as $imageDBName => $dummy) {
         $title = Title::newFromDBkey($imageDBName);
         if (!empty($title)) {
             $mq = new self($title);
             $mq->unsetCache();
             $sendTrackEvent = true;
         }
     }
     // send track event if embed change
     if ($sendTrackEvent) {
         Track::event('embed_change');
     }
     wfProfileOut(__METHOD__);
     return true;
 }
示例#17
0
 /**
  * Show the special page
  *
  * @param $subpage Mixed: parameter passed to the page or null
  */
 public function execute($subpage)
 {
     global $wgRequest, $wgUser, $wgOut;
     $this->setHeaders();
     $hash_key = $wgRequest->getText('key', null);
     $email = $token = $timestamp = null;
     if (!empty($hash_key)) {
         #$hask_key = urldecode ( $hash_key );
         $data = Wikia::verifyUserSecretKey($hash_key, 'sha256');
         error_log("data = " . print_r($data, true));
         if (!empty($data)) {
             $username = isset($data['user']) ? $data['user'] : null;
             $token = isset($data['token']) ? $data['token'] : null;
             $timestamp = isset($data['signature1']) ? $data['signature1'] : null;
             $oUser = User::newFromName($username);
             $email = $oUser->getEmail();
         }
     } else {
         $email = $wgRequest->getText('email', null);
         $token = $wgRequest->getText('token', null);
         $timestamp = $wgRequest->getText('timestamp', null);
     }
     if ($email == null || $token == null || $timestamp == null) {
         #give up now, abandon all hope.
         $wgOut->addWikiMsg('unsubscribe-badaccess');
         return;
     }
     #validate timestamp isnt spoiled (you only have 7 days)
     $timeCutoff = strtotime("7 days ago");
     if ($timestamp <= $timeCutoff) {
         $wgOut->addWikiMsg('unsubscribe-badtime');
         // $wgOut->addHTML("timestamp={$timestamp}\n"); #DEVL (remove before release)
         // $wgOut->addHTML("timeCutoff={$timeCutoff}\n"); #DEVL (remove before release)
         return;
     }
     #generate what the token SHOULD be
     $shouldToken = wfGenerateUnsubToken($email, $timestamp);
     if ($token != $shouldToken) {
         $wgOut->addWikiMsg('unsubscribe-badtoken');
         // $wgOut->addHTML("shouldtoken={$shouldToken}\n"); #DEVL (remove before release)
         return;
     }
     #does the non-blank email they gave us look like an email?
     if (Sanitizer::validateEmail($email) == false) {
         #email wasnt blank, but didnt look like any email
         $wgOut->addWikiMsg('unsubscribe-bademail');
         // $wgOut->addHTML("email={$email}\n"); #DEVL (remove before release)
         return;
     }
     #at this point, the 3 params check out.
     #is this their 2nd pass at this?
     $confirmed = $wgRequest->getBool('confirm', null);
     if ($wgRequest->wasPosted() && $confirmed) {
         #this is the 2nd round, they pushed the button, so do it
         $this->procUnsub($email);
     } else {
         #this is 1st pass, give them a button to push
         $this->showInfo($email, $token, $timestamp);
     }
 }
示例#18
0
 /**
  * This method is called via hook at the end of the request handling
  *
  * Make the list of unique URLs and send them to Fastly via Scribe queue
  *
  * @author macbre
  *
  * @return bool true - it's a hook
  */
 static function onRestInPeace()
 {
     // don't process an empty queue
     if (empty(self::$urls)) {
         return true;
     }
     wfProfileIn(__METHOD__);
     $scribe = WScribeClient::singleton(self::SCRIBE_KEY);
     try {
         wfDebug(sprintf("%s: sending %d unique URLs to the purger (%d items were queued in total)\n", __METHOD__, count(self::$urls), self::$urlsCount));
         foreach (self::$urls as $url => $data) {
             wfDebug(sprintf("%s: %s\n", __METHOD__, $url));
             // send to Scribe queue
             $scribe->send(json_encode($data));
             // debugging data to be sent to both sFlow (for monitoring) and Kibana (for debugging)
             $context = ['url' => $data['url'], 'method' => $data['method']];
             // log purges using SFlow (BAC-1258)
             SFlow::operation('varnish.purge', $context);
             // log purges using Kibana (BAC-1317)
             WikiaLogger::instance()->info('varnish.purge', $context);
         }
     } catch (TException $e) {
         Wikia::log(__METHOD__, 'scribeClient exception', $e->getMessage());
     }
     wfProfileOut(__METHOD__);
     return true;
 }
 public static function onArticleViewAfterParser(Article $article, ParserOutput $parserOutput)
 {
     global $wgCityId, $wgDBname;
     // we collect production data from Oasis only
     /*
     $app = F::app();
     if ( !$app->checkSkin( 'oasis', $app->wg->Skin )
     		|| $app->wg->DevelEnvironment || $app->wg->StagingEnvironment ) {
     	return true;
     }
     */
     if (class_exists('WScribeClient')) {
         try {
             $title = $article->getTitle();
             $fields = array('wikiId' => intval($wgCityId), 'databaseName' => $wgDBname, 'articleId' => $title->getArticleID(), 'namespaceId' => $title->getNamespace(), 'articleTitle' => $title->getText(), 'parserTime' => $parserOutput->getPerformanceStats('time'), 'wikitextSize' => $parserOutput->getPerformanceStats('wikitextSize'), 'htmlSize' => $parserOutput->getPerformanceStats('htmlSize'), 'expFuncCount' => $parserOutput->getPerformanceStats('expFuncCount'), 'nodeCount' => $parserOutput->getPerformanceStats('nodeCount'), 'postExpandSize' => $parserOutput->getPerformanceStats('postExpandSize'), 'tempArgSize' => $parserOutput->getPerformanceStats('tempArgSize'));
             $data = json_encode($fields);
             WScribeClient::singleton(self::SCRIBE_KEY)->send($data);
         } catch (TException $e) {
             Wikia::log(__METHOD__, 'scribeClient exception', $e->getMessage());
         }
     }
     // Logging parser activity for monitoring
     // wiki and article info are sent to logstash anyways so no need to repeat them here
     WikiaLogger::instance()->info("Parser execution", ['parser-time' => round($parserOutput->getPerformanceStats('time') * 1000), 'node-count' => (int) $parserOutput->getPerformanceStats('nodeCount'), 'wikitext-size' => (int) $parserOutput->getPerformanceStats('wikitextSize'), 'skin-name' => RequestContext::getMain()->getSkin()->getSkinName()]);
     return true;
 }
	/**
	 * Render blog listing
	 *
	 * Output HTML just for Oasis which will be hidden by default
	 */
	static function renderBlogListing(&$html, $posts, $aOptions, $sPager = null) {
		wfProfileIn(__METHOD__);

		// macbre: prevent PHP warnings and try to find the reason of them
		if (!is_array($posts)) {
			$url = wfGetCurrentUrl();
			Wikia::log(__METHOD__, false, "\$posts is not an array - {$url['url']}", true);

			wfProfileOut(__METHOD__);
			return true;
		}

		$additionalClass = '';
		if (!empty($aOptions['class'])) {
			$additionalClass = ' '.$aOptions['class'];
		}

		$seeMoreUrl = (isset($aOptions['seemore']) ? $aOptions['seemore'] : "");
		if ($aOptions['type'] == 'box') {
			$html .= F::app()->getView( 'BlogListing', 'Index', array('posts' => $posts, 'blogListingClass' => "WikiaBlogListingBox module $additionalClass", 'title' => $aOptions['title'], 'seeMoreUrl' => $seeMoreUrl))->render();
		} else {
			$html .= F::app()->getView( 'BlogListing', 'Index', array('posts' => $posts, 'blogListingClass' => "WikiaBlogListing$additionalClass", 'title' => $aOptions['title'], 'pager' => $sPager, 'seeMoreUrl' => $seeMoreUrl))->render();
		}

		wfProfileOut(__METHOD__);
		return true;
	}
示例#21
0
 private function getTag()
 {
     $dbname = F::app()->wg->DBname;
     $t = F::app()->wg->Title;
     $title = $t->getText();
     if ($dbname == 'dehauptseite') {
         if (Wikia::isMainPage()) {
             return 'RC_WIKIA_HOME';
         }
         if (strpos($title, 'Mobil') === 0) {
             return 'RC_WIKIA_MOBIL';
         }
         if (in_array($title, array('Videospiele', 'Entertainment', 'Lifestyle'))) {
             return 'RC_WIKIA_START';
         }
         if (WikiaPageType::getPageType() == 'search') {
             return 'RC_WIKIA_SEARCH';
         }
         return 'RC_WIKIA_SVCE';
     }
     if ($dbname == 'de') {
         if ($t->getNamespace() == NS_FORUM) {
             return 'RC_WIKIA_PIN';
         }
         return 'RC_WIKIA_COMMUNITY';
     }
     if (HubService::getComscoreCategory(F::app()->wg->CityId)->cat_name == 'Entertainment') {
         return 'RC_WIKIA_UGCENT';
     }
     return 'RC_WIKIA_UGC';
 }
 /**
  * Load JS needed to display the VideosModule at the bottom of the article content
  * @param OutputPage $out
  * @param string $text
  * @return bool
  */
 public static function onOutputPageBeforeHTML(OutputPage $out, &$text)
 {
     wfProfileIn(__METHOD__);
     // Check if we're on a page where we want to show the Videos Module.
     // If we're not, stop right here.
     if (!self::canShowVideosModule()) {
         wfProfileOut(__METHOD__);
         return true;
     }
     // On file pages, this hook can be called multiple times, so we're going to check if the
     // assets are loaded already before we load them again.
     $app = F::app();
     // Don't do anything if we've already loaded the assets
     if ($app->wg->VideosModuleAssetsLoaded) {
         wfProfileOut(__METHOD__);
         return true;
     }
     // Don't do anything if this is the main page of a site with the VPT enabled
     if ($app->wg->Title->isMainPage() && $app->wg->EnableVideoPageToolExt) {
         wfProfileOut(__METHOD__);
         return true;
     }
     JSMessages::enqueuePackage('VideosModule', JSMessages::EXTERNAL);
     if ($app->checkSkin('venus')) {
         Wikia::addAssetsToOutput('videos_module_venus_js');
         Wikia::addAssetsToOutput('videos_module_venus_scss');
     } else {
         Wikia::addAssetsToOutput('videos_module_js');
     }
     $app->wg->VideosModuleAssetsLoaded = true;
     wfProfileOut(__METHOD__);
     return true;
 }
示例#23
0
 public function buildWhiteList()
 {
     wfProfileIn(__METHOD__);
     $whitelist = array();
     $content = wfMsgForContent(self::SPAM_WHITELIST_TITLE);
     if (wfemptyMsg(self::SPAM_WHITELIST_TITLE, $content)) {
         wfProfileOut(__METHOD__);
         return $whitelist;
     }
     $content = array_filter(array_map('trim', preg_replace('/#.*$/', '', explode("\n", $content))));
     if (!empty($content)) {
         foreach ($content as $regex) {
             $regex = str_replace('/', '\\/', preg_replace('|\\\\*/|', '/', $regex));
             $regex = "/https?:\\/\\/+[a-z0-9_.-]*{$regex}/i";
             wfsuppressWarnings();
             $regexValid = preg_match($regex, '');
             wfrestoreWarnings();
             if ($regexValid === false) {
                 continue;
             }
             $whitelist[] = $regex;
         }
     }
     Wikia::log(__METHOD__, __LINE__, count($whitelist) . ' whitelist entries loaded.');
     wfProfileOut(__METHOD__);
     return $whitelist;
 }
示例#24
0
 function execute($par)
 {
     $this->mName = 'WikiaNewFiles';
     $this->setHeaders();
     Wikia::addAssetsToOutput('upload_photos_dialog_js');
     Wikia::addAssetsToOutput('upload_photos_dialog_scss');
     wfSpecialWikiaNewFiles($par, $this);
 }
示例#25
0
function runIndexer($out, $total_count, $total_num)
{
    global $IP, $wgCityId, $wgWikiaLocalSettingsPath;
    Wikia::log(__METHOD__, 'imageServingIndexer', 'next pack for:' . $wgCityId . " " . $total_count . "/" . $total_num);
    $count = 0;
    $cmd = array("SERVER_ID={$wgCityId}", "php", "{$IP}/maintenance/wikia/imageServingIndexer.php", "--do", "--list " . implode(",", $out), "--conf {$wgWikiaLocalSettingsPath}");
    system(implode(" ", $cmd), $status);
}
示例#26
0
 /**
  * Load Captcha.js on demand when we're getting an instance of a Captcha.
  */
 public static function addCaptchaJS()
 {
     // Make sure we only load FancyCaptcha library once
     if (!\F::app()->wg->CaptchaLibraryLoaded) {
         \Wikia::addAssetsToOutput('captcha_js');
         \F::app()->wg->CaptchaLibraryLoaded = true;
     }
 }
示例#27
0
 /**
  * Add JS module to the output
  * @param \OutputPage $out An output object passed from a hook
  * @return bool
  */
 public static function onBeforePageDisplay(\OutputPage $out)
 {
     // use resource loader for i18n messages in JS
     $out->addModules('ext.cookiePolicyMessages');
     // use AssetsManager for script loading to avoid race conditions (SOC-528)
     \Wikia::addAssetsToOutput('cookie_policy_js');
     return true;
 }
示例#28
0
 public function execute($subpage)
 {
     global $wgOut, $wgRequest, $wgCookiePrefix;
     wfProfileIn(__METHOD__);
     $this->mRequest = RequestContext::getMain()->getRequest();
     $this->mOut = RequestContext::getMain()->getOutput();
     $this->setHeaders();
     $this->mTitle = SpecialPage::getTitleFor("Datacenter");
     /**
      * if posted change cookie value
      */
     if ($this->mRequest->wasPosted()) {
         $val = $this->mRequest->getVal("iowacookie", 0);
         if ($val == 2) {
             $this->mOut->addHTML(Wikia::successbox("cookie set to sjc"));
             $this->mRequest->response()->setcookie($this->mCookieName, "sjc");
             $this->mCookie = "sjc";
         } elseif ($val == 1) {
             $this->mOut->addHTML(Wikia::successbox("cookie set to iowa"));
             $this->mRequest->response()->setcookie($this->mCookieName, "iowa");
             $this->mCookie = "iowa";
         } elseif ($val == 3) {
             $this->mOut->addHTML(Wikia::successbox("cookie set to ash"));
             $this->mRequest->response()->setcookie($this->mCookieName, "ash");
             $this->mCookie = "ash";
         } elseif ($val == 4) {
             $this->mOut->addHTML(Wikia::successbox("cookie set to closest"));
             $this->mRequest->response()->setcookie($this->mCookieName, "closest");
             $this->mCookie = "closest";
         } else {
             $this->mOut->addHTML(Wikia::successbox("cookie removed"));
             $this->mRequest->response()->setcookie($this->mCookieName, "sjc", 1);
             $this->mCookie = false;
         }
     } else {
         /**
          * show current value of cookie
          */
         if (isset($_COOKIE[$wgCookiePrefix . $this->mCookieName])) {
             $this->mCookie = $_COOKIE[$wgCookiePrefix . $this->mCookieName];
         }
     }
     $this->mOut->addHTML("Current value of cookie {$wgCookiePrefix}{$this->mCookieName}: <em>" . ($this->mCookie ? $this->mCookie : "not set") . "</em>");
     /**
      * show input chooser
      */
     $this->mOut->addHTML(Xml::openElement("form", array("action" => $this->mTitle->getFullURL(), "method" => "post")));
     $select = new XMLSelect("iowacookie", "iowacookie");
     $select->addOption("Switch to the closest", 4);
     $select->addOption("Switch to San Jose", 2);
     $select->addOption("Switch to Iowa", 1);
     $select->addOption("Switch to Ashburn", 3);
     $select->addOption("Remove preferences", 0);
     $this->mOut->addHTML($select->getHTML());
     $this->mOut->addHTML(Xml::submitButton("submit"));
     $this->mOut->addHTML(Xml::closeElement("form"));
     wfProfileOut(__METHOD__);
 }
    /**
     * Just render some simple 404 page
     */
    public function doRender404()
    {
        global $wgOut, $wgContLang, $wgCanonicalNamespaceNames;
        /**
         * check, maybe we have article with that title, if yes 301redirect to
         * this article
         */
        $uri = $_SERVER['REQUEST_URI'];
        if (!preg_match('!^https?://!', $uri)) {
            $uri = 'http://unused' . $uri;
        }
        $uri = substr(parse_url($uri, PHP_URL_PATH), 1);
        Wikia::log(__METHOD__, false, isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "[no referer]");
        $title = $wgContLang->ucfirst(urldecode(ltrim($uri, "/")));
        $namespace = NS_MAIN;
        /**
         * first check if title is in namespace other than main
         */
        $parts = explode(":", $title, 2);
        if (count($parts) == 2) {
            foreach ($wgCanonicalNamespaceNames as $id => $name) {
                $translated = $wgContLang->getNsText($id);
                if (strtolower($translated) === strtolower($parts[0]) || strtolower($name) === strtolower($parts[0])) {
                    $namespace = $id;
                    $title = $parts[1];
                    break;
                }
            }
        }
        /**
         * create title from parts
         */
        $oTitle = Title::newFromText($title, $namespace);
        if (!is_null($oTitle)) {
            if ($namespace == NS_SPECIAL || $namespace == NS_MEDIA) {
                /**
                 * these namespaces are special and don't have articles
                 */
                header("X-Redirected-By: Our404Handler");
                header(sprintf("Location: %s", $oTitle->getFullURL()), true, 301);
                exit(0);
            } else {
                $oArticle = new Article($oTitle);
                if ($oArticle->exists()) {
                    header("X-Redirected-By: Our404Handler");
                    header(sprintf("Location: %s", $oArticle->getTitle()->getFullURL()), true, 301);
                    exit(0);
                }
            }
        }
        /**
         * but if doesn't exist, we eventually show 404page
         */
        $wgOut->setStatusCode(404);
        $info = wfMsgForContent('message404', $uri, urldecode($title));
        $wgOut->addHTML('<h2>' . wfMsg('our404handler-oops') . '</h2>
						<div>' . $wgOut->parse($info) . '</div>');
    }
/**
 * @param Array $tabs
 * @param $namespace
 * @param $userName
 * @return bool
 */
function efUserManagementPanelAddTab(&$tabs, $namespace, $userName)
{
    global $wgTitle, $wgUser;
    if (!$wgUser->isAllowed('usermanagement')) {
        return true;
    }
    $tabs[] = array('link' => Wikia::link(SpecialPage::getTitleFor('UserManagement/' . $userName), wfMsg('usermanagement-tab-label')), 'selected' => $wgTitle->isSpecial('UserManagement'), 'data-id' => 'usermanagment');
    return true;
}