/** * This should be part of the controller, not the model */ public function isVisible() { if (!isset($this->visible)) { $this->visible = in_array(strtolower(RequestContext::getMain()->getSkin()->getSkinName()), array('oasis')) && $this->ownerUser && !$this->ownerUser->isAnon() && AchAwardingService::canEarnBadges($this->ownerUser) && !$this->ownerUser->getGlobalPreference('hidepersonalachievements'); } return $this->visible; }
/** * @dataProvider provideValidate */ public function testForm($text, $value) { $form = HTMLForm::factory('ooui', ['restrictions' => ['class' => HTMLRestrictionsField::class]]); $request = new FauxRequest(['wprestrictions' => $text], true); $context = new DerivativeContext(RequestContext::getMain()); $context->setRequest($request); $form->setContext($context); $form->setTitle(Title::newFromText('Main Page'))->setSubmitCallback(function () { return true; })->prepareForm(); $status = $form->trySubmit(); if ($status instanceof StatusValue) { $this->assertEquals($value !== false, $status->isGood()); } elseif ($value === false) { $this->assertNotSame(true, $status); } else { $this->assertSame(true, $status); } if ($value !== false) { $restrictions = $form->mFieldData['restrictions']; $this->assertInstanceOf(MWRestrictions::class, $restrictions); $this->assertEquals($value, $restrictions->toArray()['IPAddresses']); } // sanity $form->getHTML($status); }
function execute($par) { /** * Some satellite ISPs use broken precaching schemes that log people out straight after * they're logged in (bug 17790). Luckily, there's a way to detect such requests. */ if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '&') !== false) { wfDebug("Special:Userlogout request {$_SERVER['REQUEST_URI']} looks suspicious, denying.\n"); throw new HttpError(400, $this->msg('suspicious-userlogout'), $this->msg('loginerror')); } $this->setHeaders(); $this->outputHeader(); // Make sure it's possible to log out $session = MediaWiki\Session\SessionManager::getGlobalSession(); if (!$session->canSetUser()) { throw new ErrorPageError('cannotlogoutnow-title', 'cannotlogoutnow-text', [$session->getProvider()->describe(RequestContext::getMain()->getLanguage())]); } $user = $this->getUser(); $oldName = $user->getName(); $user->logout(); $loginURL = SpecialPage::getTitleFor('Userlogin')->getFullURL($this->getRequest()->getValues('returnto', 'returntoquery')); $out = $this->getOutput(); $out->addWikiMsg('logouttext', $loginURL); // Hook. $injected_html = ''; Hooks::run('UserLogoutComplete', [&$user, &$injected_html, $oldName]); $out->addHTML($injected_html); $out->returnToMain(); }
/** * @return EventRelayerGroup */ public static function singleton() { if (!self::$instance) { self::$instance = new self(RequestContext::getMain()->getConfig()); } return self::$instance; }
public function execute($params = false) { $sEditLinkText = wfMessage('bs-widget-edit')->text(); $oTitle = Title::makeTitle(NS_USER, RequestContext::getMain()->getUser()->getName() . '/Widgetbar'); $sEditLink = Linker::link($oTitle, Html::rawElement('span', array(), $sEditLinkText), array('id' => 'bs-widgetbar-edit', 'class' => 'icon-pencil clearfix'), array('action' => 'edit', 'preload' => '')); $aOut = array(); $aOut[] = '<div id="bs-widget-container" >'; $aOut[] = ' <div class="icon-plus" id="bs-widget-tab" title="' . wfMessage('bs-widget-container-tooltip')->text() . '" tabindex="100">[+/-]</div>'; $aOut[] = ' <div id="bs-flyout">'; $aOut[] = ' <h4 id="bs-flyout-heading">' . wfMessage('bs-widget-flyout-heading')->text() . '</h4>'; $aOut[] = ' <div id="bs-flyout-content">'; $aOut[] = ' <div id="bs-flyout-content-widgets">'; $aOut[] = ' <h4 id="bs-flyout-content-widgets-header">' . wfMessage("bs-widget-flyout-heading")->plain() . $sEditLink . '</h4>'; foreach ($this->_mWidgets as $oWidgetView) { if ($oWidgetView instanceof ViewWidget) { $aOut[] = $oWidgetView->execute(); } else { wfDebug(__METHOD__ . ': Invalid widget.'); } } $aOut[] = ' </div>'; $aOut[] = ' </div>'; $aOut[] = ' </div>'; $aOut[] = '</div>'; return implode("\n", $aOut); }
function wfTalkHereAjaxEditor( $page, $section, $returnto ) { global $wgRequest, $wgTitle, $wgOut; $title = Title::newFromText( $page ); if ( !$title ) { return false; } //fake editor environment $args = array( 'wpTalkHere' => '1', 'wpReturnTo' => $returnto, 'action' => 'edit', 'section' => $section ); $wgRequest = new FauxRequest( $args ); $wgTitle = $title; $article = Article::newFromTitle( $title, RequestContext::getMain() ); $editor = new TalkHereEditPage( $article ); //generate form $editor->importFormData( $wgRequest ); $editor->showEditForm(); $response = new AjaxResponse(); $response->addText( $wgOut->getHTML() ); $response->setCacheDuration( false ); //don't cache, because of tokens etc return $response; }
public function index() { $title = Title::newFromText('Version', NS_SPECIAL); $popts = ParserOptions::newFromContext(RequestContext::getMain()); $this->wg->Title = $title; $this->specialPage->setHeaders(); $softwareListPrepped = array(); foreach ($this->version->getSoftwareList() as $key => $val) { $softwareListPrepped[$this->wg->Parser->parse($key, $title, $popts)->getText()] = $this->wg->Parser->parse($val, $title, $popts)->getText(); } $this->setVal('copyRightAndAuthorList', $this->wg->Parser->parse($this->version->getCopyrightAndAuthorList(), $title, $popts)->getText()); $this->setVal('softwareInformation', $this->wg->Parser->parse($this->version->softwareInformation(), $title, $popts)->getText()); $this->setVal('extensionCredit', $this->wg->Parser->parse($this->version->getExtensionCredits(), $title, $popts)->getText()); $this->setVal('ip', str_replace('--', ' - ', htmlspecialchars($this->getContext()->getRequest()->getIP()))); $this->setVal('wikiaCodeMessage', wfMessage('wikia-version-code')->escaped()); $this->setVal('wikiaCodeVersion', $this->version->getWikiaCodeVersion()); $this->setVal('wikiaConfigMessage', wfMessage('wikia-version-config')->escaped()); $this->setVal('wikiaConfigVersion', $this->version->getWikiaConfigVersion()); $this->setVal('versionLicenseMessage', wfMessage('version-license')->escaped()); $this->setVal('versionLicenseInfoMessage', wfMessage('version-license-info')->parse()); $this->setVal('versionSoftwareMessage', wfMessage('version-software')->escaped()); $this->setVal('versionSoftwareProductMessage', wfMessage('version-software-product')->escaped()); $this->setVal('versionSoftwareVersionMessage', wfMessage('version-software-version')->escaped()); $this->setVal('versionSoftwareList', $softwareListPrepped); }
public static function purgeMainPage($args) { if ($args['name'] === 'wgEnableNjordExt') { Article::newFromTitle(Title::newFromText(self::MAINPAGE_PAGE), RequestContext::getMain())->doPurge(); } return true; }
function __construct() { //Some internal methods called from this controller need the skin to be wikiamobile //It makes sense to set it explicitly here as other skins shouldn't use it anyway RequestContext::getMain()->setSkin(Skin::newFromKey('wikiamobile')); parent::__construct(); }
function wfInstallerMain() { global $wgRequest, $wgLang, $wgMetaNamespace, $wgCanonicalNamespaceNames; $installer = InstallerOverrides::getWebInstaller($wgRequest); if (!$installer->startSession()) { if ($installer->request->getVal("css")) { // Do not display errors on css pages $installer->outputCss(); exit; } $errors = $installer->getPhpErrors(); $installer->showError('config-session-error', $errors[0]); $installer->finish(); exit; } $fingerprint = $installer->getFingerprint(); if (isset($_SESSION['installData'][$fingerprint])) { $session = $_SESSION['installData'][$fingerprint]; } else { $session = []; } if (!is_null($wgRequest->getVal('uselang'))) { $langCode = $wgRequest->getVal('uselang'); } elseif (isset($session['settings']['_UserLang'])) { $langCode = $session['settings']['_UserLang']; } else { $langCode = 'en'; } $wgLang = Language::factory($langCode); RequestContext::getMain()->setLanguage($wgLang); $installer->setParserLanguage($wgLang); $wgMetaNamespace = $wgCanonicalNamespaceNames[NS_PROJECT]; $session = $installer->execute($session); $_SESSION['installData'][$fingerprint] = $session; }
/** * Produces the actual output. * @param array $params List of parameters for the rendering of output. * @return string The rendered HTML of the extension list */ public function execute($params = false) { global $wgBlueSpiceExtInfo, $wgVersion; $aExtensionInfo = array(); foreach ($this->mExtensions as $aExtension) { if (!isset($aExtension[EXTINFO::NAME])) { continue; } $aExtensionInfoArray = array('name' => array($aExtension[EXTINFO::NAME], $this->getHelpdeskUrl($aExtension)), 'version' => $aExtension[EXTINFO::VERSION] === 'default' ? $wgBlueSpiceExtInfo['version'] : $aExtension[EXTINFO::VERSION], 'package' => !isset($aExtension[EXTINFO::PACKAGE]) || $aExtension[EXTINFO::PACKAGE] === 'default' ? $wgBlueSpiceExtInfo['package'] : $aExtension[EXTINFO::PACKAGE], 'description' => wfMessage($aExtension[EXTINFO::DESCRIPTION])->escaped(), 'status' => $aExtension[EXTINFO::STATUS] === 'default' ? $wgBlueSpiceExtInfo['status'] : $aExtension[EXTINFO::STATUS]); $aExtensionInfo[] = $aExtensionInfoArray; } RequestContext::getMain()->getOutput()->addJsConfigVars('aExtensionInfo', $aExtensionInfo); $sCreditsLink = ' (<a href="' . SpecialPage::getTitleFor('SpecialCredits')->getFullURL() . '">Credits</a>)'; $sVersion = $wgBlueSpiceExtInfo['version'] . ($wgBlueSpiceExtInfo['status'] !== 'stable' ? ' ' . $wgBlueSpiceExtInfo['status'] : ''); $aOut = array(); $aOut[] = '<table class="bs-softwaretable">'; $aOut[] = '<tr>'; $aOut[] = '<th>' . wfMessage('bs-extensioninfo-software')->plain() . '</th>'; $aOut[] = '<th>' . wfMessage('bs-extensioninfo-version')->plain() . '</th>'; $aOut[] = '</tr>'; $aOut[] = '<tr>'; $aOut[] = '<td><a title="' . $wgBlueSpiceExtInfo['url'] . '" href="' . $wgBlueSpiceExtInfo['url'] . '">' . $wgBlueSpiceExtInfo['name'] . '</a>' . $sCreditsLink . '</td>'; $aOut[] = '<td>' . $sVersion . '</td>'; $aOut[] = '</tr>'; $aOut[] = '<tr>'; $aOut[] = '<td><a title="MediaWiki" href="http://www.mediawiki.org/"> MediaWiki </a></td>'; $oTitle = SpecialPage::getTitleFor("Version"); $aOut[] = '<td><a title="' . $oTitle->getFullText() . '" href="' . $oTitle->getFullURL() . '">' . $wgVersion . '</a></td>'; $aOut[] = '</tr>'; $aOut[] = '</table>'; $aOut[] = '<div id="bs-extensioninfo-grid"></div>'; return implode("\n", $aOut); }
public function testLessFileCompilation() { $thisString = $this->toString(); $this->assertTrue(is_string($this->file) && is_file($this->file) && is_readable($this->file), "{$thisString} must refer to a readable file"); $compiler = ResourceLoader::getLessCompiler(RequestContext::getMain()->getConfig()); $this->assertNotNull($compiler->compileFile($this->file)); }
public function index() { $bodyContent = $this->request->getVal('bodyText', ''); $categoryLinks = $this->request->getVal('categoryLinks', ''); $afterBodyHtml = ''; $afterContentHookText = null; // this hook allows adding extra HTML just after <body> opening tag // append your content to $html variable instead of echoing // (taken from Monaco skin) $this->wf->RunHooks('GetHTMLAfterBody', array(RequestContext::getMain()->getSkin(), &$afterBodyHtml)); // this hook is needed for SMW's factbox if (!$this->wf->RunHooks('SkinAfterContent', array(&$afterContentHookText))) { $afterContentHookText = ''; } /* Dont show header if user profile page */ if ($this->wg->Title->getNamespace() !== NS_USER) { $this->response->setVal('pageHeaderContent', $this->app->renderView('WikiaMobilePageHeaderService', 'index')); } else { $this->response->setVal('pageHeaderContent', ''); } $this->response->setVal('bodyContent', $bodyContent); $this->response->setVal('relatedPages', !empty($this->wg->EnableRelatedPagesExt) && empty($this->wg->MakeWikiWebsite) && empty($this->wg->EnableAnswers) ? $this->app->renderView('RelatedPagesController', 'index') : null); $this->response->setVal('categoryLinks', $this->app->renderView('WikiaMobileCategoryService', 'index', array('categoryLinks' => $categoryLinks))); $this->response->setVal('navMenu', $this->app->renderView('WikiaMobileNavigationService', 'navMenu')); $this->response->setVal('afterBodyContent', $afterBodyHtml); $this->response->setVal('afterContentHookText', $afterContentHookText); }
/** * @brief Api entry point to get a page and globals and messages that are relevant to the page * * @example wikia.php?controller=CuratedContent&method=getPage&page={Title} */ public function getPage() { global $wgTitle; // This will always return json $this->response->setFormat('json'); $this->cacheResponseFor(7, self::DAYS); // set mobile skin as this is based on it RequestContext::getMain()->setSkin(Skin::newFromKey('wikiamobile')); $titleName = $this->getVal('page'); $title = Title::newFromText($titleName); if ($title instanceof Title) { RequestContext::getMain()->setTitle($title); $wgTitle = $title; $revId = $title->getLatestRevID(); $articleId = $title->getArticleID(); if ($revId > 0) { try { $relatedPages = $this->app->sendRequest('RelatedPagesApi', 'getList', ['ids' => [$articleId]])->getVal('items')[$articleId]; if (!empty($relatedPages)) { $this->response->setVal('relatedPages', $relatedPages); } } catch (NotFoundApiException $error) { // If RelatedPagesApi is not available don't throw it to app } $this->response->setVal('html', $this->sendSelfRequest('renderPage', array('page' => $titleName))->toString()); $this->response->setVal('revisionid', $revId); } else { throw new NotFoundApiException('Revision ID = 0'); } } else { throw new NotFoundApiException('Title not found'); } }
protected function getDetails() { $article = \Article::newFromTitle($this->commentTitle, \RequestContext::getMain()); $service = new \ArticleService($article); $snippet = $service->getTextSnippet(); return $snippet; }
private static function getManager($continue, $allModules, $generatedModules) { $context = new DerivativeContext(RequestContext::getMain()); $context->setRequest(new FauxRequest(array('continue' => $continue))); $main = new ApiMain($context); return new ApiContinuationManager($main, $allModules, $generatedModules); }
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; }
protected function setUp() { parent::setUp(); // Avoid 'GetHumanTimestamp' hook and others $this->setMwGlobals('wgHooks', array()); RequestContext::getMain()->setLanguage(Language::factory('en')); }
/** * @covers RequestContext::importScopedSession */ public function testImportScopedSession() { $context = RequestContext::getMain(); $oInfo = $context->exportSession(); $this->assertEquals('127.0.0.1', $oInfo['ip'], "Correct initial IP address."); $this->assertEquals(0, $oInfo['userId'], "Correct initial user ID."); $user = User::newFromName('UnitTestContextUser'); $user->addToDatabase(); $sinfo = array('sessionId' => 'd612ee607c87e749ef14da4983a702cd', 'userId' => $user->getId(), 'ip' => '192.0.2.0', 'headers' => array('USER-AGENT' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0')); // importScopedSession() sets these variables $this->setMwGlobals(array('wgUser' => new User(), 'wgRequest' => new FauxRequest())); $sc = RequestContext::importScopedSession($sinfo); // load new context $info = $context->exportSession(); $this->assertEquals($sinfo['ip'], $info['ip'], "Correct IP address."); $this->assertEquals($sinfo['headers'], $info['headers'], "Correct headers."); $this->assertEquals($sinfo['sessionId'], $info['sessionId'], "Correct session ID."); $this->assertEquals($sinfo['userId'], $info['userId'], "Correct user ID."); $this->assertEquals($sinfo['ip'], $context->getRequest()->getIP(), "Correct context IP address."); $this->assertEquals($sinfo['headers'], $context->getRequest()->getAllHeaders(), "Correct context headers."); $this->assertEquals($sinfo['sessionId'], session_id(), "Correct context session ID."); $this->assertEquals(true, $context->getUser()->isLoggedIn(), "Correct context user."); $this->assertEquals($sinfo['userId'], $context->getUser()->getId(), "Correct context user ID."); $this->assertEquals('UnitTestContextUser', $context->getUser()->getName(), "Correct context user name."); unset($sc); // restore previous context $info = $context->exportSession(); $this->assertEquals($oInfo['ip'], $info['ip'], "Correct restored IP address."); $this->assertEquals($oInfo['headers'], $info['headers'], "Correct restored headers."); $this->assertEquals($oInfo['sessionId'], $info['sessionId'], "Correct restored session ID."); $this->assertEquals($oInfo['userId'], $info['userId'], "Correct restored user ID."); }
protected function runOnPageSet(ApiPageSet $pageSet) { $articles = array_map(function (Title $item) { return Article::newFromTitle($item, RequestContext::getMain()); }, $pageSet->getGoodTitles()); /** * @var Article $article */ foreach ($articles as $id => $article) { $d = $article->getParserOutput()->getProperty(PortableInfoboxDataService::INFOBOXES_PROPERTY_NAME); if (is_array($d)) { $inf = []; foreach (array_keys($d) as $k => $v) { $inf[$k] = []; } $pageSet->getResult()->setIndexedTagName($inf, 'infobox'); $pageSet->getResult()->addValue(['query', 'pages', $id], 'infoboxes', $inf); foreach ($d as $count => $infobox) { $s = isset($infobox['sources']) ? $infobox['sources'] : []; $pageSet->getResult()->addValue(['query', 'pages', $id, 'infoboxes', $count], 'id', $count); $pageSet->getResult()->setIndexedTagName($s, "source"); $pageSet->getResult()->addValue(['query', 'pages', $id, 'infoboxes', $count], 'sources', $s); } } } }
public function execute() { global $wgUser; $wgUser = User::newFromName('Maintenance script'); RequestContext::getMain()->setUser($wgUser); $dbr = CentralAuthUser::getCentralSlaveDB(); if ($this->getOption('fix', false) !== false) { $this->fix = true; } if ($this->getOption('safe-migrate', false) !== false) { $this->safe = true; $this->migrate = true; } if ($this->getOption('migrate', false) !== false) { $this->migrate = true; } if ($this->getOption('suppressrc', false) !== false) { $this->suppressRC = true; } $end = $dbr->selectField('globaluser', 'MAX(gu_id)'); for ($cur = 0; $cur <= $end; $cur += $this->mBatchSize) { $this->output("PROGRESS: {$cur} / {$end}\n"); $result = $dbr->select(array('globaluser', 'localuser'), array('gu_name'), array('lu_name' => null, "gu_id >= {$cur}", 'gu_id < ' . ($cur + $this->mBatchSize)), __METHOD__, array('ORDER BY' => 'gu_id'), array('localuser' => array('LEFT JOIN', 'gu_name=lu_name'))); foreach ($result as $row) { $this->process($row->gu_name); } if ($this->fix) { CentralAuthUser::waitForSlaves(); } } $this->output("done.\n"); }
public function testBeginLinkAttempt() { $badReq = $this->getMockBuilder(AuthenticationRequest::class)->setMethods(['getUniqueId'])->getMockForAbstractClass(); $badReq->expects($this->any())->method('getUniqueId')->will($this->returnValue("BadReq")); $user = \User::newFromName('UTSysop'); $provider = \TestingAccessWrapper::newFromObject(new ConfirmLinkSecondaryAuthenticationProvider()); $request = new \FauxRequest(); $manager = $this->getMockBuilder(AuthManager::class)->setMethods(['allowsAuthenticationDataChange'])->setConstructorArgs([$request, \RequestContext::getMain()->getConfig()])->getMock(); $manager->expects($this->any())->method('allowsAuthenticationDataChange')->will($this->returnCallback(function ($req) { return $req->getUniqueId() !== 'BadReq' ? \StatusValue::newGood() : \StatusValue::newFatal('no'); })); $provider->setManager($manager); $this->assertEquals(AuthenticationResponse::newAbstain(), $provider->beginLinkAttempt($user, 'state')); $request->getSession()->setSecret('state', ['maybeLink' => []]); $this->assertEquals(AuthenticationResponse::newAbstain(), $provider->beginLinkAttempt($user, 'state')); $reqs = $this->getLinkRequests(); $request->getSession()->setSecret('state', ['maybeLink' => $reqs + ['BadReq' => $badReq]]); $res = $provider->beginLinkAttempt($user, 'state'); $this->assertInstanceOf(AuthenticationResponse::class, $res); $this->assertSame(AuthenticationResponse::UI, $res->status); $this->assertSame('authprovider-confirmlink-message', $res->message->getKey()); $this->assertCount(1, $res->neededRequests); $req = $res->neededRequests[0]; $this->assertInstanceOf(ConfirmLinkAuthenticationRequest::class, $req); $expectReqs = $this->getLinkRequests(); foreach ($expectReqs as $r) { $r->action = AuthManager::ACTION_CHANGE; $r->username = $user->getName(); } $this->assertEquals($expectReqs, \TestingAccessWrapper::newFromObject($req)->linkRequests); }
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; }
public static function getUsername() { $conf = RequestContext::getMain()->getConfig(); $headerName = $conf->get('SSOHeader'); $remoteDomain = $conf->get('AuthRemoteuserDomain'); $remoteDomains = array_flip(array_merge([$remoteDomain], $conf->get('AuthRemoteuserDomains'))); $username = $conf->get('Request')->getHeader($headerName); if (!$username) { wfDebugLog(__CLASS__, "The webserver should set {$headerName}."); return false; } if ($remoteDomains) { $bits = explode('@', $username); if (count($bits) !== 2) { throw new MWException("Couldn't get username and domain " . "from {$username}"); } $username = $bits[0]; $userDomain = $bits[1]; if (isset($userDomain) && !isset($remoteDomains[$userDomain])) { throw new MWException("Username didn't have the right domain. " . "Got '{$userDomain}', wanted one of '" . implode(", ", $remoteDomains) . "'."); } if (isset($remoteDomains[$userDomain]) && $userDomain !== $remoteDomain) { $username = "******"; } } return $username; }
/** * Does the API request and returns the result. * * The returned value is an array containing * - the result data (array) * - the request (WebRequest) * - the session data of the request (array) * - if $appendModule is true, the Api module $module * * @param array $params * @param array|null $session * @param bool $appendModule * @param User|null $user * * @return array */ protected function doApiRequest(array $params, array $session = null, $appendModule = false, User $user = null) { global $wgRequest, $wgUser; if (is_null($session)) { // re-use existing global session by default $session = $wgRequest->getSessionArray(); } // set up global environment if ($user) { $wgUser = $user; } $wgRequest = new FauxRequest($params, true, $session); RequestContext::getMain()->setRequest($wgRequest); RequestContext::getMain()->setUser($wgUser); // set up local environment $context = $this->apiContext->newTestContext($wgRequest, $wgUser); $module = new ApiMain($context, true); // run it! $module->execute(); // construct result $results = array($module->getResult()->getResultData(null, array('Strip' => 'all')), $context->getRequest(), $context->getRequest()->getSessionArray()); if ($appendModule) { $results[] = $module; } return $results; }
public function getBatchCallHtml() { $this->batchHtmlCalled = true; $out = "<!-- ## BEGIN " . __CLASS__ . '::' . __METHOD__ . " ## -->\n"; // Make a call for each slot. $this->slotsToCall = AdEngine::getInstance()->getSlotNamesForProvider($this->provider_id); $out .= '<script type="text/javascript">' . "\n"; if (!$this->iframeRendering) { foreach ($this->slotsToCall as $slotname) { $out .= 'GA_googleAddSlot("' . $this->adManagerId . '","' . $slotname . '");' . "\n"; // Set up key values $out .= $this->getProviderValues($slotname); } } // ###### Our custom key values // Always pass the hub as a key value $out .= $this->getTargetingValue('hub', $this->getHub()) . "\n"; // And skin $out .= $this->getTargetingValue('skin_name', RequestContext::getMain()->getSkin()->getSkinName()) . "\n"; // And languages $out .= 'GA_googleAddAttr("cont_lang", wgContentLanguage);' . "\n"; $out .= 'GA_googleAddAttr("user_lang", wgUserLanguage);' . "\n"; // And dbname $out .= 'GA_googleAddAttr("dbname", wgDB);' . "\n"; // ###### Ad Sense attributes $out .= $this->getAdSenseAttr() . "\n" . '</script>' . "\n"; // Make the call for all the ads if (!$this->iframeRendering) { $out .= '<script type="text/javascript">GA_googleFetchAds();</script>' . "\n"; } $out .= "<!-- ## END " . __CLASS__ . '::' . __METHOD__ . " ## -->\n"; return $out; }
/** * @param string $id Session ID * @param array|mixed $blob Session metadata and data * @param int $expiry Expiry */ public function setRawSession($id, $blob, $expiry = 0) { if ($expiry <= 0) { $expiry = \RequestContext::getMain()->getConfig()->get('ObjectCacheSessionExpiry'); } $this->set(wfMemcKey('MWSession', $id), $blob, $expiry); }
/** * Whether CategorySelect should be used for the current request. * @return Boolean */ public static function isEnabled() { wfProfileIn(__METHOD__); if (!isset(self::$isEnabled)) { $app = F::app(); $request = $app->wg->Request; $title = $app->wg->Title; $user = $app->wg->User; $action = $request->getVal('action', 'view'); $undo = $request->getVal('undo'); $undoafter = $request->getVal('undoafter'); $viewModeActions = array('view', 'purge'); $editModeActions = array('edit', 'submit'); $supportedActions = array_merge($viewModeActions, $editModeActions); $supportedSkins = array('SkinAnswers', 'SkinOasis', 'SkinVenus'); $isViewMode = in_array($action, $viewModeActions); $isEditMode = in_array($action, $editModeActions); $extraNamespacesOnView = array(NS_FILE, NS_CATEGORY); $extraNamespacesOnEdit = array(NS_FILE, NS_CATEGORY, NS_USER, NS_SPECIAL); $isEnabled = true; if ($request->getVal('usecatsel', '') == 'no' || $user->getGlobalPreference('disablecategoryselect') || !in_array(get_class(RequestContext::getMain()->getSkin()), $supportedSkins) || !in_array($action, $supportedActions) || $title->isCssJsSubpage() || $action == 'view' && !$title->exists() || $action == 'purge' && $user->isAnon() && !$request->wasPosted() || $undo > 0 && $undoafter > 0 || $title->mNamespace == NS_TEMPLATE || $isViewMode && !in_array($title->mNamespace, array_merge($app->wg->ContentNamespaces, $extraNamespacesOnView)) || $isEditMode && !in_array($title->mNamespace, array_merge($app->wg->ContentNamespaces, $extraNamespacesOnEdit))) { $isEnabled = false; } self::$isEnabled = $isEnabled; } wfProfileOut(__METHOD__); return self::$isEnabled; }
/** * @param IContextSource|null $context */ public function __construct(IContextSource $context = null) { if (!$context) { $context = RequestContext::getMain(); } $this->context = $context; }
function streamAppleTouch() { global $wgAppleTouchIcon; wfResetOutputBuffers(); if ($wgAppleTouchIcon === false) { # That's not very helpful, that's where we are already header('HTTP/1.1 404 Not Found'); faviconShowError('$wgAppleTouchIcon is configured incorrectly, ' . 'it must be set to something other than false \\n'); return; } $req = RequestContext::getMain()->getRequest(); if ($req->getHeader('X-Favicon-Loop') !== false) { header('HTTP/1.1 500 Internal Server Error'); faviconShowError('Proxy forwarding loop detected'); return; } $url = wfExpandUrl($wgAppleTouchIcon, PROTO_CANONICAL); $client = MWHttpRequest::factory($url); $client->setHeader('X-Favicon-Loop', '1'); $status = $client->execute(); if (!$status->isOK()) { header('HTTP/1.1 500 Internal Server Error'); faviconShowError("Failed to fetch URL \"{$url}\""); return; } $content = $client->getContent(); header('Content-Length: ' . strlen($content)); header('Content-Type: ' . $client->getResponseHeader('Content-Type')); header('Cache-Control: public'); header('Expires: ' . gmdate('r', time() + 86400)); echo $content; }