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
;
37 * This serves as the entry point to the MediaWiki session handling system.
42 final class SessionManager
implements SessionManagerInterface
{
43 /** @var SessionManager|null */
44 private static $instance = null;
46 /** @var Session|null */
47 private static $globalSession = null;
49 /** @var WebRequest|null */
50 private static $globalSessionRequest = null;
52 /** @var LoggerInterface */
58 /** @var CachedBagOStuff|null */
61 /** @var SessionProvider[] */
62 private $sessionProviders = null;
65 private $varyCookies = null;
68 private $varyHeaders = null;
70 /** @var SessionBackend[] */
71 private $allSessionBackends = array();
73 /** @var SessionId[] */
74 private $allSessionIds = array();
77 private $preventUsers = array();
80 * Get the global SessionManager
81 * @return SessionManagerInterface
82 * (really a SessionManager, but this is to make IDEs less confused)
84 public static function singleton() {
85 if ( self
::$instance === null ) {
86 self
::$instance = new self();
88 return self
::$instance;
92 * Get the "global" session
94 * If PHP's session_id() has been set, returns that session. Otherwise
95 * returns the session for RequestContext::getMain()->getRequest().
99 public static function getGlobalSession() {
100 if ( !PHPSessionHandler
::isEnabled() ) {
106 $request = \RequestContext
::getMain()->getRequest();
108 !self
::$globalSession // No global session is set up yet
109 || self
::$globalSessionRequest !== $request // The global WebRequest changed
110 ||
$id !== '' && self
::$globalSession->getId() !== $id // Someone messed with session_id()
112 self
::$globalSessionRequest = $request;
114 // session_id() wasn't used, so fetch the Session from the WebRequest.
115 // We use $request->getSession() instead of $singleton->getSessionForRequest()
116 // because doing the latter would require a public
117 // "$request->getSessionId()" method that would confuse end
118 // users by returning SessionId|null where they'd expect it to
119 // be short for $request->getSession()->getId(), and would
120 // wind up being a duplicate of the code in
121 // $request->getSession() anyway.
122 self
::$globalSession = $request->getSession();
124 // Someone used session_id(), so we need to follow suit.
125 // Note this overwrites whatever session might already be
126 // associated with $request with the one for $id.
127 self
::$globalSession = self
::singleton()->getSessionById( $id, true, $request )
128 ?
: $request->getSession();
131 return self
::$globalSession;
135 * @param array $options
136 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
137 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
138 * - store: BagOStuff to store session data in.
140 public function __construct( $options = array() ) {
141 if ( isset( $options['config'] ) ) {
142 $this->config
= $options['config'];
143 if ( !$this->config
instanceof Config
) {
144 throw new \
InvalidArgumentException(
145 '$options[\'config\'] must be an instance of Config'
149 $this->config
= \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
152 if ( isset( $options['logger'] ) ) {
153 if ( !$options['logger'] instanceof LoggerInterface
) {
154 throw new \
InvalidArgumentException(
155 '$options[\'logger\'] must be an instance of LoggerInterface'
158 $this->setLogger( $options['logger'] );
160 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' ) );
163 if ( isset( $options['store'] ) ) {
164 if ( !$options['store'] instanceof BagOStuff
) {
165 throw new \
InvalidArgumentException(
166 '$options[\'store\'] must be an instance of BagOStuff'
169 $store = $options['store'];
171 $store = \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
172 $store->setLogger( $this->logger
);
174 $this->store
= $store instanceof CachedBagOStuff ?
$store : new CachedBagOStuff( $store );
176 register_shutdown_function( array( $this, 'shutdown' ) );
179 public function setLogger( LoggerInterface
$logger ) {
180 $this->logger
= $logger;
183 public function getSessionForRequest( WebRequest
$request ) {
184 $info = $this->getSessionInfoForRequest( $request );
187 $session = $this->getEmptySession( $request );
189 $session = $this->getSessionFromInfo( $info, $request );
194 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
195 if ( !self
::validateSessionId( $id ) ) {
196 throw new \
InvalidArgumentException( 'Invalid session ID' );
199 $request = new FauxRequest
;
204 // Test this here to provide a better log message for the common case
206 $key = wfMemcKey( 'MWSession', $id );
207 if ( is_array( $this->store
->get( $key ) ) ) {
208 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array( 'id' => $id, 'idIsSafe' => true ) );
209 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
210 $session = $this->getSessionFromInfo( $info, $request );
214 if ( $create && $session === null ) {
217 $session = $this->getEmptySessionInternal( $request, $id );
218 } catch ( \Exception
$ex ) {
219 $this->logger
->error( __METHOD__
. ': failed to create empty session: ' .
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 ) {
282 $infos = array( $info );
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 if ( $this->varyHeaders
=== null ) {
301 foreach ( $this->getProviders() as $provider ) {
302 foreach ( $provider->getVaryHeaders() as $header => $options ) {
303 if ( !isset( $headers[$header] ) ) {
304 $headers[$header] = array();
306 if ( is_array( $options ) ) {
307 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
311 $this->varyHeaders
= $headers;
313 return $this->varyHeaders
;
316 public function getVaryCookies() {
317 if ( $this->varyCookies
=== null ) {
319 foreach ( $this->getProviders() as $provider ) {
320 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
322 $this->varyCookies
= array_values( array_unique( $cookies ) );
324 return $this->varyCookies
;
328 * Validate a session ID
332 public static function validateSessionId( $id ) {
333 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
337 * @name Internal methods
342 * Auto-create the given user, if necessary
343 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
344 * @note This more properly belongs in AuthManager, but we need it now.
345 * When AuthManager comes, this will be deprecated and will pass-through
346 * to the corresponding AuthManager method.
347 * @param User $user User to auto-create
348 * @return bool Success
350 public static function autoCreateUser( User
$user ) {
353 $logger = self
::singleton()->logger
;
355 // Much of this code is based on that in CentralAuth
357 // Try the local user from the slave DB
358 $localId = User
::idFromName( $user->getName() );
360 // Fetch the user ID from the master, so that we don't try to create the user
361 // when they already exist, due to replication lag
362 // @codeCoverageIgnoreStart
363 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
364 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
366 // @codeCoverageIgnoreEnd
369 // User exists after all.
370 $user->setId( $localId );
375 // Denied by AuthPlugin? But ignore AuthPlugin itself.
376 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
377 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
383 // Wiki is read-only?
384 if ( wfReadOnly() ) {
385 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
391 $userName = $user->getName();
393 // Check the session, if we tried to create this user already there's
394 // no point in retrying.
395 $session = self
::getGlobalSession();
396 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
398 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
404 // Is the IP user able to create accounts?
406 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
407 ||
$anon->isBlockedFromCreateAccount()
409 // Blacklist the user to avoid repeated DB queries subsequently
410 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
411 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
418 // Check for validity of username
419 if ( !User
::isCreatableName( $userName ) ) {
420 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
421 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
428 // Give other extensions a chance to stop auto creation.
429 $user->loadDefaults( $userName );
431 if ( !\Hooks
::run( 'AbortAutoAccount', array( $user, &$abortMessage ) ) ) {
432 // In this case we have no way to return the message to the user,
433 // but we can log it.
434 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
435 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
442 // Make sure the name has not been changed
443 if ( $user->getName() !== $userName ) {
446 throw new \
UnexpectedValueException(
447 'AbortAutoAccount hook tried to change the user name'
451 // Ignore warnings about master connections/writes...hard to avoid here
452 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
454 $cache = \ObjectCache
::getLocalClusterInstance();
455 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
456 if ( $cache->get( $backoffKey ) ) {
457 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
463 // Checks passed, create the user...
464 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
465 $logger->info( __METHOD__
. ": creating new user ($userName) - from: $from" );
468 // Insert the user into the local DB master
469 $status = $user->addToDatabase();
470 if ( !$status->isOK() ) {
471 // @codeCoverageIgnoreStart
472 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText() );
476 // @codeCoverageIgnoreEnd
478 } catch ( \Exception
$ex ) {
479 // @codeCoverageIgnoreStart
480 $logger->error( __METHOD__
. ': failed with exception ' . $ex->getMessage() );
481 // Do not keep throwing errors for a while
482 $cache->set( $backoffKey, 1, 600 );
483 // Bubble up error; which should normally trigger DB rollbacks
485 // @codeCoverageIgnoreEnd
490 $wgAuth->initUser( $tmpUser, true );
491 if ( $tmpUser !== $user ) {
492 $logger->warning( __METHOD__
. ': ' .
493 get_class( $wgAuth ) . '::initUser() replaced the user object' );
496 # Notify hooks (e.g. Newuserlog)
497 \Hooks
::run( 'AuthPluginAutoCreate', array( $user ) );
498 \Hooks
::run( 'LocalUserCreated', array( $user, true ) );
500 $user->saveSettings();
503 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
505 # Watch user's userpage and talk page
506 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
512 * Prevent future sessions for the user
514 * The intention is that the named account will never again be usable for
515 * normal login (i.e. there is no way to undo the prevention of access).
517 * @private For use from \\User::newSystemUser only
518 * @param string $username
520 public function preventSessionsForUser( $username ) {
521 $this->preventUsers
[$username] = true;
523 // Instruct the session providers to kill any other sessions too.
524 foreach ( $this->getProviders() as $provider ) {
525 $provider->preventSessionsForUser( $username );
530 * Test if a user is prevented
531 * @private For use from SessionBackend only
532 * @param string $username
535 public function isUserSessionPrevented( $username ) {
536 return !empty( $this->preventUsers
[$username] );
540 * Get the available SessionProviders
541 * @return SessionProvider[]
543 protected function getProviders() {
544 if ( $this->sessionProviders
=== null ) {
545 $this->sessionProviders
= array();
546 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
547 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
548 $provider->setLogger( $this->logger
);
549 $provider->setConfig( $this->config
);
550 $provider->setManager( $this );
551 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
552 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
554 $this->sessionProviders
[(string)$provider] = $provider;
557 return $this->sessionProviders
;
561 * Get a session provider by name
563 * Generally, this will only be used by internal implementation of some
564 * special session-providing mechanism. General purpose code, if it needs
565 * to access a SessionProvider at all, will use Session::getProvider().
567 * @param string $name
568 * @return SessionProvider|null
570 public function getProvider( $name ) {
571 $providers = $this->getProviders();
572 return isset( $providers[$name] ) ?
$providers[$name] : null;
576 * Save all active sessions on shutdown
577 * @private For internal use with register_shutdown_function()
579 public function shutdown() {
580 if ( $this->allSessionBackends
) {
581 $this->logger
->debug( 'Saving all sessions on shutdown' );
582 if ( session_id() !== '' ) {
583 // @codeCoverageIgnoreStart
584 session_write_close();
586 // @codeCoverageIgnoreEnd
587 foreach ( $this->allSessionBackends
as $backend ) {
588 $backend->save( true );
594 * Fetch the SessionInfo(s) for a request
595 * @param WebRequest $request
596 * @return SessionInfo|null
598 private function getSessionInfoForRequest( WebRequest
$request ) {
599 // Call all providers to fetch "the" session
601 foreach ( $this->getProviders() as $provider ) {
602 $info = $provider->provideSessionInfo( $request );
606 if ( $info->getProvider() !== $provider ) {
607 throw new \
UnexpectedValueException(
608 "$provider returned session info for a different provider: $info"
614 // Sort the SessionInfos. Then find the first one that can be
615 // successfully loaded, and then all the ones after it with the same
617 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
620 $info = array_pop( $infos );
621 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
624 $info = array_pop( $infos );
625 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
626 // We hit a lower priority, stop checking.
629 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
630 // This is going to error out below, but we want to
631 // provide a complete list.
638 if ( count( $retInfos ) > 1 ) {
639 $ex = new \
OverflowException(
640 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
642 $ex->sessionInfos
= $retInfos;
646 return $retInfos ?
$retInfos[0] : null;
650 * Load and verify the session info against the store
652 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
653 * @param WebRequest $request
654 * @return bool Whether the session info matches the stored data (if any)
656 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
657 $key = wfMemcKey( 'MWSession', $info->getId() );
658 $blob = $this->store
->get( $key );
660 $newParams = array();
662 if ( $blob !== false ) {
663 // Sanity check: blob must be an array, if it's saved at all
664 if ( !is_array( $blob ) ) {
665 $this->logger
->warning( "Session $info: Bad data" );
666 $this->store
->delete( $key );
670 // Sanity check: blob has data and metadata arrays
671 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
672 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
674 $this->logger
->warning( "Session $info: Bad data structure" );
675 $this->store
->delete( $key );
679 $data = $blob['data'];
680 $metadata = $blob['metadata'];
682 // Sanity check: metadata must be an array and must contain certain
683 // keys, if it's saved at all
684 if ( !array_key_exists( 'userId', $metadata ) ||
685 !array_key_exists( 'userName', $metadata ) ||
686 !array_key_exists( 'userToken', $metadata ) ||
687 !array_key_exists( 'provider', $metadata )
689 $this->logger
->warning( "Session $info: Bad metadata" );
690 $this->store
->delete( $key );
694 // First, load the provider from metadata, or validate it against the metadata.
695 $provider = $info->getProvider();
696 if ( $provider === null ) {
697 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
699 $this->logger
->warning( "Session $info: Unknown provider, " . $metadata['provider'] );
700 $this->store
->delete( $key );
703 } elseif ( $metadata['provider'] !== (string)$provider ) {
704 $this->logger
->warning( "Session $info: Wrong provider, " .
705 $metadata['provider'] . ' !== ' . $provider );
709 // Load provider metadata from metadata, or validate it against the metadata
710 $providerMetadata = $info->getProviderMetadata();
711 if ( isset( $metadata['providerMetadata'] ) ) {
712 if ( $providerMetadata === null ) {
713 $newParams['metadata'] = $metadata['providerMetadata'];
716 $newProviderMetadata = $provider->mergeMetadata(
717 $metadata['providerMetadata'], $providerMetadata
719 if ( $newProviderMetadata !== $providerMetadata ) {
720 $newParams['metadata'] = $newProviderMetadata;
722 } catch ( \UnexpectedValueException
$ex ) {
723 $this->logger
->warning( "Session $info: Metadata merge failed: " . $ex->getMessage() );
729 // Next, load the user from metadata, or validate it against the metadata.
730 $userInfo = $info->getUserInfo();
732 // For loading, id is preferred to name.
734 if ( $metadata['userId'] ) {
735 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
736 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
737 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
739 $userInfo = UserInfo
::newAnonymous();
741 } catch ( \InvalidArgumentException
$ex ) {
742 $this->logger
->error( "Session $info: " . $ex->getMessage() );
745 $newParams['userInfo'] = $userInfo;
747 // User validation passes if user ID matches, or if there
748 // is no saved ID and the names match.
749 if ( $metadata['userId'] ) {
750 if ( $metadata['userId'] !== $userInfo->getId() ) {
751 $this->logger
->warning( "Session $info: User ID mismatch, " .
752 $metadata['userId'] . ' !== ' . $userInfo->getId() );
756 // If the user was renamed, probably best to fail here.
757 if ( $metadata['userName'] !== null &&
758 $userInfo->getName() !== $metadata['userName']
760 $this->logger
->warning( "Session $info: User ID matched but name didn't (rename?), " .
761 $metadata['userName'] . ' !== ' . $userInfo->getName() );
765 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
766 if ( $metadata['userName'] !== $userInfo->getName() ) {
767 $this->logger
->warning( "Session $info: User name mismatch, " .
768 $metadata['userName'] . ' !== ' . $userInfo->getName() );
771 } elseif ( !$userInfo->isAnon() ) {
772 // Metadata specifies an anonymous user, but the passed-in
773 // user isn't anonymous.
774 $this->logger
->warning(
775 "Session $info: Metadata has an anonymous user, " .
776 'but a non-anon user was provided'
782 // And if we have a token in the metadata, it must match the loaded/provided user.
783 if ( $metadata['userToken'] !== null &&
784 $userInfo->getToken() !== $metadata['userToken']
786 $this->logger
->warning( "Session $info: User token mismatch" );
789 if ( !$userInfo->isVerified() ) {
790 $newParams['userInfo'] = $userInfo->verified();
793 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
794 $newParams['remembered'] = true;
796 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
797 $newParams['forceHTTPS'] = true;
799 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
800 $newParams['persisted'] = true;
803 if ( !$info->isIdSafe() ) {
804 $newParams['idIsSafe'] = true;
807 // No metadata, so we can't load the provider if one wasn't given.
808 if ( $info->getProvider() === null ) {
809 $this->logger
->warning( "Session $info: Null provider and no metadata" );
813 // If no user was provided and no metadata, it must be anon.
814 if ( !$info->getUserInfo() ) {
815 if ( $info->getProvider()->canChangeUser() ) {
816 $newParams['userInfo'] = UserInfo
::newAnonymous();
819 "Session $info: No user provided and provider cannot set user"
823 } elseif ( !$info->getUserInfo()->isVerified() ) {
824 $this->logger
->warning(
825 "Session $info: Unverified user provided and no metadata to auth it"
833 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
834 // The ID doesn't come from the user, so it should be safe
835 // (and if not, nothing we can do about it anyway)
836 $newParams['idIsSafe'] = true;
840 // Construct the replacement SessionInfo, if necessary
842 $newParams['copyFrom'] = $info;
843 $info = new SessionInfo( $info->getPriority(), $newParams );
846 // Allow the provider to check the loaded SessionInfo
847 $providerMetadata = $info->getProviderMetadata();
848 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
851 if ( $providerMetadata !== $info->getProviderMetadata() ) {
852 $info = new SessionInfo( $info->getPriority(), array(
853 'metadata' => $providerMetadata,
858 // Give hooks a chance to abort. Combined with the SessionMetadata
859 // hook, this can allow for tying a session to an IP address or the
861 $reason = 'Hook aborted';
864 array( &$reason, $info, $request, $metadata, $data )
866 $this->logger
->warning( "Session $info: $reason" );
874 * Create a session corresponding to the passed SessionInfo
875 * @private For use by a SessionProvider that needs to specially create its
877 * @param SessionInfo $info
878 * @param WebRequest $request
881 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
882 $id = $info->getId();
884 if ( !isset( $this->allSessionBackends
[$id] ) ) {
885 if ( !isset( $this->allSessionIds
[$id] ) ) {
886 $this->allSessionIds
[$id] = new SessionId( $id );
888 $backend = new SessionBackend(
889 $this->allSessionIds
[$id],
893 $this->config
->get( 'ObjectCacheSessionExpiry' )
895 $this->allSessionBackends
[$id] = $backend;
896 $delay = $backend->delaySave();
898 $backend = $this->allSessionBackends
[$id];
899 $delay = $backend->delaySave();
900 if ( $info->wasPersisted() ) {
903 if ( $info->wasRemembered() ) {
904 $backend->setRememberUser( true );
908 $request->setSessionId( $backend->getSessionId() );
909 $session = $backend->getSession( $request );
911 if ( !$info->isIdSafe() ) {
915 \ScopedCallback
::consume( $delay );
920 * Deregister a SessionBackend
921 * @private For use from \\MediaWiki\\Session\\SessionBackend only
922 * @param SessionBackend $backend
924 public function deregisterSessionBackend( SessionBackend
$backend ) {
925 $id = $backend->getId();
926 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
927 $this->allSessionBackends
[$id] !== $backend ||
928 $this->allSessionIds
[$id] !== $backend->getSessionId()
930 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
933 unset( $this->allSessionBackends
[$id] );
934 // Explicitly do not unset $this->allSessionIds[$id]
938 * Change a SessionBackend's ID
939 * @private For use from \\MediaWiki\\Session\\SessionBackend only
940 * @param SessionBackend $backend
942 public function changeBackendId( SessionBackend
$backend ) {
943 $sessionId = $backend->getSessionId();
944 $oldId = (string)$sessionId;
945 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
946 $this->allSessionBackends
[$oldId] !== $backend ||
947 $this->allSessionIds
[$oldId] !== $sessionId
949 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
952 $newId = $this->generateSessionId();
954 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
955 $sessionId->setId( $newId );
956 $this->allSessionBackends
[$newId] = $backend;
957 $this->allSessionIds
[$newId] = $sessionId;
961 * Generate a new random session ID
964 public function generateSessionId() {
966 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
967 $key = wfMemcKey( 'MWSession', $id );
968 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
973 * Call setters on a PHPSessionHandler
974 * @private Use PhpSessionHandler::install()
975 * @param PHPSessionHandler $handler
977 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
978 $handler->setManager( $this, $this->store
, $this->logger
);
982 * Reset the internal caching for unit testing
984 public static function resetCache() {
985 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
986 // @codeCoverageIgnoreStart
987 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
988 // @codeCoverageIgnoreEnd
991 self
::$globalSession = null;
992 self
::$globalSessionRequest = null;