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
91 public static function singleton() {
92 if ( self
::$instance === null ) {
93 self
::$instance = new self();
95 return self
::$instance;
99 * Get the "global" session
101 * If PHP's session_id() has been set, returns that session. Otherwise
102 * returns the session for RequestContext::getMain()->getRequest().
106 public static function getGlobalSession() {
107 if ( !PHPSessionHandler
::isEnabled() ) {
113 $request = \RequestContext
::getMain()->getRequest();
115 !self
::$globalSession // No global session is set up yet
116 || self
::$globalSessionRequest !== $request // The global WebRequest changed
117 ||
$id !== '' && self
::$globalSession->getId() !== $id // Someone messed with session_id()
119 self
::$globalSessionRequest = $request;
121 // session_id() wasn't used, so fetch the Session from the WebRequest.
122 // We use $request->getSession() instead of $singleton->getSessionForRequest()
123 // because doing the latter would require a public
124 // "$request->getSessionId()" method that would confuse end
125 // users by returning SessionId|null where they'd expect it to
126 // be short for $request->getSession()->getId(), and would
127 // wind up being a duplicate of the code in
128 // $request->getSession() anyway.
129 self
::$globalSession = $request->getSession();
131 // Someone used session_id(), so we need to follow suit.
132 // Note this overwrites whatever session might already be
133 // associated with $request with the one for $id.
134 self
::$globalSession = self
::singleton()->getSessionById( $id, true, $request )
135 ?
: $request->getSession();
138 return self
::$globalSession;
142 * @param array $options
143 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
144 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
145 * - store: BagOStuff to store session data in.
147 public function __construct( $options = [] ) {
148 if ( isset( $options['config'] ) ) {
149 $this->config
= $options['config'];
150 if ( !$this->config
instanceof Config
) {
151 throw new \
InvalidArgumentException(
152 '$options[\'config\'] must be an instance of Config'
156 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
159 if ( isset( $options['logger'] ) ) {
160 if ( !$options['logger'] instanceof LoggerInterface
) {
161 throw new \
InvalidArgumentException(
162 '$options[\'logger\'] must be an instance of LoggerInterface'
165 $this->setLogger( $options['logger'] );
167 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' ) );
170 if ( isset( $options['store'] ) ) {
171 if ( !$options['store'] instanceof BagOStuff
) {
172 throw new \
InvalidArgumentException(
173 '$options[\'store\'] must be an instance of BagOStuff'
176 $store = $options['store'];
178 $store = \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
180 $this->store
= $store instanceof CachedBagOStuff ?
$store : new CachedBagOStuff( $store );
182 register_shutdown_function( [ $this, 'shutdown' ] );
185 public function setLogger( LoggerInterface
$logger ) {
186 $this->logger
= $logger;
189 public function getSessionForRequest( WebRequest
$request ) {
190 $info = $this->getSessionInfoForRequest( $request );
193 $session = $this->getEmptySession( $request );
195 $session = $this->getSessionFromInfo( $info, $request );
200 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
201 if ( !self
::validateSessionId( $id ) ) {
202 throw new \
InvalidArgumentException( 'Invalid session ID' );
205 $request = new FauxRequest
;
209 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [ 'id' => $id, 'idIsSafe' => true ] );
211 // If we already have the backend loaded, use it directly
212 if ( isset( $this->allSessionBackends
[$id] ) ) {
213 return $this->getSessionFromInfo( $info, $request );
216 // Test if the session is in storage, and if so try to load it.
217 $key = $this->store
->makeKey( 'MWSession', $id );
218 if ( is_array( $this->store
->get( $key ) ) ) {
219 $create = false; // If loading fails, don't bother creating because it probably will fail too.
220 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
221 $session = $this->getSessionFromInfo( $info, $request );
225 if ( $create && $session === null ) {
228 $session = $this->getEmptySessionInternal( $request, $id );
229 } catch ( \Exception
$ex ) {
230 $this->logger
->error( 'Failed to create empty session: {exception}',
232 'method' => __METHOD__
,
242 public function getEmptySession( WebRequest
$request = null ) {
243 return $this->getEmptySessionInternal( $request );
247 * @see SessionManagerInterface::getEmptySession
248 * @param WebRequest|null $request
249 * @param string|null $id ID to force on the new session
252 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
253 if ( $id !== null ) {
254 if ( !self
::validateSessionId( $id ) ) {
255 throw new \
InvalidArgumentException( 'Invalid session ID' );
258 $key = $this->store
->makeKey( 'MWSession', $id );
259 if ( is_array( $this->store
->get( $key ) ) ) {
260 throw new \
InvalidArgumentException( 'Session ID already exists' );
264 $request = new FauxRequest
;
268 foreach ( $this->getProviders() as $provider ) {
269 $info = $provider->newSessionInfo( $id );
273 if ( $info->getProvider() !== $provider ) {
274 throw new \
UnexpectedValueException(
275 "$provider returned an empty session info for a different provider: $info"
278 if ( $id !== null && $info->getId() !== $id ) {
279 throw new \
UnexpectedValueException(
280 "$provider returned empty session info with a wrong id: " .
281 $info->getId() . ' != ' . $id
284 if ( !$info->isIdSafe() ) {
285 throw new \
UnexpectedValueException(
286 "$provider returned empty session info with id flagged unsafe"
289 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
290 if ( $compare > 0 ) {
293 if ( $compare === 0 ) {
300 // Make sure there's exactly one
301 if ( count( $infos ) > 1 ) {
302 throw new \
UnexpectedValueException(
303 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
305 } elseif ( count( $infos ) < 1 ) {
306 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
309 return $this->getSessionFromInfo( $infos[0], $request );
312 public function invalidateSessionsForUser( User
$user ) {
314 $user->saveSettings();
316 foreach ( $this->getProviders() as $provider ) {
317 $provider->invalidateSessionsForUser( $user );
321 public function getVaryHeaders() {
322 // @codeCoverageIgnoreStart
323 // @phan-suppress-next-line PhanUndeclaredConstant
324 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
327 // @codeCoverageIgnoreEnd
328 if ( $this->varyHeaders
=== null ) {
330 foreach ( $this->getProviders() as $provider ) {
331 foreach ( $provider->getVaryHeaders() as $header => $options ) {
332 # Note that the $options value returned has been deprecated
334 $headers[$header] = null;
337 $this->varyHeaders
= $headers;
339 return $this->varyHeaders
;
342 public function getVaryCookies() {
343 // @codeCoverageIgnoreStart
344 // @phan-suppress-next-line PhanUndeclaredConstant
345 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
348 // @codeCoverageIgnoreEnd
349 if ( $this->varyCookies
=== null ) {
351 foreach ( $this->getProviders() as $provider ) {
352 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
354 $this->varyCookies
= array_values( array_unique( $cookies ) );
356 return $this->varyCookies
;
360 * Validate a session ID
364 public static function validateSessionId( $id ) {
365 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
369 * @name Internal methods
374 * Prevent future sessions for the user
376 * The intention is that the named account will never again be usable for
377 * normal login (i.e. there is no way to undo the prevention of access).
379 * @private For use from \User::newSystemUser only
380 * @param string $username
382 public function preventSessionsForUser( $username ) {
383 $this->preventUsers
[$username] = true;
385 // Instruct the session providers to kill any other sessions too.
386 foreach ( $this->getProviders() as $provider ) {
387 $provider->preventSessionsForUser( $username );
392 * Test if a user is prevented
393 * @private For use from SessionBackend only
394 * @param string $username
397 public function isUserSessionPrevented( $username ) {
398 return !empty( $this->preventUsers
[$username] );
402 * Get the available SessionProviders
403 * @return SessionProvider[]
405 protected function getProviders() {
406 if ( $this->sessionProviders
=== null ) {
407 $this->sessionProviders
= [];
408 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
409 $provider = ObjectFactory
::getObjectFromSpec( $spec );
410 $provider->setLogger( $this->logger
);
411 $provider->setConfig( $this->config
);
412 $provider->setManager( $this );
413 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
414 // @phan-suppress-next-line PhanTypeSuspiciousStringExpression
415 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
417 $this->sessionProviders
[(string)$provider] = $provider;
420 return $this->sessionProviders
;
424 * Get a session provider by name
426 * Generally, this will only be used by internal implementation of some
427 * special session-providing mechanism. General purpose code, if it needs
428 * to access a SessionProvider at all, will use Session::getProvider().
430 * @param string $name
431 * @return SessionProvider|null
433 public function getProvider( $name ) {
434 $providers = $this->getProviders();
435 return $providers[$name] ??
null;
439 * Save all active sessions on shutdown
440 * @private For internal use with register_shutdown_function()
442 public function shutdown() {
443 if ( $this->allSessionBackends
) {
444 $this->logger
->debug( 'Saving all sessions on shutdown' );
445 if ( session_id() !== '' ) {
446 // @codeCoverageIgnoreStart
447 session_write_close();
449 // @codeCoverageIgnoreEnd
450 foreach ( $this->allSessionBackends
as $backend ) {
451 $backend->shutdown();
457 * Fetch the SessionInfo(s) for a request
458 * @param WebRequest $request
459 * @return SessionInfo|null
461 private function getSessionInfoForRequest( WebRequest
$request ) {
462 // Call all providers to fetch "the" session
464 foreach ( $this->getProviders() as $provider ) {
465 $info = $provider->provideSessionInfo( $request );
469 if ( $info->getProvider() !== $provider ) {
470 throw new \
UnexpectedValueException(
471 "$provider returned session info for a different provider: $info"
477 // Sort the SessionInfos. Then find the first one that can be
478 // successfully loaded, and then all the ones after it with the same
480 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
483 $info = array_pop( $infos );
484 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
487 $info = array_pop( $infos );
488 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
489 // We hit a lower priority, stop checking.
492 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
493 // This is going to error out below, but we want to
494 // provide a complete list.
497 // Session load failed, so unpersist it from this request
498 $info->getProvider()->unpersistSession( $request );
502 // Session load failed, so unpersist it from this request
503 $info->getProvider()->unpersistSession( $request );
507 if ( count( $retInfos ) > 1 ) {
508 $ex = new \
OverflowException(
509 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
511 $ex->sessionInfos
= $retInfos;
515 return $retInfos ?
$retInfos[0] : null;
519 * Load and verify the session info against the store
521 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
522 * @param WebRequest $request
523 * @return bool Whether the session info matches the stored data (if any)
525 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
526 $key = $this->store
->makeKey( 'MWSession', $info->getId() );
527 $blob = $this->store
->get( $key );
529 // If we got data from the store and the SessionInfo says to force use,
530 // "fail" means to delete the data from the store and retry. Otherwise,
531 // "fail" is just return false.
532 if ( $info->forceUse() && $blob !== false ) {
533 $failHandler = function () use ( $key, &$info, $request ) {
534 $this->store
->delete( $key );
535 return $this->loadSessionInfoFromStore( $info, $request );
538 $failHandler = function () {
545 if ( $blob !== false ) {
546 // Sanity check: blob must be an array, if it's saved at all
547 if ( !is_array( $blob ) ) {
548 $this->logger
->warning( 'Session "{session}": Bad data', [
551 $this->store
->delete( $key );
552 return $failHandler();
555 // Sanity check: blob has data and metadata arrays
556 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
557 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
559 $this->logger
->warning( 'Session "{session}": Bad data structure', [
562 $this->store
->delete( $key );
563 return $failHandler();
566 $data = $blob['data'];
567 $metadata = $blob['metadata'];
569 // Sanity check: metadata must be an array and must contain certain
570 // keys, if it's saved at all
571 if ( !array_key_exists( 'userId', $metadata ) ||
572 !array_key_exists( 'userName', $metadata ) ||
573 !array_key_exists( 'userToken', $metadata ) ||
574 !array_key_exists( 'provider', $metadata )
576 $this->logger
->warning( 'Session "{session}": Bad metadata', [
579 $this->store
->delete( $key );
580 return $failHandler();
583 // First, load the provider from metadata, or validate it against the metadata.
584 $provider = $info->getProvider();
585 if ( $provider === null ) {
586 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
588 $this->logger
->warning(
589 'Session "{session}": Unknown provider ' . $metadata['provider'],
594 $this->store
->delete( $key );
595 return $failHandler();
597 } elseif ( $metadata['provider'] !== (string)$provider ) {
598 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
599 $metadata['provider'] . ' !== ' . $provider,
603 return $failHandler();
606 // Load provider metadata from metadata, or validate it against the metadata
607 $providerMetadata = $info->getProviderMetadata();
608 if ( isset( $metadata['providerMetadata'] ) ) {
609 if ( $providerMetadata === null ) {
610 $newParams['metadata'] = $metadata['providerMetadata'];
613 $newProviderMetadata = $provider->mergeMetadata(
614 $metadata['providerMetadata'], $providerMetadata
616 if ( $newProviderMetadata !== $providerMetadata ) {
617 $newParams['metadata'] = $newProviderMetadata;
619 } catch ( MetadataMergeException
$ex ) {
620 $this->logger
->warning(
621 'Session "{session}": Metadata merge failed: {exception}',
625 ] +
$ex->getContext()
627 return $failHandler();
632 // Next, load the user from metadata, or validate it against the metadata.
633 $userInfo = $info->getUserInfo();
635 // For loading, id is preferred to name.
637 if ( $metadata['userId'] ) {
638 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
639 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
640 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
642 $userInfo = UserInfo
::newAnonymous();
644 } catch ( \InvalidArgumentException
$ex ) {
645 $this->logger
->error( 'Session "{session}": {exception}', [
649 return $failHandler();
651 $newParams['userInfo'] = $userInfo;
653 // User validation passes if user ID matches, or if there
654 // is no saved ID and the names match.
655 if ( $metadata['userId'] ) {
656 if ( $metadata['userId'] !== $userInfo->getId() ) {
657 $this->logger
->warning(
658 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
661 'uid_a' => $metadata['userId'],
662 'uid_b' => $userInfo->getId(),
664 return $failHandler();
667 // If the user was renamed, probably best to fail here.
668 if ( $metadata['userName'] !== null &&
669 $userInfo->getName() !== $metadata['userName']
671 $this->logger
->warning(
672 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
675 'uname_a' => $metadata['userName'],
676 'uname_b' => $userInfo->getName(),
678 return $failHandler();
681 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
682 if ( $metadata['userName'] !== $userInfo->getName() ) {
683 $this->logger
->warning(
684 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
687 'uname_a' => $metadata['userName'],
688 'uname_b' => $userInfo->getName(),
690 return $failHandler();
692 } elseif ( !$userInfo->isAnon() ) {
693 // Metadata specifies an anonymous user, but the passed-in
694 // user isn't anonymous.
695 $this->logger
->warning(
696 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
700 return $failHandler();
704 // And if we have a token in the metadata, it must match the loaded/provided user.
705 if ( $metadata['userToken'] !== null &&
706 $userInfo->getToken() !== $metadata['userToken']
708 $this->logger
->warning( 'Session "{session}": User token mismatch', [
711 return $failHandler();
713 if ( !$userInfo->isVerified() ) {
714 $newParams['userInfo'] = $userInfo->verified();
717 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
718 $newParams['remembered'] = true;
720 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
721 $newParams['forceHTTPS'] = true;
723 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
724 $newParams['persisted'] = true;
727 if ( !$info->isIdSafe() ) {
728 $newParams['idIsSafe'] = true;
731 // No metadata, so we can't load the provider if one wasn't given.
732 if ( $info->getProvider() === null ) {
733 $this->logger
->warning(
734 'Session "{session}": Null provider and no metadata',
738 return $failHandler();
741 // If no user was provided and no metadata, it must be anon.
742 if ( !$info->getUserInfo() ) {
743 if ( $info->getProvider()->canChangeUser() ) {
744 $newParams['userInfo'] = UserInfo
::newAnonymous();
747 'Session "{session}": No user provided and provider cannot set user',
751 return $failHandler();
753 } elseif ( !$info->getUserInfo()->isVerified() ) {
754 // probably just a session timeout
756 'Session "{session}": Unverified user provided and no metadata to auth it',
760 return $failHandler();
766 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
767 // The ID doesn't come from the user, so it should be safe
768 // (and if not, nothing we can do about it anyway)
769 $newParams['idIsSafe'] = true;
773 // Construct the replacement SessionInfo, if necessary
775 $newParams['copyFrom'] = $info;
776 $info = new SessionInfo( $info->getPriority(), $newParams );
779 // Allow the provider to check the loaded SessionInfo
780 $providerMetadata = $info->getProviderMetadata();
781 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
782 return $failHandler();
784 if ( $providerMetadata !== $info->getProviderMetadata() ) {
785 $info = new SessionInfo( $info->getPriority(), [
786 'metadata' => $providerMetadata,
791 // Give hooks a chance to abort. Combined with the SessionMetadata
792 // hook, this can allow for tying a session to an IP address or the
794 $reason = 'Hook aborted';
797 [ &$reason, $info, $request, $metadata, $data ]
799 $this->logger
->warning( 'Session "{session}": ' . $reason, [
802 return $failHandler();
809 * Create a Session corresponding to the passed SessionInfo
810 * @private For use by a SessionProvider that needs to specially create its
811 * own Session. Most session providers won't need this.
812 * @param SessionInfo $info
813 * @param WebRequest $request
816 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
817 // @codeCoverageIgnoreStart
818 if ( defined( 'MW_NO_SESSION' ) ) {
819 // @phan-suppress-next-line PhanUndeclaredConstant
820 if ( MW_NO_SESSION
=== 'warn' ) {
821 // Undocumented safety case for converting existing entry points
822 $this->logger
->error( 'Sessions are supposed to be disabled for this entry point', [
823 'exception' => new \
BadMethodCallException( 'Sessions are disabled for this entry point' ),
826 throw new \
BadMethodCallException( 'Sessions are disabled for this entry point' );
829 // @codeCoverageIgnoreEnd
831 $id = $info->getId();
833 if ( !isset( $this->allSessionBackends
[$id] ) ) {
834 if ( !isset( $this->allSessionIds
[$id] ) ) {
835 $this->allSessionIds
[$id] = new SessionId( $id );
837 $backend = new SessionBackend(
838 $this->allSessionIds
[$id],
842 $this->config
->get( 'ObjectCacheSessionExpiry' )
844 $this->allSessionBackends
[$id] = $backend;
845 $delay = $backend->delaySave();
847 $backend = $this->allSessionBackends
[$id];
848 $delay = $backend->delaySave();
849 if ( $info->wasPersisted() ) {
852 if ( $info->wasRemembered() ) {
853 $backend->setRememberUser( true );
857 $request->setSessionId( $backend->getSessionId() );
858 $session = $backend->getSession( $request );
860 if ( !$info->isIdSafe() ) {
864 \Wikimedia\ScopedCallback
::consume( $delay );
869 * Deregister a SessionBackend
870 * @private For use from \MediaWiki\Session\SessionBackend only
871 * @param SessionBackend $backend
873 public function deregisterSessionBackend( SessionBackend
$backend ) {
874 $id = $backend->getId();
875 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
876 $this->allSessionBackends
[$id] !== $backend ||
877 $this->allSessionIds
[$id] !== $backend->getSessionId()
879 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
882 unset( $this->allSessionBackends
[$id] );
883 // Explicitly do not unset $this->allSessionIds[$id]
887 * Change a SessionBackend's ID
888 * @private For use from \MediaWiki\Session\SessionBackend only
889 * @param SessionBackend $backend
891 public function changeBackendId( SessionBackend
$backend ) {
892 $sessionId = $backend->getSessionId();
893 $oldId = (string)$sessionId;
894 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
895 $this->allSessionBackends
[$oldId] !== $backend ||
896 $this->allSessionIds
[$oldId] !== $sessionId
898 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
901 $newId = $this->generateSessionId();
903 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
904 $sessionId->setId( $newId );
905 $this->allSessionBackends
[$newId] = $backend;
906 $this->allSessionIds
[$newId] = $sessionId;
910 * Generate a new random session ID
913 public function generateSessionId() {
915 $id = \Wikimedia\base_convert
( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
916 $key = $this->store
->makeKey( 'MWSession', $id );
917 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
922 * Call setters on a PHPSessionHandler
923 * @private Use PhpSessionHandler::install()
924 * @param PHPSessionHandler $handler
926 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
927 $handler->setManager( $this, $this->store
, $this->logger
);
931 * Reset the internal caching for unit testing
932 * @protected Unit tests only
934 public static function resetCache() {
935 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
936 // @codeCoverageIgnoreStart
937 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
938 // @codeCoverageIgnoreEnd
941 self
::$globalSession = null;
942 self
::$globalSessionRequest = null;