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 Psr\Log\LoggerInterface
;
36 * This serves as the entry point to the MediaWiki session handling system.
41 final class SessionManager
implements SessionManagerInterface
{
42 /** @var SessionManager|null */
43 private static $instance = null;
45 /** @var Session|null */
46 private static $globalSession = null;
48 /** @var WebRequest|null */
49 private static $globalSessionRequest = null;
51 /** @var LoggerInterface */
57 /** @var BagOStuff|null */
60 /** @var SessionProvider[] */
61 private $sessionProviders = null;
64 private $varyCookies = null;
67 private $varyHeaders = null;
69 /** @var SessionBackend[] */
70 private $allSessionBackends = array();
72 /** @var SessionId[] */
73 private $allSessionIds = array();
76 private $preventUsers = array();
79 * Get the global SessionManager
80 * @return SessionManagerInterface
81 * (really a SessionManager, but this is to make IDEs less confused)
83 public static function singleton() {
84 if ( self
::$instance === null ) {
85 self
::$instance = new self();
87 return self
::$instance;
91 * Get the "global" session
93 * If PHP's session_id() has been set, returns that session. Otherwise
94 * returns the session for RequestContext::getMain()->getRequest().
98 public static function getGlobalSession() {
99 if ( !PHPSessionHandler
::isEnabled() ) {
105 $request = \RequestContext
::getMain()->getRequest();
107 !self
::$globalSession // No global session is set up yet
108 || self
::$globalSessionRequest !== $request // The global WebRequest changed
109 ||
$id !== '' && self
::$globalSession->getId() !== $id // Someone messed with session_id()
111 self
::$globalSessionRequest = $request;
113 // session_id() wasn't used, so fetch the Session from the WebRequest.
114 // We use $request->getSession() instead of $singleton->getSessionForRequest()
115 // because doing the latter would require a public
116 // "$request->getSessionId()" method that would confuse end
117 // users by returning SessionId|null where they'd expect it to
118 // be short for $request->getSession()->getId(), and would
119 // wind up being a duplicate of the code in
120 // $request->getSession() anyway.
121 self
::$globalSession = $request->getSession();
123 // Someone used session_id(), so we need to follow suit.
124 // Note this overwrites whatever session might already be
125 // associated with $request with the one for $id.
126 self
::$globalSession = self
::singleton()->getSessionById( $id, true, $request )
127 ?
: $request->getSession();
130 return self
::$globalSession;
134 * @param array $options
135 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
136 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
137 * - store: BagOStuff to store session data in.
139 public function __construct( $options = array() ) {
140 if ( isset( $options['config'] ) ) {
141 $this->config
= $options['config'];
142 if ( !$this->config
instanceof Config
) {
143 throw new \
InvalidArgumentException(
144 '$options[\'config\'] must be an instance of Config'
148 $this->config
= \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
151 if ( isset( $options['logger'] ) ) {
152 if ( !$options['logger'] instanceof LoggerInterface
) {
153 throw new \
InvalidArgumentException(
154 '$options[\'logger\'] must be an instance of LoggerInterface'
157 $this->setLogger( $options['logger'] );
159 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' ) );
162 if ( isset( $options['store'] ) ) {
163 if ( !$options['store'] instanceof BagOStuff
) {
164 throw new \
InvalidArgumentException(
165 '$options[\'store\'] must be an instance of BagOStuff'
168 $this->store
= $options['store'];
170 $this->store
= \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
171 $this->store
->setLogger( $this->logger
);
174 register_shutdown_function( array( $this, 'shutdown' ) );
177 public function setLogger( LoggerInterface
$logger ) {
178 $this->logger
= $logger;
181 public function getPersistedSessionId( WebRequest
$request ) {
182 $info = $this->getSessionInfoForRequest( $request );
183 if ( $info && $info->wasPersisted() ) {
184 return $info->getId();
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
;
211 // Test this here to provide a better log message for the common case
213 $key = wfMemcKey( 'MWSession', $id );
214 if ( is_array( $this->store
->get( $key ) ) ) {
215 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array( 'id' => $id, 'idIsSafe' => true ) );
216 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
217 $session = $this->getSessionFromInfo( $info, $request );
221 if ( $create && $session === null ) {
224 $session = $this->getEmptySessionInternal( $request, $id );
225 } catch ( \Exception
$ex ) {
226 $this->logger
->error( __METHOD__
. ': failed to create empty session: ' .
235 public function getEmptySession( WebRequest
$request = null ) {
236 return $this->getEmptySessionInternal( $request );
240 * @see SessionManagerInterface::getEmptySession
241 * @param WebRequest|null $request
242 * @param string|null $id ID to force on the new session
245 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
246 if ( $id !== null ) {
247 if ( !self
::validateSessionId( $id ) ) {
248 throw new \
InvalidArgumentException( 'Invalid session ID' );
251 $key = wfMemcKey( 'MWSession', $id );
252 if ( is_array( $this->store
->get( $key ) ) ) {
253 throw new \
InvalidArgumentException( 'Session ID already exists' );
257 $request = new FauxRequest
;
261 foreach ( $this->getProviders() as $provider ) {
262 $info = $provider->newSessionInfo( $id );
266 if ( $info->getProvider() !== $provider ) {
267 throw new \
UnexpectedValueException(
268 "$provider returned an empty session info for a different provider: $info"
271 if ( $id !== null && $info->getId() !== $id ) {
272 throw new \
UnexpectedValueException(
273 "$provider returned empty session info with a wrong id: " .
274 $info->getId() . ' != ' . $id
277 if ( !$info->isIdSafe() ) {
278 throw new \
UnexpectedValueException(
279 "$provider returned empty session info with id flagged unsafe"
282 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
283 if ( $compare > 0 ) {
286 if ( $compare === 0 ) {
289 $infos = array( $info );
293 // Make sure there's exactly one
294 if ( count( $infos ) > 1 ) {
295 throw new \
UnexpectedValueException(
296 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
298 } elseif ( count( $infos ) < 1 ) {
299 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
302 return $this->getSessionFromInfo( $infos[0], $request );
305 public function getVaryHeaders() {
306 if ( $this->varyHeaders
=== null ) {
308 foreach ( $this->getProviders() as $provider ) {
309 foreach ( $provider->getVaryHeaders() as $header => $options ) {
310 if ( !isset( $headers[$header] ) ) {
311 $headers[$header] = array();
313 if ( is_array( $options ) ) {
314 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
318 $this->varyHeaders
= $headers;
320 return $this->varyHeaders
;
323 public function getVaryCookies() {
324 if ( $this->varyCookies
=== null ) {
326 foreach ( $this->getProviders() as $provider ) {
327 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
329 $this->varyCookies
= array_values( array_unique( $cookies ) );
331 return $this->varyCookies
;
335 * Validate a session ID
339 public static function validateSessionId( $id ) {
340 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
344 * @name Internal methods
349 * Auto-create the given user, if necessary
350 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
351 * @note This more properly belongs in AuthManager, but we need it now.
352 * When AuthManager comes, this will be deprecated and will pass-through
353 * to the corresponding AuthManager method.
354 * @param User $user User to auto-create
355 * @return bool Success
357 public static function autoCreateUser( User
$user ) {
360 $logger = self
::singleton()->logger
;
362 // Much of this code is based on that in CentralAuth
364 // Try the local user from the slave DB
365 $localId = User
::idFromName( $user->getName() );
367 // Fetch the user ID from the master, so that we don't try to create the user
368 // when they already exist, due to replication lag
369 // @codeCoverageIgnoreStart
370 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
371 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
373 // @codeCoverageIgnoreEnd
376 // User exists after all.
377 $user->setId( $localId );
382 // Denied by AuthPlugin? But ignore AuthPlugin itself.
383 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
384 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
390 // Wiki is read-only?
391 if ( wfReadOnly() ) {
392 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
398 $userName = $user->getName();
400 // Check the session, if we tried to create this user already there's
401 // no point in retrying.
402 $session = self
::getGlobalSession();
403 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
405 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
411 // Is the IP user able to create accounts?
413 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
414 ||
$anon->isBlockedFromCreateAccount()
416 // Blacklist the user to avoid repeated DB queries subsequently
417 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
418 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
425 // Check for validity of username
426 if ( !User
::isCreatableName( $userName ) ) {
427 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
428 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
435 // Give other extensions a chance to stop auto creation.
436 $user->loadDefaults( $userName );
438 if ( !\Hooks
::run( 'AbortAutoAccount', array( $user, &$abortMessage ) ) ) {
439 // In this case we have no way to return the message to the user,
440 // but we can log it.
441 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
442 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
449 // Make sure the name has not been changed
450 if ( $user->getName() !== $userName ) {
453 throw new \
UnexpectedValueException(
454 'AbortAutoAccount hook tried to change the user name'
458 // Ignore warnings about master connections/writes...hard to avoid here
459 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
461 $cache = \ObjectCache
::getLocalClusterInstance();
462 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
463 if ( $cache->get( $backoffKey ) ) {
464 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
470 // Checks passed, create the user...
471 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
472 $logger->info( __METHOD__
. ": creating new user ($userName) - from: $from" );
475 // Insert the user into the local DB master
476 $status = $user->addToDatabase();
477 if ( !$status->isOK() ) {
478 // @codeCoverageIgnoreStart
479 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText() );
483 // @codeCoverageIgnoreEnd
485 } catch ( \Exception
$ex ) {
486 // @codeCoverageIgnoreStart
487 $logger->error( __METHOD__
. ': failed with exception ' . $ex->getMessage() );
488 // Do not keep throwing errors for a while
489 $cache->set( $backoffKey, 1, 600 );
490 // Bubble up error; which should normally trigger DB rollbacks
492 // @codeCoverageIgnoreEnd
495 # Notify hooks (e.g. Newuserlog)
496 \Hooks
::run( 'AuthPluginAutoCreate', array( $user ) );
497 \Hooks
::run( 'LocalUserCreated', array( $user, true ) );
500 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
502 # Watch user's userpage and talk page
503 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
509 * Prevent future sessions for the user
511 * The intention is that the named account will never again be usable for
512 * normal login (i.e. there is no way to undo the prevention of access).
514 * @private For use from \\User::newSystemUser only
515 * @param string $username
517 public function preventSessionsForUser( $username ) {
518 $this->preventUsers
[$username] = true;
520 // Reset the user's token to kill existing sessions
521 $user = User
::newFromName( $username );
522 if ( $user && $user->getToken() ) {
523 $user->setToken( true );
524 $user->saveSettings();
527 // Instruct the session providers to kill any other sessions too.
528 foreach ( $this->getProviders() as $provider ) {
529 $provider->preventSessionsForUser( $username );
534 * Test if a user is prevented
535 * @private For use from SessionBackend only
536 * @param string $username
539 public function isUserSessionPrevented( $username ) {
540 return !empty( $this->preventUsers
[$username] );
544 * Get the available SessionProviders
545 * @return SessionProvider[]
547 protected function getProviders() {
548 if ( $this->sessionProviders
=== null ) {
549 $this->sessionProviders
= array();
550 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
551 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
552 $provider->setLogger( $this->logger
);
553 $provider->setConfig( $this->config
);
554 $provider->setManager( $this );
555 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
556 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
558 $this->sessionProviders
[(string)$provider] = $provider;
561 return $this->sessionProviders
;
565 * Get a session provider by name
567 * Generally, this will only be used by internal implementation of some
568 * special session-providing mechanism. General purpose code, if it needs
569 * to access a SessionProvider at all, will use Session::getProvider().
571 * @param string $name
572 * @return SessionProvider|null
574 public function getProvider( $name ) {
575 $providers = $this->getProviders();
576 return isset( $providers[$name] ) ?
$providers[$name] : null;
580 * Save all active sessions on shutdown
581 * @private For internal use with register_shutdown_function()
583 public function shutdown() {
584 if ( $this->allSessionBackends
) {
585 $this->logger
->debug( 'Saving all sessions on shutdown' );
586 if ( session_id() !== '' ) {
587 // @codeCoverageIgnoreStart
588 session_write_close();
590 // @codeCoverageIgnoreEnd
591 foreach ( $this->allSessionBackends
as $backend ) {
592 $backend->save( true );
598 * Fetch the SessionInfo(s) for a request
599 * @param WebRequest $request
600 * @return SessionInfo|null
602 private function getSessionInfoForRequest( WebRequest
$request ) {
603 // Call all providers to fetch "the" session
605 foreach ( $this->getProviders() as $provider ) {
606 $info = $provider->provideSessionInfo( $request );
610 if ( $info->getProvider() !== $provider ) {
611 throw new \
UnexpectedValueException(
612 "$provider returned session info for a different provider: $info"
618 // Sort the SessionInfos. Then find the first one that can be
619 // successfully loaded, and then all the ones after it with the same
621 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
624 $info = array_pop( $infos );
625 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
628 $info = array_pop( $infos );
629 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
630 // We hit a lower priority, stop checking.
633 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
634 // This is going to error out below, but we want to
635 // provide a complete list.
642 if ( count( $retInfos ) > 1 ) {
643 $ex = new \
OverflowException(
644 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
646 $ex->sessionInfos
= $retInfos;
650 return $retInfos ?
$retInfos[0] : null;
654 * Load and verify the session info against the store
656 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
657 * @param WebRequest $request
658 * @return bool Whether the session info matches the stored data (if any)
660 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
661 $key = wfMemcKey( 'MWSession', $info->getId() );
662 $blob = $this->store
->get( $key );
664 $newParams = array();
666 if ( $blob !== false ) {
667 // Sanity check: blob must be an array, if it's saved at all
668 if ( !is_array( $blob ) ) {
669 $this->logger
->warning( "Session $info: Bad data" );
670 $this->store
->delete( $key );
674 // Sanity check: blob has data and metadata arrays
675 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
676 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
678 $this->logger
->warning( "Session $info: Bad data structure" );
679 $this->store
->delete( $key );
683 $data = $blob['data'];
684 $metadata = $blob['metadata'];
686 // Sanity check: metadata must be an array and must contain certain
687 // keys, if it's saved at all
688 if ( !array_key_exists( 'userId', $metadata ) ||
689 !array_key_exists( 'userName', $metadata ) ||
690 !array_key_exists( 'userToken', $metadata ) ||
691 !array_key_exists( 'provider', $metadata )
693 $this->logger
->warning( "Session $info: Bad metadata" );
694 $this->store
->delete( $key );
698 // First, load the provider from metadata, or validate it against the metadata.
699 $provider = $info->getProvider();
700 if ( $provider === null ) {
701 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
703 $this->logger
->warning( "Session $info: Unknown provider, " . $metadata['provider'] );
704 $this->store
->delete( $key );
707 } elseif ( $metadata['provider'] !== (string)$provider ) {
708 $this->logger
->warning( "Session $info: Wrong provider, " .
709 $metadata['provider'] . ' !== ' . $provider );
713 // Load provider metadata from metadata, or validate it against the metadata
714 $providerMetadata = $info->getProviderMetadata();
715 if ( isset( $metadata['providerMetadata'] ) ) {
716 if ( $providerMetadata === null ) {
717 $newParams['metadata'] = $metadata['providerMetadata'];
720 $newProviderMetadata = $provider->mergeMetadata(
721 $metadata['providerMetadata'], $providerMetadata
723 if ( $newProviderMetadata !== $providerMetadata ) {
724 $newParams['metadata'] = $newProviderMetadata;
726 } catch ( \UnexpectedValueException
$ex ) {
727 $this->logger
->warning( "Session $info: Metadata merge failed: " . $ex->getMessage() );
733 // Next, load the user from metadata, or validate it against the metadata.
734 $userInfo = $info->getUserInfo();
736 // For loading, id is preferred to name.
738 if ( $metadata['userId'] ) {
739 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
740 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
741 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
743 $userInfo = UserInfo
::newAnonymous();
745 } catch ( \InvalidArgumentException
$ex ) {
746 $this->logger
->error( "Session $info: " . $ex->getMessage() );
749 $newParams['userInfo'] = $userInfo;
751 // User validation passes if user ID matches, or if there
752 // is no saved ID and the names match.
753 if ( $metadata['userId'] ) {
754 if ( $metadata['userId'] !== $userInfo->getId() ) {
755 $this->logger
->warning( "Session $info: User ID mismatch, " .
756 $metadata['userId'] . ' !== ' . $userInfo->getId() );
760 // If the user was renamed, probably best to fail here.
761 if ( $metadata['userName'] !== null &&
762 $userInfo->getName() !== $metadata['userName']
764 $this->logger
->warning( "Session $info: User ID matched but name didn't (rename?), " .
765 $metadata['userName'] . ' !== ' . $userInfo->getName() );
769 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
770 if ( $metadata['userName'] !== $userInfo->getName() ) {
771 $this->logger
->warning( "Session $info: User name mismatch, " .
772 $metadata['userName'] . ' !== ' . $userInfo->getName() );
775 } elseif ( !$userInfo->isAnon() ) {
776 // Metadata specifies an anonymous user, but the passed-in
777 // user isn't anonymous.
778 $this->logger
->warning(
779 "Session $info: Metadata has an anonymous user, " .
780 'but a non-anon user was provided'
786 // And if we have a token in the metadata, it must match the loaded/provided user.
787 if ( $metadata['userToken'] !== null &&
788 $userInfo->getToken() !== $metadata['userToken']
790 $this->logger
->warning( "Session $info: User token mismatch" );
793 if ( !$userInfo->isVerified() ) {
794 $newParams['userInfo'] = $userInfo->verified();
797 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
798 $newParams['remembered'] = true;
800 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
801 $newParams['forceHTTPS'] = true;
804 if ( !$info->isIdSafe() ) {
805 $newParams['idIsSafe'] = true;
808 // No metadata, so we can't load the provider if one wasn't given.
809 if ( $info->getProvider() === null ) {
810 $this->logger
->warning( "Session $info: Null provider and no metadata" );
814 // If no user was provided and no metadata, it must be anon.
815 if ( !$info->getUserInfo() ) {
816 if ( $info->getProvider()->canChangeUser() ) {
817 $newParams['userInfo'] = UserInfo
::newAnonymous();
820 "Session $info: No user provided and provider cannot set user"
824 } elseif ( !$info->getUserInfo()->isVerified() ) {
825 $this->logger
->warning(
826 "Session $info: Unverified user provided and no metadata to auth it"
834 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
835 // The ID doesn't come from the user, so it should be safe
836 // (and if not, nothing we can do about it anyway)
837 $newParams['idIsSafe'] = true;
841 // Construct the replacement SessionInfo, if necessary
843 $newParams['copyFrom'] = $info;
844 $info = new SessionInfo( $info->getPriority(), $newParams );
847 // Allow the provider to check the loaded SessionInfo
848 $providerMetadata = $info->getProviderMetadata();
849 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
852 if ( $providerMetadata !== $info->getProviderMetadata() ) {
853 $info = new SessionInfo( $info->getPriority(), array(
854 'metadata' => $providerMetadata,
859 // Give hooks a chance to abort. Combined with the SessionMetadata
860 // hook, this can allow for tying a session to an IP address or the
862 $reason = 'Hook aborted';
865 array( &$reason, $info, $request, $metadata, $data )
867 $this->logger
->warning( "Session $info: $reason" );
875 * Create a session corresponding to the passed SessionInfo
876 * @private For use by a SessionProvider that needs to specially create its
878 * @param SessionInfo $info
879 * @param WebRequest $request
882 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
883 $id = $info->getId();
885 if ( !isset( $this->allSessionBackends
[$id] ) ) {
886 if ( !isset( $this->allSessionIds
[$id] ) ) {
887 $this->allSessionIds
[$id] = new SessionId( $id );
889 $backend = new SessionBackend(
890 $this->allSessionIds
[$id],
894 $this->config
->get( 'ObjectCacheSessionExpiry' )
896 $this->allSessionBackends
[$id] = $backend;
897 $delay = $backend->delaySave();
899 $backend = $this->allSessionBackends
[$id];
900 $delay = $backend->delaySave();
901 if ( $info->wasPersisted() ) {
904 if ( $info->wasRemembered() ) {
905 $backend->setRememberUser( true );
909 $request->setSessionId( $backend->getSessionId() );
910 $session = $backend->getSession( $request );
912 if ( !$info->isIdSafe() ) {
916 \ScopedCallback
::consume( $delay );
921 * Deregister a SessionBackend
922 * @private For use from \\MediaWiki\\Session\\SessionBackend only
923 * @param SessionBackend $backend
925 public function deregisterSessionBackend( SessionBackend
$backend ) {
926 $id = $backend->getId();
927 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
928 $this->allSessionBackends
[$id] !== $backend ||
929 $this->allSessionIds
[$id] !== $backend->getSessionId()
931 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
934 unset( $this->allSessionBackends
[$id] );
935 // Explicitly do not unset $this->allSessionIds[$id]
939 * Change a SessionBackend's ID
940 * @private For use from \\MediaWiki\\Session\\SessionBackend only
941 * @param SessionBackend $backend
943 public function changeBackendId( SessionBackend
$backend ) {
944 $sessionId = $backend->getSessionId();
945 $oldId = (string)$sessionId;
946 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
947 $this->allSessionBackends
[$oldId] !== $backend ||
948 $this->allSessionIds
[$oldId] !== $sessionId
950 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
953 $newId = $this->generateSessionId();
955 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
956 $sessionId->setId( $newId );
957 $this->allSessionBackends
[$newId] = $backend;
958 $this->allSessionIds
[$newId] = $sessionId;
962 * Generate a new random session ID
965 public function generateSessionId() {
967 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
968 $key = wfMemcKey( 'MWSession', $id );
969 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
974 * Call setters on a PHPSessionHandler
975 * @private Use PhpSessionHandler::install()
976 * @param PHPSessionHandler $handler
978 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
979 $handler->setManager( $this, $this->store
, $this->logger
);
983 * Reset the internal caching for unit testing
985 public static function resetCache() {
986 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
987 // @codeCoverageIgnoreStart
988 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
989 // @codeCoverageIgnoreEnd
992 self
::$globalSession = null;
993 self
::$globalSessionRequest = null;