/**
  * Prepares DataExtension objects data from a city_cat_mapping record
  * @param  int $iCityId  A wiki's ID
  * @return array         An array with city_cat_mapping DataExtension objects data in a valid format
  */
 public function prepareCityCatMappingDataExtensionForCreate($iCityId)
 {
     $aCityCatMappingDataExtension = [];
     $aCustomerKeys = $this->getCustomerKeys();
     $oWikiFactoryHub = new \WikiFactoryHub();
     $aCategories = $oWikiFactoryHub->getWikiCategories($iCityId);
     $aCityCatMappingDataExtension['DataExtension'] = [];
     foreach ($aCategories as $aCategory) {
         $aCityCatMappingDataExtension['DataExtension'][] = ['CustomerKey' => $aCustomerKeys['city_cat_mapping'], 'Properties' => ['city_id' => $iCityId, 'cat_id' => $aCategory['cat_id']]];
     }
     return $aCityCatMappingDataExtension;
 }
Esempio n. 2
0
 /**
  * getInstance
  *
  * get singleton instance of class
  *
  * @access public
  * @author Krzysztof Krzyżaniak <*****@*****.**>
  *
  * @return WikiFactoryHub object
  */
 public static function getInstance()
 {
     if (self::$mInstance === false) {
         self::$mInstance = new WikiFactoryHub();
     }
     return self::$mInstance;
 }
 /**
  * @author Michał Roszka <*****@*****.**>
  * 
  * This method is most likely to be removed. I created it so I can continue
  * styling the modal window for Gaming Calendar without hardcoding HTML anywhere.
  */
 public function getModalLayout()
 {
     global $wgCityId;
     $catName = WikiFactoryHub::getInstance()->getCategoryName($wgCityId);
     $this->setVal('calendarHeading', $this->wf->msgForContent('gamingcalendar-heading', $catName));
     $this->setVal('wgBlankImgUrl', $this->wg->BlankImgUrl);
 }
 /**
  * Main method for displaying hub pages
  */
 public function index()
 {
     global $wgCityId;
     $wikiFactoryHub = WikiFactoryHub::getInstance();
     $verticalId = $wikiFactoryHub->getVerticalId($wgCityId);
     $currentHub = '';
     $allVerticals = $wikiFactoryHub->getAllVerticals();
     if (isset($allVerticals[$verticalId]['short'])) {
         $currentHub = $allVerticals[$verticalId]['short'];
     }
     $this->setVal('currentHub', $currentHub);
     if (!$this->checkAccess()) {
         $titleText = $this->getContext()->getTitle()->getText();
         $titleTextSplit = explode('/', $titleText);
         $this->hubUrl = $titleTextSplit[0];
         $this->app->wg->Out->setStatusCode(404);
         $this->overrideTemplate('404');
         return;
     }
     $editHubModel = new EditHubModel();
     $this->modules = array();
     foreach ($editHubModel->getModulesIds() as $moduleId) {
         $this->modules[$moduleId] = $this->renderModule($editHubModel, $moduleId, $editHubModel->getNotTranslatedModuleName($moduleId));
     }
     $this->response->addAsset('wikiahubs_v3');
     $this->response->addAsset('wikiahubs_v3_modal');
     $this->response->addAsset('wikiahubs_v3_scss');
     $this->response->addAsset('wikiahubs_v3_scss_mobile');
     $this->wg->Out->addJsConfigVars(['wgWikiaHubsVerticalId' => $this->verticalId]);
     if (F::app()->checkSkin('wikiamobile')) {
         $this->overrideTemplate('wikiamobileindex');
     }
 }
	/**
	 * @author Inez Korczynski <*****@*****.**>
	 */
	private function getWikiaFooterLinks() {
		wfProfileIn( __METHOD__ );

		global $wgCityId;
		$catId = WikiFactoryHub::getInstance()->getCategoryId( $wgCityId );
		$message_key = 'shared-Oasis-footer-wikia-links';
		$nodes = array();

		if ( !isset( $catId ) || null == ( $lines = getMessageAsArray( $message_key . '-' . $catId ) ) ) {
			if ( null == ( $lines = getMessageAsArray( $message_key ) ) ) {
				wfProfileOut( __METHOD__ );
				return $nodes;
			}
		}

		foreach( $lines as $line ) {
			$depth = strrpos( $line, '*' );
			if( $depth === 0 ) {
				$nodes[] = parseItem( $line );
			}
		}

		wfProfileOut( __METHOD__ );
		return $nodes;
	}
 public static function getLiftiumOptionsScript()
 {
     wfProfileIn(__METHOD__);
     global $wgDBname, $wgTitle, $wgLang, $wgDartCustomKeyValues, $wgCityId;
     // See Liftium.js for documentation on options
     $options = array();
     $options['pubid'] = 999;
     $options['baseUrl'] = '/__varnish_liftium/';
     $options['kv_wgDBname'] = $wgDBname;
     if (is_object($wgTitle)) {
         $options['kv_article_id'] = $wgTitle->getArticleID();
         $options['kv_wpage'] = $wgTitle->getPartialURL();
     }
     $hub = WikiFactoryHub::getInstance();
     $options['kv_Hub'] = $hub->getCategoryName($wgCityId);
     $options['kv_skin'] = RequestContext::getMain()->getSkin()->getSkinName();
     $options['kv_user_lang'] = $wgLang->getCode();
     $options['kv_cont_lang'] = $GLOBALS['wgLanguageCode'];
     $options['kv_isMainPage'] = WikiaPageType::isMainPage();
     $options['kv_page_type'] = WikiaPageType::getPageType();
     $options['geoUrl'] = "http://geoiplookup.wikia.com/";
     if (!empty($wgDartCustomKeyValues)) {
         $options['kv_dart'] = $wgDartCustomKeyValues;
     }
     $options['kv_domain'] = $_SERVER['HTTP_HOST'];
     $options['hasMoreCalls'] = true;
     $options['isCalledAfterOnload'] = true;
     $options['maxLoadDelay'] = 6000;
     $js = "LiftiumOptions = " . json_encode($options) . ";\n";
     $out = "\n<!-- Liftium options -->\n";
     $out .= Html::inlineScript($js) . "\n";
     wfProfileOut(__METHOD__);
     return $out;
 }
 /**
  * Hooks that export wiki vertical and categories on frontend
  *
  * @param Array $vars - (reference) js variables
  * @param Array $scripts - (reference) js scripts
  * @param Skin $skin - skins
  * @return Boolean True - to continue hooks execution
  */
 public static function onWikiaSkinTopScripts(&$vars, &$scripts, $skin)
 {
     global $wgCityId;
     $wikiFactoryHub = WikiFactoryHub::getInstance();
     $vars['wgWikiVertical'] = $wikiFactoryHub->getWikiVertical($wgCityId)['short'];
     $vars['wgWikiCategories'] = $wikiFactoryHub->getWikiCategoryNames($wgCityId);
     return true;
 }
 /**
  * @deprecated
  * @return array
  */
 public static function getCachedCategory()
 {
     global $wgCityId;
     wfProfileIn(__METHOD__);
     $hub = WikiFactoryHub::getInstance();
     $cat = array('id' => $hub->getCategoryId($wgCityId), 'short' => $hub->getCategoryShort($wgCityId));
     wfProfileOut(__METHOD__);
     return $cat;
 }
 private function getVerticalShortName()
 {
     global $wgCityId;
     $wikiVertical = WikiFactoryHub::getInstance()->getWikiVertical($wgCityId);
     if ($wikiVertical['id']) {
         return $wikiVertical['short'];
     }
     return null;
 }
 public function index()
 {
     global $wgSuppressWikiHeader, $wgSuppressPageHeader, $wgSuppressFooter, $wgSuppressAds, $wgSuppressToolbar, $fbOnLoginJsOverride, $wgRequest, $wgUser;
     wfProfileIn(__METHOD__);
     // hide some default oasis UI things
     $wgSuppressWikiHeader = true;
     $wgSuppressPageHeader = true;
     $wgSuppressFooter = false;
     $wgSuppressAds = true;
     $wgSuppressToolbar = true;
     // store the fact we're on CNW
     F::app()->wg->atCreateNewWikiPage = true;
     // reuiqred for FB Connect to work
     $this->response->addAsset('extensions/wikia/UserLogin/js/UserLoginFacebookPageInit.js');
     // fbconnected means user has gone through step 2 to login via facebook.
     // Therefore, we need to reload some values and start at the step after signup/login
     $fbconnected = $wgRequest->getVal('fbconnected');
     $fbreturn = $wgRequest->getVal('fbreturn');
     if (!empty($fbconnected) && $fbconnected === '1' || !empty($fbreturn) && $fbreturn === '1') {
         $this->LoadState();
         $this->currentStep = 'DescWiki';
     } else {
         $this->currentStep = '';
     }
     // form field values
     $hubs = WikiFactoryHub::getInstance();
     $this->aCategories = $hubs->getCategories();
     $this->aTopLanguages = explode(',', wfMsg('autocreatewiki-language-top-list'));
     $languages = wfGetFixedLanguageNames();
     asort($languages);
     $this->aLanguages = $languages;
     $useLang = $wgRequest->getVal('uselang', $wgUser->getOption('language'));
     // falling back to english (BugId:3538)
     if (!array_key_exists($useLang, $this->aLanguages)) {
         $useLang = 'en';
     }
     $params['wikiLanguage'] = empty($useLang) ? $this->wg->LanguageCode : $useLang;
     // precedence: selected form field, uselang, default wiki lang
     // facebook callback overwrite on login.  CreateNewWiki re-uses current login stuff.
     $fbOnLoginJsOverride = 'WikiBuilder.fbLoginCallback();';
     // export info if user is logged in
     $this->isUserLoggedIn = $wgUser->isLoggedIn();
     // remove wikia plus for now for all languages
     $this->skipWikiaPlus = true;
     $this->keys = CreateNewWikiObfuscate::generateValidSeeds();
     $_SESSION['cnw-answer'] = CreateNewWikiObfuscate::generateAnswer($this->keys);
     // prefill
     $params['wikiName'] = $wgRequest->getVal('wikiName', '');
     $params['wikiDomain'] = $wgRequest->getVal('wikiDomain', '');
     $this->params = $params;
     $this->signupUrl = '';
     if (!empty($this->wg->EnableUserLoginExt)) {
         $signupTitle = Title::newFromText('UserSignup', NS_SPECIAL);
         $this->signupUrl = $signupTitle->getFullURL();
     }
     wfProfileOut(__METHOD__);
 }
Esempio n. 11
0
 protected function appendCategory($property)
 {
     $oHub = WikiFactoryHub::getInstance();
     $catId = $oHub->getCategoryId($this->cityId);
     $catName = $oHub->getCategoryName($this->cityId);
     $data = array("catid" => $catId, "catname" => $catName);
     $result = $this->getResult();
     $result->setIndexedTagName($data, $property);
     $result->addValue('query', $property, $data);
 }
Esempio n. 12
0
 public static function loadData($forceRefresh = false, $forceLanguage = null)
 {
     global $wgMemc, $wgStatsDB, $wgContLang, $wgExternalSharedDB, $wgStatsDBEnabled;
     wfProfileIn(__METHOD__);
     self::$mLanguage = !empty($forceLanguage) ? $forceLanguage : $wgContLang->getCode();
     $cacheKey = self::CACHE_KEY_TOKEN . ':' . strtoupper(self::$mLanguage);
     self::$mData = $wgMemc->get($cacheKey);
     if (empty(self::$mData) || $forceRefresh) {
         self::$mData = array();
         $wikisIDs = array();
         // get all the active wikis selected by the sales team
         $wikiFactoryRecommended = WikiFactory::getVarByName(self::WF_VAR_NAME, null);
         self::$mData['recommended'] = array();
         if (!empty($wikiFactoryRecommended) && !empty($wikiFactoryRecommended->cv_variable_id)) {
             $dbr = WikiFactory::db(DB_SLAVE);
             $res = $dbr->select(array('city_list', 'city_variables'), 'city_id', array('city_id = cv_city_id', 'city_public' => 1, 'city_lang' => self::$mLanguage, 'cv_variable_id' => $wikiFactoryRecommended->cv_variable_id, 'cv_value' => serialize(true)));
             while ($row = $dbr->fetchObject($res)) {
                 self::$mData['recommended'][] = $row->city_id;
             }
             $dbr->freeResult($res);
         }
         $counter = 0;
         self::$mData['hubs'] = array();
         if (!empty($wgStatsDBEnabled)) {
             $langs = array(self::$mLanguage);
             $wikis = DataMartService::getTopWikisByPageviews(DataMartService::PERIOD_ID_MONTHLY, 200, $langs, null, 1);
             $minPageViews = isset(self::$pageviewsLimits[self::$mLanguage]) ? self::$pageviewsLimits[self::$mLanguage] : self::$pageviewsLimits['default'];
             foreach ($wikis as $wikiID => $pvCount) {
                 if ($pvCount >= $minPageViews) {
                     $hub = WikiFactoryHub::getInstance();
                     $cat_id = $hub->getCategoryId($wikiID);
                     if (!$cat_id) {
                         continue;
                     }
                     if (!isset(self::$mData['hubs'][$cat_id])) {
                         self::$mData['hubs'][$cat_id] = array();
                     }
                     self::$mData['hubs'][$cat_id][] = $wikiID;
                     $counter++;
                 }
             }
         }
         // removing entries from hubs that have a match in recommended
         if (!empty(self::$mData['recommended']) && !empty(self::$mData['hubs'])) {
             $counter = 0;
             foreach (self::$mData['hubs'] as $hubID => &$item) {
                 $item = array_diff($item, self::$mData['recommended']);
                 $counter += count($item);
             }
         }
         self::$mData['total'] = $counter;
         $wgMemc->set($cacheKey, self::$mData, 3600 * self::CACHE_EXPIRY);
     }
     wfProfileOut(__METHOD__);
 }
 /**
  * Get wiki vertical
  * @return string - wiki vertical
  */
 public function getWikiVertical()
 {
     wfProfileIn(__METHOD__);
     $verticalId = WikiFactoryHub::getInstance()->getVerticalId($this->wg->CityId);
     if (empty(self::$verticals[$verticalId])) {
         $verticalId = WikiFactoryHub::VERTICAL_ID_OTHER;
     }
     $name = self::$verticals[$verticalId];
     wfProfileOut(__METHOD__);
     return $name;
 }
 public function executeIndex()
 {
     global $wgCityId;
     wfProfileIn(__METHOD__);
     // load assets
     $extPath = F::app()->wg->extensionsPath;
     F::app()->wg->out->addScript("<script src=\"{$extPath}/wikia/GamingCalendar/js/GamingCalendar.js\"></script>");
     F::app()->wg->out->addStyle(AssetsManager::getInstance()->getSassCommonURL('extensions/wikia/GamingCalendar/css/GamingCalendar.scss'));
     $catName = WikiFactoryHub::getInstance()->getCategoryName($wgCityId);
     $this->moduleTitle = F::app()->wf->msgForContent('gamingcalendar-heading', $catName);
     wfProfileOut(__METHOD__);
 }
 /**
  * Get wiki vertical
  *
  * @return string - wiki vertical
  */
 protected function initCategories()
 {
     $name = '';
     $categoryId = \WikiFactoryHub::getInstance()->getCategoryId($this->wg->CityId);
     if (!empty($categoryId)) {
         // get vertical id
         $verticalId = \HubService::getCanonicalCategoryId($categoryId);
         if (array_key_exists($verticalId, self::$pageCategories)) {
             $name = self::$pageCategories[$verticalId];
         }
     }
     $this->categories = $name;
 }
Esempio n. 16
0
/**
 * MW1.19 - ResourceLoaderStartUpModule class adds more variables
 * @param array $vars JS variables to be added at the bottom of the page
 * @param OutputPage $out
 * @return bool return true - it's a hook
 */
function wfMakeGlobalVariablesScript(array &$vars, OutputPage $out)
{
    wfProfileIn(__METHOD__);
    global $wgMemc, $wgPrivateTracker, $wgExtensionsPath, $wgArticle, $wgSitename, $wgDisableAnonymousEditing, $wgCityId, $wgGroupPermissions, $wgBlankImgUrl, $wgCookieDomain, $wgCookiePath, $wgResourceBasePath;
    $skin = $out->getSkin();
    $title = $out->getTitle();
    // FIXME: This needs to be converted to getVerticalId when the data is available (PLATFORM-267)
    $hubService = WikiFactoryHub::getInstance();
    $catId = $hubService->getCategoryId($wgCityId);
    if (isset($catId)) {
        $vars['wgCatId'] = $catId;
    } else {
        $vars['wgCatId'] = 0;
    }
    $vars['wgBlankImgUrl'] = $wgBlankImgUrl;
    if (!empty($wgPrivateTracker)) {
        $vars['wgPrivateTracker'] = true;
    }
    // TODO: use wgMainPageTitle instead?
    $vars['wgMainpage'] = wfMsgForContent('mainpage');
    if (Wikia::isMainPage()) {
        $vars['wgIsMainpage'] = true;
    }
    if (Wikia::isContentNamespace()) {
        $vars['wgIsContentNamespace'] = true;
    }
    // TODO: is this one really needed?
    if (isset($skin->themename)) {
        $vars['themename'] = $skin->themename;
    }
    $vars['wgExtensionsPath'] = $wgExtensionsPath;
    $vars['wgResourceBasePath'] = $wgResourceBasePath;
    $vars['wgSitename'] = $wgSitename;
    // Set the JavaScript variable which is used by AJAX request to make data caching possible - Inez
    $vars['wgMWrevId'] = $wgMemc->get(wfMemcKey('wgMWrevId'));
    // macbre: get revision ID of current article
    if (($title->isContentPage() || $title->isTalkPage()) && !is_null($wgArticle)) {
        $vars['wgRevisionId'] = !empty($wgArticle->mRevision) ? $wgArticle->mRevision->getId() : intval($wgArticle->mLatest);
    }
    // is anon editing disabled?
    if ($wgDisableAnonymousEditing || $wgGroupPermissions['user']['edit'] === false) {
        $vars['wgDisableAnonymousEditing'] = true;
    }
    // moved from Interstitial.php
    $vars['wgCookieDomain'] = $wgCookieDomain;
    $vars['wgCookiePath'] = $wgCookiePath;
    wfProfileOut(__METHOD__);
    return true;
}
 /**
  * @param Array $params
  * @return array
  */
 protected function prepareParameters($params)
 {
     $params['limit'] = $this->getModel()->getWamLimitForHubPage();
     if (!empty($params['ts']) && $params['ts'] >= strtotime(date('d-m-Y'))) {
         $params['ts'] = null;
     }
     if (empty($params['image_height'])) {
         $params['image_height'] = $this->getModel()->getImageHeight();
     }
     if (empty($params['image_width'])) {
         $params['image_width'] = $this->getModel()->getImageWidth();
     }
     if (empty($this->verticalId)) {
         $this->verticalId = WikiFactoryHub::getInstance()->getVerticalId($this->cityId);
     }
     if (empty($this->langCode)) {
         $this->langCode = $this->app->wg->ContLang->getCode();
     }
     return parent::prepareParameters(['wam_day' => $params['ts'], 'vertical_id' => $this->verticalId, 'wiki_lang' => $this->langCode, 'exclude_blacklist' => true, 'fetch_admins' => true, 'fetch_wiki_images' => true, 'limit' => $params['limit'], 'sort_column' => 'wam_index', 'sort_direction' => 'DESC', 'wiki_image_height' => $params['image_height'], 'wiki_image_width' => $params['image_width']]);
 }
 public function getContext(Title $title, $skinName)
 {
     $wrapper = new GlobalStateWrapper(['wgTitle' => $title]);
     $wg = F::app()->wg;
     return $wrapper->wrap(function () use($title, $wg, $skinName) {
         $wikiFactoryHub = WikiFactoryHub::getInstance();
         $hubService = new HubService();
         $adPageTypeService = new AdEngine2PageTypeService();
         $wikiaPageType = new WikiaPageType();
         $sevenOneMediaCombinedUrl = null;
         if (!empty($wg->AdDriverUseSevenOneMedia)) {
             // TODO: implicitly gets the skin from the context!
             $sevenOneMediaCombinedUrl = ResourceLoader::makeCustomURL($wg->Out, ['wikia.ext.adengine.sevenonemedia'], 'scripts');
         }
         $monetizationServiceAds = null;
         if (!empty($wg->AdDriverUseMonetizationService) && !empty($wg->EnableMonetizationModuleExt)) {
             $monetizationServiceAds = F::app()->sendRequest('MonetizationModule', 'index')->getData()['data'];
         }
         $langCode = $title->getPageLanguage()->getCode();
         return ['opts' => $this->filterOutEmptyItems(['adsInContent' => $wg->EnableAdsInContent, 'delayBtf' => $wg->AdDriverDelayBelowTheFold, 'enableAdsInMaps' => $wg->AdDriverEnableAdsInMaps, 'pageType' => $adPageTypeService->getPageType(), 'paidAssetDropConfig' => $wg->PaidAssetDropConfig, 'showAds' => $adPageTypeService->areAdsShowableOnPage(), 'trackSlotState' => $wg->AdDriverTrackState, 'usePostScribe' => $wg->Request->getBool('usepostscribe', false)]), 'targeting' => $this->filterOutEmptyItems(['enablePageCategories' => array_search($langCode, $wg->AdPageLevelCategoryLangs) !== false, 'pageArticleId' => $title->getArticleId(), 'pageIsArticle' => !!$title->getArticleId(), 'pageIsHub' => $wikiaPageType->isWikiaHub(), 'pageName' => $title->getPrefixedDBKey(), 'pageType' => $wikiaPageType->getPageType(), 'sevenOneMediaSub2Site' => $wg->AdDriverSevenOneMediaOverrideSub2Site, 'skin' => $skinName, 'wikiCategory' => $wikiFactoryHub->getCategoryShort($wg->CityId), 'wikiCustomKeyValues' => $wg->DartCustomKeyValues, 'wikiDbName' => $wg->DBname, 'wikiDirectedAtChildren' => $wg->WikiDirectedAtChildrenByFounder || $wg->WikiDirectedAtChildrenByStaff, 'wikiIsCorporate' => $wikiaPageType->isCorporatePage(), 'wikiIsTop1000' => $wg->AdDriverWikiIsTop1000, 'wikiLanguage' => $langCode, 'wikiVertical' => $hubService->getCategoryInfoForCity($wg->CityId)->cat_name]), 'providers' => $this->filterOutEmptyItems(['monetizationService' => $wg->AdDriverUseMonetizationService, 'monetizationServiceAds' => $monetizationServiceAds, 'sevenOneMedia' => $wg->AdDriverUseSevenOneMedia, 'sevenOneMediaCombinedUrl' => $sevenOneMediaCombinedUrl, 'taboola' => $wg->AdDriverUseTaboola]), 'slots' => $this->filterOutEmptyItems(['exitstitial' => $wg->EnableOutboundScreenExt, 'exitstitialRedirectDelay' => $wg->OutboundScreenRedirectDelay, 'invisibleHighImpact' => $wg->AdDriverEnableInvisibleHighImpactSlot]), 'forcedProvider' => $wg->AdDriverForcedProvider];
     });
 }
Esempio n. 19
0
 /**
  * main entry point, create wiki with given parameters
  *
  * @throw CreateWikiException an exception with status of operation set
  */
 public function create()
 {
     global $wgExternalSharedDB, $wgSharedDB, $wgUser;
     $then = microtime(true);
     // Set this flag to ensure that all select operations go against master
     // Slave lag can cause random errors during wiki creation process
     global $wgForceMasterDatabase;
     $wgForceMasterDatabase = true;
     wfProfileIn(__METHOD__);
     if (wfReadOnly()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('DB is read only', self::ERROR_READONLY);
     }
     // check founder
     if ($this->mFounder->isAnon()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Founder is anon', self::ERROR_USER_IN_ANON);
     }
     // check executables
     $status = $this->checkExecutables();
     if ($status != 0) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('checkExecutables() failed', $status);
     }
     // check domains
     $status = $this->checkDomain();
     if ($status != 0) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Check domain failed', $status);
     }
     // prepare all values needed for creating wiki
     $this->prepareValues();
     // prevent domain to be registered more than once
     if (!AutoCreateWiki::lockDomain($this->mDomain)) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Domain name taken', self::ERROR_DOMAIN_NAME_TAKEN);
     }
     // start counting time
     $this->mCurrTime = wfTime();
     // check and create database
     $this->mDBw = wfGetDB(DB_MASTER, array(), $wgExternalSharedDB);
     # central
     ///
     // local database handled is handler to cluster we create new wiki.
     // It doesn't have to be the same like wikifactory cluster or db cluster
     // where Special:CreateWiki exists.
     //
     // @todo do not use hardcoded name, code below is only for test
     //
     // set $activeCluster to false if you want to create wikis on first
     // cluster
     //
     $this->mClusterDB = self::ACTIVE_CLUSTER ? "wikicities_" . self::ACTIVE_CLUSTER : "wikicities";
     $this->mNewWiki->dbw = wfGetDB(DB_MASTER, array(), $this->mClusterDB);
     // database handler, old $dbwTarget
     // check if database is creatable
     // @todo move all database creation checkers to canCreateDatabase
     if (!$this->canCreateDatabase()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('DB exists - ' . $this->mNewWiki->dbname, self::ERROR_DATABASE_ALREADY_EXISTS);
     } else {
         $this->mNewWiki->dbw->query(sprintf("CREATE DATABASE `%s`", $this->mNewWiki->dbname));
         wfDebugLog("createwiki", "Database {$this->mNewWiki->dbname} created\n", true);
     }
     /**
      * create position in wiki.factory
      * (I like sprintf construction, so sue me)
      */
     if (!$this->addToCityList()) {
         wfDebugLog("createwiki", __METHOD__ . ": Cannot set data in city_list table\n", true);
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Cannot add wiki to city_list', self::ERROR_DATABASE_WRITE_TO_CITY_LIST_BROKEN);
     }
     // set new city_id
     $this->mNewWiki->city_id = $this->mDBw->insertId();
     if (empty($this->mNewWiki->city_id)) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Cannot set data in city_list table. city_id is empty after insert', self::ERROR_DATABASE_WIKI_FACTORY_TABLES_BROKEN);
     }
     wfDebugLog("createwiki", __METHOD__ . ": Row added added into city_list table, city_id = {$this->mNewWiki->city_id}\n", true);
     /**
      * add domain and www.domain to the city_domains table
      */
     if (!$this->addToCityDomains()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Cannot set data in city_domains table', self::ERROR_DATABASE_WRITE_TO_CITY_DOMAINS_BROKEN);
     }
     wfDebugLog("createwiki", __METHOD__ . ": Row added into city_domains table, city_id = {$this->mNewWiki->city_id}\n", true);
     /**
      * create image folder
      */
     global $wgEnableSwiftFileBackend;
     if (empty($wgEnableSwiftFileBackend)) {
         wfMkdirParents("{$this->mNewWiki->images_dir}");
         wfDebugLog("createwiki", __METHOD__ . ": Folder {$this->mNewWiki->images_dir} created\n", true);
     }
     // Force initialize uploader user from correct shared db
     $uploader = User::newFromName('CreateWiki script');
     $uploader->getId();
     $oldUser = $wgUser;
     $wgUser = $uploader;
     /**
      * wikifactory variables
      */
     wfDebugLog("createwiki", __METHOD__ . ": Populating city_variables\n", true);
     $this->setWFVariables();
     $tmpSharedDB = $wgSharedDB;
     $wgSharedDB = $this->mNewWiki->dbname;
     $this->mDBw->commit(__METHOD__);
     // commit shared DB changes
     /**
      * we got empty database created, now we have to create tables and
      * populate it with some default values
      */
     wfDebugLog("createwiki", __METHOD__ . ": Creating tables in database\n", true);
     $this->mNewWiki->dbw = wfGetDB(DB_MASTER, array(), $this->mNewWiki->dbname);
     if (!$this->createTables()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Creating tables not finished', self::ERROR_SQL_FILE_BROKEN);
     }
     /**
      * import language starter
      */
     if (!$this->importStarter()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Starter import failed', self::ERROR_SQL_FILE_BROKEN);
     }
     /**
      * making the wiki founder a sysop/bureaucrat
      */
     wfDebugLog("createwiki", __METHOD__ . ": Create user sysop/bureaucrat for user: {$this->mNewWiki->founderId} \n", true);
     if (!$this->addUserToGroups()) {
         wfDebugLog("createwiki", __METHOD__ . ": Create user sysop/bureaucrat for user: {$this->mNewWiki->founderId} failed \n", true);
     }
     /**
      * init site_stats table (add empty row)
      */
     $this->mNewWiki->dbw->insert("site_stats", array("ss_row_id" => "1"), __METHOD__);
     /**
      * copy default logo
      */
     $res = ImagesService::uploadImageFromUrl(self::CREATEWIKI_LOGO, (object) ['name' => 'Wiki.png'], $uploader);
     if ($res['status'] === true) {
         wfDebugLog("createwiki", __METHOD__ . ": Default logo has been uploaded\n", true);
     } else {
         wfDebugLog("createwiki", __METHOD__ . ": Default logo has not been uploaded - " . print_r($res['errors'], true) . "\n", true);
     }
     /**
      * destroy connection to newly created database
      */
     $this->waitForSlaves(__METHOD__);
     $wgSharedDB = $tmpSharedDB;
     $oHub = WikiFactoryHub::getInstance();
     $oHub->setVertical($this->mNewWiki->city_id, $this->mNewWiki->vertical, "CW Setup");
     wfDebugLog("createwiki", __METHOD__ . ": Wiki added to the vertical: {$this->mNewWiki->vertical} \n", true);
     for ($i = 0; $i < count($this->mNewWiki->categories); $i++) {
         $oHub->addCategory($this->mNewWiki->city_id, $this->mNewWiki->categories[$i]);
         wfDebugLog("createwiki", __METHOD__ . ": Wiki added to the category: {$this->mNewWiki->categories[$i]} \n", true);
     }
     /**
      * define wiki type
      */
     $wiki_type = 'default';
     /**
      * modify variables
      */
     global $wgUniversalCreationVariables;
     if (!empty($wgUniversalCreationVariables) && !empty($wiki_type) && isset($wgUniversalCreationVariables[$wiki_type])) {
         $this->addCustomSettings(0, $wgUniversalCreationVariables[$wiki_type], "universal");
         wfDebugLog("createwiki", __METHOD__ . ": Custom settings added for wiki_type: {$wiki_type} \n", true);
     }
     /**
      * set variables per language
      */
     global $wgLangCreationVariables;
     $langCreationVar = isset($wgLangCreationVariables[$wiki_type]) ? $wgLangCreationVariables[$wiki_type] : $wgLangCreationVariables;
     $this->addCustomSettings($this->mNewWiki->language, $langCreationVar, "language");
     wfDebugLog("createwiki", __METHOD__ . ": Custom settings added for wiki_type: {$wiki_type} and language: {$this->mNewWiki->language} \n", true);
     /**
      * set tags per language and per hub
      * @FIXME the switch is !@#$ creazy, but I didn't find a core function
      */
     $tags = new WikiFactoryTags($this->mNewWiki->city_id);
     $langTag = $this->mNewWiki->language;
     if ($langTag !== 'en') {
         switch ($langTag) {
             case 'pt-br':
                 $langTag = 'pt';
                 break;
             case 'zh-tw':
             case 'zh-hk':
             case 'zh-clas':
             case 'zh-class':
             case 'zh-classical':
             case 'zh-cn':
             case 'zh-hans':
             case 'zh-hant':
             case 'zh-min-':
             case 'zh-min-n':
             case 'zh-mo':
             case 'zh-sg':
             case 'zh-yue':
                 $langTag = 'zh';
                 break;
         }
         $tags->addTagsByName($langTag);
     }
     /**
      * move main page -> this code exists in CreateWikiLocalJob - so it is not needed anymore
      */
     /**
      * Unset database from mNewWiki, because database objects cannot be serialized from MW1.19
      */
     unset($this->mNewWiki->dbw);
     // Restore wgUser
     $wgUser = $oldUser;
     unset($oldUser);
     /**
      * Schedule an async task
      */
     $creationTask = new \Wikia\Tasks\Tasks\CreateNewWikiTask();
     $job_params = new stdClass();
     foreach ($this->mNewWiki as $id => $value) {
         if (!is_object($value)) {
             $job_params->{$id} = $value;
         }
     }
     // BugId:15644 - I need to pass this to CreateWikiLocalJob::changeStarterContributions
     $job_params->sDbStarter = $this->sDbStarter;
     $task_id = (new \Wikia\Tasks\AsyncTaskList())->wikiId($this->mNewWiki->city_id)->prioritize()->add($creationTask->call('postCreationSetup', $job_params))->add($creationTask->call('maintenance', rtrim($this->mNewWiki->url, "/")))->queue();
     wfDebugLog("createwiki", __METHOD__ . ": Local maintenance task added as {$task_id}\n", true);
     $this->info(__METHOD__ . ': done', ['task_id' => $task_id, 'took' => microtime(true) - $then]);
     wfProfileOut(__METHOD__);
 }
Esempio n. 20
0
 /**
  * Finds wikis which name, domain or topic match a string optionally filtering by vertical (hub) and/or language
  *
  * @param string $string search term
  * @param mixed $hub [OPTIONAL] The name of the vertical as a string(e.g. Gaming, Entertainment,
  * Lifestyle, etc.) or it's related numeric ID to use as a filter
  * @param string $lang [OPTIONAL] The language code (e.g. en, de, fr, es, it, etc.) to use as a filter
  * @param bool [OPTIONAL] Include the domain name in the search, defaults to false
  *
  * @return array A collection of results with id, name, hub, language, topic, domain
  */
 public function getByString($string, array $langs = null, $hub = null, $includeDomain = false)
 {
     wfProfileIn(__METHOD__);
     $wikis = [];
     if (!empty($string)) {
         $hubId = null;
         if (!empty($hub)) {
             if (is_string($hub)) {
                 //this has it's own memcache layer (24h)
                 $hubData = WikiFactoryHub::getInstance()->getCategoryByName($hub);
                 if (is_array($hubData)) {
                     $hubId = $hubData['id'];
                 }
             } elseif (is_integer($hub)) {
                 $hubId = $hub;
             }
         }
         if (empty($hub) || !empty($hub) && is_integer($hubId)) {
             $cacheKey = wfSharedMemcKey(__METHOD__, self::CACHE_VERSION, md5(strtolower($string)), $hubId, implode(',', $langs), !empty($includeDomain) ? 'includeDomain' : null);
             $wikis = $this->app->wg->Memc->get($cacheKey);
             if (!is_array($wikis)) {
                 $wikis = [];
                 $db = $this->getSharedDB();
                 $string = $db->addQuotes("%{$string}%");
                 $varId = (int) WikiFactory::getVarByName('wgWikiTopics', null)->cv_variable_id;
                 $tables = array('city_list', 'city_variables');
                 $clause = array("city_list.city_title LIKE {$string}");
                 if (!empty($includeDomain)) {
                     $clause[] = "city_list.city_url LIKE {$string}";
                 }
                 $clause[] = "city_variables.cv_value LIKE {$string}";
                 $where = array('city_list.city_public' => 1, '(' . implode(' OR ', $clause) . ')');
                 $join = array('city_variables' => array('LEFT JOIN', "city_list.city_id = city_variables.cv_city_id AND city_variables.cv_variable_id = {$varId}"));
                 if (!empty($langs)) {
                     $langs = $db->makeList($langs);
                     $where[] = 'city_list.city_lang IN (' . $langs . ')';
                 }
                 if (is_integer($hubId)) {
                     $tables[] = 'city_cat_mapping';
                     $where['city_cat_mapping.cat_id'] = $hubId;
                     $join['city_cat_mapping'] = array('LEFT JOIN', 'city_list.city_id = city_cat_mapping.city_id');
                 }
                 $rows = $db->select($tables, array('city_list.city_id', 'city_list.city_lang', 'city_list.city_title', 'city_variables.cv_value'), $where, __METHOD__, array('LIMIT' => self::MAX_WIKI_RESULTS), $join);
                 while ($row = $db->fetchObject($rows)) {
                     $wikis[] = array('id' => $row->city_id, 'name' => $row->city_title, 'hub' => !empty($hub) && is_string($hub) ? $hub : $this->getVerticalByWikiId($row->city_id), 'language' => $row->city_lang, 'topic' => !empty($row->cv_value) ? unserialize($row->cv_value) : null, 'domain' => $this->getDomainByWikiId($row->city_id));
                 }
                 $this->wg->Memc->set($cacheKey, $wikis, 43200);
             }
         }
     }
     wfProfileOut(__METHOD__);
     return $wikis;
 }
Esempio n. 21
0
 function getPageHeader()
 {
     global $wgScript, $wgRequest;
     $self = $this->getTitle();
     $this->getLangs();
     $hubs = WikiFactoryHub::getInstance();
     // fixme, this logic (and the form) need to be split into Verticals and Categories
     $hubs = $hubs->getAllCategories();
     $this->hubs = array(0 => 'All');
     if (!empty($hubs)) {
         foreach ($hubs as $id => $hub_options) {
             $this->hubs[$id] = $hub_options['name'];
         }
     }
     # Form tag
     $out = Xml::openElement('form', array('method' => 'get', 'action' => $wgScript)) . '<fieldset>' . Xml::element('legend', array(), wfMsg('newwikis'));
     $out .= Html::hidden('title', $self->getPrefixedDbKey());
     # First character in title name
     $out .= Xml::label(wfMsg('newwikisstart'), 'offset') . ' ' . Xml::input('start', 20, $this->firstChar, array('id' => 'offset')) . ' ';
     # Group drop-down list
     $out .= Xml::label(wfMsg('yourlanguage'), 'language') . ' ' . Xml::openElement('select', array('name' => 'language', 'id' => 'language')) . Xml::option(wfMsg('autocreatewiki-language-all'), '');
     $out .= Xml::element('optgroup', array('label' => wfMsg('autocreatewiki-language-top', count($this->mTopLanguages))), '');
     foreach ($this->mTopLanguages as $sLang) {
         $out .= Xml::option($this->mLanguages[$sLang], $sLang, $sLang == $this->lang);
     }
     $out .= Xml::element('optgroup', array('label' => wfMsg('autocreatewiki-language-all')), '');
     foreach ($this->mLanguages as $sLang => $sLangName) {
         $out .= Xml::option($sLangName, $sLang, $sLang == $this->lang);
     }
     $out .= Xml::closeElement('select');
     $out .= '&nbsp;';
     $out .= Xml::label(wfMsg('autocreatewiki-category-label'), 'hub') . ' ';
     $out .= Xml::openElement('select', array('name' => 'hub', 'id' => 'hub'));
     foreach ($this->hubs as $sHub => $sHubName) {
         $out .= Xml::option($sHubName, $sHub, $sHub == $this->hub);
     }
     $out .= Xml::closeElement('select');
     $out .= '<br />';
     # Submit button and form bottom
     if ($this->mLimit) {
         $out .= Html::hidden('limit', $this->mLimit);
     }
     $out .= Xml::submitButton(wfMsg('allpagessubmit'));
     $out .= '</fieldset>' . Xml::closeElement('form');
     return $out;
 }
Esempio n. 22
0
 public static function checkCategoryIsCorrect($sValue)
 {
     wfProfileIn(__METHOD__);
     $hubs = WikiFactoryHub::getInstance();
     $aCategories = $hubs->getCategories();
     $sResponse = "";
     if ($sValue == "") {
         $sResponse = wfMsg('autocreatewiki-empty-category');
     } elseif (!empty($aCategories) && !in_array($sValue, array_keys($aCategories))) {
         $sResponse = wfMsg('autocreatewiki-invalid-category');
     }
     wfProfileOut(__METHOD__);
     return $sResponse;
 }
Esempio n. 23
0
 public function getCategoriesRecords()
 {
     global $wgUser, $wgLang, $wgExternalSharedDB;
     wfProfileIn(__METHOD__);
     /* db */
     $dbr = wfGetDB(DB_SLAVE, "stats", $wgExternalSharedDB);
     /* check params */
     $this->mLimit = !empty($this->axLimit) ? intval($this->axLimit) : self::LIMIT;
     $this->mOffset = !empty($this->axOffset) ? intval($this->axOffset) : 0;
     #----
     $where = array("ccm.city_id = cl.city_id");
     $what = "IFNULL(date_format(cl.city_created, '%Y-%m'), '0000-00')";
     if (!empty($this->axDaily)) {
         $what = "IFNULL(date_format(cl.city_created, '%Y-%m-%d'), '0000-00-00')";
     }
     $hubs = WikiFactoryHub::getInstance();
     $aCategories = $hubs->getAllCategories(false, true);
     $AWCMetrics = array();
     $AWCCitiesCount = 0;
     $oRow = $dbr->selectRow("( select distinct({$what}) from city_list cl ) as c", array(" count(*) as cnt "), array(), __METHOD__);
     if ($oRow) {
         $AWCCitiesCount = $oRow->cnt;
     }
     if ($AWCCitiesCount > 0) {
         $oRes = $dbr->select("city_cat_mapping as ccm, city_list as cl", array("{$what} as row_date, count(*) as cnt"), $where, __METHOD__, array('GROUP BY' => 'row_date', 'ORDER BY' => 'row_date DESC', 'LIMIT' => $this->mLimit, 'OFFSET' => $this->mOffset));
         while ($oRow = $dbr->fetchObject($oRes)) {
             $firstDate = $lastDate = '';
             if (empty($this->axDaily)) {
                 $sDate = $oRow->row_date == '0000-00' ? '1970-01' : $oRow->row_date;
                 $dateArr = explode('-', $sDate);
                 $stamp = mktime(23, 59, 59, $dateArr[1], 1, $dateArr[0]);
                 $out = $wgLang->sprintfDate("M Y", wfTimestamp(TS_MW, $stamp));
                 $firstDate = sprintf("%s-01 00:00:00", $sDate);
                 $lastDate = sprintf("%s 23:59:59 \n\n", date("Y-m-d", strtotime('-1 second', strtotime('+1 month', strtotime($dateArr[0] . '-' . $dateArr[1] . '-01 00:00:00')))));
             } else {
                 $sDate = $oRow->row_date == '0000-00-00' ? '1970-01-01' : $oRow->row_date;
                 $dateArr = explode('-', $sDate);
                 $stamp = mktime(23, 59, 59, $dateArr[1], $dateArr[2], $dateArr[0]);
                 $out = $wgLang->date(wfTimestamp(TS_MW, $stamp), true);
                 $firstDate = sprintf("%s 00:00:00", $sDate);
                 $lastDate = sprintf("%s 23:59:59", $sDate);
             }
             $AWCMetrics[$out] = array('count' => $oRow->cnt, 'hubs' => array(), 'start' => $firstDate, 'end' => $lastDate);
         }
         $dbr->freeResult($oRes);
         if (!empty($AWCMetrics)) {
             foreach ($AWCMetrics as $date => $records) {
                 $where = array("ccm.city_id = cl.city_id", "cl.city_created between '" . $records['start'] . "' and '" . $records['end'] . "'");
                 $oRes = $dbr->select("city_cat_mapping as ccm, city_list as cl", array("ccm.cat_id, count(*) as cnt"), $where, __METHOD__, array('GROUP BY' => 'cat_id'));
                 while ($oRow = $dbr->fetchObject($oRes)) {
                     $AWCMetrics[$date]['hubs'][$oRow->cat_id] = array('catName' => isset($aCategories[$oRow->cat_id]) ? $aCategories[$oRow->cat_id]['name'] : "Undefined", 'count' => $oRow->cnt);
                 }
                 $dbr->freeResult($oRes);
             }
         }
     }
     wfProfileOut(__METHOD__);
     return array($AWCMetrics, $AWCCitiesCount, $aCategories);
 }
Esempio n. 24
0
 private static function allowResultsForEditedArticles($row, $from_db = false)
 {
     global $wgTTCache;
     wfProfileIn(__METHOD__);
     $result = array();
     $memkey = wfMemcKey(__METHOD__, 'oWikia', intval($row['wikia']));
     $oWikia = $wgTTCache->get($memkey);
     if (!isset($oWikia)) {
         $allowed = true;
         /*
          * check city list
          */
         $oWikia = WikiFactory::getWikiByID($row['wikia']);
         if (!$oWikia) {
             $allowed = false;
         }
         /*
          * check city lang
          */
         if ($allowed && !in_array($oWikia->city_lang, self::$allowedLanguages)) {
             $allowed = false;
         }
         /*
          * check sitename
          */
         if ($allowed) {
             $siteName = WikiFactory::getVarByName('wgSitename', $row['wikia']);
             if (!$siteName) {
                 $allowed = false;
             }
         }
         /*
          * check wikiname
          */
         $oWikia->city_sitename = "";
         if ($allowed) {
             $oWikia->city_sitename = unserialize($siteName->cv_value);
             if (!$oWikia->city_sitename) {
                 $allowed = false;
             } else {
                 foreach (self::$excludeNames as $search) {
                     $pos = stripos($oWikia->city_sitename, $search);
                     if ($pos !== false) {
                         $allowed = false;
                     }
                 }
             }
         }
         if (!$allowed) {
             $oWikia = 'ERROR';
         }
         # set in memc
         if ($oWikia != 'ERROR') {
             $wgTTCache->set($memkey, $oWikia, 60 * 60);
         }
     }
     if ($oWikia == 'ERROR') {
         wfProfileOut(__METHOD__);
         return false;
     }
     /* check article */
     $memkey = wfMemcKey(__METHOD__, 'article', intval($row['wikia']), intval($row['page']), $oWikia->city_dbname);
     $result = $from_db === true ? null : $wgTTCache->get($memkey);
     if (!isset($result)) {
         $allowedPage = true;
         /*
          * check Title && Wiki domain
          */
         $oGTitle = GlobalTitle::newFromId($row['page'], $row['wikia'], $oWikia->city_dbname);
         if (!is_object($oGTitle)) {
             $allowedPage = false;
         }
         if ($allowedPage) {
             $wikiaUrl = $oGTitle->getServer();
             $pageUrl = $oGTitle->getFullURL();
             $articleName = $oGTitle->getArticleName();
             $oRegexCore = new TextRegexCore(self::$excludeWikiDomainsKey, 0);
             if (is_object($oRegexCore)) {
                 $allowed = $oRegexCore->isAllowedText($wikiaUrl, "", false);
                 if (!$allowed) {
                     $allowedPage = false;
                 }
             }
         }
         /*
          * check hub name
          */
         if ($allowedPage) {
             $hubName = WikiFactoryHub::getInstance()->getCategoryName($row['wikia']);
             if (in_array($hubName, self::$excludeWikiHubs)) {
                 $allowedPage = false;
             }
         }
         /*
          * check article name
          */
         if ($allowedPage) {
             $oRegexArticles = new TextRegexCore(self::$excludeWikiArticles, 0);
             if (is_object($oRegexArticles)) {
                 $filterText = sprintf("%s:%s", $oWikia->city_dbname, $articleName);
                 $allowed = $oRegexArticles->isAllowedText($filterText, "", false);
                 if (!$allowed) {
                     $allowedPage = false;
                 }
             }
         }
         if (!$allowedPage) {
             $result = 'ERROR';
         } else {
             /*
              * ok
              */
             $result = array('wikia' => $oWikia->city_sitename, 'db' => $oWikia->city_dbname, 'hub' => $hubName, 'page_name' => $articleName, 'wikia_url' => $wikiaUrl, 'page_url' => $pageUrl, 'count' => $row['count']);
             # set in memc
             $wgTTCache->set($memkey, $result, 60 * 30);
         }
     }
     if ($result == 'ERROR') {
         $result = false;
     }
     wfProfileOut(__METHOD__);
     return $result;
 }
Esempio n. 25
0
 public function execute($wikiID)
 {
     global $wgOut, $wgRequest, $wgCityId, $wgUser;
     wfProfileIn(__METHOD__);
     $this->setHeaders();
     $firstVisit = true;
     $wikiID = !empty($wikiID) ? (int) $wikiID : $wgCityId;
     if (isset($_COOKIE[$this->mCookieName])) {
         $this->mCookie = json_decode($_COOKIE[$this->mCookieName]);
         $firstVisit = false;
     } else {
         $this->mCookie = new stdClass();
         $this->mCookie->origHub = null;
         $this->mCookie->langCode = null;
         $this->mCookie->history = array();
         if (!empty($wikiID)) {
             $hub = WikiFactoryHub::getInstance();
             // FIXME: change this to verticalId
             $cat_id = $hub->getCategoryId($wikiID);
             if ($cat_id) {
                 $this->mCookie->origHub = $cat_id;
                 $this->mCookie->langCode = WikiFactory::getWikiByID($wikiID)->city_lang;
                 $this->mCookie->history[] = $wikiID;
             }
         }
     }
     $this->loadData();
     $historyCount = count($this->mCookie->history);
     // reset the history if the user visited all the possible targets
     if ($historyCount >= $this->mData['total']) {
         $this->mCookie->history = array($wikiID);
     }
     // if language other than English and list of targets exhausted fall back to english
     if (($historyCount >= $this->mData['total'] || $this->mData['total'] == 0 && (count($this->mData['recommended']) == 0 || !$firstVisit)) && $this->mCookie->langCode != 'en') {
         $this->mCookie->langCode = 'en';
         $this->loadData();
     }
     $destinationID = null;
     $from = null;
     srand(time());
     // pick a recommended wiki the first time
     if ($firstVisit && !empty($this->mData['recommended'])) {
         $destinationID = $this->mData['recommended'][array_rand($this->mData['recommended'])];
         $from = 'recommended';
     } elseif (!empty($this->mCookie->origHub) && !empty($this->mData['hubs'][$this->mCookie->origHub])) {
         $currentHub = array_diff($this->mData['hubs'][$this->mCookie->origHub], $this->mCookie->history);
         if (count($currentHub) && count($this->mCookie->history) < RandomWikiHelper::TRACK_LIMIT) {
             $destinationID = $currentHub[array_rand($currentHub)];
             $from = 'origHub';
         }
     }
     // in case no wiki has been selected in the previous block pick a wiki from a random hub
     if (empty($destinationID)) {
         $hubsCount = count($this->mData['hubs']);
         $hub = array_rand($this->mData['hubs'], $hubsCount);
         if (!is_array($hub)) {
             $hub = array($hub);
         }
         foreach ($hub as $key) {
             $tmpHub = array_diff($this->mData['hubs'][$key], $this->mCookie->history);
             if (!count($tmpHub)) {
                 continue;
             }
             $itemKey = array_rand($tmpHub);
             $destinationID = $tmpHub[$itemKey];
             $from = "hub {$itemKey}";
         }
     }
     $this->mCookie->history[] = $destinationID;
     $cookieValue = json_encode($this->mCookie);
     $wgRequest->response()->setcookie(self::COOKIE_NAME_TOKEN, $cookieValue, time() + 3600 * self::COOKIE_EXPIRY);
     $url = WikiFactory::getVarValueByName('wgServer', $destinationID);
     //FB#1033: avoid being sent to Special:WikiActivity when logged-in, see MyHomw::getInitialMainPage
     if ($wgUser->isLoggedIn()) {
         $url .= '?redirect=no';
     }
     // Redirect the user to a randomly-chosen wiki (or not if profiling requested)
     $profiling = $wgRequest->getInt('forceprofile', 0);
     if ($profiling !== 1) {
         $wgOut->redirect($url);
     }
     wfProfileOut(__METHOD__);
 }
 public function getVerticalName($verticalId)
 {
     $wikiFactoryHub = WikiFactoryHub::getInstance();
     /** @var WikiFactoryHub $wikiFactoryHub */
     $wikiaHub = $wikiFactoryHub->getCategory($verticalId);
     return wfMsgForContent('hub-' . $wikiaHub['name']);
 }
Esempio n. 27
0
 private static function constructCategoryInfoFromCategoryId($categoryId)
 {
     $categoryId = self::getCanonicalCategoryId($categoryId);
     $categoryRow = WikiFactoryHub::getInstance()->getCategory($categoryId);
     $categoryInfo = new stdClass();
     $categoryInfo->cat_id = $categoryId;
     $categoryInfo->cat_name = $categoryRow['name'];
     return $categoryInfo;
 }
Esempio n. 28
0
 public static function getCachedCategory()
 {
     wfProfileIn(__METHOD__);
     static $cat;
     if (!empty($cat)) {
         wfProfileOut(__METHOD__);
         // This function already called
         return $cat;
     }
     if (!empty($_GET['forceCategory'])) {
         wfProfileOut(__METHOD__);
         // Passed in through the url, or hard coded on a test_page. ;-)
         return $_GET['forceCategory'];
     }
     global $wgMemc, $wgCityId, $wgRequest;
     $cacheKey = wfMemcKey(__CLASS__ . 'category', self::cacheKeyVersion);
     $cat = $wgMemc->get($cacheKey);
     if (!empty($cat) && $wgRequest->getVal('action') != 'purge') {
         wfProfileOut(__METHOD__);
         return $cat;
     }
     $hub = WikiFactoryHub::getInstance();
     $cat = array('id' => $hub->getCategoryId($wgCityId), 'name' => $hub->getCategoryName($wgCityId), 'short' => $hub->getCategoryShort($wgCityId));
     $wgMemc->set($cacheKey, $cat, self::cacheTimeout);
     wfProfileOut(__METHOD__);
     return $cat;
 }
Esempio n. 29
0
 private function showActivity($subpage = '')
 {
     global $wgUser, $wgContLang, $wgLang, $wgOut, $wgJsMimeType, $wgResourceBasePath;
     wfProfileIn(__METHOD__);
     $wgOut->addScript("<script type=\"{$wgJsMimeType}\" src=\"{$wgResourceBasePath}/resources/wikia/libraries/jquery/datatables/jquery.dataTables.min.js\"></script>\n");
     @(list(, $pyear, $pmonth, $plang, $pcat) = explode("/", $subpage));
     $aTopLanguages = explode(',', wfMsg('wikistats_language_toplist'));
     $aLanguages = wfGetFixedLanguageNames();
     asort($aLanguages);
     #-
     $hubs = WikiFactoryHub::getInstance();
     $_cats = $hubs->getCategories();
     $aCategories = array();
     if (!empty($_cats)) {
         foreach ($_cats as $id => $cat) {
             if (!isset($aCategories[$id])) {
                 $aCategories[$id] = $cat['name'];
                 if ($pcat == $cat['name']) {
                     $pcat = intval($id);
                 }
             }
         }
     }
     if (!is_numeric($pcat)) {
         $pcat = 0;
     }
     if (empty($pyear)) {
         $pyear = date('Y');
     }
     if (empty($pmonth)) {
         $pmonth = date('m');
     }
     #$rows = $this->mStats->userEdits(1);
     $oTmpl = new EasyTemplate(dirname(__FILE__) . "/templates/");
     $oTmpl->set_vars(array("user" => $wgUser, "cityId" => $this->mCityId, "wgContLang" => $wgContLang, "wgLang" => $wgLang, "topLanguages" => $aTopLanguages, "aLanguages" => $aLanguages, "categories" => $aCategories, "pyear" => $pyear, "pmonth" => $pmonth, "plang" => !empty($plang) ? $plang : $wgLang->getCode(), "pcat" => $pcat));
     $wgOut->addHTML($oTmpl->render("wiki_activity"));
     wfProfileOut(__METHOD__);
 }
Esempio n. 30
0
 public static function getCalendarTypes()
 {
     if (!empty(self::$CALENDAR_TYPES)) {
         return self::$CALENDAR_TYPES;
     }
     $categories = WikiFactoryHub::getInstance()->getCategories();
     foreach ($categories as $catData) {
         self::$CALENDAR_TYPES[$catData['short']] = $catData['name'];
     }
     return self::$CALENDAR_TYPES;
 }