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 ) ) ) {
206 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [ 'id' => $id, 'idIsSafe' => true ] );
207 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
208 $session = $this->getSessionFromInfo( $info, $request );
212 if ( $create && $session === null ) {
215 $session = $this->getEmptySessionInternal( $request, $id );
216 } catch ( \Exception
$ex ) {
217 $this->logger
->error( 'Failed to create empty session: {exception}',
219 'method' => __METHOD__
,
229 public function getEmptySession( WebRequest
$request = null ) {
230 return $this->getEmptySessionInternal( $request );
234 * @see SessionManagerInterface::getEmptySession
235 * @param WebRequest|null $request
236 * @param string|null $id ID to force on the new session
239 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
240 if ( $id !== null ) {
241 if ( !self
::validateSessionId( $id ) ) {
242 throw new \
InvalidArgumentException( 'Invalid session ID' );
245 $key = wfMemcKey( 'MWSession', $id );
246 if ( is_array( $this->store
->get( $key ) ) ) {
247 throw new \
InvalidArgumentException( 'Session ID already exists' );
251 $request = new FauxRequest
;
255 foreach ( $this->getProviders() as $provider ) {
256 $info = $provider->newSessionInfo( $id );
260 if ( $info->getProvider() !== $provider ) {
261 throw new \
UnexpectedValueException(
262 "$provider returned an empty session info for a different provider: $info"
265 if ( $id !== null && $info->getId() !== $id ) {
266 throw new \
UnexpectedValueException(
267 "$provider returned empty session info with a wrong id: " .
268 $info->getId() . ' != ' . $id
271 if ( !$info->isIdSafe() ) {
272 throw new \
UnexpectedValueException(
273 "$provider returned empty session info with id flagged unsafe"
276 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
277 if ( $compare > 0 ) {
280 if ( $compare === 0 ) {
287 // Make sure there's exactly one
288 if ( count( $infos ) > 1 ) {
289 throw new \
UnexpectedValueException(
290 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
292 } elseif ( count( $infos ) < 1 ) {
293 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
296 return $this->getSessionFromInfo( $infos[0], $request );
299 public function getVaryHeaders() {
300 // @codeCoverageIgnoreStart
301 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
304 // @codeCoverageIgnoreEnd
305 if ( $this->varyHeaders
=== null ) {
307 foreach ( $this->getProviders() as $provider ) {
308 foreach ( $provider->getVaryHeaders() as $header => $options ) {
309 if ( !isset( $headers[$header] ) ) {
310 $headers[$header] = [];
312 if ( is_array( $options ) ) {
313 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
317 $this->varyHeaders
= $headers;
319 return $this->varyHeaders
;
322 public function getVaryCookies() {
323 // @codeCoverageIgnoreStart
324 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
327 // @codeCoverageIgnoreEnd
328 if ( $this->varyCookies
=== null ) {
330 foreach ( $this->getProviders() as $provider ) {
331 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
333 $this->varyCookies
= array_values( array_unique( $cookies ) );
335 return $this->varyCookies
;
339 * Validate a session ID
343 public static function validateSessionId( $id ) {
344 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
348 * @name Internal methods
353 * Auto-create the given user, if necessary
354 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
355 * @note This more properly belongs in AuthManager, but we need it now.
356 * When AuthManager comes, this will be deprecated and will pass-through
357 * to the corresponding AuthManager method.
358 * @param User $user User to auto-create
359 * @return bool Success
361 public static function autoCreateUser( User
$user ) {
364 $logger = self
::singleton()->logger
;
366 // Much of this code is based on that in CentralAuth
368 // Try the local user from the slave DB
369 $localId = User
::idFromName( $user->getName() );
372 // Fetch the user ID from the master, so that we don't try to create the user
373 // when they already exist, due to replication lag
374 // @codeCoverageIgnoreStart
375 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
376 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
377 $flags = User
::READ_LATEST
;
379 // @codeCoverageIgnoreEnd
382 // User exists after all.
383 $user->setId( $localId );
384 $user->loadFromId( $flags );
388 // Denied by AuthPlugin? But ignore AuthPlugin itself.
389 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
390 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
396 // Wiki is read-only?
397 if ( wfReadOnly() ) {
398 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
404 $userName = $user->getName();
406 // Check the session, if we tried to create this user already there's
407 // no point in retrying.
408 $session = self
::getGlobalSession();
409 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
411 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
417 // Is the IP user able to create accounts?
419 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
420 ||
$anon->isBlockedFromCreateAccount()
422 // Blacklist the user to avoid repeated DB queries subsequently
423 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
424 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
431 // Check for validity of username
432 if ( !User
::isCreatableName( $userName ) ) {
433 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
434 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
441 // Give other extensions a chance to stop auto creation.
442 $user->loadDefaults( $userName );
444 if ( !\Hooks
::run( 'AbortAutoAccount', [ $user, &$abortMessage ] ) ) {
445 // In this case we have no way to return the message to the user,
446 // but we can log it.
447 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
448 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
455 // Make sure the name has not been changed
456 if ( $user->getName() !== $userName ) {
459 throw new \
UnexpectedValueException(
460 'AbortAutoAccount hook tried to change the user name'
464 // Ignore warnings about master connections/writes...hard to avoid here
465 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
467 $cache = \ObjectCache
::getLocalClusterInstance();
468 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
469 if ( $cache->get( $backoffKey ) ) {
470 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
476 // Checks passed, create the user...
477 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
478 $logger->info( __METHOD__
. ': creating new user ({username}) - from: {url}',
480 'username' => $userName,
485 // Insert the user into the local DB master
486 $status = $user->addToDatabase();
487 if ( !$status->isOK() ) {
488 // @codeCoverageIgnoreStart
489 // double-check for a race condition (T70012)
490 $id = User
::idFromName( $user->getName(), User
::READ_LATEST
);
492 $logger->info( __METHOD__
. ': tried to autocreate existing user',
494 'username' => $userName,
497 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText(),
499 'username' => $userName,
503 $user->loadFromId( User
::READ_LATEST
);
505 // @codeCoverageIgnoreEnd
507 } catch ( \Exception
$ex ) {
508 // @codeCoverageIgnoreStart
509 $logger->error( __METHOD__
. ': failed with exception {exception}', [
511 'username' => $userName,
513 // Do not keep throwing errors for a while
514 $cache->set( $backoffKey, 1, 600 );
515 // Bubble up error; which should normally trigger DB rollbacks
517 // @codeCoverageIgnoreEnd
521 // @codeCoverageIgnoreStart
523 $wgAuth->initUser( $tmpUser, true );
524 if ( $tmpUser !== $user ) {
525 $logger->warning( __METHOD__
. ': ' .
526 get_class( $wgAuth ) . '::initUser() replaced the user object' );
528 // @codeCoverageIgnoreEnd
530 # Notify hooks (e.g. Newuserlog)
531 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ] );
532 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
534 $user->saveSettings();
537 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
539 # Watch user's userpage and talk page
540 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
546 * Prevent future sessions for the user
548 * The intention is that the named account will never again be usable for
549 * normal login (i.e. there is no way to undo the prevention of access).
551 * @private For use from \\User::newSystemUser only
552 * @param string $username
554 public function preventSessionsForUser( $username ) {
555 $this->preventUsers
[$username] = true;
557 // Instruct the session providers to kill any other sessions too.
558 foreach ( $this->getProviders() as $provider ) {
559 $provider->preventSessionsForUser( $username );
564 * Test if a user is prevented
565 * @private For use from SessionBackend only
566 * @param string $username
569 public function isUserSessionPrevented( $username ) {
570 return !empty( $this->preventUsers
[$username] );
574 * Get the available SessionProviders
575 * @return SessionProvider[]
577 protected function getProviders() {
578 if ( $this->sessionProviders
=== null ) {
579 $this->sessionProviders
= [];
580 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
581 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
582 $provider->setLogger( $this->logger
);
583 $provider->setConfig( $this->config
);
584 $provider->setManager( $this );
585 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
586 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
588 $this->sessionProviders
[(string)$provider] = $provider;
591 return $this->sessionProviders
;
595 * Get a session provider by name
597 * Generally, this will only be used by internal implementation of some
598 * special session-providing mechanism. General purpose code, if it needs
599 * to access a SessionProvider at all, will use Session::getProvider().
601 * @param string $name
602 * @return SessionProvider|null
604 public function getProvider( $name ) {
605 $providers = $this->getProviders();
606 return isset( $providers[$name] ) ?
$providers[$name] : null;
610 * Save all active sessions on shutdown
611 * @private For internal use with register_shutdown_function()
613 public function shutdown() {
614 if ( $this->allSessionBackends
) {
615 $this->logger
->debug( 'Saving all sessions on shutdown' );
616 if ( session_id() !== '' ) {
617 // @codeCoverageIgnoreStart
618 session_write_close();
620 // @codeCoverageIgnoreEnd
621 foreach ( $this->allSessionBackends
as $backend ) {
622 $backend->save( true );
628 * Fetch the SessionInfo(s) for a request
629 * @param WebRequest $request
630 * @return SessionInfo|null
632 private function getSessionInfoForRequest( WebRequest
$request ) {
633 // Call all providers to fetch "the" session
635 foreach ( $this->getProviders() as $provider ) {
636 $info = $provider->provideSessionInfo( $request );
640 if ( $info->getProvider() !== $provider ) {
641 throw new \
UnexpectedValueException(
642 "$provider returned session info for a different provider: $info"
648 // Sort the SessionInfos. Then find the first one that can be
649 // successfully loaded, and then all the ones after it with the same
651 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
654 $info = array_pop( $infos );
655 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
658 $info = array_pop( $infos );
659 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
660 // We hit a lower priority, stop checking.
663 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
664 // This is going to error out below, but we want to
665 // provide a complete list.
668 // Session load failed, so unpersist it from this request
669 $info->getProvider()->unpersistSession( $request );
673 // Session load failed, so unpersist it from this request
674 $info->getProvider()->unpersistSession( $request );
678 if ( count( $retInfos ) > 1 ) {
679 $ex = new \
OverflowException(
680 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
682 $ex->sessionInfos
= $retInfos;
686 return $retInfos ?
$retInfos[0] : null;
690 * Load and verify the session info against the store
692 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
693 * @param WebRequest $request
694 * @return bool Whether the session info matches the stored data (if any)
696 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
697 $key = wfMemcKey( 'MWSession', $info->getId() );
698 $blob = $this->store
->get( $key );
702 if ( $blob !== false ) {
703 // Sanity check: blob must be an array, if it's saved at all
704 if ( !is_array( $blob ) ) {
705 $this->logger
->warning( 'Session "{session}": Bad data', [
708 $this->store
->delete( $key );
712 // Sanity check: blob has data and metadata arrays
713 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
714 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
716 $this->logger
->warning( 'Session "{session}": Bad data structure', [
719 $this->store
->delete( $key );
723 $data = $blob['data'];
724 $metadata = $blob['metadata'];
726 // Sanity check: metadata must be an array and must contain certain
727 // keys, if it's saved at all
728 if ( !array_key_exists( 'userId', $metadata ) ||
729 !array_key_exists( 'userName', $metadata ) ||
730 !array_key_exists( 'userToken', $metadata ) ||
731 !array_key_exists( 'provider', $metadata )
733 $this->logger
->warning( 'Session "{session}": Bad metadata', [
736 $this->store
->delete( $key );
740 // First, load the provider from metadata, or validate it against the metadata.
741 $provider = $info->getProvider();
742 if ( $provider === null ) {
743 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
745 $this->logger
->warning(
746 'Session "{session}": Unknown provider ' . $metadata['provider'],
751 $this->store
->delete( $key );
754 } elseif ( $metadata['provider'] !== (string)$provider ) {
755 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
756 $metadata['provider'] . ' !== ' . $provider,
763 // Load provider metadata from metadata, or validate it against the metadata
764 $providerMetadata = $info->getProviderMetadata();
765 if ( isset( $metadata['providerMetadata'] ) ) {
766 if ( $providerMetadata === null ) {
767 $newParams['metadata'] = $metadata['providerMetadata'];
770 $newProviderMetadata = $provider->mergeMetadata(
771 $metadata['providerMetadata'], $providerMetadata
773 if ( $newProviderMetadata !== $providerMetadata ) {
774 $newParams['metadata'] = $newProviderMetadata;
776 } catch ( MetadataMergeException
$ex ) {
777 $this->logger
->warning(
778 'Session "{session}": Metadata merge failed: {exception}',
782 ] +
$ex->getContext()
789 // Next, load the user from metadata, or validate it against the metadata.
790 $userInfo = $info->getUserInfo();
792 // For loading, id is preferred to name.
794 if ( $metadata['userId'] ) {
795 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
796 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
797 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
799 $userInfo = UserInfo
::newAnonymous();
801 } catch ( \InvalidArgumentException
$ex ) {
802 $this->logger
->error( 'Session "{session}": {exception}', [
808 $newParams['userInfo'] = $userInfo;
810 // User validation passes if user ID matches, or if there
811 // is no saved ID and the names match.
812 if ( $metadata['userId'] ) {
813 if ( $metadata['userId'] !== $userInfo->getId() ) {
814 $this->logger
->warning(
815 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
818 'uid_a' => $metadata['userId'],
819 'uid_b' => $userInfo->getId(),
824 // If the user was renamed, probably best to fail here.
825 if ( $metadata['userName'] !== null &&
826 $userInfo->getName() !== $metadata['userName']
828 $this->logger
->warning(
829 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
832 'uname_a' => $metadata['userName'],
833 'uname_b' => $userInfo->getName(),
838 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
839 if ( $metadata['userName'] !== $userInfo->getName() ) {
840 $this->logger
->warning(
841 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
844 'uname_a' => $metadata['userName'],
845 'uname_b' => $userInfo->getName(),
849 } elseif ( !$userInfo->isAnon() ) {
850 // Metadata specifies an anonymous user, but the passed-in
851 // user isn't anonymous.
852 $this->logger
->warning(
853 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
861 // And if we have a token in the metadata, it must match the loaded/provided user.
862 if ( $metadata['userToken'] !== null &&
863 $userInfo->getToken() !== $metadata['userToken']
865 $this->logger
->warning( 'Session "{session}": User token mismatch', [
870 if ( !$userInfo->isVerified() ) {
871 $newParams['userInfo'] = $userInfo->verified();
874 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
875 $newParams['remembered'] = true;
877 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
878 $newParams['forceHTTPS'] = true;
880 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
881 $newParams['persisted'] = true;
884 if ( !$info->isIdSafe() ) {
885 $newParams['idIsSafe'] = true;
888 // No metadata, so we can't load the provider if one wasn't given.
889 if ( $info->getProvider() === null ) {
890 $this->logger
->warning(
891 'Session "{session}": Null provider and no metadata',
898 // If no user was provided and no metadata, it must be anon.
899 if ( !$info->getUserInfo() ) {
900 if ( $info->getProvider()->canChangeUser() ) {
901 $newParams['userInfo'] = UserInfo
::newAnonymous();
904 'Session "{session}": No user provided and provider cannot set user',
910 } elseif ( !$info->getUserInfo()->isVerified() ) {
911 $this->logger
->warning(
912 'Session "{session}": Unverified user provided and no metadata to auth it',
922 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
923 // The ID doesn't come from the user, so it should be safe
924 // (and if not, nothing we can do about it anyway)
925 $newParams['idIsSafe'] = true;
929 // Construct the replacement SessionInfo, if necessary
931 $newParams['copyFrom'] = $info;
932 $info = new SessionInfo( $info->getPriority(), $newParams );
935 // Allow the provider to check the loaded SessionInfo
936 $providerMetadata = $info->getProviderMetadata();
937 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
940 if ( $providerMetadata !== $info->getProviderMetadata() ) {
941 $info = new SessionInfo( $info->getPriority(), [
942 'metadata' => $providerMetadata,
947 // Give hooks a chance to abort. Combined with the SessionMetadata
948 // hook, this can allow for tying a session to an IP address or the
950 $reason = 'Hook aborted';
953 [ &$reason, $info, $request, $metadata, $data ]
955 $this->logger
->warning( 'Session "{session}": ' . $reason, [
965 * Create a session corresponding to the passed SessionInfo
966 * @private For use by a SessionProvider that needs to specially create its
968 * @param SessionInfo $info
969 * @param WebRequest $request
972 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
973 // @codeCoverageIgnoreStart
974 if ( defined( 'MW_NO_SESSION' ) ) {
975 if ( MW_NO_SESSION
=== 'warn' ) {
976 // Undocumented safety case for converting existing entry points
977 $this->logger
->error( 'Sessions are supposed to be disabled for this entry point' );
979 throw new \
BadMethodCallException( 'Sessions are disabled for this entry point' );
982 // @codeCoverageIgnoreEnd
984 $id = $info->getId();
986 if ( !isset( $this->allSessionBackends
[$id] ) ) {
987 if ( !isset( $this->allSessionIds
[$id] ) ) {
988 $this->allSessionIds
[$id] = new SessionId( $id );
990 $backend = new SessionBackend(
991 $this->allSessionIds
[$id],
995 $this->config
->get( 'ObjectCacheSessionExpiry' )
997 $this->allSessionBackends
[$id] = $backend;
998 $delay = $backend->delaySave();
1000 $backend = $this->allSessionBackends
[$id];
1001 $delay = $backend->delaySave();
1002 if ( $info->wasPersisted() ) {
1003 $backend->persist();
1005 if ( $info->wasRemembered() ) {
1006 $backend->setRememberUser( true );
1010 $request->setSessionId( $backend->getSessionId() );
1011 $session = $backend->getSession( $request );
1013 if ( !$info->isIdSafe() ) {
1014 $session->resetId();
1017 \ScopedCallback
::consume( $delay );
1022 * Deregister a SessionBackend
1023 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1024 * @param SessionBackend $backend
1026 public function deregisterSessionBackend( SessionBackend
$backend ) {
1027 $id = $backend->getId();
1028 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
1029 $this->allSessionBackends
[$id] !== $backend ||
1030 $this->allSessionIds
[$id] !== $backend->getSessionId()
1032 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1035 unset( $this->allSessionBackends
[$id] );
1036 // Explicitly do not unset $this->allSessionIds[$id]
1040 * Change a SessionBackend's ID
1041 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1042 * @param SessionBackend $backend
1044 public function changeBackendId( SessionBackend
$backend ) {
1045 $sessionId = $backend->getSessionId();
1046 $oldId = (string)$sessionId;
1047 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
1048 $this->allSessionBackends
[$oldId] !== $backend ||
1049 $this->allSessionIds
[$oldId] !== $sessionId
1051 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1054 $newId = $this->generateSessionId();
1056 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
1057 $sessionId->setId( $newId );
1058 $this->allSessionBackends
[$newId] = $backend;
1059 $this->allSessionIds
[$newId] = $sessionId;
1063 * Generate a new random session ID
1066 public function generateSessionId() {
1068 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1069 $key = wfMemcKey( 'MWSession', $id );
1070 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
1075 * Call setters on a PHPSessionHandler
1076 * @private Use PhpSessionHandler::install()
1077 * @param PHPSessionHandler $handler
1079 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1080 $handler->setManager( $this, $this->store
, $this->logger
);
1084 * Reset the internal caching for unit testing
1086 public static function resetCache() {
1087 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1088 // @codeCoverageIgnoreStart
1089 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1090 // @codeCoverageIgnoreEnd
1093 self
::$globalSession = null;
1094 self
::$globalSessionRequest = null;