コード例 #1
1
 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
ファイル: SFlow.class.php プロジェクト: Tjorriemorrie/app
 /**
  * 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__);
 }
コード例 #3
0
 /**
  * Get data for displaying and playing a Related Video
  * @param int $articleId if provided, look up article by ID. Supercedes $title. Note: this forces a read from master DB, not slave.
  * @param type $title if provided, look up article by text.
  * @param string $source if video is on an external wiki, DB name of that wiki. Empty value indicates video is stored locally.
  * @param int $videoWidth Width of resulting video player, in pixels
  * @return Array 
  */
 public function getRelatedVideoData($params, $videoWidth = RelatedVideosData::DEFAULT_OASIS_VIDEO_WIDTH, $cityShort = 'life', $useMaster = 0, $videoHeight = '', $useJWPlayer = true, $autoplay = true, $inAjaxResponse = false)
 {
     $titleText = isset($params['title']) ? $params['title'] : '';
     $articleId = isset($params['articleId']) ? $params['articleId'] : 0;
     $source = isset($params['source']) ? $params['source'] : '';
     wfProfileIn(__METHOD__);
     $titleText = urldecode($titleText);
     $result = $this->getFromCache($titleText, $source, $videoWidth, $cityShort);
     if (empty($result)) {
         Wikia::log(__METHOD__, 'RelatedVideos', 'Not from cache');
         $result = array();
         $rvd = F::build('RelatedVideosData');
         /* @var $rvd RelatedVideosData */
         $result['data'] = $rvd->getVideoData($titleText, self::$width, $videoWidth, $articleId, $autoplay, $useMaster, $cityShort, $videoHeight, $useJWPlayer, $inAjaxResponse);
         if (isset($result['data']['error'])) {
             wfProfileOut(__METHOD__);
             return array();
         }
         // just to be sure and to be able to work cross devbox.
         if (!isset($result['data']['uniqueId'])) {
             wfProfileOut(__METHOD__);
             return array();
         }
         $this->saveToCache($titleText, $source, $videoWidth, $cityShort, $result);
     } else {
         Wikia::log(__METHOD__, 'RelatedVideos', 'From cache');
     }
     // add local data
     $result['data'] = $this->extendVideoByLocalParams($result['data'], $params);
     wfProfileOut(__METHOD__);
     return $result['data'];
 }
コード例 #4
0
	/**
	 * 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;
	}
コード例 #5
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;
}
コード例 #6
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;
 }
コード例 #7
0
 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;
 }
コード例 #8
0
 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');
     }
 }
コード例 #9
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;
 }
コード例 #10
0
 /**
  * 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);
 }
コード例 #11
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);
}
コード例 #12
0
    /**
     * 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>');
    }
コード例 #13
0
 /**
  * Called from Phalanx::getFromFilter
  *
  * @param $blockType int numeric ID of block type
  */
 public static function setType($blockType)
 {
     if (isset(self::$typesMap[$blockType])) {
         self::$typeName = self::$typesMap[$blockType];
         wfDebug(__METHOD__ . ": type #{$blockType}\n");
     } else {
         self::$typeName = null;
         Wikia::log(__METHOD__, false, "not recognized type provided: #{$blockType}", true);
     }
 }
コード例 #14
0
 protected function loadStructuredData(EditHubModel $model, $params)
 {
     try {
         $apiResponse = $this->app->sendRequest('WAMApi', 'getWAMIndex', $params)->getData();
     } catch (WikiaHttpException $e) {
         $logMsg = 'Message: ' . $e->getLogMessage() . ' Details: ' . $e->getDetails();
         Wikia::log(__METHOD__, false, $logMsg);
         Wikia::logBacktrace(__METHOD__);
     }
     $data = ['vertical_id' => $params['vertical_id'], 'api_response' => $apiResponse];
     return $this->getStructuredData($data);
 }
コード例 #15
0
 function execute($params)
 {
     global $wgRequest, $wgOut, $wgTitle, $wgUser;
     global $wgContLang, $wgProxyKey, $wgParser;
     $article = $wgRequest->getText('article', $params);
     $map = $wgRequest->getText('map', $params);
     $wgOut->disable();
     header("Cache-Control: no-cache, must-revalidate");
     header("Content-type: application/vnd.google-earth.kml+xml");
     header('Content-Disposition: attachment; filename="' . $article . '.kml"');
     $title = Title::newFromText($article);
     /* Wikia change begin - @author: Sebastian Marzjan */
     /* fogbugz BugID #18043 */
     if ($title instanceof Title) {
         /* Wikia change end */
         $revision = Revision::newFromTitle($title);
         /* Wikia change begin - @author: Sebastian Marzjan */
         /* fogbugz BugID #18043 */
         if (!$revision instanceof Revision) {
             $errorMessage = 'SpecialGoogleMapsKML.php ' . __LINE__ . ' - no revision for ' . $article . ' / ' . $title->getArticleID();
             Wikia::log(__METHOD__, false, $errorMessage);
             echo "No article revisions found by the name of {$article}";
             return false;
         }
         /* Wikia change end */
         $mapOptions = GoogleMaps::getMapSettings($title, array('icons' => 'http://maps.google.com/mapfiles/kml/pal4/{label}.png', 'icon' => 'icon57'));
         $exporter = new GoogleMapsKmlExporter($wgContLang, str_replace('{label}', $mapOptions['icon'], $mapOptions['icons']));
         $wgParser->mOptions = ParserOptions::newFromUser($wgUser);
         $wgParser->mOptions->setEditSection(false);
         $wgParser->mTitle = $wgTitle;
         $wgParser->clearState();
         $localParser = new Parser();
         $localParser->mTitle = $title;
         $localParser->mOptions = $wgParser->mOptions;
         if (preg_match_all("/<googlemap( .*?|)>(.*?)<\\/googlemap>/s", $revision->getText(), $matches)) {
             $exporter->addFileHeader();
             for ($i = 0; $i < count($matches[2]); $i++) {
                 $attrs = Sanitizer::decodeTagAttributes($matches[1][$i]);
                 $mapOptions['version'] = isset($attrs['version']) ? $attrs['version'] : "0";
                 $exporter->addHeader(isset($attrs['title']) ? $attrs['title'] : "Map #" . ($i + 1));
                 GoogleMaps::renderContent($matches[2][$i], $wgParser, $localParser, $exporter, $mapOptions);
                 $exporter->addTrailer();
             }
             $exporter->addFileTrailer();
             echo $exporter->render();
         } else {
             echo "No maps in {$article}!";
         }
     } else {
         echo "No article found by the name of {$article}";
     }
 }
コード例 #16
0
 public function getCode()
 {
     $response = $this->getResponse();
     $response->setContentType('text/javascript; charset=utf-8');
     $storageModel = new MySQLKeyValueModel();
     try {
         $this->code = $storageModel->get(self::OPTIMIZELY_SCRIPT_KEY);
     } catch (Exception $e) {
         Wikia::log(__METHOD__, false, 'Cannot read Optimizely code from storage.');
         $this->code = '';
     }
     $response->setCacheValidity(self::CACHE_DURATION);
 }
コード例 #17
0
 public static function isValidColor($sColor)
 {
     // First try
     $isHexColor = preg_match('/^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$/', $sColor);
     if (!empty($isHexColor)) {
         return true;
     }
     // Last chance: array is not proper hash so maybe it is predefined color name
     $aColorArray = array('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen');
     $isColorName = in_array(strtolower($sColor), $aColorArray);
     Wikia::log(__METHOD__, "JKU", "[{$sColor}] is not a valid color name");
     return $isColorName;
 }
コード例 #18
0
 private function clearCache($langCode)
 {
     $this->wg->Memc->delete($this->getCollectionsListCacheKey($langCode));
     $this->wg->Memc->delete($this->getCollectionsListVisualizationCacheKey($langCode));
     $visualization = new CityVisualization();
     $corporateModel = new WikiaCorporateModel();
     foreach ($this->getList($langCode) as $collection) {
         $this->wg->Memc->delete($visualization->getCollectionCacheKey($collection['id']));
         $title = GlobalTitle::newMainPage($corporateModel->getCorporateWikiIdByLang($langCode));
         $title->purgeSquid();
         Wikia::log(__METHOD__, '', 'Purged memcached for collection #' . $collection['id']);
     }
 }
コード例 #19
0
 /**
  * isDomainExists
  *
  * check in city_domains if we have such wikia in city_domains
  *
  * @param string $name: domain name
  * @param string $language default null - choosen language
  * @param mixed  $type type of domain, default false = wikia.com
  *
  * @return integer - 0 or 1
  */
 public static function domainExists($name, $language = null, $type = false)
 {
     global $wgExternalSharedDB;
     $sDomain = Wikia::fixDomainName($name, $language, $type);
     Wikia::log(__METHOD__, "domain", "{$sDomain} name={$name}, language={$language}, type={$type}");
     $dbr = wfGetDB(DB_SLAVE, array(), $wgExternalSharedDB);
     $oRow = $dbr->selectRow("city_domains", array("city_id"), array("city_domain" => $sDomain), __METHOD__);
     if (!isset($oRow->city_id)) {
         $oRow = $dbr->selectRow("city_domains", array("city_id"), array("city_domain" => sprintf("%s.%s", "www", $sDomain)), __METHOD__);
     }
     $result = !empty($oRow->city_id) ? true : false;
     return $result;
 }
コード例 #20
0
 public function __construct(WebRequest $request)
 {
     parent::__construct($request);
     global $IP, $wgUser;
     $ac = new AssetsConfig();
     $assets = $ac->resolve($this->mOid, true, !isset($this->mParams['minify']) || $this->mParams['minify'] == true, $this->mParams);
     $this->mContentType = $ac->getGroupType($this->mOid);
     foreach ($assets as $asset) {
         // reference to a file to be fetched by the browser from external server (BugId:9522)
         if (substr($asset, 0, 10) == '#external_') {
             // do nothing
         } else {
             if (Http::isValidURI($asset)) {
                 $params = array();
                 $url = parse_url($asset);
                 if (isset($url['query'])) {
                     parse_str($url['query'], $params);
                 }
                 // Start checking the url to see if it is something we care about (BugId:30188)
                 if (isset($params['action']) && $params['action'] == 'raw' && isset($params['gen']) && $params['gen'] == 'js') {
                     //$this->mContent .= RequestContext::getMain()->getSkin()->generateUserJs(); // FIXME
                 } else {
                     if (isset($params['action']) && $params['action'] == 'raw' && isset($params['gen']) && $params['gen'] == 'css') {
                         //$this->mContent .= RequestContext::getMain()->getSkin()->generateUserStylesheet(); // FIXME
                     } else {
                         //Debug added on May 4, 2012 to inquire external requests spikes
                         $start = microtime(true);
                         $this->mContent .= HTTP::get($asset);
                         $totalTime = microtime(true) - $start;
                         if ($totalTime >= 1) {
                             Wikia::log(__METHOD__, false, "oid: {$this->mOid}, totalTime: {$totalTime}, asset: {$asset}, referrer: {$_SERVER['HTTP_REFERER']}, entrypoint: {$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}", true);
                         }
                     }
                 }
             } else {
                 $this->mContent .= file_get_contents($IP . '/' . $asset);
             }
         }
         if ($this->mContentType == AssetsManager::TYPE_JS) {
             // add semicolon to separate concatenated files (BugId:20272)
             // but only for JS (BugId:20824)
             $this->mContent .= ";\n";
         }
     }
     // For RTE only
     // TODO: add "filters" definitions to config.php
     if ($this->mOid == 'rte' || $this->mOid == 'eplrte' || $this->mOid == 'mini_editor_rte_js') {
         $this->mContent = preg_replace('#^.*@Packager\\.RemoveLine.*$#m', '', $this->mContent);
         $this->mContent = str_replace("", '', $this->mContent);
     }
 }
コード例 #21
0
 public static function axDownloadCSV()
 {
     Wikia::log(__METHOD__, 'Depreciated?');
     $SponsorshipDashboard = new SponsorshipDashboard();
     if (isset($_GET['elementId']) && !empty($_GET['elementId']) && $SponsorshipDashboard->isAllowed()) {
         $report = new SponsorshipDashboardReport($_GET['elementId']);
         $report->loadReportParams();
         $dataFormatter = SponsorshipDashboardOutputCSV::newFromReport($report);
         echo $dataFormatter->getHTML();
         exit;
     } else {
         echo wfMsg('sponsorship-dashboard-not-allowed');
     }
 }
コード例 #22
0
 /**
  * Send data via Scribe
  *
  * @param ProfilerData $data
  */
 public function send(ProfilerData $data)
 {
     if (!$this->checkDependencies()) {
         return;
     }
     $scribeKey = $this->getScribeKey($data->getEngine());
     $data = array('time' => microtime(true), 'engine' => $data->getEngine(), 'profile' => $data->getProfile(), 'context' => Transaction::getAttributes(), 'request' => $data->getRequest(), 'entries' => $data->getEntries());
     $data = json_encode($data);
     try {
         WScribeClient::singleton($scribeKey)->send($data);
     } catch (TException $e) {
         Wikia::log(__METHOD__, 'scribeClient exception', $e->getMessage());
     }
 }
コード例 #23
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 = $app->wf->SharedMemcKey('WikiaBarContents', $vertical, $language, WikiaBarModel::WIKIA_BAR_MCACHE_VERSION);
                 Wikia::log(__METHOD__, '', 'Purging ' . $dataMemcKey);
                 $app->wg->memc->set($dataMemcKey, null);
             }
         }
     }
     return true;
 }
コード例 #24
0
ファイル: MenuUserCommand.php プロジェクト: Tjorriemorrie/app
 protected static function renderDataList($list)
 {
     $result = array();
     foreach ($list as $v) {
         if (is_object($v)) {
             $item = $v->getRenderData();
             if ($item) {
                 $result[] = $item;
             }
         } else {
             Wikia::log(__METHOD__, false, 'BugID: 21498');
             Wikia::logBacktrace(__METHOD__);
         }
     }
     return $result;
 }
コード例 #25
0
 /**
  * Send a set of events with a provided context
  *
  * @param array $events set of events to be sent
  * @param array $context request context to be attached to each event (can be empty)
  */
 private static function send(array $events, array $context = array())
 {
     // no data to send
     if (empty($events)) {
         return;
     }
     $data = ['time' => microtime(true), 'app' => Transaction::APP_NAME, 'context' => $context, 'events' => $events];
     $data = json_encode($data);
     try {
         WScribeClient::singleton(self::SCRIBE_KEY)->send($data);
     } catch (TException $e) {
         if (is_callable('Wikia::log')) {
             Wikia::log(__METHOD__, 'scribeClient exception', $e->getMessage());
         }
     }
 }
コード例 #26
0
ファイル: Preferences.php プロジェクト: Tjorriemorrie/app
 /**
  * @throws MWException
  * @param $user User
  * @param $context IContextSource
  * @return array|null
  */
 static function getPreferences($user, IContextSource $context)
 {
     if (self::$defaultPreferences) {
         return self::$defaultPreferences;
     }
     $defaultPreferences = array();
     self::profilePreferences($user, $context, $defaultPreferences);
     self::skinPreferences($user, $context, $defaultPreferences);
     self::filesPreferences($user, $context, $defaultPreferences);
     self::datetimePreferences($user, $context, $defaultPreferences);
     self::renderingPreferences($user, $context, $defaultPreferences);
     self::editingPreferences($user, $context, $defaultPreferences);
     self::rcPreferences($user, $context, $defaultPreferences);
     self::watchlistPreferences($user, $context, $defaultPreferences);
     self::searchPreferences($user, $context, $defaultPreferences);
     self::miscPreferences($user, $context, $defaultPreferences);
     wfRunHooks('GetPreferences', array($user, &$defaultPreferences));
     ## Remove preferences that wikis don't want to use
     global $wgHiddenPrefs;
     foreach ($wgHiddenPrefs as $pref) {
         if (isset($defaultPreferences[$pref])) {
             unset($defaultPreferences[$pref]);
         }
     }
     ## Prod in defaults from the user
     foreach ($defaultPreferences as $name => &$info) {
         $prefFromUser = self::getUserPreference($name, $info, $user);
         $field = HTMLForm::loadInputFromParameters($name, $info);
         // For validation
         $defaultOptions = User::getDefaultOptions();
         $globalDefault = isset($defaultOptions[$name]) ? $defaultOptions[$name] : null;
         // If it validates, set it as the default
         if (isset($info['default'])) {
             // Already set, no problem
             continue;
         } elseif (!is_null($prefFromUser) && $field->validate($prefFromUser, $user->mOptions) === true) {
             $info['default'] = $prefFromUser;
         } elseif ($field->validate($globalDefault, $user->mOptions) === true) {
             $info['default'] = $globalDefault;
         } else {
             Wikia::log(__METHOD__, 'JKU', "Global default '{$globalDefault}' is invalid for field {$name}");
             throw new MWException("Global default '{$globalDefault}' is invalid for field {$name}");
         }
     }
     self::$defaultPreferences = $defaultPreferences;
     return $defaultPreferences;
 }
コード例 #27
0
 public static function badWordsTest($title)
 {
     global $wgLanguageCode;
     wfProfileIn(__METHOD__);
     $text = preg_replace('/[^\\PP]+/', '', $title->getText());
     $text = preg_replace('/\\s+/', ' ', $text);
     $blocksData = Phalanx::getFromFilter(Phalanx::TYPE_ANSWERS_QUESTION_TITLE, $wgLanguageCode);
     $blockData = null;
     $result = Phalanx::findBlocked($text, $blocksData, true, $blockData);
     if ($result['blocked']) {
         Wikia::log(__METHOD__, __LINE__, "Block '{$result['msg']}' blocked '{$text}'.");
         wfProfileOut(__METHOD__);
         return false;
     }
     wfProfileOut(__METHOD__);
     return true;
 }
コード例 #28
0
 public static function isAllowedText($text, $where, $split)
 {
     wfProfileIn(__METHOD__);
     $text = trim($text);
     $blocksData = Phalanx::getFromFilter(Phalanx::TYPE_WIKI_CREATION);
     if (!empty($blocksData) && !empty($text)) {
         $blockData = null;
         $result = Phalanx::findBlocked($text, $blocksData, true, $blockData);
         if ($result['blocked']) {
             wfProfileOut(__METHOD__);
             Wikia::log(__METHOD__, __LINE__, "Block '{$result['msg']}' blocked '{$text}'.");
             return false;
         }
     }
     wfProfileOut(__METHOD__);
     return true;
 }
コード例 #29
0
 public static function filterWordsTest($question)
 {
     wfProfileIn(__METHOD__);
     $text = preg_replace('/\\pP+/', '', $question);
     $text = preg_replace('/\\s+/', ' ', $text);
     $blocksData = Phalanx::getFromFilter(Phalanx::TYPE_ANSWERS_RECENT_QUESTIONS);
     if (!empty($blocksData) && !empty($text)) {
         $blockData = null;
         $result = Phalanx::findBlocked($text, $blocksData, true, $blockData);
         if ($result['blocked']) {
             Wikia::log(__METHOD__, __LINE__, "Block '{$result['msg']}' blocked '{$text}'.");
             wfProfileOut(__METHOD__);
             return false;
         }
     }
     wfProfileOut(__METHOD__);
     return true;
 }
コード例 #30
0
 public static function serve(WebRequest $request)
 {
     try {
         switch ($request->getText('type')) {
             case 'one':
                 $builder = new AssetsManagerOneBuilder($request);
                 break;
             case 'group':
                 $builder = new AssetsManagerGroupBuilder($request);
                 break;
             case 'groups':
                 $builder = new AssetsManagerGroupsBuilder($request);
                 break;
             case 'sass':
                 $builder = new AssetsManagerSassBuilder($request);
                 break;
             default:
                 Wikia::log(__METHOD__, false, "Unknown type: {$_SERVER['REQUEST_URI']}", true);
                 Wikia::log(__METHOD__, false, AssetsManager::getRequestDetails(), true);
                 throw new Exception('Unknown type.');
         }
     } catch (Exception $e) {
         header('HTTP/1.1 404 Not Found');
         echo $e->getMessage();
         return;
     }
     $headers = array();
     if ($builder->getContentType()) {
         $headers['Content-Type'] = $builder->getContentType();
     }
     // BugId:31327
     $headers['Vary'] = $builder->getVary();
     $cacheDuration = $builder->getCacheDuration();
     if ($cacheDuration > 0) {
         $headers['Expires'] = gmdate('D, d M Y H:i:s \\G\\M\\T', strtotime($cacheDuration . ' seconds'));
         $headers['X-Pass-Cache-Control'] = $builder->getCacheMode() . ', max-age=' . $cacheDuration;
         $headers['Cache-Control'] = $builder->getCacheMode() . ', max-age=' . $cacheDuration;
     }
     $headers['Last-Modified'] = gmdate('D, d M Y H:i:s \\G\\M\\T');
     foreach ($headers as $k => $v) {
         header($k . ': ' . $v);
     }
     echo $builder->getContent();
 }