3 * MediaWiki\Session entry point
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 namespace MediaWiki\Session
;
26 use Psr\Log\LoggerInterface
;
36 * This serves as the entry point to the MediaWiki session handling system.
41 final class SessionManager
implements SessionManagerInterface
{
42 /** @var SessionManager|null */
43 private static $instance = null;
45 /** @var Session|null */
46 private static $globalSession = null;
48 /** @var WebRequest|null */
49 private static $globalSessionRequest = null;
51 /** @var LoggerInterface */
57 /** @var BagOStuff|null */
60 /** @var SessionProvider[] */
61 private $sessionProviders = null;
64 private $varyCookies = null;
67 private $varyHeaders = null;
69 /** @var SessionBackend[] */
70 private $allSessionBackends = array();
72 /** @var SessionId[] */
73 private $allSessionIds = array();
76 private $preventUsers = array();
79 * Get the global SessionManager
80 * @return SessionManagerInterface
81 * (really a SessionManager, but this is to make IDEs less confused)
83 public static function singleton() {
84 if ( self
::$instance === null ) {
85 self
::$instance = new self();
87 return self
::$instance;
91 * Get the "global" session
93 * If PHP's session_id() has been set, returns that session. Otherwise
94 * returns the session for RequestContext::getMain()->getRequest().
98 public static function getGlobalSession() {
99 if ( !PHPSessionHandler
::isEnabled() ) {
105 $request = \RequestContext
::getMain()->getRequest();
107 !self
::$globalSession // No global session is set up yet
108 || self
::$globalSessionRequest !== $request // The global WebRequest changed
109 ||
$id !== '' && self
::$globalSession->getId() !== $id // Someone messed with session_id()
111 self
::$globalSessionRequest = $request;
113 // session_id() wasn't used, so fetch the Session from the WebRequest.
114 // We use $request->getSession() instead of $singleton->getSessionForRequest()
115 // because doing the latter would require a public
116 // "$request->getSessionId()" method that would confuse end
117 // users by returning SessionId|null where they'd expect it to
118 // be short for $request->getSession()->getId(), and would
119 // wind up being a duplicate of the code in
120 // $request->getSession() anyway.
121 self
::$globalSession = $request->getSession();
123 // Someone used session_id(), so we need to follow suit.
124 // Note this overwrites whatever session might already be
125 // associated with $request with the one for $id.
126 self
::$globalSession = self
::singleton()->getSessionById( $id, true, $request )
127 ?
: $request->getSession();
130 return self
::$globalSession;
134 * @param array $options
135 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
136 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
137 * - store: BagOStuff to store session data in.
139 public function __construct( $options = array() ) {
140 if ( isset( $options['config'] ) ) {
141 $this->config
= $options['config'];
142 if ( !$this->config
instanceof Config
) {
143 throw new \
InvalidArgumentException(
144 '$options[\'config\'] must be an instance of Config'
148 $this->config
= \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
151 if ( isset( $options['logger'] ) ) {
152 if ( !$options['logger'] instanceof LoggerInterface
) {
153 throw new \
InvalidArgumentException(
154 '$options[\'logger\'] must be an instance of LoggerInterface'
157 $this->setLogger( $options['logger'] );
159 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' ) );
162 if ( isset( $options['store'] ) ) {
163 if ( !$options['store'] instanceof BagOStuff
) {
164 throw new \
InvalidArgumentException(
165 '$options[\'store\'] must be an instance of BagOStuff'
168 $this->store
= $options['store'];
170 $this->store
= \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
171 $this->store
->setLogger( $this->logger
);
174 register_shutdown_function( array( $this, 'shutdown' ) );
177 public function setLogger( LoggerInterface
$logger ) {
178 $this->logger
= $logger;
181 public function getPersistedSessionId( WebRequest
$request ) {
182 $info = $this->getSessionInfoForRequest( $request );
183 if ( $info && $info->wasPersisted() ) {
184 return $info->getId();
190 public function getSessionForRequest( WebRequest
$request ) {
191 $info = $this->getSessionInfoForRequest( $request );
194 $session = $this->getEmptySession( $request );
196 $session = $this->getSessionFromInfo( $info, $request );
201 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
202 if ( !self
::validateSessionId( $id ) ) {
203 throw new \
InvalidArgumentException( 'Invalid session ID' );
206 $request = new FauxRequest
;
211 // Test this here to provide a better log message for the common case
213 $key = wfMemcKey( 'MWSession', $id );
214 if ( is_array( $this->store
->get( $key ) ) ) {
215 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array( 'id' => $id, 'idIsSafe' => true ) );
216 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
217 $session = $this->getSessionFromInfo( $info, $request );
221 if ( $create && $session === null ) {
224 $session = $this->getEmptySessionInternal( $request, $id );
225 } catch ( \Exception
$ex ) {
226 $this->logger
->error( __METHOD__
. ': failed to create empty session: ' .
235 public function getEmptySession( WebRequest
$request = null ) {
236 return $this->getEmptySessionInternal( $request );
240 * @see SessionManagerInterface::getEmptySession
241 * @param WebRequest|null $request
242 * @param string|null $id ID to force on the new session
245 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
246 if ( $id !== null ) {
247 if ( !self
::validateSessionId( $id ) ) {
248 throw new \
InvalidArgumentException( 'Invalid session ID' );
251 $key = wfMemcKey( 'MWSession', $id );
252 if ( is_array( $this->store
->get( $key ) ) ) {
253 throw new \
InvalidArgumentException( 'Session ID already exists' );
257 $request = new FauxRequest
;
261 foreach ( $this->getProviders() as $provider ) {
262 $info = $provider->newSessionInfo( $id );
266 if ( $info->getProvider() !== $provider ) {
267 throw new \
UnexpectedValueException(
268 "$provider returned an empty session info for a different provider: $info"
271 if ( $id !== null && $info->getId() !== $id ) {
272 throw new \
UnexpectedValueException(
273 "$provider returned empty session info with a wrong id: " .
274 $info->getId() . ' != ' . $id
277 if ( !$info->isIdSafe() ) {
278 throw new \
UnexpectedValueException(
279 "$provider returned empty session info with id flagged unsafe"
282 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
283 if ( $compare > 0 ) {
286 if ( $compare === 0 ) {
289 $infos = array( $info );
293 // Make sure there's exactly one
294 if ( count( $infos ) > 1 ) {
295 throw new \
UnexpectedValueException(
296 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
298 } elseif ( count( $infos ) < 1 ) {
299 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
302 return $this->getSessionFromInfo( $infos[0], $request );
305 public function getVaryHeaders() {
306 if ( $this->varyHeaders
=== null ) {
308 foreach ( $this->getProviders() as $provider ) {
309 foreach ( $provider->getVaryHeaders() as $header => $options ) {
310 if ( !isset( $headers[$header] ) ) {
311 $headers[$header] = array();
313 if ( is_array( $options ) ) {
314 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
318 $this->varyHeaders
= $headers;
320 return $this->varyHeaders
;
323 public function getVaryCookies() {
324 if ( $this->varyCookies
=== null ) {
326 foreach ( $this->getProviders() as $provider ) {
327 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
329 $this->varyCookies
= array_values( array_unique( $cookies ) );
331 return $this->varyCookies
;
335 * Validate a session ID
339 public static function validateSessionId( $id ) {
340 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
344 * @name Internal methods
349 * Auto-create the given user, if necessary
350 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
351 * @note This more properly belongs in AuthManager, but we need it now.
352 * When AuthManager comes, this will be deprecated and will pass-through
353 * to the corresponding AuthManager method.
354 * @param User $user User to auto-create
355 * @return bool Success
357 public static function autoCreateUser( User
$user ) {
360 $logger = self
::singleton()->logger
;
362 // Much of this code is based on that in CentralAuth
364 // Try the local user from the slave DB
365 $localId = User
::idFromName( $user->getName() );
367 // Fetch the user ID from the master, so that we don't try to create the user
368 // when they already exist, due to replication lag
369 // @codeCoverageIgnoreStart
370 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
371 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
373 // @codeCoverageIgnoreEnd
376 // User exists after all.
377 $user->setId( $localId );
382 // Denied by AuthPlugin? But ignore AuthPlugin itself.
383 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
384 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
390 // Wiki is read-only?
391 if ( wfReadOnly() ) {
392 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
398 $userName = $user->getName();
400 // Check the session, if we tried to create this user already there's
401 // no point in retrying.
402 $session = self
::getGlobalSession();
403 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
405 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
411 // Is the IP user able to create accounts?
413 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
414 ||
$anon->isBlockedFromCreateAccount()
416 // Blacklist the user to avoid repeated DB queries subsequently
417 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
418 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
425 // Check for validity of username
426 if ( !User
::isCreatableName( $userName ) ) {
427 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
428 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
435 // Give other extensions a chance to stop auto creation.
436 $user->loadDefaults( $userName );
438 if ( !\Hooks
::run( 'AbortAutoAccount', array( $user, &$abortMessage ) ) ) {
439 // In this case we have no way to return the message to the user,
440 // but we can log it.
441 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
442 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
449 // Make sure the name has not been changed
450 if ( $user->getName() !== $userName ) {
453 throw new \
UnexpectedValueException(
454 'AbortAutoAccount hook tried to change the user name'
458 // Ignore warnings about master connections/writes...hard to avoid here
459 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
461 $cache = \ObjectCache
::getLocalClusterInstance();
462 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
463 if ( $cache->get( $backoffKey ) ) {
464 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
470 // Checks passed, create the user...
471 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
472 $logger->info( __METHOD__
. ": creating new user ($userName) - from: $from" );
475 // Insert the user into the local DB master
476 $status = $user->addToDatabase();
477 if ( !$status->isOK() ) {
478 // @codeCoverageIgnoreStart
479 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText() );
483 // @codeCoverageIgnoreEnd
485 } catch ( \Exception
$ex ) {
486 // @codeCoverageIgnoreStart
487 $logger->error( __METHOD__
. ': failed with exception ' . $ex->getMessage() );
488 // Do not keep throwing errors for a while
489 $cache->set( $backoffKey, 1, 600 );
490 // Bubble up error; which should normally trigger DB rollbacks
492 // @codeCoverageIgnoreEnd
495 # Notify hooks (e.g. Newuserlog)
496 \Hooks
::run( 'AuthPluginAutoCreate', array( $user ) );
497 \Hooks
::run( 'LocalUserCreated', array( $user, true ) );
499 # Notify AuthPlugin too
501 $wgAuth->initUser( $tmpUser, true );
502 if ( $tmpUser !== $user ) {
503 $logger->warning( __METHOD__
. ': ' .
504 get_class( $wgAuth ) . '::initUser() replaced the user object' );
507 $user->saveSettings();
510 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
512 # Watch user's userpage and talk page
513 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
519 * Prevent future sessions for the user
521 * The intention is that the named account will never again be usable for
522 * normal login (i.e. there is no way to undo the prevention of access).
524 * @private For use from \\User::newSystemUser only
525 * @param string $username
527 public function preventSessionsForUser( $username ) {
528 $this->preventUsers
[$username] = true;
530 // Reset the user's token to kill existing sessions
531 $user = User
::newFromName( $username );
532 if ( $user && $user->getToken() ) {
533 $user->setToken( true );
534 $user->saveSettings();
537 // Instruct the session providers to kill any other sessions too.
538 foreach ( $this->getProviders() as $provider ) {
539 $provider->preventSessionsForUser( $username );
544 * Test if a user is prevented
545 * @private For use from SessionBackend only
546 * @param string $username
549 public function isUserSessionPrevented( $username ) {
550 return !empty( $this->preventUsers
[$username] );
554 * Get the available SessionProviders
555 * @return SessionProvider[]
557 protected function getProviders() {
558 if ( $this->sessionProviders
=== null ) {
559 $this->sessionProviders
= array();
560 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
561 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
562 $provider->setLogger( $this->logger
);
563 $provider->setConfig( $this->config
);
564 $provider->setManager( $this );
565 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
566 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
568 $this->sessionProviders
[(string)$provider] = $provider;
571 return $this->sessionProviders
;
575 * Get a session provider by name
577 * Generally, this will only be used by internal implementation of some
578 * special session-providing mechanism. General purpose code, if it needs
579 * to access a SessionProvider at all, will use Session::getProvider().
581 * @param string $name
582 * @return SessionProvider|null
584 public function getProvider( $name ) {
585 $providers = $this->getProviders();
586 return isset( $providers[$name] ) ?
$providers[$name] : null;
590 * Save all active sessions on shutdown
591 * @private For internal use with register_shutdown_function()
593 public function shutdown() {
594 if ( $this->allSessionBackends
) {
595 $this->logger
->debug( 'Saving all sessions on shutdown' );
596 if ( session_id() !== '' ) {
597 // @codeCoverageIgnoreStart
598 session_write_close();
600 // @codeCoverageIgnoreEnd
601 foreach ( $this->allSessionBackends
as $backend ) {
602 $backend->save( true );
608 * Fetch the SessionInfo(s) for a request
609 * @param WebRequest $request
610 * @return SessionInfo|null
612 private function getSessionInfoForRequest( WebRequest
$request ) {
613 // Call all providers to fetch "the" session
615 foreach ( $this->getProviders() as $provider ) {
616 $info = $provider->provideSessionInfo( $request );
620 if ( $info->getProvider() !== $provider ) {
621 throw new \
UnexpectedValueException(
622 "$provider returned session info for a different provider: $info"
628 // Sort the SessionInfos. Then find the first one that can be
629 // successfully loaded, and then all the ones after it with the same
631 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
634 $info = array_pop( $infos );
635 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
638 $info = array_pop( $infos );
639 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
640 // We hit a lower priority, stop checking.
643 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
644 // This is going to error out below, but we want to
645 // provide a complete list.
652 if ( count( $retInfos ) > 1 ) {
653 $ex = new \
OverflowException(
654 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
656 $ex->sessionInfos
= $retInfos;
660 return $retInfos ?
$retInfos[0] : null;
664 * Load and verify the session info against the store
666 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
667 * @param WebRequest $request
668 * @return bool Whether the session info matches the stored data (if any)
670 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
671 $key = wfMemcKey( 'MWSession', $info->getId() );
672 $blob = $this->store
->get( $key );
674 $newParams = array();
676 if ( $blob !== false ) {
677 // Sanity check: blob must be an array, if it's saved at all
678 if ( !is_array( $blob ) ) {
679 $this->logger
->warning( "Session $info: Bad data" );
680 $this->store
->delete( $key );
684 // Sanity check: blob has data and metadata arrays
685 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
686 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
688 $this->logger
->warning( "Session $info: Bad data structure" );
689 $this->store
->delete( $key );
693 $data = $blob['data'];
694 $metadata = $blob['metadata'];
696 // Sanity check: metadata must be an array and must contain certain
697 // keys, if it's saved at all
698 if ( !array_key_exists( 'userId', $metadata ) ||
699 !array_key_exists( 'userName', $metadata ) ||
700 !array_key_exists( 'userToken', $metadata ) ||
701 !array_key_exists( 'provider', $metadata )
703 $this->logger
->warning( "Session $info: Bad metadata" );
704 $this->store
->delete( $key );
708 // First, load the provider from metadata, or validate it against the metadata.
709 $provider = $info->getProvider();
710 if ( $provider === null ) {
711 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
713 $this->logger
->warning( "Session $info: Unknown provider, " . $metadata['provider'] );
714 $this->store
->delete( $key );
717 } elseif ( $metadata['provider'] !== (string)$provider ) {
718 $this->logger
->warning( "Session $info: Wrong provider, " .
719 $metadata['provider'] . ' !== ' . $provider );
723 // Load provider metadata from metadata, or validate it against the metadata
724 $providerMetadata = $info->getProviderMetadata();
725 if ( isset( $metadata['providerMetadata'] ) ) {
726 if ( $providerMetadata === null ) {
727 $newParams['metadata'] = $metadata['providerMetadata'];
730 $newProviderMetadata = $provider->mergeMetadata(
731 $metadata['providerMetadata'], $providerMetadata
733 if ( $newProviderMetadata !== $providerMetadata ) {
734 $newParams['metadata'] = $newProviderMetadata;
736 } catch ( \UnexpectedValueException
$ex ) {
737 $this->logger
->warning( "Session $info: Metadata merge failed: " . $ex->getMessage() );
743 // Next, load the user from metadata, or validate it against the metadata.
744 $userInfo = $info->getUserInfo();
746 // For loading, id is preferred to name.
748 if ( $metadata['userId'] ) {
749 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
750 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
751 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
753 $userInfo = UserInfo
::newAnonymous();
755 } catch ( \InvalidArgumentException
$ex ) {
756 $this->logger
->error( "Session $info: " . $ex->getMessage() );
759 $newParams['userInfo'] = $userInfo;
761 // User validation passes if user ID matches, or if there
762 // is no saved ID and the names match.
763 if ( $metadata['userId'] ) {
764 if ( $metadata['userId'] !== $userInfo->getId() ) {
765 $this->logger
->warning( "Session $info: User ID mismatch, " .
766 $metadata['userId'] . ' !== ' . $userInfo->getId() );
770 // If the user was renamed, probably best to fail here.
771 if ( $metadata['userName'] !== null &&
772 $userInfo->getName() !== $metadata['userName']
774 $this->logger
->warning( "Session $info: User ID matched but name didn't (rename?), " .
775 $metadata['userName'] . ' !== ' . $userInfo->getName() );
779 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
780 if ( $metadata['userName'] !== $userInfo->getName() ) {
781 $this->logger
->warning( "Session $info: User name mismatch, " .
782 $metadata['userName'] . ' !== ' . $userInfo->getName() );
785 } elseif ( !$userInfo->isAnon() ) {
786 // Metadata specifies an anonymous user, but the passed-in
787 // user isn't anonymous.
788 $this->logger
->warning(
789 "Session $info: Metadata has an anonymous user, " .
790 'but a non-anon user was provided'
796 // And if we have a token in the metadata, it must match the loaded/provided user.
797 if ( $metadata['userToken'] !== null &&
798 $userInfo->getToken() !== $metadata['userToken']
800 $this->logger
->warning( "Session $info: User token mismatch" );
803 if ( !$userInfo->isVerified() ) {
804 $newParams['userInfo'] = $userInfo->verified();
807 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
808 $newParams['remembered'] = true;
810 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
811 $newParams['forceHTTPS'] = true;
814 if ( !$info->isIdSafe() ) {
815 $newParams['idIsSafe'] = true;
818 // No metadata, so we can't load the provider if one wasn't given.
819 if ( $info->getProvider() === null ) {
820 $this->logger
->warning( "Session $info: Null provider and no metadata" );
824 // If no user was provided and no metadata, it must be anon.
825 if ( !$info->getUserInfo() ) {
826 if ( $info->getProvider()->canChangeUser() ) {
827 $newParams['userInfo'] = UserInfo
::newAnonymous();
830 "Session $info: No user provided and provider cannot set user"
834 } elseif ( !$info->getUserInfo()->isVerified() ) {
835 $this->logger
->warning(
836 "Session $info: Unverified user provided and no metadata to auth it"
844 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
845 // The ID doesn't come from the user, so it should be safe
846 // (and if not, nothing we can do about it anyway)
847 $newParams['idIsSafe'] = true;
851 // Construct the replacement SessionInfo, if necessary
853 $newParams['copyFrom'] = $info;
854 $info = new SessionInfo( $info->getPriority(), $newParams );
857 // Allow the provider to check the loaded SessionInfo
858 $providerMetadata = $info->getProviderMetadata();
859 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
862 if ( $providerMetadata !== $info->getProviderMetadata() ) {
863 $info = new SessionInfo( $info->getPriority(), array(
864 'metadata' => $providerMetadata,
869 // Give hooks a chance to abort. Combined with the SessionMetadata
870 // hook, this can allow for tying a session to an IP address or the
872 $reason = 'Hook aborted';
875 array( &$reason, $info, $request, $metadata, $data )
877 $this->logger
->warning( "Session $info: $reason" );
885 * Create a session corresponding to the passed SessionInfo
886 * @private For use by a SessionProvider that needs to specially create its
888 * @param SessionInfo $info
889 * @param WebRequest $request
892 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
893 $id = $info->getId();
895 if ( !isset( $this->allSessionBackends
[$id] ) ) {
896 if ( !isset( $this->allSessionIds
[$id] ) ) {
897 $this->allSessionIds
[$id] = new SessionId( $id );
899 $backend = new SessionBackend(
900 $this->allSessionIds
[$id],
904 $this->config
->get( 'ObjectCacheSessionExpiry' )
906 $this->allSessionBackends
[$id] = $backend;
907 $delay = $backend->delaySave();
909 $backend = $this->allSessionBackends
[$id];
910 $delay = $backend->delaySave();
911 if ( $info->wasPersisted() ) {
914 if ( $info->wasRemembered() ) {
915 $backend->setRememberUser( true );
919 $request->setSessionId( $backend->getSessionId() );
920 $session = $backend->getSession( $request );
922 if ( !$info->isIdSafe() ) {
926 \ScopedCallback
::consume( $delay );
931 * Deregister a SessionBackend
932 * @private For use from \\MediaWiki\\Session\\SessionBackend only
933 * @param SessionBackend $backend
935 public function deregisterSessionBackend( SessionBackend
$backend ) {
936 $id = $backend->getId();
937 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
938 $this->allSessionBackends
[$id] !== $backend ||
939 $this->allSessionIds
[$id] !== $backend->getSessionId()
941 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
944 unset( $this->allSessionBackends
[$id] );
945 // Explicitly do not unset $this->allSessionIds[$id]
949 * Change a SessionBackend's ID
950 * @private For use from \\MediaWiki\\Session\\SessionBackend only
951 * @param SessionBackend $backend
953 public function changeBackendId( SessionBackend
$backend ) {
954 $sessionId = $backend->getSessionId();
955 $oldId = (string)$sessionId;
956 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
957 $this->allSessionBackends
[$oldId] !== $backend ||
958 $this->allSessionIds
[$oldId] !== $sessionId
960 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
963 $newId = $this->generateSessionId();
965 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
966 $sessionId->setId( $newId );
967 $this->allSessionBackends
[$newId] = $backend;
968 $this->allSessionIds
[$newId] = $sessionId;
972 * Generate a new random session ID
975 public function generateSessionId() {
977 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
978 $key = wfMemcKey( 'MWSession', $id );
979 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
984 * Call setters on a PHPSessionHandler
985 * @private Use PhpSessionHandler::install()
986 * @param PHPSessionHandler $handler
988 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
989 $handler->setManager( $this, $this->store
, $this->logger
);
993 * Reset the internal caching for unit testing
995 public static function resetCache() {
996 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
997 // @codeCoverageIgnoreStart
998 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
999 // @codeCoverageIgnoreEnd
1002 self
::$globalSession = null;
1003 self
::$globalSessionRequest = null;