protected function getArticleData($pageId)
 {
     global $wgVideoHandlersVideosMigrated;
     $oTitle = Title::newFromID($pageId);
     $oMemCache = F::App()->wg->memc;
     $sKey = wfSharedMemcKey('category_exhibition_article_cache_0', $pageId, F::App()->wg->cityId, $this->isVerify(), $wgVideoHandlersVideosMigrated ? 1 : 0, $this->getTouched($oTitle));
     $cachedResult = $oMemCache->get($sKey);
     if (!empty($cachedResult)) {
         return $cachedResult;
     }
     $snippetText = '';
     $imageUrl = $this->getImageFromPageId($pageId);
     // if category has no images in page content, look for images and articles in category
     if ($imageUrl == '') {
         $resultArray = $this->getCategoryImageOrSnippet($pageId);
         $snippetText = $resultArray['snippetText'];
         $imageUrl = $resultArray['imageUrl'];
         if (empty($snippetText) && empty($imageUrl)) {
             $snippetService = new ArticleService($oTitle);
             $snippetText = $snippetService->getTextSnippet();
         }
     }
     $returnData = array('id' => $pageId, 'title' => $oTitle->getText(), 'url' => $oTitle->getFullURL(), 'img' => $imageUrl, 'width' => $this->thumbWidth, 'height' => $this->thumbHeight, 'sortType' => $this->getSortType(), 'displayType' => $this->getDisplayType(), 'snippet' => $snippetText);
     // will be purged elsewhere after edit
     $oMemCache->set($sKey, $returnData, 60 * 60 * 24 * 7);
     return $returnData;
 }
 private function getGlobalFooterLinks()
 {
     global $wgCityId, $wgContLang, $wgLang, $wgMemc;
     wfProfileIn(__METHOD__);
     $verticalId = WikiFactoryHub::getInstance()->getVerticalId($wgCityId);
     $memcKey = wfSharedMemcKey(self::MEMC_KEY_GLOBAL_FOOTER_LINKS, $wgContLang->getCode(), $wgLang->getCode(), $verticalId, self::MEMC_KEY_GLOBAL_FOOTER_VERSION);
     $globalFooterLinks = $wgMemc->get($memcKey);
     if (!empty($globalFooterLinks)) {
         wfProfileOut(__METHOD__);
         return $globalFooterLinks;
     }
     if (is_null($globalFooterLinks = getMessageAsArray(self::MESSAGE_KEY_GLOBAL_FOOTER_LINKS . '-' . $verticalId))) {
         if (is_null($globalFooterLinks = getMessageAsArray(self::MESSAGE_KEY_GLOBAL_FOOTER_LINKS))) {
             wfProfileOut(__METHOD__);
             WikiaLogger::instance()->error("Global Footer's links not found in messages", ['exception' => new Exception()]);
             return [];
         }
     }
     $parsedLinks = [];
     foreach ($globalFooterLinks as $link) {
         $link = trim($link);
         if (strpos($link, '*') === 0) {
             $parsedLink = parseItem($link);
             if (strpos($parsedLink['text'], 'LICENSE') !== false || $parsedLink['text'] == 'GFDL') {
                 $parsedLink['isLicense'] = true;
             } else {
                 $parsedLink['isLicense'] = false;
             }
             $parsedLinks[] = $parsedLink;
         }
     }
     $wgMemc->set($memcKey, $parsedLinks, self::MEMC_EXPIRY);
     wfProfileOut(__METHOD__);
     return $parsedLinks;
 }
Пример #3
0
 protected function getExternalData()
 {
     global $wgCityId;
     // Prevent recursive loop
     if ($wgCityId == self::EXTERNAL_DATA_SOURCE_WIKI_ID) {
         return array();
     }
     if (self::$externalData === false) {
         global $wgLang, $wgMemc;
         $code = $wgLang->getCode();
         $key = wfSharedMemcKey('user-command-special-page', 'lang', $code);
         $data = $wgMemc->get($key);
         if (empty($data)) {
             $data = array();
             $external = Http::get($this->getExternalDataUrl($code));
             $external = json_decode($external, true);
             if (is_array($external) && !empty($external['allOptions']) && is_array($external['allOptions'])) {
                 foreach ($external['allOptions'] as $option) {
                     $data[$option['id']] = $option;
                 }
             }
             $wgMemc->set($key, $data, self::EXTERNAL_DATA_CACHE_TTL);
         }
         self::$externalData = $data;
     }
     return self::$externalData;
 }
Пример #4
0
 /**
  * @group UsingDB
  */
 public function testCache()
 {
     $user = $this->getTestUser();
     //create object here, so we use the same one all the time, that way we can test local cache
     $object = new UserService();
     $cachedLocalUser = $this->invokePrivateMethod('UserService', 'getUserFromLocalCacheById', $user->getId(), $object);
     $cachedLocalUserByName = $this->invokePrivateMethod('UserService', 'getUserFromLocalCacheByName', $user->getName(), $object);
     //values are not cached localy yet
     $this->assertEquals(false, $cachedLocalUser);
     $this->assertEquals(false, $cachedLocalUserByName);
     //cache user, both locally and mem cached
     $this->invokePrivateMethod('UserService', 'cacheUser', $user, $object);
     //do the assertion again, local cache should have hit one
     $cachedLocalUser = $this->invokePrivateMethod('UserService', 'getUserFromLocalCacheById', $user->getId(), $object);
     $cachedLocalUserByName = $this->invokePrivateMethod('UserService', 'getUserFromLocalCacheByName', $user->getName(), $object);
     $this->assertEquals($user, $cachedLocalUser);
     $this->assertEquals($user, $cachedLocalUserByName);
     //check if user was cached in memcache, use new object for that
     $cachedMemCacheById = $this->invokePrivateMethod('UserService', 'getUserFromMemCacheById', $user->getId());
     $cachedMemCacheByName = $this->invokePrivateMethod('UserService', 'getUserFromMemCacheByName', $user->getName());
     $this->assertEquals($user, $cachedMemCacheById);
     $this->assertEquals($user, $cachedMemCacheByName);
     //need for deleting form cache test values
     $sharedIdKey = wfSharedMemcKey("UserCache:" . $user->getId());
     $sharedNameKey = wfSharedMemcKey("UserCache:" . $user->getName());
     //remove user from memcache
     F::app()->wg->memc->delete($sharedIdKey);
     F::app()->wg->memc->delete($sharedNameKey);
     //do assert against memcache again
     $cachedMemCacheById = $this->invokePrivateMethod('UserService', 'getUserFromMemCacheById', $user->getId());
     $cachedMemCacheByName = $this->invokePrivateMethod('UserService', 'getUserFromMemCacheByName', $user->getName());
     $this->assertEquals(false, $cachedMemCacheById);
     $this->assertEquals(false, $cachedMemCacheByName);
 }
 /**
  * @desc Returns an array with all available components configuration
  *
  * @return array
  */
 public function getAllComponents()
 {
     $components = WikiaDataAccess::cache(wfSharedMemcKey(__CLASS__, 'all_components_list_with_details', self::MEMCACHE_VERSION_KEY, $this->userLangCode), Wikia\UI\Factory::MEMCACHE_EXPIRATION, [$this, 'getAllComponentsFromDirectories']);
     $this->initComponents($components);
     $this->includeComponentsAssets($components);
     return $components;
 }
 public function getCommercialUseNotAllowedWikis()
 {
     if (empty(self::$wikiList)) {
         self::$wikiList = WikiaDataAccess::cache(wfSharedMemcKey(self::CACHE_KEY_COMMERCIAL_NOT_ALLOWED), self::CACHE_VALID_TIME, function () {
             return $this->getWikisWithVar();
         });
     }
     return self::$wikiList;
 }
 public function getGameCacheValue()
 {
     $factory = new ScavengerHuntGames();
     $gameId = $this->getVal('gameId', '');
     $readWrite = $this->getVal('readwrite', 0);
     $key = wfSharedMemcKey('ScavengerHuntGameIndex', $gameId, $readWrite ? 1 : 0, ScavengerHuntGames::CACHE_VERSION);
     $this->setVal('key', $key);
     $this->setVal('response', unserialize($factory->getCache()->get($key)));
 }
Пример #8
0
 function __construct($cache, $key)
 {
     $this->memc = $cache;
     if (empty($key)) {
         throw new Exception('Key is empty');
     }
     $this->key = $key;
     $this->lockKey = wfSharedMemcKey('MemcacheSyncLock', $key);
     $this->instance = uniqid('', true);
 }
Пример #9
0
 /**
  * @param int $articleId
  * @param int $limit - max limit = 10
  * @return array of articles with details
  */
 public function get($articleId, $limit)
 {
     wfProfileIn(__METHOD__);
     $hubName = $this->getHubName();
     $lang = $this->getContentLangCode();
     $out = \WikiaDataAccess::cache(\wfSharedMemcKey('RecommendationApi', self::RECOMMENDATION_ENGINE, $hubName, $lang, self::MCACHE_VERSION), \WikiaResponse::CACHE_STANDARD, function () use($hubName, $lang) {
         $topArticles = $this->getTopArticles($hubName, $lang);
         return $this->getArticlesInfo($topArticles);
     });
     shuffle($out);
     $out = array_slice($out, 0, $limit);
     wfProfileOut(__METHOD__);
     return $out;
 }
Пример #10
0
 /**
  * Return memcache key used for given message / variable
  *
  * City ID can be specified to return key for different wiki
  *
  * @param string $messageName message / variable name
  * @param int|bool $cityId city ID (false - default to current wiki)
  * @return string memcache key
  */
 private function getMemcKey($messageName, $cityId = false)
 {
     if ($this->useSharedMemcKey) {
         $wikiId = substr(wfSharedMemcKey(), 0, -1);
     } else {
         $wikiId = is_numeric($cityId) ? $cityId : intval($this->wg->CityId);
         // fix for internal and staff (BugId:15149)
         if ($wikiId == 0) {
             $wikiId = $this->wg->DBname;
         }
     }
     $messageName = str_replace(' ', '_', $messageName);
     return implode(':', array(__CLASS__, $wikiId, $this->wg->Lang->getCode(), $messageName, self::version));
 }
Пример #11
0
 public static function onWikiFactoryVarChanged($cv_name, $city_id, $value)
 {
     $app = F::app();
     if (self::isWikiaBarConfig($city_id, $cv_name)) {
         Wikia::log(__METHOD__, '', 'Updating WikiaBar config caches after change');
         foreach ($value as $vertical => $languages) {
             foreach ($languages as $language => $content) {
                 $dataMemcKey = wfSharedMemcKey('WikiaBarContents', $vertical, $language, WikiaBarModel::WIKIA_BAR_MCACHE_VERSION);
                 Wikia::log(__METHOD__, '', 'Purging ' . $dataMemcKey);
                 $app->wg->memc->set($dataMemcKey, null);
             }
         }
     }
     return true;
 }
	public function index() {
		global $wgCityId, $wgLang, $wgContLang, $wgMemc;
		$catId = WikiFactoryHub::getInstance()->getCategoryId( $wgCityId );
		$mKey = wfSharedMemcKey( 'mOasisFooterLinks', $wgContLang->getCode(), $wgLang->getCode(), $catId );

		$this->footer_links = $wgMemc->get( $mKey );
		$this->copyright = RequestContext::getMain()->getSkin()->getCopyright();

		if ( empty( $this->footer_links ) ) {
			$this->footer_links = $this->getWikiaFooterLinks();
			$wgMemc->set( $mKey, $this->footer_links, 86400 );
		}

		$this->hub = $this->getHub();
	}
Пример #13
0
 /**
  * @access private
  *
  * @param String $format	format of list: csv or xml
  */
 private function generateList($format)
 {
     global $wgOut, $wgMemc, $wgExternalSharedDB;
     $res = $wgMemc->get(wfSharedMemcKey("{$format}-city-list"));
     $filename = "{$format}_city_list.{$format}";
     $wgOut->disable();
     if ($format === "xml") {
         header("Content-type: application/xml; charset=UTF-8");
     } else {
         header("Content-type: text/csv; charset=UTF-8");
     }
     $wgOut->sendCacheControl();
     print gzinflate($res);
     exit;
 }
Пример #14
0
 public static function getImageSrcByTitle($cityId, $articleTitle, $width = null, $height = null)
 {
     global $wgMemc;
     wfProfileIn(__METHOD__);
     $imageKey = wfSharedMemcKey('image_url_from_wiki', $cityId . $articleTitle . $width . $height);
     $imageSrc = $wgMemc->get($imageKey);
     if ($imageSrc === false) {
         $globalFile = GlobalFile::newFromText($articleTitle, $cityId);
         if ($globalFile->exists()) {
             $imageSrc = $globalFile->getCrop($width, $height);
         } else {
             $imageSrc = null;
         }
         $wgMemc->set($imageKey, $imageSrc, 60 * 60 * 24 * 3);
     }
     wfProfileOut(__METHOD__);
     return $imageSrc;
 }
Пример #15
0
function generateList($format)
{
    global $wgMemc, $wgExternalSharedDB;
    $func = "begin_" . $format;
    $res = $func();
    $dbr = WikiFactory::db(DB_SLAVE, array(), $wgExternalSharedDB);
    $sth = $dbr->select(array("city_list"), array("city_title", "city_lang", "city_url", "city_id"), array("city_public = 1"), __METHOD__);
    while ($row = $dbr->fetchObject($sth)) {
        $row->category = WikiFactory::getCategory($row->city_id);
        $func = "body_" . $format;
        $res .= $func($row);
    }
    $func = "end_" . $format;
    $res .= $func();
    if (!empty($res)) {
        $gz_res = gzdeflate($res, 3);
        $wgMemc->set(wfSharedMemcKey("{$format}-city-list"), $gz_res, 3600 * 6);
    }
}
Пример #16
0
 public function initFromCookie()
 {
     global $wgMemc, $wgDBcluster, $wgCookiePrefix, $wgRequest;
     wfDebug(__METHOD__ . " \n");
     if (wfReadOnly()) {
         wfDebug(__METHOD__ . ": Cannot load from session - DB is running with the --read-only option ");
         return false;
     }
     // Copy safety check from User.php
     $uid = intval(isset($_COOKIE["{$wgCookiePrefix}UserID"]) ? $_COOKIE["{$wgCookiePrefix}UserID"] : 0);
     if ($uid != 0 && isset($_SESSION['wsUserID']) && $uid != $_SESSION['wsUserID']) {
         $wgRequest->response()->setcookie("UserID", '', time() - 86400);
         $wgRequest->response()->setcookie("UserName", '', time() - 86400);
         $wgRequest->response()->setcookie("_session", '', time() - 86400);
         $wgRequest->response()->setcookie("Token", '', time() - 86400);
         trigger_error("###INEZ### {$_SESSION['wsUserID']}\n", E_USER_WARNING);
         return false;
     }
     wfDebug(__METHOD__ . ": user from session: {$uid} \n");
     if (empty($uid)) {
         return false;
     }
     // exists on central
     $this->initFromId($uid);
     // exists on local
     $User = null;
     if (!empty($this->mRow)) {
         $memkey = sprintf("extuser:%d:%s", $this->getId(), $wgDBcluster);
         $user_touched = $wgMemc->get($memkey);
         if ($user_touched != $this->getUserTouched()) {
             $_key = wfSharedMemcKey("user_touched", $this->getId());
             wfDebug(__METHOD__ . ": user touched is different on central and {$wgDBcluster} \n");
             wfDebug(__METHOD__ . ": clear {$_key} \n");
             $wgMemc->set($memkey, $this->getUserTouched());
             $wgMemc->delete($_key);
         } else {
             $User = $this->getLocalUser();
         }
     }
     wfDebug(__METHOD__ . ": return user object \n");
     return is_null($User);
 }
Пример #17
0
 public function get_data()
 {
     wfProfileIn(__METHOD__);
     // get data
     $curdate = date('Ymd');
     $memKey = wfSharedMemcKey('customreport', $this->code, $curdate, $this->days);
     $this->data = $this->wg->Memc->get($memKey);
     if (!is_array($this->data)) {
         $this->data = $this->{'get_' . $this->code}();
         $this->patch_zero();
         $this->wg->Memc->set($memKey, $this->data, 3600 * 24);
     }
     // convert array to xml
     $xml = array();
     foreach ($this->data as $key => $value) {
         $xml[] = $this->convertDataToXML($key, $value);
     }
     wfProfileOut(__METHOD__);
     return $xml;
 }
 private function getData()
 {
     global $wgMemc;
     static $localCache;
     if ($localCache) {
         return $localCache;
     }
     $now = $this->getCurrentTimestamp();
     $memKey = wfSharedMemcKey('adengine', __METHOD__, self::CACHE_BUSTER);
     $cached = $wgMemc->get($memKey);
     if (is_array($cached) && $cached['ttl'] > $now) {
         // Cache hit!
         $localCache = $cached;
         return $cached;
     }
     // Cache miss, need to re-download the scripts
     $generated = $this->generateData();
     if ($generated === false) {
         // HTTP request didn't work
         if (is_array($cached)) {
             // Oh, we still have the thing cached
             // Let's use the script for the next a few minutes
             $cached['ttl'] = $now + self::TTL_GRACE;
             $wgMemc->set($memKey, $cached);
             $localCache = $cached;
             return $cached;
         }
         $error = 'Failed to download SevenOne Media files and had no cached script';
         $data = ['script' => 'var SEVENONEMEDIA_ERROR = ' . json_encode($error) . ';', 'modTime' => $now, 'ttl' => $now + self::TTL_GRACE];
         $wgMemc->set($memKey, $data);
         $localCache = $data;
         return $data;
     }
     $data = ['script' => $generated, 'modTime' => $now, 'ttl' => $now + self::TTL_SCRIPTS];
     if ($generated === $cached['script']) {
         $data['modTime'] = $cached['modTime'];
     }
     $wgMemc->set($memKey, $data);
     $localCache = $data;
     return $data;
 }
Пример #19
0
 /**
  * Get details about one or more wikis
  *
  * @param Array $wikiIds An array of one or more wiki ID's
  * @param bool $getBlocked If set to true, will return also blocked (not displayed on global page) wikias
  *
  * @return Array A collection of results, the index is the wiki ID and each item has a name,
  * url, lang, hubId, headline, desc, image and flags index.
  */
 public function getDetails(array $wikiIds = null, $getBlocked = false)
 {
     wfProfileIn(__METHOD__);
     $results = array();
     if (!empty($wikiIds)) {
         $notFound = array();
         foreach ($wikiIds as $index => $val) {
             $val = (int) $val;
             if (!empty($val)) {
                 $cacheKey = wfSharedMemcKey(__METHOD__, self::CACHE_VERSION, $val);
                 $item = $this->wg->Memc->get($cacheKey);
                 if (is_array($item)) {
                     $results[$val] = $item;
                 } else {
                     $notFound[] = $val;
                 }
             }
         }
         $wikiIds = $notFound;
     }
     if (!empty($wikiIds)) {
         $db = $this->getSharedDB();
         $where = array('city_list.city_public' => 1, 'city_list.city_id IN (' . implode(',', $wikiIds) . ')');
         if (!$getBlocked) {
             $where[] = '((city_visualization.city_flags & ' . self::FLAG_BLOCKED . ') != ' . self::FLAG_BLOCKED . ' OR city_visualization.city_flags IS NULL)';
         }
         $rows = $db->select(array('city_visualization', 'city_list'), array('city_list.city_id', 'city_list.city_title', 'city_list.city_url', 'city_visualization.city_lang_code', 'city_visualization.city_vertical', 'city_visualization.city_headline', 'city_visualization.city_description', 'city_visualization.city_main_image', 'city_visualization.city_flags'), $where, __METHOD__, array(), array('city_visualization' => array('LEFT JOIN', 'city_list.city_id = city_visualization.city_id')));
         while ($row = $db->fetchObject($rows)) {
             $item = array('name' => $row->city_title, 'url' => $row->city_url, 'lang' => $row->city_lang_code, 'hubId' => $row->city_vertical, 'headline' => $row->city_headline, 'desc' => $row->city_description, 'image' => PromoImage::fromPathname($row->city_main_image)->ensureCityIdIsSet($row->city_id)->getPathname(), 'flags' => array('official' => ($row->city_flags & self::FLAG_OFFICIAL) == self::FLAG_OFFICIAL, 'promoted' => ($row->city_flags & self::FLAG_PROMOTED) == self::FLAG_PROMOTED));
             $cacheKey = wfSharedMemcKey(__METHOD__, self::CACHE_VERSION, $row->city_id);
             $this->wg->Memc->set($cacheKey, $item, 43200);
             $results[$row->city_id] = $item;
         }
     }
     wfProfileOut(__METHOD__);
     return $results;
 }
 private static function isWikiExists($sName)
 {
     global $wgExternalSharedDB, $wgMemc;
     $cacheKey = wfSharedMemcKey(__METHOD__ . ':' . $sName);
     $cachedValue = $wgMemc->get($cacheKey);
     if (is_numeric($cachedValue)) {
         if ($cachedValue > 0) {
             return $cachedValue;
         } else {
             return false;
         }
     }
     $DBr = wfGetDB(DB_SLAVE, array(), $wgExternalSharedDB);
     $dbResult = $DBr->Query('SELECT city_id' . ' FROM city_domains' . ' WHERE city_domain = ' . $DBr->AddQuotes("{$sName}.wikia.com") . ' LIMIT 1' . ';', __METHOD__);
     if ($row = $DBr->FetchObject($dbResult)) {
         $DBr->FreeResult($dbResult);
         $wgMemc->set($cacheKey, intval($row->city_id), self::IS_WIKI_EXISTS_CACHE_TTL);
         return intval($row->city_id);
     } else {
         $DBr->FreeResult($dbResult);
         $wgMemc->set($cacheKey, 0, self::IS_WIKI_EXISTS_CACHE_TTL);
         return false;
     }
 }
Пример #21
0
 protected function getIdsBlacklistedWikis()
 {
     $blacklistIds = WikiaDataAccess::cache(wfSharedMemcKey('wam_blacklist', self::MEMCACHE_VER), self::CACHE_DURATION, function () {
         $contentWarningWikis = $excludedWikis = [];
         // Exlude wikias with ContentWarning extension enabled
         $blacklistExtVarId = WikiFactory::getVarIdByName(self::WAM_BLACKLIST_EXT_VAR_NAME);
         if ($blacklistExtVarId) {
             $contentWarningWikis = array_keys(WikiFactory::getListOfWikisWithVar($blacklistExtVarId, 'bool', '=', true));
         }
         // Exclude wikias with an exclusion flag set to true
         $blacklistFlagVarId = WikiFactory::getVarIdByName(self::WAM_EXCLUDE_FLAG_NAME);
         if ($blacklistFlagVarId) {
             $excludedWikis = array_keys(WikiFactory::getListOfWikisWithVar($blacklistFlagVarId, 'bool', '=', true));
         }
         return array_merge($contentWarningWikis, $excludedWikis);
     });
     return $blacklistIds;
 }
Пример #22
0
 private static function purgeCacheDependingOnCats($title, $reason = null)
 {
     $app = F::app();
     $purged = false;
     wfDebugLog(__CLASS__, __METHOD__ . 'fetching categories from MASTER');
     $categories = self::getCategoriesFromTitle($title, true);
     if (self::hasCssUpdatesCat($categories)) {
         wfDebugLog(__CLASS__, __METHOD__ . $reason);
         WikiaDataAccess::cachePurge(wfSharedMemcKey(SpecialCssModel::MEMC_KEY, $app->wg->DBname));
         $purged = true;
     }
     return $purged;
 }
Пример #23
0
 /**
  * @desc Checks if the email provided is wikia mail and within the limit specified by $wgAccountsPerEmail
  *
  * @param $sEmail - email address to check
  * @return bool - TRUE if the email can be registered, otherwise FALSE
  */
 public static function withinEmailRegLimit($sEmail)
 {
     global $wgAccountsPerEmail, $wgMemc;
     if (isset($wgAccountsPerEmail) && is_numeric($wgAccountsPerEmail) && !self::isWikiaEmail($sEmail)) {
         $key = wfSharedMemcKey("UserLogin", "AccountsPerEmail", $sEmail);
         $count = $wgMemc->get($key);
         if ($count !== false && (int) $count >= (int) $wgAccountsPerEmail) {
             return false;
         }
     }
     return true;
 }
Пример #24
0
 private function getMemcKey($ixBug)
 {
     $key = wfSharedMemcKey(__CLASS__, 'Cases', $ixBug);
     return $key;
 }
Пример #25
0
 /**
  * Sets wiki specific user option
  * into wikia_user_properties table from wiki DB
  * @since Nov 2013
  * @author Kamil Koterba
  *
  * @param String $optionName name of wiki specific user option
  * @param String $optionValue option value to be set
  * @param int $wikiId Integer Id of wiki - specifies wiki from which to get editcount, 0 for current wiki
  * @return $optionVal string|null
  */
 public function setOptionWiki($optionName, $optionVal, $wikiId = 0)
 {
     wfProfileIn(__METHOD__);
     $dbName = false;
     if ($wikiId != 0) {
         $dbName = WikiFactory::IDtoDB($wikiId);
     } else {
         $wikiId = $this->wg->CityId;
     }
     $this->loadOptionsWiki($wikiId);
     // checks if isset and loads if empty (to make sure we don't loose anything
     $dbw = $this->getWikiDB(DB_MASTER, $dbName);
     $dbw->replace('wikia_user_properties', array(), array('wup_user' => $this->userId, 'wup_property' => $optionName, 'wup_value' => $optionVal), __METHOD__);
     $this->optionsAllWikis[$wikiId][$optionName] = $optionVal;
     $key = wfSharedMemcKey('optionsWiki', $wikiId, $this->userId);
     $this->wg->Memc->set($key, $this->optionsAllWikis[$wikiId], self::CACHE_TTL);
     wfProfileOut(__METHOD__);
     return $optionVal;
 }
Пример #26
0
/**
 * @param OutputPage $out
 * @param $text
 * @return bool
 */
function SharedHelpHook(&$out, &$text)
{
    global $wgTitle, $wgMemc, $wgSharedDB, $wgCityId, $wgHelpWikiId, $wgContLang, $wgLanguageCode, $wgArticlePath;
    /* Insurance that hook will be called only once #BugId:  */
    static $wasCalled = false;
    if ($wasCalled == true) {
        return true;
    }
    $wasCalled = true;
    if (empty($wgHelpWikiId) || $wgCityId == $wgHelpWikiId) {
        # Do not proceed if we don't have a help wiki or are on it
        return true;
    }
    if (!$out->isArticle()) {
        # Do not process for pages other then articles
        return true;
    }
    wfProfileIn(__METHOD__);
    # Do not process if explicitly told not to
    $mw = MagicWord::get('MAG_NOSHAREDHELP');
    if ($mw->match($text) || strpos($text, NOSHAREDHELP_MARKER) !== false) {
        wfProfileOut(__METHOD__);
        return true;
    }
    if ($wgTitle->getNamespace() == NS_HELP) {
        # Initialize shared and local variables
        # Canonical namespace is added here in case we ever want to share other namespaces (e.g. Advice)
        $sharedArticleKey = $wgSharedDB . ':sharedArticles:' . $wgHelpWikiId . ':' . MWNamespace::getCanonicalName($wgTitle->getNamespace()) . ':' . $wgTitle->getDBkey() . ':' . SHAREDHELP_CACHE_VERSION;
        $sharedArticle = $wgMemc->get($sharedArticleKey);
        $sharedServer = WikiFactory::getVarValueByName('wgServer', $wgHelpWikiId);
        $sharedScript = WikiFactory::getVarValueByName('wgScript', $wgHelpWikiId);
        $sharedArticlePath = WikiFactory::getVarValueByName('wgArticlePath', $wgHelpWikiId);
        // get defaults
        // in case anybody's curious: no, we can't use $wgScript cause that may be overridden locally :/
        // @TODO pull this from somewhere instead of hardcoding
        if (empty($sharedArticlePath)) {
            $sharedArticlePath = '/wiki/$1';
        }
        if (empty($sharedScript)) {
            $sharedScript = '/index.php';
        }
        $sharedArticlePathClean = str_replace('$1', '', $sharedArticlePath);
        $localArticlePathClean = str_replace('$1', '', $wgArticlePath);
        # Try to get content from memcache
        if (!empty($sharedArticle['timestamp'])) {
            if (wfTimestamp() - (int) $sharedArticle['timestamp'] < 600) {
                if (isset($sharedArticle['exists']) && $sharedArticle['exists'] == 0) {
                    wfProfileOut(__METHOD__);
                    return true;
                } else {
                    if (!empty($sharedArticle['cachekey'])) {
                        wfDebug("SharedHelp: trying parser cache {$sharedArticle['cachekey']}\n");
                        $key1 = str_replace('-1!', '-0!', $sharedArticle['cachekey']);
                        $key2 = str_replace('-0!', '-1!', $sharedArticle['cachekey']);
                        $parser = $wgMemc->get($key1);
                        if (!empty($parser) && is_object($parser)) {
                            $content = $parser->mText;
                        } else {
                            $parser = $wgMemc->get($key2);
                            if (!empty($parser) && is_object($parser)) {
                                $content = $parser->mText;
                            }
                        }
                    }
                }
            }
        }
        # If getting content from memcache failed (invalidate) then just download it via HTTP
        if (empty($content)) {
            $urlTemplate = $sharedServer . $sharedScript . "?title=Help:%s&action=render";
            $articleUrl = sprintf($urlTemplate, urlencode($wgTitle->getDBkey()));
            list($content, $c) = SharedHttp::get($articleUrl);
            # if we had redirect, then store it somewhere
            if (curl_getinfo($c, CURLINFO_HTTP_CODE) == 301) {
                if (preg_match("/^Location: ([^\n]+)/m", $content, $dest_url)) {
                    $destinationUrl = $dest_url[1];
                }
            }
            global $wgServer, $wgArticlePath, $wgRequest, $wgTitle;
            $helpNs = $wgContLang->getNsText(NS_HELP);
            $sk = RequestContext::getMain()->getSkin();
            if (!empty($_SESSION['SH_redirected'])) {
                $from_link = Title::newfromText($helpNs . ":" . $_SESSION['SH_redirected']);
                $redir = $sk->makeKnownLinkObj($from_link, '', 'redirect=no', '', '', 'rel="nofollow"');
                $s = wfMsg('redirectedfrom', $redir);
                $out->setSubtitle($s);
                $_SESSION['SH_redirected'] = '';
            }
            if (isset($destinationUrl)) {
                $destinationPageIndex = strpos($destinationUrl, "{$helpNs}:");
                # if $helpNs was not found, assume we're on help.wikia.com and try again
                if ($destinationPageIndex === false) {
                    $destinationPageIndex = strpos($destinationUrl, MWNamespace::getCanonicalName(NS_HELP) . ":");
                }
                $destinationPage = substr($destinationUrl, $destinationPageIndex);
                $link = $wgServer . str_replace("\$1", $destinationPage, $wgArticlePath);
                if ('no' != $wgRequest->getVal('redirect')) {
                    $_SESSION['SH_redirected'] = $wgTitle->getText();
                    $out->redirect($link);
                    $wasRedirected = true;
                } else {
                    $content = "\n\n" . wfMsg('shared_help_was_redirect', "<a href=" . $link . ">{$destinationPage}</a>");
                }
            } else {
                $tmp = explode("\r\n\r\n", $content, 2);
                $content = isset($tmp[1]) ? $tmp[1] : '';
            }
            if (strpos($content, '"noarticletext"') > 0) {
                $sharedArticle = array('exists' => 0, 'timestamp' => wfTimestamp());
                $wgMemc->set($sharedArticleKey, $sharedArticle);
                wfProfileOut(__METHOD__);
                return true;
            } else {
                $contentA = explode("\n", $content);
                $tmp = isset($contentA[count($contentA) - 2]) ? $contentA[count($contentA) - 2] : '';
                $idx1 = strpos($tmp, 'key');
                $idx2 = strpos($tmp, 'end');
                $key = trim(substr($tmp, $idx1 + 4, $idx2 - $idx1));
                $sharedArticle = array('cachekey' => $key, 'timestamp' => wfTimestamp());
                $wgMemc->set($sharedArticleKey, $sharedArticle);
                wfDebug("SharedHelp: using parser cache {$sharedArticle['cachekey']}\n");
            }
            curl_close($c);
        }
        if (empty($content)) {
            wfProfileOut(__METHOD__);
            return true;
        } else {
            // So we don't return 404s for local requests to these pages as they have content (BugID: 44611)
            $out->setStatusCode(200);
        }
        //process article if not redirected before
        if (empty($wasRedirected)) {
            # get rid of editsection links
            $content = preg_replace("|<span class=\"editsection( .*)?\"><a href=\".*?\" title=\".*?\">.*?<\\/a><\\/span>|", "", $content);
            $content = strtr($content, array('showTocToggle();' => "showTocToggle('sharedtoctitle', 'sharedtoc', 'sharedtogglelink');", '<table id="toc" class="toc"' => '<table id="sharedtoc" class="toc"', '<div id="toctitle">' => '<div id="sharedtoctitle" class="toctitle">', 'data-image-name' => 'data-shared-help="true" data-image-name'));
            # namespaces to skip when replacing links
            $skipNamespaces = array();
            $skipNamespaces[] = $wgContLang->getNsText(NS_CATEGORY);
            $skipNamespaces[] = $wgContLang->getNsText(NS_IMAGE);
            $skipNamespaces[] = $wgContLang->getNsText(NS_FILE);
            if (defined('NS_VIDEO')) {
                $skipNamespaces[] = $wgContLang->getNsText(NS_VIDEO);
            }
            $skipNamespaces[] = "Advice";
            if ($wgLanguageCode != 'en') {
                $skipNamespaces[] = MWNamespace::getCanonicalName(NS_CATEGORY);
                $skipNamespaces[] = MWNamespace::getCanonicalName(NS_IMAGE);
                if (defined('NS_VIDEO')) {
                    $skipNamespaces[] = MWNamespace::getCanonicalName(NS_VIDEO);
                }
            }
            # replace help wiki links with local links, except for special namespaces defined above
            $content = preg_replace("|{$sharedServer}{$sharedArticlePathClean}(?!" . implode(")(?!", $skipNamespaces) . ")|", $localArticlePathClean, $content);
            # replace help wiki project namespace with local project namespace
            $sharedMetaNamespace = WikiFactory::getVarValueByName('wgMetaNamespace', $wgHelpWikiId);
            if (empty($sharedMetaNamespace)) {
                # use wgSitename if empty, per MW docs
                $sharedMetaNamespace = WikiFactory::getVarValueByName('wgSitename', $wgHelpWikiId);
                $sharedMetaNamespace = str_replace(' ', '_', $sharedMetaNamespace);
            }
            if (!empty($sharedMetaNamespace)) {
                global $wgMetaNamespace;
                $content = preg_replace("|{$localArticlePathClean}{$sharedMetaNamespace}|", $localArticlePathClean . $wgMetaNamespace, $content);
            }
            /* Tomasz Odrobny #36016 */
            $sharedRedirectsArticlesKey = wfSharedMemcKey('sharedRedirectsArticles', $wgHelpWikiId, MWNamespace::getCanonicalName($wgTitle->getNamespace()), $wgTitle->getDBkey());
            $articleLink = $wgMemc->get($sharedRedirectsArticlesKey, null);
            if ($articleLink == null) {
                $articleLink = MWNamespace::getCanonicalName(NS_HELP_TALK) . ':' . $wgTitle->getDBkey();
                $apiUrl = $sharedServer . "/api.php?action=query&redirects&format=json&titles=" . $articleLink;
                $file = @file_get_contents($apiUrl, FALSE);
                $APIOut = json_decode($file);
                if (isset($APIOut->query) && isset($APIOut->query->redirects) && count($APIOut->query->redirects) > 0) {
                    $articleLink = str_replace(" ", "_", $APIOut->query->redirects[0]->to);
                }
                $wgMemc->set($sharedRedirectsArticlesKey, $articleLink, 60 * 60 * 12);
            }
            $helpSitename = WikiFactory::getVarValueByName('wgSitename', $wgHelpWikiId);
            // "this text is stored..."
            $info = '<div class="sharedHelpInfo plainlinks" style="text-align: right; font-size: smaller;padding: 5px">' . wfMsgExt('shared_help_info', 'parseinline', $sharedServer . $sharedArticlePathClean . $articleLink, $helpSitename) . '</div>';
            if (strpos($text, '"noarticletext"') > 0) {
                $text = '<div style="border: solid 1px; padding: 10px; margin: 5px" class="sharedHelp">' . $info . $content . '<div style="clear:both"></div></div>';
            } else {
                $text = $text . '<div style="border: solid 1px; padding: 10px; margin: 5px" class="sharedHelp">' . $info . $content . '<div style="clear:both"></div></div>';
            }
        }
    }
    wfProfileOut(__METHOD__);
    return true;
}
Пример #27
0
 /**
  * memcKey
  *
  * combine/prepare cache keys
  *
  * @return string
  */
 private function memcKey()
 {
     return wfSharedMemcKey('globaltitle', $this->mCityId);
 }
Пример #28
0
 /**
  * Return the memcache key for storing cross-wiki "user_touched" value.
  *
  * It's used to refresh user caches on Wiki B when user changes his setting on Wiki A
  *
  * @author wikia
  *
  * @param int $user_id
  * @return string memcache key
  */
 public static function getUserTouchedKey($user_id)
 {
     return wfSharedMemcKey("user_touched", 'v1', $user_id);
 }
Пример #29
0
 /**
  * Get memcache key for given WF variable data
  *
  * @param int $city_id wiki ID
  * @param int $var_id variable ID
  * @return string formatted memcache key
  */
 protected static function getVarValueKey($city_id, $var_id)
 {
     return wfSharedMemcKey('wikifactory:variables:value:v5', $city_id, $var_id);
 }
 protected function getArticleData($pageId)
 {
     global $wgVideoHandlersVideosMigrated;
     $oTitle = Title::newFromID($pageId);
     if (!$oTitle instanceof Title) {
         return false;
     }
     $oMemCache = F::App()->wg->memc;
     $sKey = wfSharedMemcKey('category_exhibition_category_cache_1', $pageId, F::App()->wg->cityId, $this->isVerify(), $wgVideoHandlersVideosMigrated ? 1 : 0, $this->getTouched($oTitle));
     $cachedResult = $oMemCache->get($sKey);
     if (!empty($cachedResult)) {
         return $cachedResult;
     }
     $snippetText = '';
     $imageUrl = $this->getImageFromPageId($pageId);
     if (empty($imageUrl)) {
         $snippetService = new ArticleService($oTitle);
         $snippetText = $snippetService->getTextSnippet();
     }
     $returnData = array('id' => $pageId, 'img' => $imageUrl, 'width' => $this->thumbWidth, 'height' => $this->thumbHeight, 'snippet' => $snippetText, 'title' => $this->getTitleForElement($oTitle), 'url' => $oTitle->getFullURL());
     // will be purged elsewhere after edit
     $oMemCache->set($sKey, $returnData, 60 * 60 * 24);
     return $returnData;
 }