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
;
35 * This serves as the entry point to the MediaWiki session handling system.
40 final class SessionManager
implements SessionManagerInterface
{
41 /** @var SessionManager|null */
42 private static $instance = null;
44 /** @var Session|null */
45 private static $globalSession = null;
47 /** @var WebRequest|null */
48 private static $globalSessionRequest = null;
50 /** @var LoggerInterface */
56 /** @var CachedBagOStuff|null */
59 /** @var SessionProvider[] */
60 private $sessionProviders = null;
63 private $varyCookies = null;
66 private $varyHeaders = null;
68 /** @var SessionBackend[] */
69 private $allSessionBackends = [];
71 /** @var SessionId[] */
72 private $allSessionIds = [];
75 private $preventUsers = [];
78 * Get the global SessionManager
79 * @return SessionManagerInterface
80 * (really a SessionManager, but this is to make IDEs less confused)
82 public static function singleton() {
83 if ( self
::$instance === null ) {
84 self
::$instance = new self();
86 return self
::$instance;
90 * Get the "global" session
92 * If PHP's session_id() has been set, returns that session. Otherwise
93 * returns the session for RequestContext::getMain()->getRequest().
97 public static function getGlobalSession() {
98 if ( !PHPSessionHandler
::isEnabled() ) {
104 $request = \RequestContext
::getMain()->getRequest();
106 !self
::$globalSession // No global session is set up yet
107 || self
::$globalSessionRequest !== $request // The global WebRequest changed
108 ||
$id !== '' && self
::$globalSession->getId() !== $id // Someone messed with session_id()
110 self
::$globalSessionRequest = $request;
112 // session_id() wasn't used, so fetch the Session from the WebRequest.
113 // We use $request->getSession() instead of $singleton->getSessionForRequest()
114 // because doing the latter would require a public
115 // "$request->getSessionId()" method that would confuse end
116 // users by returning SessionId|null where they'd expect it to
117 // be short for $request->getSession()->getId(), and would
118 // wind up being a duplicate of the code in
119 // $request->getSession() anyway.
120 self
::$globalSession = $request->getSession();
122 // Someone used session_id(), so we need to follow suit.
123 // Note this overwrites whatever session might already be
124 // associated with $request with the one for $id.
125 self
::$globalSession = self
::singleton()->getSessionById( $id, true, $request )
126 ?
: $request->getSession();
129 return self
::$globalSession;
133 * @param array $options
134 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
135 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
136 * - store: BagOStuff to store session data in.
138 public function __construct( $options = [] ) {
139 if ( isset( $options['config'] ) ) {
140 $this->config
= $options['config'];
141 if ( !$this->config
instanceof Config
) {
142 throw new \
InvalidArgumentException(
143 '$options[\'config\'] must be an instance of Config'
147 $this->config
= \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
150 if ( isset( $options['logger'] ) ) {
151 if ( !$options['logger'] instanceof LoggerInterface
) {
152 throw new \
InvalidArgumentException(
153 '$options[\'logger\'] must be an instance of LoggerInterface'
156 $this->setLogger( $options['logger'] );
158 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' ) );
161 if ( isset( $options['store'] ) ) {
162 if ( !$options['store'] instanceof BagOStuff
) {
163 throw new \
InvalidArgumentException(
164 '$options[\'store\'] must be an instance of BagOStuff'
167 $store = $options['store'];
169 $store = \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
171 $this->store
= $store instanceof CachedBagOStuff ?
$store : new CachedBagOStuff( $store );
173 register_shutdown_function( [ $this, 'shutdown' ] );
176 public function setLogger( LoggerInterface
$logger ) {
177 $this->logger
= $logger;
180 public function getSessionForRequest( WebRequest
$request ) {
181 $info = $this->getSessionInfoForRequest( $request );
184 $session = $this->getEmptySession( $request );
186 $session = $this->getSessionFromInfo( $info, $request );
191 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
192 if ( !self
::validateSessionId( $id ) ) {
193 throw new \
InvalidArgumentException( 'Invalid session ID' );
196 $request = new FauxRequest
;
201 // Test this here to provide a better log message for the common case
203 $key = wfMemcKey( 'MWSession', $id );
204 if ( is_array( $this->store
->get( $key ) ) ) {
205 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [ 'id' => $id, 'idIsSafe' => true ] );
206 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
207 $session = $this->getSessionFromInfo( $info, $request );
211 if ( $create && $session === null ) {
214 $session = $this->getEmptySessionInternal( $request, $id );
215 } catch ( \Exception
$ex ) {
216 $this->logger
->error( 'Failed to create empty session: {exception}',
218 'method' => __METHOD__
,
228 public function getEmptySession( WebRequest
$request = null ) {
229 return $this->getEmptySessionInternal( $request );
233 * @see SessionManagerInterface::getEmptySession
234 * @param WebRequest|null $request
235 * @param string|null $id ID to force on the new session
238 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
239 if ( $id !== null ) {
240 if ( !self
::validateSessionId( $id ) ) {
241 throw new \
InvalidArgumentException( 'Invalid session ID' );
244 $key = wfMemcKey( 'MWSession', $id );
245 if ( is_array( $this->store
->get( $key ) ) ) {
246 throw new \
InvalidArgumentException( 'Session ID already exists' );
250 $request = new FauxRequest
;
254 foreach ( $this->getProviders() as $provider ) {
255 $info = $provider->newSessionInfo( $id );
259 if ( $info->getProvider() !== $provider ) {
260 throw new \
UnexpectedValueException(
261 "$provider returned an empty session info for a different provider: $info"
264 if ( $id !== null && $info->getId() !== $id ) {
265 throw new \
UnexpectedValueException(
266 "$provider returned empty session info with a wrong id: " .
267 $info->getId() . ' != ' . $id
270 if ( !$info->isIdSafe() ) {
271 throw new \
UnexpectedValueException(
272 "$provider returned empty session info with id flagged unsafe"
275 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
276 if ( $compare > 0 ) {
279 if ( $compare === 0 ) {
286 // Make sure there's exactly one
287 if ( count( $infos ) > 1 ) {
288 throw new \
UnexpectedValueException(
289 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
291 } elseif ( count( $infos ) < 1 ) {
292 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
295 return $this->getSessionFromInfo( $infos[0], $request );
298 public function getVaryHeaders() {
299 // @codeCoverageIgnoreStart
300 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
303 // @codeCoverageIgnoreEnd
304 if ( $this->varyHeaders
=== null ) {
306 foreach ( $this->getProviders() as $provider ) {
307 foreach ( $provider->getVaryHeaders() as $header => $options ) {
308 if ( !isset( $headers[$header] ) ) {
309 $headers[$header] = [];
311 if ( is_array( $options ) ) {
312 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
316 $this->varyHeaders
= $headers;
318 return $this->varyHeaders
;
321 public function getVaryCookies() {
322 // @codeCoverageIgnoreStart
323 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
326 // @codeCoverageIgnoreEnd
327 if ( $this->varyCookies
=== null ) {
329 foreach ( $this->getProviders() as $provider ) {
330 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
332 $this->varyCookies
= array_values( array_unique( $cookies ) );
334 return $this->varyCookies
;
338 * Validate a session ID
342 public static function validateSessionId( $id ) {
343 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
347 * @name Internal methods
352 * Auto-create the given user, if necessary
353 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
354 * @note This more properly belongs in AuthManager, but we need it now.
355 * When AuthManager comes, this will be deprecated and will pass-through
356 * to the corresponding AuthManager method.
357 * @param User $user User to auto-create
358 * @return bool Success
360 public static function autoCreateUser( User
$user ) {
363 $logger = self
::singleton()->logger
;
365 // Much of this code is based on that in CentralAuth
367 // Try the local user from the slave DB
368 $localId = User
::idFromName( $user->getName() );
371 // Fetch the user ID from the master, so that we don't try to create the user
372 // when they already exist, due to replication lag
373 // @codeCoverageIgnoreStart
374 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
375 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
376 $flags = User
::READ_LATEST
;
378 // @codeCoverageIgnoreEnd
381 // User exists after all.
382 $user->setId( $localId );
383 $user->loadFromId( $flags );
387 // Denied by AuthPlugin? But ignore AuthPlugin itself.
388 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
389 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
395 // Wiki is read-only?
396 if ( wfReadOnly() ) {
397 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
403 $userName = $user->getName();
405 // Check the session, if we tried to create this user already there's
406 // no point in retrying.
407 $session = self
::getGlobalSession();
408 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
410 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
416 // Is the IP user able to create accounts?
418 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
419 ||
$anon->isBlockedFromCreateAccount()
421 // Blacklist the user to avoid repeated DB queries subsequently
422 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
423 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
430 // Check for validity of username
431 if ( !User
::isCreatableName( $userName ) ) {
432 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
433 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
440 // Give other extensions a chance to stop auto creation.
441 $user->loadDefaults( $userName );
443 if ( !\Hooks
::run( 'AbortAutoAccount', [ $user, &$abortMessage ] ) ) {
444 // In this case we have no way to return the message to the user,
445 // but we can log it.
446 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
447 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
454 // Make sure the name has not been changed
455 if ( $user->getName() !== $userName ) {
458 throw new \
UnexpectedValueException(
459 'AbortAutoAccount hook tried to change the user name'
463 // Ignore warnings about master connections/writes...hard to avoid here
464 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
466 $cache = \ObjectCache
::getLocalClusterInstance();
467 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
468 if ( $cache->get( $backoffKey ) ) {
469 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
475 // Checks passed, create the user...
476 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
477 $logger->info( __METHOD__
. ': creating new user ({username}) - from: {url}',
479 'username' => $userName,
484 // Insert the user into the local DB master
485 $status = $user->addToDatabase();
486 if ( !$status->isOK() ) {
487 // @codeCoverageIgnoreStart
488 // double-check for a race condition (T70012)
489 $id = User
::idFromName( $user->getName(), User
::READ_LATEST
);
491 $logger->info( __METHOD__
. ': tried to autocreate existing user',
493 'username' => $userName,
496 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText(),
498 'username' => $userName,
502 $user->loadFromId( User
::READ_LATEST
);
504 // @codeCoverageIgnoreEnd
506 } catch ( \Exception
$ex ) {
507 // @codeCoverageIgnoreStart
508 $logger->error( __METHOD__
. ': failed with exception {exception}', [
510 'username' => $userName,
512 // Do not keep throwing errors for a while
513 $cache->set( $backoffKey, 1, 600 );
514 // Bubble up error; which should normally trigger DB rollbacks
516 // @codeCoverageIgnoreEnd
520 // @codeCoverageIgnoreStart
522 $wgAuth->initUser( $tmpUser, true );
523 if ( $tmpUser !== $user ) {
524 $logger->warning( __METHOD__
. ': ' .
525 get_class( $wgAuth ) . '::initUser() replaced the user object' );
527 // @codeCoverageIgnoreEnd
529 # Notify hooks (e.g. Newuserlog)
530 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ] );
531 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
533 $user->saveSettings();
536 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
538 # Watch user's userpage and talk page
539 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
545 * Prevent future sessions for the user
547 * The intention is that the named account will never again be usable for
548 * normal login (i.e. there is no way to undo the prevention of access).
550 * @private For use from \\User::newSystemUser only
551 * @param string $username
553 public function preventSessionsForUser( $username ) {
554 $this->preventUsers
[$username] = true;
556 // Instruct the session providers to kill any other sessions too.
557 foreach ( $this->getProviders() as $provider ) {
558 $provider->preventSessionsForUser( $username );
563 * Test if a user is prevented
564 * @private For use from SessionBackend only
565 * @param string $username
568 public function isUserSessionPrevented( $username ) {
569 return !empty( $this->preventUsers
[$username] );
573 * Get the available SessionProviders
574 * @return SessionProvider[]
576 protected function getProviders() {
577 if ( $this->sessionProviders
=== null ) {
578 $this->sessionProviders
= [];
579 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
580 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
581 $provider->setLogger( $this->logger
);
582 $provider->setConfig( $this->config
);
583 $provider->setManager( $this );
584 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
585 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
587 $this->sessionProviders
[(string)$provider] = $provider;
590 return $this->sessionProviders
;
594 * Get a session provider by name
596 * Generally, this will only be used by internal implementation of some
597 * special session-providing mechanism. General purpose code, if it needs
598 * to access a SessionProvider at all, will use Session::getProvider().
600 * @param string $name
601 * @return SessionProvider|null
603 public function getProvider( $name ) {
604 $providers = $this->getProviders();
605 return isset( $providers[$name] ) ?
$providers[$name] : null;
609 * Save all active sessions on shutdown
610 * @private For internal use with register_shutdown_function()
612 public function shutdown() {
613 if ( $this->allSessionBackends
) {
614 $this->logger
->debug( 'Saving all sessions on shutdown' );
615 if ( session_id() !== '' ) {
616 // @codeCoverageIgnoreStart
617 session_write_close();
619 // @codeCoverageIgnoreEnd
620 foreach ( $this->allSessionBackends
as $backend ) {
621 $backend->save( true );
627 * Fetch the SessionInfo(s) for a request
628 * @param WebRequest $request
629 * @return SessionInfo|null
631 private function getSessionInfoForRequest( WebRequest
$request ) {
632 // Call all providers to fetch "the" session
634 foreach ( $this->getProviders() as $provider ) {
635 $info = $provider->provideSessionInfo( $request );
639 if ( $info->getProvider() !== $provider ) {
640 throw new \
UnexpectedValueException(
641 "$provider returned session info for a different provider: $info"
647 // Sort the SessionInfos. Then find the first one that can be
648 // successfully loaded, and then all the ones after it with the same
650 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
653 $info = array_pop( $infos );
654 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
657 $info = array_pop( $infos );
658 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
659 // We hit a lower priority, stop checking.
662 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
663 // This is going to error out below, but we want to
664 // provide a complete list.
667 // Session load failed, so unpersist it from this request
668 $info->getProvider()->unpersistSession( $request );
672 // Session load failed, so unpersist it from this request
673 $info->getProvider()->unpersistSession( $request );
677 if ( count( $retInfos ) > 1 ) {
678 $ex = new \
OverflowException(
679 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
681 $ex->sessionInfos
= $retInfos;
685 return $retInfos ?
$retInfos[0] : null;
689 * Load and verify the session info against the store
691 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
692 * @param WebRequest $request
693 * @return bool Whether the session info matches the stored data (if any)
695 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
696 $key = wfMemcKey( 'MWSession', $info->getId() );
697 $blob = $this->store
->get( $key );
701 if ( $blob !== false ) {
702 // Sanity check: blob must be an array, if it's saved at all
703 if ( !is_array( $blob ) ) {
704 $this->logger
->warning( 'Session "{session}": Bad data', [
707 $this->store
->delete( $key );
711 // Sanity check: blob has data and metadata arrays
712 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
713 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
715 $this->logger
->warning( 'Session "{session}": Bad data structure', [
718 $this->store
->delete( $key );
722 $data = $blob['data'];
723 $metadata = $blob['metadata'];
725 // Sanity check: metadata must be an array and must contain certain
726 // keys, if it's saved at all
727 if ( !array_key_exists( 'userId', $metadata ) ||
728 !array_key_exists( 'userName', $metadata ) ||
729 !array_key_exists( 'userToken', $metadata ) ||
730 !array_key_exists( 'provider', $metadata )
732 $this->logger
->warning( 'Session "{session}": Bad metadata', [
735 $this->store
->delete( $key );
739 // First, load the provider from metadata, or validate it against the metadata.
740 $provider = $info->getProvider();
741 if ( $provider === null ) {
742 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
744 $this->logger
->warning(
745 'Session "{session}": Unknown provider ' . $metadata['provider'],
750 $this->store
->delete( $key );
753 } elseif ( $metadata['provider'] !== (string)$provider ) {
754 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
755 $metadata['provider'] . ' !== ' . $provider,
762 // Load provider metadata from metadata, or validate it against the metadata
763 $providerMetadata = $info->getProviderMetadata();
764 if ( isset( $metadata['providerMetadata'] ) ) {
765 if ( $providerMetadata === null ) {
766 $newParams['metadata'] = $metadata['providerMetadata'];
769 $newProviderMetadata = $provider->mergeMetadata(
770 $metadata['providerMetadata'], $providerMetadata
772 if ( $newProviderMetadata !== $providerMetadata ) {
773 $newParams['metadata'] = $newProviderMetadata;
775 } catch ( MetadataMergeException
$ex ) {
776 $this->logger
->warning(
777 'Session "{session}": Metadata merge failed: {exception}',
781 ] +
$ex->getContext()
788 // Next, load the user from metadata, or validate it against the metadata.
789 $userInfo = $info->getUserInfo();
791 // For loading, id is preferred to name.
793 if ( $metadata['userId'] ) {
794 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
795 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
796 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
798 $userInfo = UserInfo
::newAnonymous();
800 } catch ( \InvalidArgumentException
$ex ) {
801 $this->logger
->error( 'Session "{session}": {exception}', [
807 $newParams['userInfo'] = $userInfo;
809 // User validation passes if user ID matches, or if there
810 // is no saved ID and the names match.
811 if ( $metadata['userId'] ) {
812 if ( $metadata['userId'] !== $userInfo->getId() ) {
813 $this->logger
->warning(
814 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
817 'uid_a' => $metadata['userId'],
818 'uid_b' => $userInfo->getId(),
823 // If the user was renamed, probably best to fail here.
824 if ( $metadata['userName'] !== null &&
825 $userInfo->getName() !== $metadata['userName']
827 $this->logger
->warning(
828 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
831 'uname_a' => $metadata['userName'],
832 'uname_b' => $userInfo->getName(),
837 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
838 if ( $metadata['userName'] !== $userInfo->getName() ) {
839 $this->logger
->warning(
840 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
843 'uname_a' => $metadata['userName'],
844 'uname_b' => $userInfo->getName(),
848 } elseif ( !$userInfo->isAnon() ) {
849 // Metadata specifies an anonymous user, but the passed-in
850 // user isn't anonymous.
851 $this->logger
->warning(
852 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
860 // And if we have a token in the metadata, it must match the loaded/provided user.
861 if ( $metadata['userToken'] !== null &&
862 $userInfo->getToken() !== $metadata['userToken']
864 $this->logger
->warning( 'Session "{session}": User token mismatch', [
869 if ( !$userInfo->isVerified() ) {
870 $newParams['userInfo'] = $userInfo->verified();
873 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
874 $newParams['remembered'] = true;
876 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
877 $newParams['forceHTTPS'] = true;
879 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
880 $newParams['persisted'] = true;
883 if ( !$info->isIdSafe() ) {
884 $newParams['idIsSafe'] = true;
887 // No metadata, so we can't load the provider if one wasn't given.
888 if ( $info->getProvider() === null ) {
889 $this->logger
->warning(
890 'Session "{session}": Null provider and no metadata',
897 // If no user was provided and no metadata, it must be anon.
898 if ( !$info->getUserInfo() ) {
899 if ( $info->getProvider()->canChangeUser() ) {
900 $newParams['userInfo'] = UserInfo
::newAnonymous();
903 'Session "{session}": No user provided and provider cannot set user',
909 } elseif ( !$info->getUserInfo()->isVerified() ) {
910 $this->logger
->warning(
911 'Session "{session}": Unverified user provided and no metadata to auth it',
921 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
922 // The ID doesn't come from the user, so it should be safe
923 // (and if not, nothing we can do about it anyway)
924 $newParams['idIsSafe'] = true;
928 // Construct the replacement SessionInfo, if necessary
930 $newParams['copyFrom'] = $info;
931 $info = new SessionInfo( $info->getPriority(), $newParams );
934 // Allow the provider to check the loaded SessionInfo
935 $providerMetadata = $info->getProviderMetadata();
936 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
939 if ( $providerMetadata !== $info->getProviderMetadata() ) {
940 $info = new SessionInfo( $info->getPriority(), [
941 'metadata' => $providerMetadata,
946 // Give hooks a chance to abort. Combined with the SessionMetadata
947 // hook, this can allow for tying a session to an IP address or the
949 $reason = 'Hook aborted';
952 [ &$reason, $info, $request, $metadata, $data ]
954 $this->logger
->warning( 'Session "{session}": ' . $reason, [
964 * Create a session corresponding to the passed SessionInfo
965 * @private For use by a SessionProvider that needs to specially create its
967 * @param SessionInfo $info
968 * @param WebRequest $request
971 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
972 // @codeCoverageIgnoreStart
973 if ( defined( 'MW_NO_SESSION' ) ) {
974 if ( MW_NO_SESSION
=== 'warn' ) {
975 // Undocumented safety case for converting existing entry points
976 $this->logger
->error( 'Sessions are supposed to be disabled for this entry point' );
978 throw new \
BadMethodCallException( 'Sessions are disabled for this entry point' );
981 // @codeCoverageIgnoreEnd
983 $id = $info->getId();
985 if ( !isset( $this->allSessionBackends
[$id] ) ) {
986 if ( !isset( $this->allSessionIds
[$id] ) ) {
987 $this->allSessionIds
[$id] = new SessionId( $id );
989 $backend = new SessionBackend(
990 $this->allSessionIds
[$id],
994 $this->config
->get( 'ObjectCacheSessionExpiry' )
996 $this->allSessionBackends
[$id] = $backend;
997 $delay = $backend->delaySave();
999 $backend = $this->allSessionBackends
[$id];
1000 $delay = $backend->delaySave();
1001 if ( $info->wasPersisted() ) {
1002 $backend->persist();
1004 if ( $info->wasRemembered() ) {
1005 $backend->setRememberUser( true );
1009 $request->setSessionId( $backend->getSessionId() );
1010 $session = $backend->getSession( $request );
1012 if ( !$info->isIdSafe() ) {
1013 $session->resetId();
1016 \ScopedCallback
::consume( $delay );
1021 * Deregister a SessionBackend
1022 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1023 * @param SessionBackend $backend
1025 public function deregisterSessionBackend( SessionBackend
$backend ) {
1026 $id = $backend->getId();
1027 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
1028 $this->allSessionBackends
[$id] !== $backend ||
1029 $this->allSessionIds
[$id] !== $backend->getSessionId()
1031 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1034 unset( $this->allSessionBackends
[$id] );
1035 // Explicitly do not unset $this->allSessionIds[$id]
1039 * Change a SessionBackend's ID
1040 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1041 * @param SessionBackend $backend
1043 public function changeBackendId( SessionBackend
$backend ) {
1044 $sessionId = $backend->getSessionId();
1045 $oldId = (string)$sessionId;
1046 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
1047 $this->allSessionBackends
[$oldId] !== $backend ||
1048 $this->allSessionIds
[$oldId] !== $sessionId
1050 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1053 $newId = $this->generateSessionId();
1055 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
1056 $sessionId->setId( $newId );
1057 $this->allSessionBackends
[$newId] = $backend;
1058 $this->allSessionIds
[$newId] = $sessionId;
1062 * Generate a new random session ID
1065 public function generateSessionId() {
1067 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1068 $key = wfMemcKey( 'MWSession', $id );
1069 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
1074 * Call setters on a PHPSessionHandler
1075 * @private Use PhpSessionHandler::install()
1076 * @param PHPSessionHandler $handler
1078 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1079 $handler->setManager( $this, $this->store
, $this->logger
);
1083 * Reset the internal caching for unit testing
1085 public static function resetCache() {
1086 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1087 // @codeCoverageIgnoreStart
1088 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1089 // @codeCoverageIgnoreEnd
1092 self
::$globalSession = null;
1093 self
::$globalSessionRequest = null;