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
;
200 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [ 'id' => $id, 'idIsSafe' => true ] );
202 // If we already have the backend loaded, use it directly
203 if ( isset( $this->allSessionBackends
[$id] ) ) {
204 return $this->getSessionFromInfo( $info, $request );
207 // Test if the session is in storage, and if so try to load it.
208 $key = wfMemcKey( 'MWSession', $id );
209 if ( is_array( $this->store
->get( $key ) ) ) {
210 $create = false; // If loading fails, don't bother creating because it probably will fail too.
211 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
212 $session = $this->getSessionFromInfo( $info, $request );
216 if ( $create && $session === null ) {
219 $session = $this->getEmptySessionInternal( $request, $id );
220 } catch ( \Exception
$ex ) {
221 $this->logger
->error( 'Failed to create empty session: {exception}',
223 'method' => __METHOD__
,
233 public function getEmptySession( WebRequest
$request = null ) {
234 return $this->getEmptySessionInternal( $request );
238 * @see SessionManagerInterface::getEmptySession
239 * @param WebRequest|null $request
240 * @param string|null $id ID to force on the new session
243 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
244 if ( $id !== null ) {
245 if ( !self
::validateSessionId( $id ) ) {
246 throw new \
InvalidArgumentException( 'Invalid session ID' );
249 $key = wfMemcKey( 'MWSession', $id );
250 if ( is_array( $this->store
->get( $key ) ) ) {
251 throw new \
InvalidArgumentException( 'Session ID already exists' );
255 $request = new FauxRequest
;
259 foreach ( $this->getProviders() as $provider ) {
260 $info = $provider->newSessionInfo( $id );
264 if ( $info->getProvider() !== $provider ) {
265 throw new \
UnexpectedValueException(
266 "$provider returned an empty session info for a different provider: $info"
269 if ( $id !== null && $info->getId() !== $id ) {
270 throw new \
UnexpectedValueException(
271 "$provider returned empty session info with a wrong id: " .
272 $info->getId() . ' != ' . $id
275 if ( !$info->isIdSafe() ) {
276 throw new \
UnexpectedValueException(
277 "$provider returned empty session info with id flagged unsafe"
280 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
281 if ( $compare > 0 ) {
284 if ( $compare === 0 ) {
291 // Make sure there's exactly one
292 if ( count( $infos ) > 1 ) {
293 throw new \
UnexpectedValueException(
294 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
296 } elseif ( count( $infos ) < 1 ) {
297 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
300 return $this->getSessionFromInfo( $infos[0], $request );
303 public function getVaryHeaders() {
304 // @codeCoverageIgnoreStart
305 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
308 // @codeCoverageIgnoreEnd
309 if ( $this->varyHeaders
=== null ) {
311 foreach ( $this->getProviders() as $provider ) {
312 foreach ( $provider->getVaryHeaders() as $header => $options ) {
313 if ( !isset( $headers[$header] ) ) {
314 $headers[$header] = [];
316 if ( is_array( $options ) ) {
317 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
321 $this->varyHeaders
= $headers;
323 return $this->varyHeaders
;
326 public function getVaryCookies() {
327 // @codeCoverageIgnoreStart
328 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
331 // @codeCoverageIgnoreEnd
332 if ( $this->varyCookies
=== null ) {
334 foreach ( $this->getProviders() as $provider ) {
335 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
337 $this->varyCookies
= array_values( array_unique( $cookies ) );
339 return $this->varyCookies
;
343 * Validate a session ID
347 public static function validateSessionId( $id ) {
348 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
352 * @name Internal methods
357 * Auto-create the given user, if necessary
358 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
359 * @note This more properly belongs in AuthManager, but we need it now.
360 * When AuthManager comes, this will be deprecated and will pass-through
361 * to the corresponding AuthManager method.
362 * @param User $user User to auto-create
363 * @return bool Success
365 public static function autoCreateUser( User
$user ) {
368 $logger = self
::singleton()->logger
;
370 // Much of this code is based on that in CentralAuth
372 // Try the local user from the slave DB
373 $localId = User
::idFromName( $user->getName() );
376 // Fetch the user ID from the master, so that we don't try to create the user
377 // when they already exist, due to replication lag
378 // @codeCoverageIgnoreStart
379 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
380 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
381 $flags = User
::READ_LATEST
;
383 // @codeCoverageIgnoreEnd
386 // User exists after all.
387 $user->setId( $localId );
388 $user->loadFromId( $flags );
392 // Denied by AuthPlugin? But ignore AuthPlugin itself.
393 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
394 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
400 // Wiki is read-only?
401 if ( wfReadOnly() ) {
402 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
408 $userName = $user->getName();
410 // Check the session, if we tried to create this user already there's
411 // no point in retrying.
412 $session = self
::getGlobalSession();
413 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
415 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
421 // Is the IP user able to create accounts?
423 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
424 ||
$anon->isBlockedFromCreateAccount()
426 // Blacklist the user to avoid repeated DB queries subsequently
427 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
428 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
435 // Check for validity of username
436 if ( !User
::isCreatableName( $userName ) ) {
437 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
438 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
445 // Give other extensions a chance to stop auto creation.
446 $user->loadDefaults( $userName );
448 if ( !\Hooks
::run( 'AbortAutoAccount', [ $user, &$abortMessage ] ) ) {
449 // In this case we have no way to return the message to the user,
450 // but we can log it.
451 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
452 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
459 // Make sure the name has not been changed
460 if ( $user->getName() !== $userName ) {
463 throw new \
UnexpectedValueException(
464 'AbortAutoAccount hook tried to change the user name'
468 // Ignore warnings about master connections/writes...hard to avoid here
469 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
471 $cache = \ObjectCache
::getLocalClusterInstance();
472 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
473 if ( $cache->get( $backoffKey ) ) {
474 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
480 // Checks passed, create the user...
481 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
482 $logger->info( __METHOD__
. ': creating new user ({username}) - from: {url}',
484 'username' => $userName,
489 // Insert the user into the local DB master
490 $status = $user->addToDatabase();
491 if ( !$status->isOK() ) {
492 // @codeCoverageIgnoreStart
493 // double-check for a race condition (T70012)
494 $id = User
::idFromName( $user->getName(), User
::READ_LATEST
);
496 $logger->info( __METHOD__
. ': tried to autocreate existing user',
498 'username' => $userName,
501 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText(),
503 'username' => $userName,
507 $user->loadFromId( User
::READ_LATEST
);
509 // @codeCoverageIgnoreEnd
511 } catch ( \Exception
$ex ) {
512 // @codeCoverageIgnoreStart
513 $logger->error( __METHOD__
. ': failed with exception {exception}', [
515 'username' => $userName,
517 // Do not keep throwing errors for a while
518 $cache->set( $backoffKey, 1, 600 );
519 // Bubble up error; which should normally trigger DB rollbacks
521 // @codeCoverageIgnoreEnd
525 // @codeCoverageIgnoreStart
527 $wgAuth->initUser( $tmpUser, true );
528 if ( $tmpUser !== $user ) {
529 $logger->warning( __METHOD__
. ': ' .
530 get_class( $wgAuth ) . '::initUser() replaced the user object' );
532 // @codeCoverageIgnoreEnd
534 # Notify hooks (e.g. Newuserlog)
535 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ] );
536 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
538 $user->saveSettings();
541 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
543 # Watch user's userpage and talk page
544 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
550 * Prevent future sessions for the user
552 * The intention is that the named account will never again be usable for
553 * normal login (i.e. there is no way to undo the prevention of access).
555 * @private For use from \\User::newSystemUser only
556 * @param string $username
558 public function preventSessionsForUser( $username ) {
559 $this->preventUsers
[$username] = true;
561 // Instruct the session providers to kill any other sessions too.
562 foreach ( $this->getProviders() as $provider ) {
563 $provider->preventSessionsForUser( $username );
568 * Test if a user is prevented
569 * @private For use from SessionBackend only
570 * @param string $username
573 public function isUserSessionPrevented( $username ) {
574 return !empty( $this->preventUsers
[$username] );
578 * Get the available SessionProviders
579 * @return SessionProvider[]
581 protected function getProviders() {
582 if ( $this->sessionProviders
=== null ) {
583 $this->sessionProviders
= [];
584 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
585 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
586 $provider->setLogger( $this->logger
);
587 $provider->setConfig( $this->config
);
588 $provider->setManager( $this );
589 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
590 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
592 $this->sessionProviders
[(string)$provider] = $provider;
595 return $this->sessionProviders
;
599 * Get a session provider by name
601 * Generally, this will only be used by internal implementation of some
602 * special session-providing mechanism. General purpose code, if it needs
603 * to access a SessionProvider at all, will use Session::getProvider().
605 * @param string $name
606 * @return SessionProvider|null
608 public function getProvider( $name ) {
609 $providers = $this->getProviders();
610 return isset( $providers[$name] ) ?
$providers[$name] : null;
614 * Save all active sessions on shutdown
615 * @private For internal use with register_shutdown_function()
617 public function shutdown() {
618 if ( $this->allSessionBackends
) {
619 $this->logger
->debug( 'Saving all sessions on shutdown' );
620 if ( session_id() !== '' ) {
621 // @codeCoverageIgnoreStart
622 session_write_close();
624 // @codeCoverageIgnoreEnd
625 foreach ( $this->allSessionBackends
as $backend ) {
626 $backend->save( true );
632 * Fetch the SessionInfo(s) for a request
633 * @param WebRequest $request
634 * @return SessionInfo|null
636 private function getSessionInfoForRequest( WebRequest
$request ) {
637 // Call all providers to fetch "the" session
639 foreach ( $this->getProviders() as $provider ) {
640 $info = $provider->provideSessionInfo( $request );
644 if ( $info->getProvider() !== $provider ) {
645 throw new \
UnexpectedValueException(
646 "$provider returned session info for a different provider: $info"
652 // Sort the SessionInfos. Then find the first one that can be
653 // successfully loaded, and then all the ones after it with the same
655 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
658 $info = array_pop( $infos );
659 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
662 $info = array_pop( $infos );
663 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
664 // We hit a lower priority, stop checking.
667 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
668 // This is going to error out below, but we want to
669 // provide a complete list.
672 // Session load failed, so unpersist it from this request
673 $info->getProvider()->unpersistSession( $request );
677 // Session load failed, so unpersist it from this request
678 $info->getProvider()->unpersistSession( $request );
682 if ( count( $retInfos ) > 1 ) {
683 $ex = new \
OverflowException(
684 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
686 $ex->sessionInfos
= $retInfos;
690 return $retInfos ?
$retInfos[0] : null;
694 * Load and verify the session info against the store
696 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
697 * @param WebRequest $request
698 * @return bool Whether the session info matches the stored data (if any)
700 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
701 $key = wfMemcKey( 'MWSession', $info->getId() );
702 $blob = $this->store
->get( $key );
706 if ( $blob !== false ) {
707 // Sanity check: blob must be an array, if it's saved at all
708 if ( !is_array( $blob ) ) {
709 $this->logger
->warning( 'Session "{session}": Bad data', [
712 $this->store
->delete( $key );
716 // Sanity check: blob has data and metadata arrays
717 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
718 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
720 $this->logger
->warning( 'Session "{session}": Bad data structure', [
723 $this->store
->delete( $key );
727 $data = $blob['data'];
728 $metadata = $blob['metadata'];
730 // Sanity check: metadata must be an array and must contain certain
731 // keys, if it's saved at all
732 if ( !array_key_exists( 'userId', $metadata ) ||
733 !array_key_exists( 'userName', $metadata ) ||
734 !array_key_exists( 'userToken', $metadata ) ||
735 !array_key_exists( 'provider', $metadata )
737 $this->logger
->warning( 'Session "{session}": Bad metadata', [
740 $this->store
->delete( $key );
744 // First, load the provider from metadata, or validate it against the metadata.
745 $provider = $info->getProvider();
746 if ( $provider === null ) {
747 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
749 $this->logger
->warning(
750 'Session "{session}": Unknown provider ' . $metadata['provider'],
755 $this->store
->delete( $key );
758 } elseif ( $metadata['provider'] !== (string)$provider ) {
759 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
760 $metadata['provider'] . ' !== ' . $provider,
767 // Load provider metadata from metadata, or validate it against the metadata
768 $providerMetadata = $info->getProviderMetadata();
769 if ( isset( $metadata['providerMetadata'] ) ) {
770 if ( $providerMetadata === null ) {
771 $newParams['metadata'] = $metadata['providerMetadata'];
774 $newProviderMetadata = $provider->mergeMetadata(
775 $metadata['providerMetadata'], $providerMetadata
777 if ( $newProviderMetadata !== $providerMetadata ) {
778 $newParams['metadata'] = $newProviderMetadata;
780 } catch ( MetadataMergeException
$ex ) {
781 $this->logger
->warning(
782 'Session "{session}": Metadata merge failed: {exception}',
786 ] +
$ex->getContext()
793 // Next, load the user from metadata, or validate it against the metadata.
794 $userInfo = $info->getUserInfo();
796 // For loading, id is preferred to name.
798 if ( $metadata['userId'] ) {
799 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
800 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
801 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
803 $userInfo = UserInfo
::newAnonymous();
805 } catch ( \InvalidArgumentException
$ex ) {
806 $this->logger
->error( 'Session "{session}": {exception}', [
812 $newParams['userInfo'] = $userInfo;
814 // User validation passes if user ID matches, or if there
815 // is no saved ID and the names match.
816 if ( $metadata['userId'] ) {
817 if ( $metadata['userId'] !== $userInfo->getId() ) {
818 $this->logger
->warning(
819 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
822 'uid_a' => $metadata['userId'],
823 'uid_b' => $userInfo->getId(),
828 // If the user was renamed, probably best to fail here.
829 if ( $metadata['userName'] !== null &&
830 $userInfo->getName() !== $metadata['userName']
832 $this->logger
->warning(
833 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
836 'uname_a' => $metadata['userName'],
837 'uname_b' => $userInfo->getName(),
842 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
843 if ( $metadata['userName'] !== $userInfo->getName() ) {
844 $this->logger
->warning(
845 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
848 'uname_a' => $metadata['userName'],
849 'uname_b' => $userInfo->getName(),
853 } elseif ( !$userInfo->isAnon() ) {
854 // Metadata specifies an anonymous user, but the passed-in
855 // user isn't anonymous.
856 $this->logger
->warning(
857 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
865 // And if we have a token in the metadata, it must match the loaded/provided user.
866 if ( $metadata['userToken'] !== null &&
867 $userInfo->getToken() !== $metadata['userToken']
869 $this->logger
->warning( 'Session "{session}": User token mismatch', [
874 if ( !$userInfo->isVerified() ) {
875 $newParams['userInfo'] = $userInfo->verified();
878 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
879 $newParams['remembered'] = true;
881 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
882 $newParams['forceHTTPS'] = true;
884 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
885 $newParams['persisted'] = true;
888 if ( !$info->isIdSafe() ) {
889 $newParams['idIsSafe'] = true;
892 // No metadata, so we can't load the provider if one wasn't given.
893 if ( $info->getProvider() === null ) {
894 $this->logger
->warning(
895 'Session "{session}": Null provider and no metadata',
902 // If no user was provided and no metadata, it must be anon.
903 if ( !$info->getUserInfo() ) {
904 if ( $info->getProvider()->canChangeUser() ) {
905 $newParams['userInfo'] = UserInfo
::newAnonymous();
908 'Session "{session}": No user provided and provider cannot set user',
914 } elseif ( !$info->getUserInfo()->isVerified() ) {
915 $this->logger
->warning(
916 'Session "{session}": Unverified user provided and no metadata to auth it',
926 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
927 // The ID doesn't come from the user, so it should be safe
928 // (and if not, nothing we can do about it anyway)
929 $newParams['idIsSafe'] = true;
933 // Construct the replacement SessionInfo, if necessary
935 $newParams['copyFrom'] = $info;
936 $info = new SessionInfo( $info->getPriority(), $newParams );
939 // Allow the provider to check the loaded SessionInfo
940 $providerMetadata = $info->getProviderMetadata();
941 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
944 if ( $providerMetadata !== $info->getProviderMetadata() ) {
945 $info = new SessionInfo( $info->getPriority(), [
946 'metadata' => $providerMetadata,
951 // Give hooks a chance to abort. Combined with the SessionMetadata
952 // hook, this can allow for tying a session to an IP address or the
954 $reason = 'Hook aborted';
957 [ &$reason, $info, $request, $metadata, $data ]
959 $this->logger
->warning( 'Session "{session}": ' . $reason, [
969 * Create a session corresponding to the passed SessionInfo
970 * @private For use by a SessionProvider that needs to specially create its
972 * @param SessionInfo $info
973 * @param WebRequest $request
976 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
977 // @codeCoverageIgnoreStart
978 if ( defined( 'MW_NO_SESSION' ) ) {
979 if ( MW_NO_SESSION
=== 'warn' ) {
980 // Undocumented safety case for converting existing entry points
981 $this->logger
->error( 'Sessions are supposed to be disabled for this entry point', [
982 'exception' => new \
BadMethodCallException( 'Sessions are disabled for this entry point' ),
985 throw new \
BadMethodCallException( 'Sessions are disabled for this entry point' );
988 // @codeCoverageIgnoreEnd
990 $id = $info->getId();
992 if ( !isset( $this->allSessionBackends
[$id] ) ) {
993 if ( !isset( $this->allSessionIds
[$id] ) ) {
994 $this->allSessionIds
[$id] = new SessionId( $id );
996 $backend = new SessionBackend(
997 $this->allSessionIds
[$id],
1001 $this->config
->get( 'ObjectCacheSessionExpiry' )
1003 $this->allSessionBackends
[$id] = $backend;
1004 $delay = $backend->delaySave();
1006 $backend = $this->allSessionBackends
[$id];
1007 $delay = $backend->delaySave();
1008 if ( $info->wasPersisted() ) {
1009 $backend->persist();
1011 if ( $info->wasRemembered() ) {
1012 $backend->setRememberUser( true );
1016 $request->setSessionId( $backend->getSessionId() );
1017 $session = $backend->getSession( $request );
1019 if ( !$info->isIdSafe() ) {
1020 $session->resetId();
1023 \ScopedCallback
::consume( $delay );
1028 * Deregister a SessionBackend
1029 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1030 * @param SessionBackend $backend
1032 public function deregisterSessionBackend( SessionBackend
$backend ) {
1033 $id = $backend->getId();
1034 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
1035 $this->allSessionBackends
[$id] !== $backend ||
1036 $this->allSessionIds
[$id] !== $backend->getSessionId()
1038 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1041 unset( $this->allSessionBackends
[$id] );
1042 // Explicitly do not unset $this->allSessionIds[$id]
1046 * Change a SessionBackend's ID
1047 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1048 * @param SessionBackend $backend
1050 public function changeBackendId( SessionBackend
$backend ) {
1051 $sessionId = $backend->getSessionId();
1052 $oldId = (string)$sessionId;
1053 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
1054 $this->allSessionBackends
[$oldId] !== $backend ||
1055 $this->allSessionIds
[$oldId] !== $sessionId
1057 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1060 $newId = $this->generateSessionId();
1062 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
1063 $sessionId->setId( $newId );
1064 $this->allSessionBackends
[$newId] = $backend;
1065 $this->allSessionIds
[$newId] = $sessionId;
1069 * Generate a new random session ID
1072 public function generateSessionId() {
1074 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1075 $key = wfMemcKey( 'MWSession', $id );
1076 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
1081 * Call setters on a PHPSessionHandler
1082 * @private Use PhpSessionHandler::install()
1083 * @param PHPSessionHandler $handler
1085 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1086 $handler->setManager( $this, $this->store
, $this->logger
);
1090 * Reset the internal caching for unit testing
1092 public static function resetCache() {
1093 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1094 // @codeCoverageIgnoreStart
1095 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1096 // @codeCoverageIgnoreEnd
1099 self
::$globalSession = null;
1100 self
::$globalSessionRequest = null;