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 getSessionForRequest( WebRequest
$request ) {
182 $info = $this->getSessionInfoForRequest( $request );
185 $session = $this->getEmptySession( $request );
187 $session = $this->getSessionFromInfo( $info, $request );
192 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
193 if ( !self
::validateSessionId( $id ) ) {
194 throw new \
InvalidArgumentException( 'Invalid session ID' );
197 $request = new FauxRequest
;
202 // Test this here to provide a better log message for the common case
204 $key = wfMemcKey( 'MWSession', $id );
205 if ( is_array( $this->store
->get( $key ) ) ) {
206 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array( '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( __METHOD__
. ': failed to create empty session: ' .
226 public function getEmptySession( WebRequest
$request = null ) {
227 return $this->getEmptySessionInternal( $request );
231 * @see SessionManagerInterface::getEmptySession
232 * @param WebRequest|null $request
233 * @param string|null $id ID to force on the new session
236 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
237 if ( $id !== null ) {
238 if ( !self
::validateSessionId( $id ) ) {
239 throw new \
InvalidArgumentException( 'Invalid session ID' );
242 $key = wfMemcKey( 'MWSession', $id );
243 if ( is_array( $this->store
->get( $key ) ) ) {
244 throw new \
InvalidArgumentException( 'Session ID already exists' );
248 $request = new FauxRequest
;
252 foreach ( $this->getProviders() as $provider ) {
253 $info = $provider->newSessionInfo( $id );
257 if ( $info->getProvider() !== $provider ) {
258 throw new \
UnexpectedValueException(
259 "$provider returned an empty session info for a different provider: $info"
262 if ( $id !== null && $info->getId() !== $id ) {
263 throw new \
UnexpectedValueException(
264 "$provider returned empty session info with a wrong id: " .
265 $info->getId() . ' != ' . $id
268 if ( !$info->isIdSafe() ) {
269 throw new \
UnexpectedValueException(
270 "$provider returned empty session info with id flagged unsafe"
273 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
274 if ( $compare > 0 ) {
277 if ( $compare === 0 ) {
280 $infos = array( $info );
284 // Make sure there's exactly one
285 if ( count( $infos ) > 1 ) {
286 throw new \
UnexpectedValueException(
287 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
289 } elseif ( count( $infos ) < 1 ) {
290 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
293 return $this->getSessionFromInfo( $infos[0], $request );
296 public function getVaryHeaders() {
297 if ( $this->varyHeaders
=== null ) {
299 foreach ( $this->getProviders() as $provider ) {
300 foreach ( $provider->getVaryHeaders() as $header => $options ) {
301 if ( !isset( $headers[$header] ) ) {
302 $headers[$header] = array();
304 if ( is_array( $options ) ) {
305 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
309 $this->varyHeaders
= $headers;
311 return $this->varyHeaders
;
314 public function getVaryCookies() {
315 if ( $this->varyCookies
=== null ) {
317 foreach ( $this->getProviders() as $provider ) {
318 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
320 $this->varyCookies
= array_values( array_unique( $cookies ) );
322 return $this->varyCookies
;
326 * Validate a session ID
330 public static function validateSessionId( $id ) {
331 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
335 * @name Internal methods
340 * Auto-create the given user, if necessary
341 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
342 * @note This more properly belongs in AuthManager, but we need it now.
343 * When AuthManager comes, this will be deprecated and will pass-through
344 * to the corresponding AuthManager method.
345 * @param User $user User to auto-create
346 * @return bool Success
348 public static function autoCreateUser( User
$user ) {
351 $logger = self
::singleton()->logger
;
353 // Much of this code is based on that in CentralAuth
355 // Try the local user from the slave DB
356 $localId = User
::idFromName( $user->getName() );
358 // Fetch the user ID from the master, so that we don't try to create the user
359 // when they already exist, due to replication lag
360 // @codeCoverageIgnoreStart
361 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
362 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
364 // @codeCoverageIgnoreEnd
367 // User exists after all.
368 $user->setId( $localId );
373 // Denied by AuthPlugin? But ignore AuthPlugin itself.
374 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
375 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
381 // Wiki is read-only?
382 if ( wfReadOnly() ) {
383 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
389 $userName = $user->getName();
391 // Check the session, if we tried to create this user already there's
392 // no point in retrying.
393 $session = self
::getGlobalSession();
394 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
396 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
402 // Is the IP user able to create accounts?
404 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
405 ||
$anon->isBlockedFromCreateAccount()
407 // Blacklist the user to avoid repeated DB queries subsequently
408 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
409 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
416 // Check for validity of username
417 if ( !User
::isCreatableName( $userName ) ) {
418 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
419 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
426 // Give other extensions a chance to stop auto creation.
427 $user->loadDefaults( $userName );
429 if ( !\Hooks
::run( 'AbortAutoAccount', array( $user, &$abortMessage ) ) ) {
430 // In this case we have no way to return the message to the user,
431 // but we can log it.
432 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
433 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
440 // Make sure the name has not been changed
441 if ( $user->getName() !== $userName ) {
444 throw new \
UnexpectedValueException(
445 'AbortAutoAccount hook tried to change the user name'
449 // Ignore warnings about master connections/writes...hard to avoid here
450 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
452 $cache = \ObjectCache
::getLocalClusterInstance();
453 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
454 if ( $cache->get( $backoffKey ) ) {
455 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
461 // Checks passed, create the user...
462 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
463 $logger->info( __METHOD__
. ": creating new user ($userName) - from: $from" );
466 // Insert the user into the local DB master
467 $status = $user->addToDatabase();
468 if ( !$status->isOK() ) {
469 // @codeCoverageIgnoreStart
470 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText() );
474 // @codeCoverageIgnoreEnd
476 } catch ( \Exception
$ex ) {
477 // @codeCoverageIgnoreStart
478 $logger->error( __METHOD__
. ': failed with exception ' . $ex->getMessage() );
479 // Do not keep throwing errors for a while
480 $cache->set( $backoffKey, 1, 600 );
481 // Bubble up error; which should normally trigger DB rollbacks
483 // @codeCoverageIgnoreEnd
486 # Notify hooks (e.g. Newuserlog)
487 \Hooks
::run( 'AuthPluginAutoCreate', array( $user ) );
488 \Hooks
::run( 'LocalUserCreated', array( $user, true ) );
490 # Notify AuthPlugin too
492 $wgAuth->initUser( $tmpUser, true );
493 if ( $tmpUser !== $user ) {
494 $logger->warning( __METHOD__
. ': ' .
495 get_class( $wgAuth ) . '::initUser() replaced the user object' );
498 $user->saveSettings();
501 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
503 # Watch user's userpage and talk page
504 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
510 * Prevent future sessions for the user
512 * The intention is that the named account will never again be usable for
513 * normal login (i.e. there is no way to undo the prevention of access).
515 * @private For use from \\User::newSystemUser only
516 * @param string $username
518 public function preventSessionsForUser( $username ) {
519 $this->preventUsers
[$username] = true;
521 // Reset the user's token to kill existing sessions
522 $user = User
::newFromName( $username );
523 if ( $user && $user->getToken() ) {
524 $user->setToken( true );
525 $user->saveSettings();
528 // Instruct the session providers to kill any other sessions too.
529 foreach ( $this->getProviders() as $provider ) {
530 $provider->preventSessionsForUser( $username );
535 * Test if a user is prevented
536 * @private For use from SessionBackend only
537 * @param string $username
540 public function isUserSessionPrevented( $username ) {
541 return !empty( $this->preventUsers
[$username] );
545 * Get the available SessionProviders
546 * @return SessionProvider[]
548 protected function getProviders() {
549 if ( $this->sessionProviders
=== null ) {
550 $this->sessionProviders
= array();
551 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
552 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
553 $provider->setLogger( $this->logger
);
554 $provider->setConfig( $this->config
);
555 $provider->setManager( $this );
556 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
557 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
559 $this->sessionProviders
[(string)$provider] = $provider;
562 return $this->sessionProviders
;
566 * Get a session provider by name
568 * Generally, this will only be used by internal implementation of some
569 * special session-providing mechanism. General purpose code, if it needs
570 * to access a SessionProvider at all, will use Session::getProvider().
572 * @param string $name
573 * @return SessionProvider|null
575 public function getProvider( $name ) {
576 $providers = $this->getProviders();
577 return isset( $providers[$name] ) ?
$providers[$name] : null;
581 * Save all active sessions on shutdown
582 * @private For internal use with register_shutdown_function()
584 public function shutdown() {
585 if ( $this->allSessionBackends
) {
586 $this->logger
->debug( 'Saving all sessions on shutdown' );
587 if ( session_id() !== '' ) {
588 // @codeCoverageIgnoreStart
589 session_write_close();
591 // @codeCoverageIgnoreEnd
592 foreach ( $this->allSessionBackends
as $backend ) {
593 $backend->save( true );
599 * Fetch the SessionInfo(s) for a request
600 * @param WebRequest $request
601 * @return SessionInfo|null
603 private function getSessionInfoForRequest( WebRequest
$request ) {
604 // Call all providers to fetch "the" session
606 foreach ( $this->getProviders() as $provider ) {
607 $info = $provider->provideSessionInfo( $request );
611 if ( $info->getProvider() !== $provider ) {
612 throw new \
UnexpectedValueException(
613 "$provider returned session info for a different provider: $info"
619 // Sort the SessionInfos. Then find the first one that can be
620 // successfully loaded, and then all the ones after it with the same
622 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
625 $info = array_pop( $infos );
626 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
629 $info = array_pop( $infos );
630 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
631 // We hit a lower priority, stop checking.
634 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
635 // This is going to error out below, but we want to
636 // provide a complete list.
643 if ( count( $retInfos ) > 1 ) {
644 $ex = new \
OverflowException(
645 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
647 $ex->sessionInfos
= $retInfos;
651 return $retInfos ?
$retInfos[0] : null;
655 * Load and verify the session info against the store
657 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
658 * @param WebRequest $request
659 * @return bool Whether the session info matches the stored data (if any)
661 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
662 $key = wfMemcKey( 'MWSession', $info->getId() );
663 $blob = $this->store
->get( $key );
665 $newParams = array();
667 if ( $blob !== false ) {
668 // Sanity check: blob must be an array, if it's saved at all
669 if ( !is_array( $blob ) ) {
670 $this->logger
->warning( "Session $info: Bad data" );
671 $this->store
->delete( $key );
675 // Sanity check: blob has data and metadata arrays
676 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
677 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
679 $this->logger
->warning( "Session $info: Bad data structure" );
680 $this->store
->delete( $key );
684 $data = $blob['data'];
685 $metadata = $blob['metadata'];
687 // Sanity check: metadata must be an array and must contain certain
688 // keys, if it's saved at all
689 if ( !array_key_exists( 'userId', $metadata ) ||
690 !array_key_exists( 'userName', $metadata ) ||
691 !array_key_exists( 'userToken', $metadata ) ||
692 !array_key_exists( 'provider', $metadata )
694 $this->logger
->warning( "Session $info: Bad metadata" );
695 $this->store
->delete( $key );
699 // First, load the provider from metadata, or validate it against the metadata.
700 $provider = $info->getProvider();
701 if ( $provider === null ) {
702 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
704 $this->logger
->warning( "Session $info: Unknown provider, " . $metadata['provider'] );
705 $this->store
->delete( $key );
708 } elseif ( $metadata['provider'] !== (string)$provider ) {
709 $this->logger
->warning( "Session $info: Wrong provider, " .
710 $metadata['provider'] . ' !== ' . $provider );
714 // Load provider metadata from metadata, or validate it against the metadata
715 $providerMetadata = $info->getProviderMetadata();
716 if ( isset( $metadata['providerMetadata'] ) ) {
717 if ( $providerMetadata === null ) {
718 $newParams['metadata'] = $metadata['providerMetadata'];
721 $newProviderMetadata = $provider->mergeMetadata(
722 $metadata['providerMetadata'], $providerMetadata
724 if ( $newProviderMetadata !== $providerMetadata ) {
725 $newParams['metadata'] = $newProviderMetadata;
727 } catch ( \UnexpectedValueException
$ex ) {
728 $this->logger
->warning( "Session $info: Metadata merge failed: " . $ex->getMessage() );
734 // Next, load the user from metadata, or validate it against the metadata.
735 $userInfo = $info->getUserInfo();
737 // For loading, id is preferred to name.
739 if ( $metadata['userId'] ) {
740 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
741 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
742 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
744 $userInfo = UserInfo
::newAnonymous();
746 } catch ( \InvalidArgumentException
$ex ) {
747 $this->logger
->error( "Session $info: " . $ex->getMessage() );
750 $newParams['userInfo'] = $userInfo;
752 // User validation passes if user ID matches, or if there
753 // is no saved ID and the names match.
754 if ( $metadata['userId'] ) {
755 if ( $metadata['userId'] !== $userInfo->getId() ) {
756 $this->logger
->warning( "Session $info: User ID mismatch, " .
757 $metadata['userId'] . ' !== ' . $userInfo->getId() );
761 // If the user was renamed, probably best to fail here.
762 if ( $metadata['userName'] !== null &&
763 $userInfo->getName() !== $metadata['userName']
765 $this->logger
->warning( "Session $info: User ID matched but name didn't (rename?), " .
766 $metadata['userName'] . ' !== ' . $userInfo->getName() );
770 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
771 if ( $metadata['userName'] !== $userInfo->getName() ) {
772 $this->logger
->warning( "Session $info: User name mismatch, " .
773 $metadata['userName'] . ' !== ' . $userInfo->getName() );
776 } elseif ( !$userInfo->isAnon() ) {
777 // Metadata specifies an anonymous user, but the passed-in
778 // user isn't anonymous.
779 $this->logger
->warning(
780 "Session $info: Metadata has an anonymous user, " .
781 'but a non-anon user was provided'
787 // And if we have a token in the metadata, it must match the loaded/provided user.
788 if ( $metadata['userToken'] !== null &&
789 $userInfo->getToken() !== $metadata['userToken']
791 $this->logger
->warning( "Session $info: User token mismatch" );
794 if ( !$userInfo->isVerified() ) {
795 $newParams['userInfo'] = $userInfo->verified();
798 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
799 $newParams['remembered'] = true;
801 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
802 $newParams['forceHTTPS'] = true;
805 if ( !$info->isIdSafe() ) {
806 $newParams['idIsSafe'] = true;
809 // No metadata, so we can't load the provider if one wasn't given.
810 if ( $info->getProvider() === null ) {
811 $this->logger
->warning( "Session $info: Null provider and no metadata" );
815 // If no user was provided and no metadata, it must be anon.
816 if ( !$info->getUserInfo() ) {
817 if ( $info->getProvider()->canChangeUser() ) {
818 $newParams['userInfo'] = UserInfo
::newAnonymous();
821 "Session $info: No user provided and provider cannot set user"
825 } elseif ( !$info->getUserInfo()->isVerified() ) {
826 $this->logger
->warning(
827 "Session $info: Unverified user provided and no metadata to auth it"
835 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
836 // The ID doesn't come from the user, so it should be safe
837 // (and if not, nothing we can do about it anyway)
838 $newParams['idIsSafe'] = true;
842 // Construct the replacement SessionInfo, if necessary
844 $newParams['copyFrom'] = $info;
845 $info = new SessionInfo( $info->getPriority(), $newParams );
848 // Allow the provider to check the loaded SessionInfo
849 $providerMetadata = $info->getProviderMetadata();
850 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
853 if ( $providerMetadata !== $info->getProviderMetadata() ) {
854 $info = new SessionInfo( $info->getPriority(), array(
855 'metadata' => $providerMetadata,
860 // Give hooks a chance to abort. Combined with the SessionMetadata
861 // hook, this can allow for tying a session to an IP address or the
863 $reason = 'Hook aborted';
866 array( &$reason, $info, $request, $metadata, $data )
868 $this->logger
->warning( "Session $info: $reason" );
876 * Create a session corresponding to the passed SessionInfo
877 * @private For use by a SessionProvider that needs to specially create its
879 * @param SessionInfo $info
880 * @param WebRequest $request
883 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
884 $id = $info->getId();
886 if ( !isset( $this->allSessionBackends
[$id] ) ) {
887 if ( !isset( $this->allSessionIds
[$id] ) ) {
888 $this->allSessionIds
[$id] = new SessionId( $id );
890 $backend = new SessionBackend(
891 $this->allSessionIds
[$id],
895 $this->config
->get( 'ObjectCacheSessionExpiry' )
897 $this->allSessionBackends
[$id] = $backend;
898 $delay = $backend->delaySave();
900 $backend = $this->allSessionBackends
[$id];
901 $delay = $backend->delaySave();
902 if ( $info->wasPersisted() ) {
905 if ( $info->wasRemembered() ) {
906 $backend->setRememberUser( true );
910 $request->setSessionId( $backend->getSessionId() );
911 $session = $backend->getSession( $request );
913 if ( !$info->isIdSafe() ) {
917 \ScopedCallback
::consume( $delay );
922 * Deregister a SessionBackend
923 * @private For use from \\MediaWiki\\Session\\SessionBackend only
924 * @param SessionBackend $backend
926 public function deregisterSessionBackend( SessionBackend
$backend ) {
927 $id = $backend->getId();
928 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
929 $this->allSessionBackends
[$id] !== $backend ||
930 $this->allSessionIds
[$id] !== $backend->getSessionId()
932 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
935 unset( $this->allSessionBackends
[$id] );
936 // Explicitly do not unset $this->allSessionIds[$id]
940 * Change a SessionBackend's ID
941 * @private For use from \\MediaWiki\\Session\\SessionBackend only
942 * @param SessionBackend $backend
944 public function changeBackendId( SessionBackend
$backend ) {
945 $sessionId = $backend->getSessionId();
946 $oldId = (string)$sessionId;
947 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
948 $this->allSessionBackends
[$oldId] !== $backend ||
949 $this->allSessionIds
[$oldId] !== $sessionId
951 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
954 $newId = $this->generateSessionId();
956 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
957 $sessionId->setId( $newId );
958 $this->allSessionBackends
[$newId] = $backend;
959 $this->allSessionIds
[$newId] = $sessionId;
963 * Generate a new random session ID
966 public function generateSessionId() {
968 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
969 $key = wfMemcKey( 'MWSession', $id );
970 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
975 * Call setters on a PHPSessionHandler
976 * @private Use PhpSessionHandler::install()
977 * @param PHPSessionHandler $handler
979 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
980 $handler->setManager( $this, $this->store
, $this->logger
);
984 * Reset the internal caching for unit testing
986 public static function resetCache() {
987 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
988 // @codeCoverageIgnoreStart
989 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
990 // @codeCoverageIgnoreEnd
993 self
::$globalSession = null;
994 self
::$globalSessionRequest = null;