public function testGetGlobalSession()
 {
     $context = \RequestContext::getMain();
     if (!PHPSessionHandler::isInstalled()) {
         PHPSessionHandler::install(SessionManager::singleton());
     }
     $rProp = new \ReflectionProperty(PHPSessionHandler::class, 'instance');
     $rProp->setAccessible(true);
     $handler = \TestingAccessWrapper::newFromObject($rProp->getValue());
     $oldEnable = $handler->enable;
     $reset[] = new \Wikimedia\ScopedCallback(function () use($handler, $oldEnable) {
         if ($handler->enable) {
             session_write_close();
         }
         $handler->enable = $oldEnable;
     });
     $reset[] = TestUtils::setSessionManagerSingleton($this->getManager());
     $handler->enable = true;
     $request = new \FauxRequest();
     $context->setRequest($request);
     $id = $request->getSession()->getId();
     session_id('');
     $session = SessionManager::getGlobalSession();
     $this->assertSame($id, $session->getId());
     session_id('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
     $session = SessionManager::getGlobalSession();
     $this->assertSame('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $session->getId());
     $this->assertSame('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $request->getSession()->getId());
     session_write_close();
     $handler->enable = false;
     $request = new \FauxRequest();
     $context->setRequest($request);
     $id = $request->getSession()->getId();
     session_id('');
     $session = SessionManager::getGlobalSession();
     $this->assertSame($id, $session->getId());
     session_id('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
     $session = SessionManager::getGlobalSession();
     $this->assertSame($id, $session->getId());
     $this->assertSame($id, $request->getSession()->getId());
 }
 /**
  * Send cache control HTTP headers
  */
 public function sendCacheControl()
 {
     $response = $this->getRequest()->response();
     $config = $this->getConfig();
     if ($config->get('UseETag') && $this->mETag) {
         $response->header("ETag: {$this->mETag}");
     }
     $this->addVaryHeader('Cookie');
     $this->addAcceptLanguage();
     # don't serve compressed data to clients who can't handle it
     # maintain different caches for logged-in users and non-logged in ones
     $response->header($this->getVaryHeader());
     if ($config->get('UseKeyHeader')) {
         $response->header($this->getKeyHeader());
     }
     if ($this->mEnableClientCache) {
         if ($config->get('UseSquid') && !SessionManager::getGlobalSession()->isPersistent() && !$this->isPrintable() && $this->mCdnMaxage != 0 && !$this->haveCacheVaryCookies()) {
             if ($config->get('UseESI')) {
                 # We'll purge the proxy cache explicitly, but require end user agents
                 # to revalidate against the proxy on each visit.
                 # Surrogate-Control controls our CDN, Cache-Control downstream caches
                 wfDebug(__METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **", 'private');
                 # start with a shorter timeout for initial testing
                 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
                 $response->header('Surrogate-Control: max-age=' . $config->get('SquidMaxage') . '+' . $this->mCdnMaxage . ', content="ESI/1.0"');
                 $response->header('Cache-Control: s-maxage=0, must-revalidate, max-age=0');
             } else {
                 # We'll purge the proxy cache for anons explicitly, but require end user agents
                 # to revalidate against the proxy on each visit.
                 # IMPORTANT! The CDN needs to replace the Cache-Control header with
                 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
                 wfDebug(__METHOD__ . ": local proxy caching; {$this->mLastModified} **", 'private');
                 # start with a shorter timeout for initial testing
                 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
                 $response->header('Cache-Control: s-maxage=' . $this->mCdnMaxage . ', must-revalidate, max-age=0');
             }
         } else {
             # We do want clients to cache if they can, but they *must* check for updates
             # on revisiting the page.
             wfDebug(__METHOD__ . ": private caching; {$this->mLastModified} **", 'private');
             $response->header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
             $response->header("Cache-Control: private, must-revalidate, max-age=0");
         }
         if ($this->mLastModified) {
             $response->header("Last-Modified: {$this->mLastModified}");
         }
     } else {
         wfDebug(__METHOD__ . ": no caching **", 'private');
         # In general, the absence of a last modified header should be enough to prevent
         # the client from using its cache. We send a few other things just to make sure.
         $response->header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
         $response->header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
         $response->header('Pragma: no-cache');
     }
 }
 /**
  * @param string|null $subPage
  */
 public function execute($subPage)
 {
     $authManager = AuthManager::singleton();
     $session = SessionManager::getGlobalSession();
     // Session data is used for various things in the authentication process, so we must make
     // sure a session cookie or some equivalent mechanism is set.
     $session->persist();
     $this->load($subPage);
     $this->setHeaders();
     $this->checkPermissions();
     // Make sure it's possible to log in
     if (!$this->isSignup() && !$session->canSetUser()) {
         throw new ErrorPageError('cannotloginnow-title', 'cannotloginnow-text', [$session->getProvider()->describe(RequestContext::getMain()->getLanguage())]);
     }
     /*
      * In the case where the user is already logged in, and was redirected to
      * the login form from a page that requires login, do not show the login
      * page. The use case scenario for this is when a user opens a large number
      * of tabs, is redirected to the login page on all of them, and then logs
      * in on one, expecting all the others to work properly.
      *
      * However, do show the form if it was visited intentionally (no 'returnto'
      * is present). People who often switch between several accounts have grown
      * accustomed to this behavior.
      *
      * Also make an exception when force=<level> is set in the URL, which means the user must
      * reauthenticate for security reasons.
      */
     if (!$this->isSignup() && !$this->mPosted && !$this->securityLevel && ($this->mReturnTo !== '' || $this->mReturnToQuery !== '') && $this->getUser()->isLoggedIn()) {
         $this->successfulAction();
     }
     // If logging in and not on HTTPS, either redirect to it or offer a link.
     global $wgSecureLogin;
     if ($this->getRequest()->getProtocol() !== 'https') {
         $title = $this->getFullTitle();
         $query = $this->getPreservedParams(false) + ['title' => null, $this->mEntryErrorType === 'error' ? 'error' : 'warning' => $this->mEntryError] + $this->getRequest()->getQueryValues();
         $url = $title->getFullURL($query, false, PROTO_HTTPS);
         if ($wgSecureLogin && !$this->mFromHTTP && wfCanIPUseHTTPS($this->getRequest()->getIP())) {
             // Avoid infinite redirect
             $url = wfAppendQuery($url, 'fromhttp=1');
             $this->getOutput()->redirect($url);
             // Since we only do this redir to change proto, always vary
             $this->getOutput()->addVaryHeader('X-Forwarded-Proto');
             return;
         } else {
             // A wiki without HTTPS login support should set $wgServer to
             // http://somehost, in which case the secure URL generated
             // above won't actually start with https://
             if (substr($url, 0, 8) === 'https://') {
                 $this->mSecureLoginUrl = $url;
             }
         }
     }
     if (!$this->isActionAllowed($this->authAction)) {
         // FIXME how do we explain this to the user? can we handle session loss better?
         // messages used: authpage-cannot-login, authpage-cannot-login-continue,
         // authpage-cannot-create, authpage-cannot-create-continue
         $this->mainLoginForm([], 'authpage-cannot-' . $this->authAction);
         return;
     }
     $status = $this->trySubmit();
     if (!$status || !$status->isGood()) {
         $this->mainLoginForm($this->authRequests, $status ? $status->getMessage() : '', 'error');
         return;
     }
     /** @var AuthenticationResponse $response */
     $response = $status->getValue();
     $returnToUrl = $this->getPageTitle('return')->getFullURL($this->getPreservedParams(true), false, PROTO_HTTPS);
     switch ($response->status) {
         case AuthenticationResponse::PASS:
             $this->logAuthResult(true);
             $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
             $this->targetUser = User::newFromName($response->username);
             if (!$this->proxyAccountCreation && $response->loginRequest && $authManager->canAuthenticateNow()) {
                 // successful registration; log the user in instantly
                 $response2 = $authManager->beginAuthentication([$response->loginRequest], $returnToUrl);
                 if ($response2->status !== AuthenticationResponse::PASS) {
                     LoggerFactory::getInstance('login')->error('Could not log in after account creation');
                     $this->successfulAction(true, Status::newFatal('createacct-loginerror'));
                     break;
                 }
             }
             if (!$this->proxyAccountCreation) {
                 // Ensure that the context user is the same as the session user.
                 $this->setSessionUserForCurrentRequest();
             }
             $this->successfulAction(true);
             break;
         case AuthenticationResponse::FAIL:
             // fall through
         // fall through
         case AuthenticationResponse::RESTART:
             unset($this->authForm);
             if ($response->status === AuthenticationResponse::FAIL) {
                 $action = $this->getDefaultAction($subPage);
                 $messageType = 'error';
             } else {
                 $action = $this->getContinueAction($this->authAction);
                 $messageType = 'warning';
             }
             $this->logAuthResult(false, $response->message ? $response->message->getKey() : '-');
             $this->loadAuth($subPage, $action, true);
             $this->mainLoginForm($this->authRequests, $response->message, $messageType);
             break;
         case AuthenticationResponse::REDIRECT:
             unset($this->authForm);
             $this->getOutput()->redirect($response->redirectTarget);
             break;
         case AuthenticationResponse::UI:
             unset($this->authForm);
             $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE : AuthManager::ACTION_LOGIN_CONTINUE;
             $this->authRequests = $response->neededRequests;
             $this->mainLoginForm($response->neededRequests, $response->message, 'warning');
             break;
         default:
             throw new LogicException('invalid AuthenticationResponse');
     }
 }
/**
 * Initialise php session
 *
 * @deprecated since 1.27, use MediaWiki\Session\SessionManager instead.
 *  Generally, "using" SessionManager will be calling ->getSessionById() or
 *  ::getGlobalSession() (depending on whether you were passing $sessionId
 *  here), then calling $session->persist().
 * @param bool|string $sessionId
 */
function wfSetupSession($sessionId = false)
{
    wfDeprecated(__FUNCTION__, '1.27');
    if ($sessionId) {
        session_id($sessionId);
    }
    $session = SessionManager::getGlobalSession();
    $session->persist();
    if (session_id() !== $session->getId()) {
        session_id($session->getId());
    }
    MediaWiki\quietCall('session_start');
}
 public function testAutoCreateUser()
 {
     global $wgGroupPermissions;
     $that = $this;
     \ObjectCache::$instances[__METHOD__] = new \HashBagOStuff();
     $this->setMwGlobals(array('wgMainCacheType' => __METHOD__));
     $this->stashMwGlobals(array('wgGroupPermissions'));
     $wgGroupPermissions['*']['createaccount'] = true;
     $wgGroupPermissions['*']['autocreateaccount'] = false;
     // Replace the global singleton with one configured for testing
     $manager = $this->getManager();
     $reset = TestUtils::setSessionManagerSingleton($manager);
     $logger = new \TestLogger(true, function ($m) {
         if (substr($m, 0, 15) === 'SessionBackend ') {
             // Don't care.
             return null;
         }
         $m = str_replace('MediaWiki\\Session\\SessionManager::autoCreateUser: '******'', $m);
         $m = preg_replace('/ - from: .*$/', ' - from: XXX', $m);
         return $m;
     });
     $manager->setLogger($logger);
     $session = SessionManager::getGlobalSession();
     // Can't create an already-existing user
     $user = User::newFromName('UTSysop');
     $id = $user->getId();
     $this->assertFalse($manager->autoCreateUser($user));
     $this->assertSame($id, $user->getId());
     $this->assertSame('UTSysop', $user->getName());
     $this->assertSame(array(), $logger->getBuffer());
     $logger->clearBuffer();
     // Sanity check that creation works at all
     $user = User::newFromName('UTSessionAutoCreate1');
     $this->assertSame(0, $user->getId(), 'sanity check');
     $this->assertTrue($manager->autoCreateUser($user));
     $this->assertNotEquals(0, $user->getId());
     $this->assertSame('UTSessionAutoCreate1', $user->getName());
     $this->assertEquals($user->getId(), User::idFromName('UTSessionAutoCreate1', User::READ_LATEST));
     $this->assertSame(array(array(LogLevel::INFO, 'creating new user (UTSessionAutoCreate1) - from: XXX')), $logger->getBuffer());
     $logger->clearBuffer();
     // Check lack of permissions
     $wgGroupPermissions['*']['createaccount'] = false;
     $wgGroupPermissions['*']['autocreateaccount'] = false;
     $user = User::newFromName('UTDoesNotExist');
     $this->assertFalse($manager->autoCreateUser($user));
     $this->assertSame(0, $user->getId());
     $this->assertNotSame('UTDoesNotExist', $user->getName());
     $this->assertEquals(0, User::idFromName('UTDoesNotExist', User::READ_LATEST));
     $session->clear();
     $this->assertSame(array(array(LogLevel::DEBUG, 'user is blocked from this wiki, blacklisting')), $logger->getBuffer());
     $logger->clearBuffer();
     // Check other permission
     $wgGroupPermissions['*']['createaccount'] = false;
     $wgGroupPermissions['*']['autocreateaccount'] = true;
     $user = User::newFromName('UTSessionAutoCreate2');
     $this->assertSame(0, $user->getId(), 'sanity check');
     $this->assertTrue($manager->autoCreateUser($user));
     $this->assertNotEquals(0, $user->getId());
     $this->assertSame('UTSessionAutoCreate2', $user->getName());
     $this->assertEquals($user->getId(), User::idFromName('UTSessionAutoCreate2', User::READ_LATEST));
     $this->assertSame(array(array(LogLevel::INFO, 'creating new user (UTSessionAutoCreate2) - from: XXX')), $logger->getBuffer());
     $logger->clearBuffer();
     // Test account-creation block
     $anon = new User();
     $block = new \Block(array('address' => $anon->getName(), 'user' => $id, 'reason' => __METHOD__, 'expiry' => time() + 100500, 'createAccount' => true));
     $block->insert();
     $this->assertInstanceOf('Block', $anon->isBlockedFromCreateAccount(), 'sanity check');
     $reset2 = new \ScopedCallback(array($block, 'delete'));
     $user = User::newFromName('UTDoesNotExist');
     $this->assertFalse($manager->autoCreateUser($user));
     $this->assertSame(0, $user->getId());
     $this->assertNotSame('UTDoesNotExist', $user->getName());
     $this->assertEquals(0, User::idFromName('UTDoesNotExist', User::READ_LATEST));
     \ScopedCallback::consume($reset2);
     $session->clear();
     $this->assertSame(array(array(LogLevel::DEBUG, 'user is blocked from this wiki, blacklisting')), $logger->getBuffer());
     $logger->clearBuffer();
     // Sanity check that creation still works
     $user = User::newFromName('UTSessionAutoCreate3');
     $this->assertSame(0, $user->getId(), 'sanity check');
     $this->assertTrue($manager->autoCreateUser($user));
     $this->assertNotEquals(0, $user->getId());
     $this->assertSame('UTSessionAutoCreate3', $user->getName());
     $this->assertEquals($user->getId(), User::idFromName('UTSessionAutoCreate3', User::READ_LATEST));
     $this->assertSame(array(array(LogLevel::INFO, 'creating new user (UTSessionAutoCreate3) - from: XXX')), $logger->getBuffer());
     $logger->clearBuffer();
     // Test prevention by AuthPlugin
     global $wgAuth;
     $oldWgAuth = $wgAuth;
     $mockWgAuth = $this->getMock('AuthPlugin', array('autoCreate'));
     $mockWgAuth->expects($this->once())->method('autoCreate')->will($this->returnValue(false));
     $this->setMwGlobals(array('wgAuth' => $mockWgAuth));
     $user = User::newFromName('UTDoesNotExist');
     $this->assertFalse($manager->autoCreateUser($user));
     $this->assertSame(0, $user->getId());
     $this->assertNotSame('UTDoesNotExist', $user->getName());
     $this->assertEquals(0, User::idFromName('UTDoesNotExist', User::READ_LATEST));
     $this->setMwGlobals(array('wgAuth' => $oldWgAuth));
     $session->clear();
     $this->assertSame(array(array(LogLevel::DEBUG, 'denied by AuthPlugin')), $logger->getBuffer());
     $logger->clearBuffer();
     // Test prevention by wfReadOnly()
     $this->setMwGlobals(array('wgReadOnly' => 'Because'));
     $user = User::newFromName('UTDoesNotExist');
     $this->assertFalse($manager->autoCreateUser($user));
     $this->assertSame(0, $user->getId());
     $this->assertNotSame('UTDoesNotExist', $user->getName());
     $this->assertEquals(0, User::idFromName('UTDoesNotExist', User::READ_LATEST));
     $this->setMwGlobals(array('wgReadOnly' => false));
     $session->clear();
     $this->assertSame(array(array(LogLevel::DEBUG, 'denied by wfReadOnly()')), $logger->getBuffer());
     $logger->clearBuffer();
     // Test prevention by a previous session
     $session->set('MWSession::AutoCreateBlacklist', 'test');
     $user = User::newFromName('UTDoesNotExist');
     $this->assertFalse($manager->autoCreateUser($user));
     $this->assertSame(0, $user->getId());
     $this->assertNotSame('UTDoesNotExist', $user->getName());
     $this->assertEquals(0, User::idFromName('UTDoesNotExist', User::READ_LATEST));
     $session->clear();
     $this->assertSame(array(array(LogLevel::DEBUG, 'blacklisted in session (test)')), $logger->getBuffer());
     $logger->clearBuffer();
     // Test uncreatable name
     $user = User::newFromName('UTDoesNotExist@');
     $this->assertFalse($manager->autoCreateUser($user));
     $this->assertSame(0, $user->getId());
     $this->assertNotSame('UTDoesNotExist@', $user->getName());
     $this->assertEquals(0, User::idFromName('UTDoesNotExist', User::READ_LATEST));
     $session->clear();
     $this->assertSame(array(array(LogLevel::DEBUG, 'Invalid username, blacklisting')), $logger->getBuffer());
     $logger->clearBuffer();
     // Test AbortAutoAccount hook
     $mock = $this->getMock(__CLASS__, array('onAbortAutoAccount'));
     $mock->expects($this->once())->method('onAbortAutoAccount')->will($this->returnCallback(function (User $user, &$msg) {
         $msg = 'No way!';
         return false;
     }));
     $this->mergeMwGlobalArrayValue('wgHooks', array('AbortAutoAccount' => array($mock)));
     $user = User::newFromName('UTDoesNotExist');
     $this->assertFalse($manager->autoCreateUser($user));
     $this->assertSame(0, $user->getId());
     $this->assertNotSame('UTDoesNotExist', $user->getName());
     $this->assertEquals(0, User::idFromName('UTDoesNotExist', User::READ_LATEST));
     $this->mergeMwGlobalArrayValue('wgHooks', array('AbortAutoAccount' => array()));
     $session->clear();
     $this->assertSame(array(array(LogLevel::DEBUG, 'denied by hook: No way!')), $logger->getBuffer());
     $logger->clearBuffer();
     // Test AbortAutoAccount hook screwing up the name
     $mock = $this->getMock('stdClass', array('onAbortAutoAccount'));
     $mock->expects($this->once())->method('onAbortAutoAccount')->will($this->returnCallback(function (User $user) {
         $user->setName('UTDoesNotExistEither');
     }));
     $this->mergeMwGlobalArrayValue('wgHooks', array('AbortAutoAccount' => array($mock)));
     try {
         $user = User::newFromName('UTDoesNotExist');
         $manager->autoCreateUser($user);
         $this->fail('Expected exception not thrown');
     } catch (\UnexpectedValueException $ex) {
         $this->assertSame('AbortAutoAccount hook tried to change the user name', $ex->getMessage());
     }
     $this->assertSame(0, $user->getId());
     $this->assertNotSame('UTDoesNotExist', $user->getName());
     $this->assertNotSame('UTDoesNotExistEither', $user->getName());
     $this->assertEquals(0, User::idFromName('UTDoesNotExist', User::READ_LATEST));
     $this->assertEquals(0, User::idFromName('UTDoesNotExistEither', User::READ_LATEST));
     $this->mergeMwGlobalArrayValue('wgHooks', array('AbortAutoAccount' => array()));
     $session->clear();
     $this->assertSame(array(), $logger->getBuffer());
     $logger->clearBuffer();
     // Test for "exception backoff"
     $user = User::newFromName('UTDoesNotExist');
     $cache = \ObjectCache::getLocalClusterInstance();
     $backoffKey = wfMemcKey('MWSession', 'autocreate-failed', md5($user->getName()));
     $cache->set($backoffKey, 1, 60 * 10);
     $this->assertFalse($manager->autoCreateUser($user));
     $this->assertSame(0, $user->getId());
     $this->assertNotSame('UTDoesNotExist', $user->getName());
     $this->assertEquals(0, User::idFromName('UTDoesNotExist', User::READ_LATEST));
     $cache->delete($backoffKey);
     $session->clear();
     $this->assertSame(array(array(LogLevel::DEBUG, 'denied by prior creation attempt failures')), $logger->getBuffer());
     $logger->clearBuffer();
     // Sanity check that creation still works, and test completion hook
     $cb = $this->callback(function (User $user) use($that) {
         $that->assertNotEquals(0, $user->getId());
         $that->assertSame('UTSessionAutoCreate4', $user->getName());
         $that->assertEquals($user->getId(), User::idFromName('UTSessionAutoCreate4', User::READ_LATEST));
         return true;
     });
     $mock = $this->getMock('stdClass', array('onAuthPluginAutoCreate', 'onLocalUserCreated'));
     $mock->expects($this->once())->method('onAuthPluginAutoCreate')->with($cb);
     $mock->expects($this->once())->method('onLocalUserCreated')->with($cb, $this->identicalTo(true));
     $this->mergeMwGlobalArrayValue('wgHooks', array('AuthPluginAutoCreate' => array($mock), 'LocalUserCreated' => array($mock)));
     $user = User::newFromName('UTSessionAutoCreate4');
     $this->assertSame(0, $user->getId(), 'sanity check');
     $this->assertTrue($manager->autoCreateUser($user));
     $this->assertNotEquals(0, $user->getId());
     $this->assertSame('UTSessionAutoCreate4', $user->getName());
     $this->assertEquals($user->getId(), User::idFromName('UTSessionAutoCreate4', User::READ_LATEST));
     $this->mergeMwGlobalArrayValue('wgHooks', array('AuthPluginAutoCreate' => array(), 'LocalUserCreated' => array()));
     $this->assertSame(array(array(LogLevel::INFO, 'creating new user (UTSessionAutoCreate4) - from: XXX')), $logger->getBuffer());
     $logger->clearBuffer();
 }
/**
 * Initialise php session
 *
 * @deprecated since 1.27, use MediaWiki\\Session\\SessionManager instead.
 *  Generally, "using" SessionManager will be calling ->getSessionById() or
 *  ::getGlobalSession() (depending on whether you were passing $sessionId
 *  here), then calling $session->persist().
 * @param bool|string $sessionId
 */
function wfSetupSession($sessionId = false)
{
    wfDeprecated(__FUNCTION__, '1.27');
    // If they're calling this, they probably want our session management even
    // if NO_SESSION was set for Setup.php.
    if (!MediaWiki\Session\PHPSessionHandler::isInstalled()) {
        MediaWiki\Session\PHPSessionHandler::install(SessionManager::singleton());
    }
    if ($sessionId) {
        session_id($sessionId);
    }
    $session = SessionManager::getGlobalSession();
    $session->persist();
    if (session_id() !== $session->getId()) {
        session_id($session->getId());
    }
    MediaWiki\quietCall('session_cache_limiter', 'private, must-revalidate');
    MediaWiki\quietCall('session_start');
}
 /**
  * Renew the user's session id, using strong entropy
  */
 private function renewSessionId()
 {
     global $wgSecureLogin, $wgCookieSecure;
     if ($wgSecureLogin && !$this->mStickHTTPS) {
         $wgCookieSecure = false;
     }
     SessionManager::getGlobalSession()->resetId();
 }
 /**
  * For backwards compatibility, open the PHP session when the global
  * session is persisted
  */
 private function checkPHPSession()
 {
     if (!$this->checkPHPSessionRecursionGuard) {
         $this->checkPHPSessionRecursionGuard = true;
         $reset = new \ScopedCallback(function () {
             $this->checkPHPSessionRecursionGuard = false;
         });
         if ($this->usePhpSessionHandling && session_id() === '' && PHPSessionHandler::isEnabled() && SessionManager::getGlobalSession()->getId() === (string) $this->id) {
             $this->logger->debug('SessionBackend "{session}" Taking over PHP session', ['session' => $this->id]);
             session_id((string) $this->id);
             \MediaWiki\quietCall('session_start');
         }
     }
 }
 /**
  * For backwards compatibility, open the PHP session when the global
  * session is persisted
  */
 private function checkPHPSession()
 {
     if (!$this->checkPHPSessionRecursionGuard) {
         $this->checkPHPSessionRecursionGuard = true;
         $ref =& $this->checkPHPSessionRecursionGuard;
         $reset = new \ScopedCallback(function () use(&$ref) {
             $ref = false;
         });
         if ($this->usePhpSessionHandling && session_id() === '' && PHPSessionHandler::isEnabled() && SessionManager::getGlobalSession()->getId() === (string) $this->id) {
             $this->logger->debug("SessionBackend {$this->id}: Taking over PHP session");
             session_id((string) $this->id);
             \MediaWiki\quietCall('session_cache_limiter', 'private, must-revalidate');
             \MediaWiki\quietCall('session_start');
         }
     }
 }
 /**
  * This should kill the session as hard as possible.
  * It will leave the cookie behind, but everything it could possibly
  * reference will be gone.
  */
 public function session_killAllEverything()
 {
     if ($this->isBatchProcessor()) {
         return;
     }
     SessionManager::getGlobalSession()->clear();
 }
 static function setupSession($sessionId = false)
 {
     SessionManager::getGlobalSession()->persist();
 }
Exemple #12
0
 /**
  * Check if all users may be assumed to have the given permission
  *
  * We generally assume so if the right is granted to '*' and isn't revoked
  * on any group. It doesn't attempt to take grants or other extension
  * limitations on rights into account in the general case, though, as that
  * would require it to always return false and defeat the purpose.
  * Specifically, session-based rights restrictions (such as OAuth or bot
  * passwords) are applied based on the current session.
  *
  * @since 1.22
  * @param string $right Right to check
  * @return bool
  */
 public static function isEveryoneAllowed($right)
 {
     global $wgGroupPermissions, $wgRevokePermissions;
     static $cache = array();
     // Use the cached results, except in unit tests which rely on
     // being able change the permission mid-request
     if (isset($cache[$right]) && !defined('MW_PHPUNIT_TEST')) {
         return $cache[$right];
     }
     if (!isset($wgGroupPermissions['*'][$right]) || !$wgGroupPermissions['*'][$right]) {
         $cache[$right] = false;
         return false;
     }
     // If it's revoked anywhere, then everyone doesn't have it
     foreach ($wgRevokePermissions as $rights) {
         if (isset($rights[$right]) && $rights[$right]) {
             $cache[$right] = false;
             return false;
         }
     }
     // Remove any rights that aren't allowed to the global-session user
     $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
     if ($allowedRights !== null && !in_array($right, $allowedRights, true)) {
         $cache[$right] = false;
         return false;
     }
     // Allow extensions to say false
     if (!Hooks::run('UserIsEveryoneAllowed', array($right))) {
         $cache[$right] = false;
         return false;
     }
     $cache[$right] = true;
     return true;
 }
 public function __construct()
 {
     /** @var SessionProvider $provider */
     $provider = SessionManager::getGlobalSession()->getProvider();
     $this->expiration = $provider->getRememberUserDuration();
 }