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.
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 CachedBagOStuff|null */
60 /** @var SessionProvider[] */
61 private $sessionProviders = null;
64 private $varyCookies = null;
67 private $varyHeaders = null;
69 /** @var SessionBackend[] */
70 private $allSessionBackends = [];
72 /** @var SessionId[] */
73 private $allSessionIds = [];
76 private $preventUsers = [];
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 = [] ) {
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 $store = $options['store'];
170 $store = \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
172 $this->store
= $store instanceof CachedBagOStuff ?
$store : new CachedBagOStuff( $store );
174 register_shutdown_function( [ $this, 'shutdown' ] );
177 public function setLogger( LoggerInterface
$logger ) {
178 $this->logger
= $logger;
181 public function getSessionForRequest( WebRequest
$request ) {
182 $info = $this->getSessionInfoForRequest( $request );
185 $session = $this->getEmptySession( $request );
187 $session = $this->getSessionFromInfo( $info, $request );
192 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
193 if ( !self
::validateSessionId( $id ) ) {
194 throw new \
InvalidArgumentException( 'Invalid session ID' );
197 $request = new FauxRequest
;
201 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [ 'id' => $id, 'idIsSafe' => true ] );
203 // If we already have the backend loaded, use it directly
204 if ( isset( $this->allSessionBackends
[$id] ) ) {
205 return $this->getSessionFromInfo( $info, $request );
208 // Test if the session is in storage, and if so try to load it.
209 $key = wfMemcKey( 'MWSession', $id );
210 if ( is_array( $this->store
->get( $key ) ) ) {
211 $create = false; // If loading fails, don't bother creating because it probably will fail too.
212 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
213 $session = $this->getSessionFromInfo( $info, $request );
217 if ( $create && $session === null ) {
220 $session = $this->getEmptySessionInternal( $request, $id );
221 } catch ( \Exception
$ex ) {
222 $this->logger
->error( 'Failed to create empty session: {exception}',
224 'method' => __METHOD__
,
234 public function getEmptySession( WebRequest
$request = null ) {
235 return $this->getEmptySessionInternal( $request );
239 * @see SessionManagerInterface::getEmptySession
240 * @param WebRequest|null $request
241 * @param string|null $id ID to force on the new session
244 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
245 if ( $id !== null ) {
246 if ( !self
::validateSessionId( $id ) ) {
247 throw new \
InvalidArgumentException( 'Invalid session ID' );
250 $key = wfMemcKey( 'MWSession', $id );
251 if ( is_array( $this->store
->get( $key ) ) ) {
252 throw new \
InvalidArgumentException( 'Session ID already exists' );
256 $request = new FauxRequest
;
260 foreach ( $this->getProviders() as $provider ) {
261 $info = $provider->newSessionInfo( $id );
265 if ( $info->getProvider() !== $provider ) {
266 throw new \
UnexpectedValueException(
267 "$provider returned an empty session info for a different provider: $info"
270 if ( $id !== null && $info->getId() !== $id ) {
271 throw new \
UnexpectedValueException(
272 "$provider returned empty session info with a wrong id: " .
273 $info->getId() . ' != ' . $id
276 if ( !$info->isIdSafe() ) {
277 throw new \
UnexpectedValueException(
278 "$provider returned empty session info with id flagged unsafe"
281 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
282 if ( $compare > 0 ) {
285 if ( $compare === 0 ) {
292 // Make sure there's exactly one
293 if ( count( $infos ) > 1 ) {
294 throw new \
UnexpectedValueException(
295 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
297 } elseif ( count( $infos ) < 1 ) {
298 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
301 return $this->getSessionFromInfo( $infos[0], $request );
304 public function invalidateSessionsForUser( User
$user ) {
308 $user->saveSettings();
310 $wgAuth->getUserInstance( $user )->resetAuthToken();
312 foreach ( $this->getProviders() as $provider ) {
313 $provider->invalidateSessionsForUser( $user );
317 public function getVaryHeaders() {
318 // @codeCoverageIgnoreStart
319 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
322 // @codeCoverageIgnoreEnd
323 if ( $this->varyHeaders
=== null ) {
325 foreach ( $this->getProviders() as $provider ) {
326 foreach ( $provider->getVaryHeaders() as $header => $options ) {
327 if ( !isset( $headers[$header] ) ) {
328 $headers[$header] = [];
330 if ( is_array( $options ) ) {
331 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
335 $this->varyHeaders
= $headers;
337 return $this->varyHeaders
;
340 public function getVaryCookies() {
341 // @codeCoverageIgnoreStart
342 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
345 // @codeCoverageIgnoreEnd
346 if ( $this->varyCookies
=== null ) {
348 foreach ( $this->getProviders() as $provider ) {
349 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
351 $this->varyCookies
= array_values( array_unique( $cookies ) );
353 return $this->varyCookies
;
357 * Validate a session ID
361 public static function validateSessionId( $id ) {
362 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
366 * @name Internal methods
371 * Auto-create the given user, if necessary
372 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
373 * @note This more properly belongs in AuthManager, but we need it now.
374 * When AuthManager comes, this will be deprecated and will pass-through
375 * to the corresponding AuthManager method.
376 * @param User $user User to auto-create
377 * @return bool Success
379 public static function autoCreateUser( User
$user ) {
382 $logger = self
::singleton()->logger
;
384 // Much of this code is based on that in CentralAuth
386 // Try the local user from the slave DB
387 $localId = User
::idFromName( $user->getName() );
390 // Fetch the user ID from the master, so that we don't try to create the user
391 // when they already exist, due to replication lag
392 // @codeCoverageIgnoreStart
393 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
394 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
395 $flags = User
::READ_LATEST
;
397 // @codeCoverageIgnoreEnd
400 // User exists after all.
401 $user->setId( $localId );
402 $user->loadFromId( $flags );
406 // Denied by AuthPlugin? But ignore AuthPlugin itself.
407 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
408 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
414 // Wiki is read-only?
415 if ( wfReadOnly() ) {
416 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
422 $userName = $user->getName();
424 // Check the session, if we tried to create this user already there's
425 // no point in retrying.
426 $session = self
::getGlobalSession();
427 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
429 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
435 // Is the IP user able to create accounts?
437 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
438 ||
$anon->isBlockedFromCreateAccount()
440 // Blacklist the user to avoid repeated DB queries subsequently
441 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
442 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
449 // Check for validity of username
450 if ( !User
::isCreatableName( $userName ) ) {
451 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
452 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
459 // Give other extensions a chance to stop auto creation.
460 $user->loadDefaults( $userName );
462 if ( !\Hooks
::run( 'AbortAutoAccount', [ $user, &$abortMessage ] ) ) {
463 // In this case we have no way to return the message to the user,
464 // but we can log it.
465 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
466 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
473 // Make sure the name has not been changed
474 if ( $user->getName() !== $userName ) {
477 throw new \
UnexpectedValueException(
478 'AbortAutoAccount hook tried to change the user name'
482 // Ignore warnings about master connections/writes...hard to avoid here
483 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
485 $cache = \ObjectCache
::getLocalClusterInstance();
486 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
487 if ( $cache->get( $backoffKey ) ) {
488 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
494 // Checks passed, create the user...
495 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
496 $logger->info( __METHOD__
. ': creating new user ({username}) - from: {url}',
498 'username' => $userName,
503 // Insert the user into the local DB master
504 $status = $user->addToDatabase();
505 if ( !$status->isOK() ) {
506 // @codeCoverageIgnoreStart
507 // double-check for a race condition (T70012)
508 $id = User
::idFromName( $user->getName(), User
::READ_LATEST
);
510 $logger->info( __METHOD__
. ': tried to autocreate existing user',
512 'username' => $userName,
516 __METHOD__
. ': failed with message ' . $status->getWikiText( false, false, 'en' ),
518 'username' => $userName,
523 $user->loadFromId( User
::READ_LATEST
);
525 // @codeCoverageIgnoreEnd
527 } catch ( \Exception
$ex ) {
528 // @codeCoverageIgnoreStart
529 $logger->error( __METHOD__
. ': failed with exception {exception}', [
531 'username' => $userName,
533 // Do not keep throwing errors for a while
534 $cache->set( $backoffKey, 1, 600 );
535 // Bubble up error; which should normally trigger DB rollbacks
537 // @codeCoverageIgnoreEnd
541 // @codeCoverageIgnoreStart
543 $wgAuth->initUser( $tmpUser, true );
544 if ( $tmpUser !== $user ) {
545 $logger->warning( __METHOD__
. ': ' .
546 get_class( $wgAuth ) . '::initUser() replaced the user object' );
548 // @codeCoverageIgnoreEnd
550 # Notify hooks (e.g. Newuserlog)
551 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ] );
552 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
554 $user->saveSettings();
557 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
559 # Watch user's userpage and talk page
560 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
566 * Prevent future sessions for the user
568 * The intention is that the named account will never again be usable for
569 * normal login (i.e. there is no way to undo the prevention of access).
571 * @private For use from \User::newSystemUser only
572 * @param string $username
574 public function preventSessionsForUser( $username ) {
575 $this->preventUsers
[$username] = true;
577 // Instruct the session providers to kill any other sessions too.
578 foreach ( $this->getProviders() as $provider ) {
579 $provider->preventSessionsForUser( $username );
584 * Test if a user is prevented
585 * @private For use from SessionBackend only
586 * @param string $username
589 public function isUserSessionPrevented( $username ) {
590 return !empty( $this->preventUsers
[$username] );
594 * Get the available SessionProviders
595 * @return SessionProvider[]
597 protected function getProviders() {
598 if ( $this->sessionProviders
=== null ) {
599 $this->sessionProviders
= [];
600 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
601 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
602 $provider->setLogger( $this->logger
);
603 $provider->setConfig( $this->config
);
604 $provider->setManager( $this );
605 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
606 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
608 $this->sessionProviders
[(string)$provider] = $provider;
611 return $this->sessionProviders
;
615 * Get a session provider by name
617 * Generally, this will only be used by internal implementation of some
618 * special session-providing mechanism. General purpose code, if it needs
619 * to access a SessionProvider at all, will use Session::getProvider().
621 * @param string $name
622 * @return SessionProvider|null
624 public function getProvider( $name ) {
625 $providers = $this->getProviders();
626 return isset( $providers[$name] ) ?
$providers[$name] : null;
630 * Save all active sessions on shutdown
631 * @private For internal use with register_shutdown_function()
633 public function shutdown() {
634 if ( $this->allSessionBackends
) {
635 $this->logger
->debug( 'Saving all sessions on shutdown' );
636 if ( session_id() !== '' ) {
637 // @codeCoverageIgnoreStart
638 session_write_close();
640 // @codeCoverageIgnoreEnd
641 foreach ( $this->allSessionBackends
as $backend ) {
642 $backend->shutdown();
648 * Fetch the SessionInfo(s) for a request
649 * @param WebRequest $request
650 * @return SessionInfo|null
652 private function getSessionInfoForRequest( WebRequest
$request ) {
653 // Call all providers to fetch "the" session
655 foreach ( $this->getProviders() as $provider ) {
656 $info = $provider->provideSessionInfo( $request );
660 if ( $info->getProvider() !== $provider ) {
661 throw new \
UnexpectedValueException(
662 "$provider returned session info for a different provider: $info"
668 // Sort the SessionInfos. Then find the first one that can be
669 // successfully loaded, and then all the ones after it with the same
671 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
674 $info = array_pop( $infos );
675 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
678 $info = array_pop( $infos );
679 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
680 // We hit a lower priority, stop checking.
683 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
684 // This is going to error out below, but we want to
685 // provide a complete list.
688 // Session load failed, so unpersist it from this request
689 $info->getProvider()->unpersistSession( $request );
693 // Session load failed, so unpersist it from this request
694 $info->getProvider()->unpersistSession( $request );
698 if ( count( $retInfos ) > 1 ) {
699 $ex = new \
OverflowException(
700 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
702 $ex->sessionInfos
= $retInfos;
706 return $retInfos ?
$retInfos[0] : null;
710 * Load and verify the session info against the store
712 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
713 * @param WebRequest $request
714 * @return bool Whether the session info matches the stored data (if any)
716 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
717 $key = wfMemcKey( 'MWSession', $info->getId() );
718 $blob = $this->store
->get( $key );
722 if ( $blob !== false ) {
723 // Sanity check: blob must be an array, if it's saved at all
724 if ( !is_array( $blob ) ) {
725 $this->logger
->warning( 'Session "{session}": Bad data', [
728 $this->store
->delete( $key );
732 // Sanity check: blob has data and metadata arrays
733 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
734 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
736 $this->logger
->warning( 'Session "{session}": Bad data structure', [
739 $this->store
->delete( $key );
743 $data = $blob['data'];
744 $metadata = $blob['metadata'];
746 // Sanity check: metadata must be an array and must contain certain
747 // keys, if it's saved at all
748 if ( !array_key_exists( 'userId', $metadata ) ||
749 !array_key_exists( 'userName', $metadata ) ||
750 !array_key_exists( 'userToken', $metadata ) ||
751 !array_key_exists( 'provider', $metadata )
753 $this->logger
->warning( 'Session "{session}": Bad metadata', [
756 $this->store
->delete( $key );
760 // First, load the provider from metadata, or validate it against the metadata.
761 $provider = $info->getProvider();
762 if ( $provider === null ) {
763 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
765 $this->logger
->warning(
766 'Session "{session}": Unknown provider ' . $metadata['provider'],
771 $this->store
->delete( $key );
774 } elseif ( $metadata['provider'] !== (string)$provider ) {
775 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
776 $metadata['provider'] . ' !== ' . $provider,
783 // Load provider metadata from metadata, or validate it against the metadata
784 $providerMetadata = $info->getProviderMetadata();
785 if ( isset( $metadata['providerMetadata'] ) ) {
786 if ( $providerMetadata === null ) {
787 $newParams['metadata'] = $metadata['providerMetadata'];
790 $newProviderMetadata = $provider->mergeMetadata(
791 $metadata['providerMetadata'], $providerMetadata
793 if ( $newProviderMetadata !== $providerMetadata ) {
794 $newParams['metadata'] = $newProviderMetadata;
796 } catch ( MetadataMergeException
$ex ) {
797 $this->logger
->warning(
798 'Session "{session}": Metadata merge failed: {exception}',
802 ] +
$ex->getContext()
809 // Next, load the user from metadata, or validate it against the metadata.
810 $userInfo = $info->getUserInfo();
812 // For loading, id is preferred to name.
814 if ( $metadata['userId'] ) {
815 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
816 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
817 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
819 $userInfo = UserInfo
::newAnonymous();
821 } catch ( \InvalidArgumentException
$ex ) {
822 $this->logger
->error( 'Session "{session}": {exception}', [
828 $newParams['userInfo'] = $userInfo;
830 // User validation passes if user ID matches, or if there
831 // is no saved ID and the names match.
832 if ( $metadata['userId'] ) {
833 if ( $metadata['userId'] !== $userInfo->getId() ) {
834 $this->logger
->warning(
835 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
838 'uid_a' => $metadata['userId'],
839 'uid_b' => $userInfo->getId(),
844 // If the user was renamed, probably best to fail here.
845 if ( $metadata['userName'] !== null &&
846 $userInfo->getName() !== $metadata['userName']
848 $this->logger
->warning(
849 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
852 'uname_a' => $metadata['userName'],
853 'uname_b' => $userInfo->getName(),
858 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
859 if ( $metadata['userName'] !== $userInfo->getName() ) {
860 $this->logger
->warning(
861 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
864 'uname_a' => $metadata['userName'],
865 'uname_b' => $userInfo->getName(),
869 } elseif ( !$userInfo->isAnon() ) {
870 // Metadata specifies an anonymous user, but the passed-in
871 // user isn't anonymous.
872 $this->logger
->warning(
873 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
881 // And if we have a token in the metadata, it must match the loaded/provided user.
882 if ( $metadata['userToken'] !== null &&
883 $userInfo->getToken() !== $metadata['userToken']
885 $this->logger
->warning( 'Session "{session}": User token mismatch', [
890 if ( !$userInfo->isVerified() ) {
891 $newParams['userInfo'] = $userInfo->verified();
894 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
895 $newParams['remembered'] = true;
897 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
898 $newParams['forceHTTPS'] = true;
900 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
901 $newParams['persisted'] = true;
904 if ( !$info->isIdSafe() ) {
905 $newParams['idIsSafe'] = true;
908 // No metadata, so we can't load the provider if one wasn't given.
909 if ( $info->getProvider() === null ) {
910 $this->logger
->warning(
911 'Session "{session}": Null provider and no metadata',
918 // If no user was provided and no metadata, it must be anon.
919 if ( !$info->getUserInfo() ) {
920 if ( $info->getProvider()->canChangeUser() ) {
921 $newParams['userInfo'] = UserInfo
::newAnonymous();
924 'Session "{session}": No user provided and provider cannot set user',
930 } elseif ( !$info->getUserInfo()->isVerified() ) {
931 $this->logger
->warning(
932 'Session "{session}": Unverified user provided and no metadata to auth it',
942 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
943 // The ID doesn't come from the user, so it should be safe
944 // (and if not, nothing we can do about it anyway)
945 $newParams['idIsSafe'] = true;
949 // Construct the replacement SessionInfo, if necessary
951 $newParams['copyFrom'] = $info;
952 $info = new SessionInfo( $info->getPriority(), $newParams );
955 // Allow the provider to check the loaded SessionInfo
956 $providerMetadata = $info->getProviderMetadata();
957 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
960 if ( $providerMetadata !== $info->getProviderMetadata() ) {
961 $info = new SessionInfo( $info->getPriority(), [
962 'metadata' => $providerMetadata,
967 // Give hooks a chance to abort. Combined with the SessionMetadata
968 // hook, this can allow for tying a session to an IP address or the
970 $reason = 'Hook aborted';
973 [ &$reason, $info, $request, $metadata, $data ]
975 $this->logger
->warning( 'Session "{session}": ' . $reason, [
985 * Create a session corresponding to the passed SessionInfo
986 * @private For use by a SessionProvider that needs to specially create its
988 * @param SessionInfo $info
989 * @param WebRequest $request
992 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
993 // @codeCoverageIgnoreStart
994 if ( defined( 'MW_NO_SESSION' ) ) {
995 if ( MW_NO_SESSION
=== 'warn' ) {
996 // Undocumented safety case for converting existing entry points
997 $this->logger
->error( 'Sessions are supposed to be disabled for this entry point', [
998 'exception' => new \
BadMethodCallException( 'Sessions are disabled for this entry point' ),
1001 throw new \
BadMethodCallException( 'Sessions are disabled for this entry point' );
1004 // @codeCoverageIgnoreEnd
1006 $id = $info->getId();
1008 if ( !isset( $this->allSessionBackends
[$id] ) ) {
1009 if ( !isset( $this->allSessionIds
[$id] ) ) {
1010 $this->allSessionIds
[$id] = new SessionId( $id );
1012 $backend = new SessionBackend(
1013 $this->allSessionIds
[$id],
1017 $this->config
->get( 'ObjectCacheSessionExpiry' )
1019 $this->allSessionBackends
[$id] = $backend;
1020 $delay = $backend->delaySave();
1022 $backend = $this->allSessionBackends
[$id];
1023 $delay = $backend->delaySave();
1024 if ( $info->wasPersisted() ) {
1025 $backend->persist();
1027 if ( $info->wasRemembered() ) {
1028 $backend->setRememberUser( true );
1032 $request->setSessionId( $backend->getSessionId() );
1033 $session = $backend->getSession( $request );
1035 if ( !$info->isIdSafe() ) {
1036 $session->resetId();
1039 \ScopedCallback
::consume( $delay );
1044 * Deregister a SessionBackend
1045 * @private For use from \MediaWiki\Session\SessionBackend only
1046 * @param SessionBackend $backend
1048 public function deregisterSessionBackend( SessionBackend
$backend ) {
1049 $id = $backend->getId();
1050 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
1051 $this->allSessionBackends
[$id] !== $backend ||
1052 $this->allSessionIds
[$id] !== $backend->getSessionId()
1054 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1057 unset( $this->allSessionBackends
[$id] );
1058 // Explicitly do not unset $this->allSessionIds[$id]
1062 * Change a SessionBackend's ID
1063 * @private For use from \MediaWiki\Session\SessionBackend only
1064 * @param SessionBackend $backend
1066 public function changeBackendId( SessionBackend
$backend ) {
1067 $sessionId = $backend->getSessionId();
1068 $oldId = (string)$sessionId;
1069 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
1070 $this->allSessionBackends
[$oldId] !== $backend ||
1071 $this->allSessionIds
[$oldId] !== $sessionId
1073 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1076 $newId = $this->generateSessionId();
1078 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
1079 $sessionId->setId( $newId );
1080 $this->allSessionBackends
[$newId] = $backend;
1081 $this->allSessionIds
[$newId] = $sessionId;
1085 * Generate a new random session ID
1088 public function generateSessionId() {
1090 $id = \Wikimedia\base_convert
( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1091 $key = wfMemcKey( 'MWSession', $id );
1092 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
1097 * Call setters on a PHPSessionHandler
1098 * @private Use PhpSessionHandler::install()
1099 * @param PHPSessionHandler $handler
1101 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1102 $handler->setManager( $this, $this->store
, $this->logger
);
1106 * Reset the internal caching for unit testing
1108 public static function resetCache() {
1109 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1110 // @codeCoverageIgnoreStart
1111 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1112 // @codeCoverageIgnoreEnd
1115 self
::$globalSession = null;
1116 self
::$globalSessionRequest = null;