3 * MediaWiki\Session entry point
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 namespace MediaWiki\Session
;
26 use MediaWiki\MediaWikiServices
;
28 use Psr\Log\LoggerInterface
;
35 use Wikimedia\ObjectFactory
;
38 * This serves as the entry point to the MediaWiki session handling system.
40 * Most methods here are for internal use by session handling code. Other callers
41 * should only use getGlobalSession and the methods of SessionManagerInterface;
42 * the rest of the functionality is exposed via MediaWiki\Session\Session methods.
44 * To provide custom session handling, implement a MediaWiki\Session\SessionProvider.
48 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
50 final class SessionManager
implements SessionManagerInterface
{
51 /** @var SessionManager|null */
52 private static $instance = null;
54 /** @var Session|null */
55 private static $globalSession = null;
57 /** @var WebRequest|null */
58 private static $globalSessionRequest = null;
60 /** @var LoggerInterface */
66 /** @var CachedBagOStuff|null */
69 /** @var SessionProvider[] */
70 private $sessionProviders = null;
73 private $varyCookies = null;
76 private $varyHeaders = null;
78 /** @var SessionBackend[] */
79 private $allSessionBackends = [];
81 /** @var SessionId[] */
82 private $allSessionIds = [];
85 private $preventUsers = [];
88 * Get the global SessionManager
89 * @return SessionManagerInterface
90 * (really a SessionManager, but this is to make IDEs less confused)
92 public static function singleton() {
93 if ( self
::$instance === null ) {
94 self
::$instance = new self();
96 return self
::$instance;
100 * Get the "global" session
102 * If PHP's session_id() has been set, returns that session. Otherwise
103 * returns the session for RequestContext::getMain()->getRequest().
107 public static function getGlobalSession() {
108 if ( !PHPSessionHandler
::isEnabled() ) {
114 $request = \RequestContext
::getMain()->getRequest();
116 !self
::$globalSession // No global session is set up yet
117 || self
::$globalSessionRequest !== $request // The global WebRequest changed
118 ||
$id !== '' && self
::$globalSession->getId() !== $id // Someone messed with session_id()
120 self
::$globalSessionRequest = $request;
122 // session_id() wasn't used, so fetch the Session from the WebRequest.
123 // We use $request->getSession() instead of $singleton->getSessionForRequest()
124 // because doing the latter would require a public
125 // "$request->getSessionId()" method that would confuse end
126 // users by returning SessionId|null where they'd expect it to
127 // be short for $request->getSession()->getId(), and would
128 // wind up being a duplicate of the code in
129 // $request->getSession() anyway.
130 self
::$globalSession = $request->getSession();
132 // Someone used session_id(), so we need to follow suit.
133 // Note this overwrites whatever session might already be
134 // associated with $request with the one for $id.
135 self
::$globalSession = self
::singleton()->getSessionById( $id, true, $request )
136 ?
: $request->getSession();
139 return self
::$globalSession;
143 * @param array $options
144 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
145 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
146 * - store: BagOStuff to store session data in.
148 public function __construct( $options = [] ) {
149 if ( isset( $options['config'] ) ) {
150 $this->config
= $options['config'];
151 if ( !$this->config
instanceof Config
) {
152 throw new \
InvalidArgumentException(
153 '$options[\'config\'] must be an instance of Config'
157 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
160 if ( isset( $options['logger'] ) ) {
161 if ( !$options['logger'] instanceof LoggerInterface
) {
162 throw new \
InvalidArgumentException(
163 '$options[\'logger\'] must be an instance of LoggerInterface'
166 $this->setLogger( $options['logger'] );
168 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' ) );
171 if ( isset( $options['store'] ) ) {
172 if ( !$options['store'] instanceof BagOStuff
) {
173 throw new \
InvalidArgumentException(
174 '$options[\'store\'] must be an instance of BagOStuff'
177 $store = $options['store'];
179 $store = \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
181 $this->store
= $store instanceof CachedBagOStuff ?
$store : new CachedBagOStuff( $store );
183 register_shutdown_function( [ $this, 'shutdown' ] );
186 public function setLogger( LoggerInterface
$logger ) {
187 $this->logger
= $logger;
190 public function getSessionForRequest( WebRequest
$request ) {
191 $info = $this->getSessionInfoForRequest( $request );
194 $session = $this->getEmptySession( $request );
196 $session = $this->getSessionFromInfo( $info, $request );
201 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
202 if ( !self
::validateSessionId( $id ) ) {
203 throw new \
InvalidArgumentException( 'Invalid session ID' );
206 $request = new FauxRequest
;
210 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [ 'id' => $id, 'idIsSafe' => true ] );
212 // If we already have the backend loaded, use it directly
213 if ( isset( $this->allSessionBackends
[$id] ) ) {
214 return $this->getSessionFromInfo( $info, $request );
217 // Test if the session is in storage, and if so try to load it.
218 $key = $this->store
->makeKey( 'MWSession', $id );
219 if ( is_array( $this->store
->get( $key ) ) ) {
220 $create = false; // If loading fails, don't bother creating because it probably will fail too.
221 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
222 $session = $this->getSessionFromInfo( $info, $request );
226 if ( $create && $session === null ) {
229 $session = $this->getEmptySessionInternal( $request, $id );
230 } catch ( \Exception
$ex ) {
231 $this->logger
->error( 'Failed to create empty session: {exception}',
233 'method' => __METHOD__
,
243 public function getEmptySession( WebRequest
$request = null ) {
244 return $this->getEmptySessionInternal( $request );
248 * @see SessionManagerInterface::getEmptySession
249 * @param WebRequest|null $request
250 * @param string|null $id ID to force on the new session
253 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
254 if ( $id !== null ) {
255 if ( !self
::validateSessionId( $id ) ) {
256 throw new \
InvalidArgumentException( 'Invalid session ID' );
259 $key = $this->store
->makeKey( 'MWSession', $id );
260 if ( is_array( $this->store
->get( $key ) ) ) {
261 throw new \
InvalidArgumentException( 'Session ID already exists' );
265 $request = new FauxRequest
;
269 foreach ( $this->getProviders() as $provider ) {
270 $info = $provider->newSessionInfo( $id );
274 if ( $info->getProvider() !== $provider ) {
275 throw new \
UnexpectedValueException(
276 "$provider returned an empty session info for a different provider: $info"
279 if ( $id !== null && $info->getId() !== $id ) {
280 throw new \
UnexpectedValueException(
281 "$provider returned empty session info with a wrong id: " .
282 $info->getId() . ' != ' . $id
285 if ( !$info->isIdSafe() ) {
286 throw new \
UnexpectedValueException(
287 "$provider returned empty session info with id flagged unsafe"
290 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
291 if ( $compare > 0 ) {
294 if ( $compare === 0 ) {
301 // Make sure there's exactly one
302 if ( count( $infos ) > 1 ) {
303 throw new \
UnexpectedValueException(
304 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
306 } elseif ( count( $infos ) < 1 ) {
307 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
310 return $this->getSessionFromInfo( $infos[0], $request );
313 public function invalidateSessionsForUser( User
$user ) {
315 $user->saveSettings();
317 $authUser = \MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ] );
319 $authUser->resetAuthToken();
322 foreach ( $this->getProviders() as $provider ) {
323 $provider->invalidateSessionsForUser( $user );
327 public function getVaryHeaders() {
328 // @codeCoverageIgnoreStart
329 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
332 // @codeCoverageIgnoreEnd
333 if ( $this->varyHeaders
=== null ) {
335 foreach ( $this->getProviders() as $provider ) {
336 foreach ( $provider->getVaryHeaders() as $header => $options ) {
337 if ( !isset( $headers[$header] ) ) {
338 $headers[$header] = [];
340 if ( is_array( $options ) ) {
341 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
345 $this->varyHeaders
= $headers;
347 return $this->varyHeaders
;
350 public function getVaryCookies() {
351 // @codeCoverageIgnoreStart
352 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
355 // @codeCoverageIgnoreEnd
356 if ( $this->varyCookies
=== null ) {
358 foreach ( $this->getProviders() as $provider ) {
359 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
361 $this->varyCookies
= array_values( array_unique( $cookies ) );
363 return $this->varyCookies
;
367 * Validate a session ID
371 public static function validateSessionId( $id ) {
372 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
376 * @name Internal methods
381 * Auto-create the given user, if necessary
382 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
383 * @deprecated since 1.27, use MediaWiki\Auth\AuthManager::autoCreateUser instead
384 * @param User $user User to auto-create
385 * @return bool Success
386 * @codeCoverageIgnore
388 public static function autoCreateUser( User
$user ) {
389 wfDeprecated( __METHOD__
, '1.27' );
390 return \MediaWiki\Auth\AuthManager
::singleton()->autoCreateUser(
392 \MediaWiki\Auth\AuthManager
::AUTOCREATE_SOURCE_SESSION
,
398 * Prevent future sessions for the user
400 * The intention is that the named account will never again be usable for
401 * normal login (i.e. there is no way to undo the prevention of access).
403 * @private For use from \User::newSystemUser only
404 * @param string $username
406 public function preventSessionsForUser( $username ) {
407 $this->preventUsers
[$username] = true;
409 // Instruct the session providers to kill any other sessions too.
410 foreach ( $this->getProviders() as $provider ) {
411 $provider->preventSessionsForUser( $username );
416 * Test if a user is prevented
417 * @private For use from SessionBackend only
418 * @param string $username
421 public function isUserSessionPrevented( $username ) {
422 return !empty( $this->preventUsers
[$username] );
426 * Get the available SessionProviders
427 * @return SessionProvider[]
429 protected function getProviders() {
430 if ( $this->sessionProviders
=== null ) {
431 $this->sessionProviders
= [];
432 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
433 $provider = ObjectFactory
::getObjectFromSpec( $spec );
434 $provider->setLogger( $this->logger
);
435 $provider->setConfig( $this->config
);
436 $provider->setManager( $this );
437 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
438 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
440 $this->sessionProviders
[(string)$provider] = $provider;
443 return $this->sessionProviders
;
447 * Get a session provider by name
449 * Generally, this will only be used by internal implementation of some
450 * special session-providing mechanism. General purpose code, if it needs
451 * to access a SessionProvider at all, will use Session::getProvider().
453 * @param string $name
454 * @return SessionProvider|null
456 public function getProvider( $name ) {
457 $providers = $this->getProviders();
458 return $providers[$name] ??
null;
462 * Save all active sessions on shutdown
463 * @private For internal use with register_shutdown_function()
465 public function shutdown() {
466 if ( $this->allSessionBackends
) {
467 $this->logger
->debug( 'Saving all sessions on shutdown' );
468 if ( session_id() !== '' ) {
469 // @codeCoverageIgnoreStart
470 session_write_close();
472 // @codeCoverageIgnoreEnd
473 foreach ( $this->allSessionBackends
as $backend ) {
474 $backend->shutdown();
480 * Fetch the SessionInfo(s) for a request
481 * @param WebRequest $request
482 * @return SessionInfo|null
484 private function getSessionInfoForRequest( WebRequest
$request ) {
485 // Call all providers to fetch "the" session
487 foreach ( $this->getProviders() as $provider ) {
488 $info = $provider->provideSessionInfo( $request );
492 if ( $info->getProvider() !== $provider ) {
493 throw new \
UnexpectedValueException(
494 "$provider returned session info for a different provider: $info"
500 // Sort the SessionInfos. Then find the first one that can be
501 // successfully loaded, and then all the ones after it with the same
503 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
506 $info = array_pop( $infos );
507 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
510 $info = array_pop( $infos );
511 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
512 // We hit a lower priority, stop checking.
515 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
516 // This is going to error out below, but we want to
517 // provide a complete list.
520 // Session load failed, so unpersist it from this request
521 $info->getProvider()->unpersistSession( $request );
525 // Session load failed, so unpersist it from this request
526 $info->getProvider()->unpersistSession( $request );
530 if ( count( $retInfos ) > 1 ) {
531 $ex = new \
OverflowException(
532 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
534 $ex->sessionInfos
= $retInfos;
538 return $retInfos ?
$retInfos[0] : null;
542 * Load and verify the session info against the store
544 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
545 * @param WebRequest $request
546 * @return bool Whether the session info matches the stored data (if any)
548 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
549 $key = $this->store
->makeKey( 'MWSession', $info->getId() );
550 $blob = $this->store
->get( $key );
552 // If we got data from the store and the SessionInfo says to force use,
553 // "fail" means to delete the data from the store and retry. Otherwise,
554 // "fail" is just return false.
555 if ( $info->forceUse() && $blob !== false ) {
556 $failHandler = function () use ( $key, &$info, $request ) {
557 $this->store
->delete( $key );
558 return $this->loadSessionInfoFromStore( $info, $request );
561 $failHandler = function () {
568 if ( $blob !== false ) {
569 // Sanity check: blob must be an array, if it's saved at all
570 if ( !is_array( $blob ) ) {
571 $this->logger
->warning( 'Session "{session}": Bad data', [
574 $this->store
->delete( $key );
575 return $failHandler();
578 // Sanity check: blob has data and metadata arrays
579 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
580 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
582 $this->logger
->warning( 'Session "{session}": Bad data structure', [
585 $this->store
->delete( $key );
586 return $failHandler();
589 $data = $blob['data'];
590 $metadata = $blob['metadata'];
592 // Sanity check: metadata must be an array and must contain certain
593 // keys, if it's saved at all
594 if ( !array_key_exists( 'userId', $metadata ) ||
595 !array_key_exists( 'userName', $metadata ) ||
596 !array_key_exists( 'userToken', $metadata ) ||
597 !array_key_exists( 'provider', $metadata )
599 $this->logger
->warning( 'Session "{session}": Bad metadata', [
602 $this->store
->delete( $key );
603 return $failHandler();
606 // First, load the provider from metadata, or validate it against the metadata.
607 $provider = $info->getProvider();
608 if ( $provider === null ) {
609 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
611 $this->logger
->warning(
612 'Session "{session}": Unknown provider ' . $metadata['provider'],
617 $this->store
->delete( $key );
618 return $failHandler();
620 } elseif ( $metadata['provider'] !== (string)$provider ) {
621 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
622 $metadata['provider'] . ' !== ' . $provider,
626 return $failHandler();
629 // Load provider metadata from metadata, or validate it against the metadata
630 $providerMetadata = $info->getProviderMetadata();
631 if ( isset( $metadata['providerMetadata'] ) ) {
632 if ( $providerMetadata === null ) {
633 $newParams['metadata'] = $metadata['providerMetadata'];
636 $newProviderMetadata = $provider->mergeMetadata(
637 $metadata['providerMetadata'], $providerMetadata
639 if ( $newProviderMetadata !== $providerMetadata ) {
640 $newParams['metadata'] = $newProviderMetadata;
642 } catch ( MetadataMergeException
$ex ) {
643 $this->logger
->warning(
644 'Session "{session}": Metadata merge failed: {exception}',
648 ] +
$ex->getContext()
650 return $failHandler();
655 // Next, load the user from metadata, or validate it against the metadata.
656 $userInfo = $info->getUserInfo();
658 // For loading, id is preferred to name.
660 if ( $metadata['userId'] ) {
661 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
662 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
663 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
665 $userInfo = UserInfo
::newAnonymous();
667 } catch ( \InvalidArgumentException
$ex ) {
668 $this->logger
->error( 'Session "{session}": {exception}', [
672 return $failHandler();
674 $newParams['userInfo'] = $userInfo;
676 // User validation passes if user ID matches, or if there
677 // is no saved ID and the names match.
678 if ( $metadata['userId'] ) {
679 if ( $metadata['userId'] !== $userInfo->getId() ) {
680 $this->logger
->warning(
681 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
684 'uid_a' => $metadata['userId'],
685 'uid_b' => $userInfo->getId(),
687 return $failHandler();
690 // If the user was renamed, probably best to fail here.
691 if ( $metadata['userName'] !== null &&
692 $userInfo->getName() !== $metadata['userName']
694 $this->logger
->warning(
695 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
698 'uname_a' => $metadata['userName'],
699 'uname_b' => $userInfo->getName(),
701 return $failHandler();
704 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
705 if ( $metadata['userName'] !== $userInfo->getName() ) {
706 $this->logger
->warning(
707 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
710 'uname_a' => $metadata['userName'],
711 'uname_b' => $userInfo->getName(),
713 return $failHandler();
715 } elseif ( !$userInfo->isAnon() ) {
716 // Metadata specifies an anonymous user, but the passed-in
717 // user isn't anonymous.
718 $this->logger
->warning(
719 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
723 return $failHandler();
727 // And if we have a token in the metadata, it must match the loaded/provided user.
728 if ( $metadata['userToken'] !== null &&
729 $userInfo->getToken() !== $metadata['userToken']
731 $this->logger
->warning( 'Session "{session}": User token mismatch', [
734 return $failHandler();
736 if ( !$userInfo->isVerified() ) {
737 $newParams['userInfo'] = $userInfo->verified();
740 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
741 $newParams['remembered'] = true;
743 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
744 $newParams['forceHTTPS'] = true;
746 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
747 $newParams['persisted'] = true;
750 if ( !$info->isIdSafe() ) {
751 $newParams['idIsSafe'] = true;
754 // No metadata, so we can't load the provider if one wasn't given.
755 if ( $info->getProvider() === null ) {
756 $this->logger
->warning(
757 'Session "{session}": Null provider and no metadata',
761 return $failHandler();
764 // If no user was provided and no metadata, it must be anon.
765 if ( !$info->getUserInfo() ) {
766 if ( $info->getProvider()->canChangeUser() ) {
767 $newParams['userInfo'] = UserInfo
::newAnonymous();
770 'Session "{session}": No user provided and provider cannot set user',
774 return $failHandler();
776 } elseif ( !$info->getUserInfo()->isVerified() ) {
777 // probably just a session timeout
779 'Session "{session}": Unverified user provided and no metadata to auth it',
783 return $failHandler();
789 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
790 // The ID doesn't come from the user, so it should be safe
791 // (and if not, nothing we can do about it anyway)
792 $newParams['idIsSafe'] = true;
796 // Construct the replacement SessionInfo, if necessary
798 $newParams['copyFrom'] = $info;
799 $info = new SessionInfo( $info->getPriority(), $newParams );
802 // Allow the provider to check the loaded SessionInfo
803 $providerMetadata = $info->getProviderMetadata();
804 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
805 return $failHandler();
807 if ( $providerMetadata !== $info->getProviderMetadata() ) {
808 $info = new SessionInfo( $info->getPriority(), [
809 'metadata' => $providerMetadata,
814 // Give hooks a chance to abort. Combined with the SessionMetadata
815 // hook, this can allow for tying a session to an IP address or the
817 $reason = 'Hook aborted';
820 [ &$reason, $info, $request, $metadata, $data ]
822 $this->logger
->warning( 'Session "{session}": ' . $reason, [
825 return $failHandler();
832 * Create a Session corresponding to the passed SessionInfo
833 * @private For use by a SessionProvider that needs to specially create its
834 * own Session. Most session providers won't need this.
835 * @param SessionInfo $info
836 * @param WebRequest $request
839 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
840 // @codeCoverageIgnoreStart
841 if ( defined( 'MW_NO_SESSION' ) ) {
842 if ( MW_NO_SESSION
=== 'warn' ) {
843 // Undocumented safety case for converting existing entry points
844 $this->logger
->error( 'Sessions are supposed to be disabled for this entry point', [
845 'exception' => new \
BadMethodCallException( 'Sessions are disabled for this entry point' ),
848 throw new \
BadMethodCallException( 'Sessions are disabled for this entry point' );
851 // @codeCoverageIgnoreEnd
853 $id = $info->getId();
855 if ( !isset( $this->allSessionBackends
[$id] ) ) {
856 if ( !isset( $this->allSessionIds
[$id] ) ) {
857 $this->allSessionIds
[$id] = new SessionId( $id );
859 $backend = new SessionBackend(
860 $this->allSessionIds
[$id],
864 $this->config
->get( 'ObjectCacheSessionExpiry' )
866 $this->allSessionBackends
[$id] = $backend;
867 $delay = $backend->delaySave();
869 $backend = $this->allSessionBackends
[$id];
870 $delay = $backend->delaySave();
871 if ( $info->wasPersisted() ) {
874 if ( $info->wasRemembered() ) {
875 $backend->setRememberUser( true );
879 $request->setSessionId( $backend->getSessionId() );
880 $session = $backend->getSession( $request );
882 if ( !$info->isIdSafe() ) {
886 \Wikimedia\ScopedCallback
::consume( $delay );
891 * Deregister a SessionBackend
892 * @private For use from \MediaWiki\Session\SessionBackend only
893 * @param SessionBackend $backend
895 public function deregisterSessionBackend( SessionBackend
$backend ) {
896 $id = $backend->getId();
897 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
898 $this->allSessionBackends
[$id] !== $backend ||
899 $this->allSessionIds
[$id] !== $backend->getSessionId()
901 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
904 unset( $this->allSessionBackends
[$id] );
905 // Explicitly do not unset $this->allSessionIds[$id]
909 * Change a SessionBackend's ID
910 * @private For use from \MediaWiki\Session\SessionBackend only
911 * @param SessionBackend $backend
913 public function changeBackendId( SessionBackend
$backend ) {
914 $sessionId = $backend->getSessionId();
915 $oldId = (string)$sessionId;
916 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
917 $this->allSessionBackends
[$oldId] !== $backend ||
918 $this->allSessionIds
[$oldId] !== $sessionId
920 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
923 $newId = $this->generateSessionId();
925 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
926 $sessionId->setId( $newId );
927 $this->allSessionBackends
[$newId] = $backend;
928 $this->allSessionIds
[$newId] = $sessionId;
932 * Generate a new random session ID
935 public function generateSessionId() {
937 $id = \Wikimedia\base_convert
( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
938 $key = $this->store
->makeKey( 'MWSession', $id );
939 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
944 * Call setters on a PHPSessionHandler
945 * @private Use PhpSessionHandler::install()
946 * @param PHPSessionHandler $handler
948 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
949 $handler->setManager( $this, $this->store
, $this->logger
);
953 * Reset the internal caching for unit testing
954 * @protected Unit tests only
956 public static function resetCache() {
957 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
958 // @codeCoverageIgnoreStart
959 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
960 // @codeCoverageIgnoreEnd
963 self
::$globalSession = null;
964 self
::$globalSessionRequest = null;