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
;
27 use Psr\Log\LoggerInterface
;
36 * This serves as the entry point to the MediaWiki session handling system.
38 * Most methods here are for internal use by session handling code. Other callers
39 * should only use getGlobalSession and the methods of SessionManagerInterface;
40 * the rest of the functionality is exposed via MediaWiki\Session\Session methods.
42 * To provide custom session handling, implement a MediaWiki\Session\SessionProvider.
46 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
48 final class SessionManager
implements SessionManagerInterface
{
49 /** @var SessionManager|null */
50 private static $instance = null;
52 /** @var Session|null */
53 private static $globalSession = null;
55 /** @var WebRequest|null */
56 private static $globalSessionRequest = null;
58 /** @var LoggerInterface */
64 /** @var CachedBagOStuff|null */
67 /** @var SessionProvider[] */
68 private $sessionProviders = null;
71 private $varyCookies = null;
74 private $varyHeaders = null;
76 /** @var SessionBackend[] */
77 private $allSessionBackends = [];
79 /** @var SessionId[] */
80 private $allSessionIds = [];
83 private $preventUsers = [];
86 * Get the global SessionManager
87 * @return SessionManagerInterface
88 * (really a SessionManager, but this is to make IDEs less confused)
90 public static function singleton() {
91 if ( self
::$instance === null ) {
92 self
::$instance = new self();
94 return self
::$instance;
98 * Get the "global" session
100 * If PHP's session_id() has been set, returns that session. Otherwise
101 * returns the session for RequestContext::getMain()->getRequest().
105 public static function getGlobalSession() {
106 if ( !PHPSessionHandler
::isEnabled() ) {
112 $request = \RequestContext
::getMain()->getRequest();
114 !self
::$globalSession // No global session is set up yet
115 || self
::$globalSessionRequest !== $request // The global WebRequest changed
116 ||
$id !== '' && self
::$globalSession->getId() !== $id // Someone messed with session_id()
118 self
::$globalSessionRequest = $request;
120 // session_id() wasn't used, so fetch the Session from the WebRequest.
121 // We use $request->getSession() instead of $singleton->getSessionForRequest()
122 // because doing the latter would require a public
123 // "$request->getSessionId()" method that would confuse end
124 // users by returning SessionId|null where they'd expect it to
125 // be short for $request->getSession()->getId(), and would
126 // wind up being a duplicate of the code in
127 // $request->getSession() anyway.
128 self
::$globalSession = $request->getSession();
130 // Someone used session_id(), so we need to follow suit.
131 // Note this overwrites whatever session might already be
132 // associated with $request with the one for $id.
133 self
::$globalSession = self
::singleton()->getSessionById( $id, true, $request )
134 ?
: $request->getSession();
137 return self
::$globalSession;
141 * @param array $options
142 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
143 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
144 * - store: BagOStuff to store session data in.
146 public function __construct( $options = [] ) {
147 if ( isset( $options['config'] ) ) {
148 $this->config
= $options['config'];
149 if ( !$this->config
instanceof Config
) {
150 throw new \
InvalidArgumentException(
151 '$options[\'config\'] must be an instance of Config'
155 $this->config
= \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
158 if ( isset( $options['logger'] ) ) {
159 if ( !$options['logger'] instanceof LoggerInterface
) {
160 throw new \
InvalidArgumentException(
161 '$options[\'logger\'] must be an instance of LoggerInterface'
164 $this->setLogger( $options['logger'] );
166 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' ) );
169 if ( isset( $options['store'] ) ) {
170 if ( !$options['store'] instanceof BagOStuff
) {
171 throw new \
InvalidArgumentException(
172 '$options[\'store\'] must be an instance of BagOStuff'
175 $store = $options['store'];
177 $store = \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
179 $this->store
= $store instanceof CachedBagOStuff ?
$store : new CachedBagOStuff( $store );
181 register_shutdown_function( [ $this, 'shutdown' ] );
184 public function setLogger( LoggerInterface
$logger ) {
185 $this->logger
= $logger;
188 public function getSessionForRequest( WebRequest
$request ) {
189 $info = $this->getSessionInfoForRequest( $request );
192 $session = $this->getEmptySession( $request );
194 $session = $this->getSessionFromInfo( $info, $request );
199 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
200 if ( !self
::validateSessionId( $id ) ) {
201 throw new \
InvalidArgumentException( 'Invalid session ID' );
204 $request = new FauxRequest
;
208 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [ 'id' => $id, 'idIsSafe' => true ] );
210 // If we already have the backend loaded, use it directly
211 if ( isset( $this->allSessionBackends
[$id] ) ) {
212 return $this->getSessionFromInfo( $info, $request );
215 // Test if the session is in storage, and if so try to load it.
216 $key = wfMemcKey( 'MWSession', $id );
217 if ( is_array( $this->store
->get( $key ) ) ) {
218 $create = false; // If loading fails, don't bother creating because it probably will fail too.
219 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
220 $session = $this->getSessionFromInfo( $info, $request );
224 if ( $create && $session === null ) {
227 $session = $this->getEmptySessionInternal( $request, $id );
228 } catch ( \Exception
$ex ) {
229 $this->logger
->error( 'Failed to create empty session: {exception}',
231 'method' => __METHOD__
,
241 public function getEmptySession( WebRequest
$request = null ) {
242 return $this->getEmptySessionInternal( $request );
246 * @see SessionManagerInterface::getEmptySession
247 * @param WebRequest|null $request
248 * @param string|null $id ID to force on the new session
251 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
252 if ( $id !== null ) {
253 if ( !self
::validateSessionId( $id ) ) {
254 throw new \
InvalidArgumentException( 'Invalid session ID' );
257 $key = wfMemcKey( 'MWSession', $id );
258 if ( is_array( $this->store
->get( $key ) ) ) {
259 throw new \
InvalidArgumentException( 'Session ID already exists' );
263 $request = new FauxRequest
;
267 foreach ( $this->getProviders() as $provider ) {
268 $info = $provider->newSessionInfo( $id );
272 if ( $info->getProvider() !== $provider ) {
273 throw new \
UnexpectedValueException(
274 "$provider returned an empty session info for a different provider: $info"
277 if ( $id !== null && $info->getId() !== $id ) {
278 throw new \
UnexpectedValueException(
279 "$provider returned empty session info with a wrong id: " .
280 $info->getId() . ' != ' . $id
283 if ( !$info->isIdSafe() ) {
284 throw new \
UnexpectedValueException(
285 "$provider returned empty session info with id flagged unsafe"
288 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
289 if ( $compare > 0 ) {
292 if ( $compare === 0 ) {
299 // Make sure there's exactly one
300 if ( count( $infos ) > 1 ) {
301 throw new \
UnexpectedValueException(
302 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
304 } elseif ( count( $infos ) < 1 ) {
305 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
308 return $this->getSessionFromInfo( $infos[0], $request );
311 public function invalidateSessionsForUser( User
$user ) {
313 $user->saveSettings();
315 $authUser = \MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ] );
317 $authUser->resetAuthToken();
320 foreach ( $this->getProviders() as $provider ) {
321 $provider->invalidateSessionsForUser( $user );
325 public function getVaryHeaders() {
326 // @codeCoverageIgnoreStart
327 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
330 // @codeCoverageIgnoreEnd
331 if ( $this->varyHeaders
=== null ) {
333 foreach ( $this->getProviders() as $provider ) {
334 foreach ( $provider->getVaryHeaders() as $header => $options ) {
335 if ( !isset( $headers[$header] ) ) {
336 $headers[$header] = [];
338 if ( is_array( $options ) ) {
339 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
343 $this->varyHeaders
= $headers;
345 return $this->varyHeaders
;
348 public function getVaryCookies() {
349 // @codeCoverageIgnoreStart
350 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
353 // @codeCoverageIgnoreEnd
354 if ( $this->varyCookies
=== null ) {
356 foreach ( $this->getProviders() as $provider ) {
357 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
359 $this->varyCookies
= array_values( array_unique( $cookies ) );
361 return $this->varyCookies
;
365 * Validate a session ID
369 public static function validateSessionId( $id ) {
370 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
374 * @name Internal methods
379 * Auto-create the given user, if necessary
380 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
381 * @deprecated since 1.27, use MediaWiki\Auth\AuthManager::autoCreateUser instead
382 * @param User $user User to auto-create
383 * @return bool Success
384 * @codeCoverageIgnore
386 public static function autoCreateUser( User
$user ) {
387 wfDeprecated( __METHOD__
, '1.27' );
388 return \MediaWiki\Auth\AuthManager
::singleton()->autoCreateUser(
390 \MediaWiki\Auth\AuthManager
::AUTOCREATE_SOURCE_SESSION
,
396 * Prevent future sessions for the user
398 * The intention is that the named account will never again be usable for
399 * normal login (i.e. there is no way to undo the prevention of access).
401 * @private For use from \User::newSystemUser only
402 * @param string $username
404 public function preventSessionsForUser( $username ) {
405 $this->preventUsers
[$username] = true;
407 // Instruct the session providers to kill any other sessions too.
408 foreach ( $this->getProviders() as $provider ) {
409 $provider->preventSessionsForUser( $username );
414 * Test if a user is prevented
415 * @private For use from SessionBackend only
416 * @param string $username
419 public function isUserSessionPrevented( $username ) {
420 return !empty( $this->preventUsers
[$username] );
424 * Get the available SessionProviders
425 * @return SessionProvider[]
427 protected function getProviders() {
428 if ( $this->sessionProviders
=== null ) {
429 $this->sessionProviders
= [];
430 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
431 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
432 $provider->setLogger( $this->logger
);
433 $provider->setConfig( $this->config
);
434 $provider->setManager( $this );
435 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
436 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
438 $this->sessionProviders
[(string)$provider] = $provider;
441 return $this->sessionProviders
;
445 * Get a session provider by name
447 * Generally, this will only be used by internal implementation of some
448 * special session-providing mechanism. General purpose code, if it needs
449 * to access a SessionProvider at all, will use Session::getProvider().
451 * @param string $name
452 * @return SessionProvider|null
454 public function getProvider( $name ) {
455 $providers = $this->getProviders();
456 return isset( $providers[$name] ) ?
$providers[$name] : null;
460 * Save all active sessions on shutdown
461 * @private For internal use with register_shutdown_function()
463 public function shutdown() {
464 if ( $this->allSessionBackends
) {
465 $this->logger
->debug( 'Saving all sessions on shutdown' );
466 if ( session_id() !== '' ) {
467 // @codeCoverageIgnoreStart
468 session_write_close();
470 // @codeCoverageIgnoreEnd
471 foreach ( $this->allSessionBackends
as $backend ) {
472 $backend->shutdown();
478 * Fetch the SessionInfo(s) for a request
479 * @param WebRequest $request
480 * @return SessionInfo|null
482 private function getSessionInfoForRequest( WebRequest
$request ) {
483 // Call all providers to fetch "the" session
485 foreach ( $this->getProviders() as $provider ) {
486 $info = $provider->provideSessionInfo( $request );
490 if ( $info->getProvider() !== $provider ) {
491 throw new \
UnexpectedValueException(
492 "$provider returned session info for a different provider: $info"
498 // Sort the SessionInfos. Then find the first one that can be
499 // successfully loaded, and then all the ones after it with the same
501 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
504 $info = array_pop( $infos );
505 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
508 $info = array_pop( $infos );
509 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
510 // We hit a lower priority, stop checking.
513 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
514 // This is going to error out below, but we want to
515 // provide a complete list.
518 // Session load failed, so unpersist it from this request
519 $info->getProvider()->unpersistSession( $request );
523 // Session load failed, so unpersist it from this request
524 $info->getProvider()->unpersistSession( $request );
528 if ( count( $retInfos ) > 1 ) {
529 $ex = new \
OverflowException(
530 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
532 $ex->sessionInfos
= $retInfos;
536 return $retInfos ?
$retInfos[0] : null;
540 * Load and verify the session info against the store
542 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
543 * @param WebRequest $request
544 * @return bool Whether the session info matches the stored data (if any)
546 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
547 $key = wfMemcKey( 'MWSession', $info->getId() );
548 $blob = $this->store
->get( $key );
550 // If we got data from the store and the SessionInfo says to force use,
551 // "fail" means to delete the data from the store and retry. Otherwise,
552 // "fail" is just return false.
553 if ( $info->forceUse() && $blob !== false ) {
554 $failHandler = function () use ( $key, &$info, $request ) {
555 $this->store
->delete( $key );
556 return $this->loadSessionInfoFromStore( $info, $request );
559 $failHandler = function () {
566 if ( $blob !== false ) {
567 // Sanity check: blob must be an array, if it's saved at all
568 if ( !is_array( $blob ) ) {
569 $this->logger
->warning( 'Session "{session}": Bad data', [
572 $this->store
->delete( $key );
573 return $failHandler();
576 // Sanity check: blob has data and metadata arrays
577 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
578 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
580 $this->logger
->warning( 'Session "{session}": Bad data structure', [
583 $this->store
->delete( $key );
584 return $failHandler();
587 $data = $blob['data'];
588 $metadata = $blob['metadata'];
590 // Sanity check: metadata must be an array and must contain certain
591 // keys, if it's saved at all
592 if ( !array_key_exists( 'userId', $metadata ) ||
593 !array_key_exists( 'userName', $metadata ) ||
594 !array_key_exists( 'userToken', $metadata ) ||
595 !array_key_exists( 'provider', $metadata )
597 $this->logger
->warning( 'Session "{session}": Bad metadata', [
600 $this->store
->delete( $key );
601 return $failHandler();
604 // First, load the provider from metadata, or validate it against the metadata.
605 $provider = $info->getProvider();
606 if ( $provider === null ) {
607 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
609 $this->logger
->warning(
610 'Session "{session}": Unknown provider ' . $metadata['provider'],
615 $this->store
->delete( $key );
616 return $failHandler();
618 } elseif ( $metadata['provider'] !== (string)$provider ) {
619 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
620 $metadata['provider'] . ' !== ' . $provider,
624 return $failHandler();
627 // Load provider metadata from metadata, or validate it against the metadata
628 $providerMetadata = $info->getProviderMetadata();
629 if ( isset( $metadata['providerMetadata'] ) ) {
630 if ( $providerMetadata === null ) {
631 $newParams['metadata'] = $metadata['providerMetadata'];
634 $newProviderMetadata = $provider->mergeMetadata(
635 $metadata['providerMetadata'], $providerMetadata
637 if ( $newProviderMetadata !== $providerMetadata ) {
638 $newParams['metadata'] = $newProviderMetadata;
640 } catch ( MetadataMergeException
$ex ) {
641 $this->logger
->warning(
642 'Session "{session}": Metadata merge failed: {exception}',
646 ] +
$ex->getContext()
648 return $failHandler();
653 // Next, load the user from metadata, or validate it against the metadata.
654 $userInfo = $info->getUserInfo();
656 // For loading, id is preferred to name.
658 if ( $metadata['userId'] ) {
659 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
660 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
661 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
663 $userInfo = UserInfo
::newAnonymous();
665 } catch ( \InvalidArgumentException
$ex ) {
666 $this->logger
->error( 'Session "{session}": {exception}', [
670 return $failHandler();
672 $newParams['userInfo'] = $userInfo;
674 // User validation passes if user ID matches, or if there
675 // is no saved ID and the names match.
676 if ( $metadata['userId'] ) {
677 if ( $metadata['userId'] !== $userInfo->getId() ) {
678 $this->logger
->warning(
679 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
682 'uid_a' => $metadata['userId'],
683 'uid_b' => $userInfo->getId(),
685 return $failHandler();
688 // If the user was renamed, probably best to fail here.
689 if ( $metadata['userName'] !== null &&
690 $userInfo->getName() !== $metadata['userName']
692 $this->logger
->warning(
693 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
696 'uname_a' => $metadata['userName'],
697 'uname_b' => $userInfo->getName(),
699 return $failHandler();
702 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
703 if ( $metadata['userName'] !== $userInfo->getName() ) {
704 $this->logger
->warning(
705 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
708 'uname_a' => $metadata['userName'],
709 'uname_b' => $userInfo->getName(),
711 return $failHandler();
713 } elseif ( !$userInfo->isAnon() ) {
714 // Metadata specifies an anonymous user, but the passed-in
715 // user isn't anonymous.
716 $this->logger
->warning(
717 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
721 return $failHandler();
725 // And if we have a token in the metadata, it must match the loaded/provided user.
726 if ( $metadata['userToken'] !== null &&
727 $userInfo->getToken() !== $metadata['userToken']
729 $this->logger
->warning( 'Session "{session}": User token mismatch', [
732 return $failHandler();
734 if ( !$userInfo->isVerified() ) {
735 $newParams['userInfo'] = $userInfo->verified();
738 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
739 $newParams['remembered'] = true;
741 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
742 $newParams['forceHTTPS'] = true;
744 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
745 $newParams['persisted'] = true;
748 if ( !$info->isIdSafe() ) {
749 $newParams['idIsSafe'] = true;
752 // No metadata, so we can't load the provider if one wasn't given.
753 if ( $info->getProvider() === null ) {
754 $this->logger
->warning(
755 'Session "{session}": Null provider and no metadata',
759 return $failHandler();
762 // If no user was provided and no metadata, it must be anon.
763 if ( !$info->getUserInfo() ) {
764 if ( $info->getProvider()->canChangeUser() ) {
765 $newParams['userInfo'] = UserInfo
::newAnonymous();
768 'Session "{session}": No user provided and provider cannot set user',
772 return $failHandler();
774 } elseif ( !$info->getUserInfo()->isVerified() ) {
775 $this->logger
->warning(
776 'Session "{session}": Unverified user provided and no metadata to auth it',
780 return $failHandler();
786 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
787 // The ID doesn't come from the user, so it should be safe
788 // (and if not, nothing we can do about it anyway)
789 $newParams['idIsSafe'] = true;
793 // Construct the replacement SessionInfo, if necessary
795 $newParams['copyFrom'] = $info;
796 $info = new SessionInfo( $info->getPriority(), $newParams );
799 // Allow the provider to check the loaded SessionInfo
800 $providerMetadata = $info->getProviderMetadata();
801 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
802 return $failHandler();
804 if ( $providerMetadata !== $info->getProviderMetadata() ) {
805 $info = new SessionInfo( $info->getPriority(), [
806 'metadata' => $providerMetadata,
811 // Give hooks a chance to abort. Combined with the SessionMetadata
812 // hook, this can allow for tying a session to an IP address or the
814 $reason = 'Hook aborted';
817 [ &$reason, $info, $request, $metadata, $data ]
819 $this->logger
->warning( 'Session "{session}": ' . $reason, [
822 return $failHandler();
829 * Create a Session corresponding to the passed SessionInfo
830 * @private For use by a SessionProvider that needs to specially create its
831 * own Session. Most session providers won't need this.
832 * @param SessionInfo $info
833 * @param WebRequest $request
836 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
837 // @codeCoverageIgnoreStart
838 if ( defined( 'MW_NO_SESSION' ) ) {
839 if ( MW_NO_SESSION
=== 'warn' ) {
840 // Undocumented safety case for converting existing entry points
841 $this->logger
->error( 'Sessions are supposed to be disabled for this entry point', [
842 'exception' => new \
BadMethodCallException( 'Sessions are disabled for this entry point' ),
845 throw new \
BadMethodCallException( 'Sessions are disabled for this entry point' );
848 // @codeCoverageIgnoreEnd
850 $id = $info->getId();
852 if ( !isset( $this->allSessionBackends
[$id] ) ) {
853 if ( !isset( $this->allSessionIds
[$id] ) ) {
854 $this->allSessionIds
[$id] = new SessionId( $id );
856 $backend = new SessionBackend(
857 $this->allSessionIds
[$id],
861 $this->config
->get( 'ObjectCacheSessionExpiry' )
863 $this->allSessionBackends
[$id] = $backend;
864 $delay = $backend->delaySave();
866 $backend = $this->allSessionBackends
[$id];
867 $delay = $backend->delaySave();
868 if ( $info->wasPersisted() ) {
871 if ( $info->wasRemembered() ) {
872 $backend->setRememberUser( true );
876 $request->setSessionId( $backend->getSessionId() );
877 $session = $backend->getSession( $request );
879 if ( !$info->isIdSafe() ) {
883 \Wikimedia\ScopedCallback
::consume( $delay );
888 * Deregister a SessionBackend
889 * @private For use from \MediaWiki\Session\SessionBackend only
890 * @param SessionBackend $backend
892 public function deregisterSessionBackend( SessionBackend
$backend ) {
893 $id = $backend->getId();
894 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
895 $this->allSessionBackends
[$id] !== $backend ||
896 $this->allSessionIds
[$id] !== $backend->getSessionId()
898 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
901 unset( $this->allSessionBackends
[$id] );
902 // Explicitly do not unset $this->allSessionIds[$id]
906 * Change a SessionBackend's ID
907 * @private For use from \MediaWiki\Session\SessionBackend only
908 * @param SessionBackend $backend
910 public function changeBackendId( SessionBackend
$backend ) {
911 $sessionId = $backend->getSessionId();
912 $oldId = (string)$sessionId;
913 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
914 $this->allSessionBackends
[$oldId] !== $backend ||
915 $this->allSessionIds
[$oldId] !== $sessionId
917 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
920 $newId = $this->generateSessionId();
922 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
923 $sessionId->setId( $newId );
924 $this->allSessionBackends
[$newId] = $backend;
925 $this->allSessionIds
[$newId] = $sessionId;
929 * Generate a new random session ID
932 public function generateSessionId() {
934 $id = \Wikimedia\base_convert
( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
935 $key = wfMemcKey( 'MWSession', $id );
936 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
941 * Call setters on a PHPSessionHandler
942 * @private Use PhpSessionHandler::install()
943 * @param PHPSessionHandler $handler
945 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
946 $handler->setManager( $this, $this->store
, $this->logger
);
950 * Reset the internal caching for unit testing
951 * @protected Unit tests only
953 public static function resetCache() {
954 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
955 // @codeCoverageIgnoreStart
956 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
957 // @codeCoverageIgnoreEnd
960 self
::$globalSession = null;
961 self
::$globalSessionRequest = null;