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 = array();
71 /** @var SessionId[] */
72 private $allSessionIds = array();
75 private $preventUsers = array();
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 = array() ) {
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' ) );
170 $store->setLogger( $this->logger
);
172 $this->store
= $store instanceof CachedBagOStuff ?
$store : new CachedBagOStuff( $store );
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( '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 ) {
283 $infos = array( $info );
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 if ( $this->varyHeaders
=== null ) {
302 foreach ( $this->getProviders() as $provider ) {
303 foreach ( $provider->getVaryHeaders() as $header => $options ) {
304 if ( !isset( $headers[$header] ) ) {
305 $headers[$header] = array();
307 if ( is_array( $options ) ) {
308 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
312 $this->varyHeaders
= $headers;
314 return $this->varyHeaders
;
317 public function getVaryCookies() {
318 if ( $this->varyCookies
=== null ) {
320 foreach ( $this->getProviders() as $provider ) {
321 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
323 $this->varyCookies
= array_values( array_unique( $cookies ) );
325 return $this->varyCookies
;
329 * Validate a session ID
333 public static function validateSessionId( $id ) {
334 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
338 * @name Internal methods
343 * Auto-create the given user, if necessary
344 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
345 * @note This more properly belongs in AuthManager, but we need it now.
346 * When AuthManager comes, this will be deprecated and will pass-through
347 * to the corresponding AuthManager method.
348 * @param User $user User to auto-create
349 * @return bool Success
351 public static function autoCreateUser( User
$user ) {
354 $logger = self
::singleton()->logger
;
356 // Much of this code is based on that in CentralAuth
358 // Try the local user from the slave DB
359 $localId = User
::idFromName( $user->getName() );
361 // Fetch the user ID from the master, so that we don't try to create the user
362 // when they already exist, due to replication lag
363 // @codeCoverageIgnoreStart
364 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
365 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
367 // @codeCoverageIgnoreEnd
370 // User exists after all.
371 $user->setId( $localId );
376 // Denied by AuthPlugin? But ignore AuthPlugin itself.
377 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
378 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
384 // Wiki is read-only?
385 if ( wfReadOnly() ) {
386 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
392 $userName = $user->getName();
394 // Check the session, if we tried to create this user already there's
395 // no point in retrying.
396 $session = self
::getGlobalSession();
397 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
399 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
405 // Is the IP user able to create accounts?
407 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
408 ||
$anon->isBlockedFromCreateAccount()
410 // Blacklist the user to avoid repeated DB queries subsequently
411 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
412 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
419 // Check for validity of username
420 if ( !User
::isCreatableName( $userName ) ) {
421 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
422 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
429 // Give other extensions a chance to stop auto creation.
430 $user->loadDefaults( $userName );
432 if ( !\Hooks
::run( 'AbortAutoAccount', array( $user, &$abortMessage ) ) ) {
433 // In this case we have no way to return the message to the user,
434 // but we can log it.
435 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
436 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
443 // Make sure the name has not been changed
444 if ( $user->getName() !== $userName ) {
447 throw new \
UnexpectedValueException(
448 'AbortAutoAccount hook tried to change the user name'
452 // Ignore warnings about master connections/writes...hard to avoid here
453 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
455 $cache = \ObjectCache
::getLocalClusterInstance();
456 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
457 if ( $cache->get( $backoffKey ) ) {
458 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
464 // Checks passed, create the user...
465 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
466 $logger->info( __METHOD__
. ': creating new user ({username}) - from: {url}',
468 'username' => $userName,
473 // Insert the user into the local DB master
474 $status = $user->addToDatabase();
475 if ( !$status->isOK() ) {
476 // @codeCoverageIgnoreStart
477 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText(),
479 'username' => $userName,
484 // @codeCoverageIgnoreEnd
486 } catch ( \Exception
$ex ) {
487 // @codeCoverageIgnoreStart
488 $logger->error( __METHOD__
. ': failed with exception {exception}', array(
490 'username' => $userName,
492 // Do not keep throwing errors for a while
493 $cache->set( $backoffKey, 1, 600 );
494 // Bubble up error; which should normally trigger DB rollbacks
496 // @codeCoverageIgnoreEnd
501 $wgAuth->initUser( $tmpUser, true );
502 if ( $tmpUser !== $user ) {
503 $logger->warning( __METHOD__
. ': ' .
504 get_class( $wgAuth ) . '::initUser() replaced the user object' );
507 # Notify hooks (e.g. Newuserlog)
508 \Hooks
::run( 'AuthPluginAutoCreate', array( $user ) );
509 \Hooks
::run( 'LocalUserCreated', array( $user, true ) );
511 $user->saveSettings();
514 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
516 # Watch user's userpage and talk page
517 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
523 * Prevent future sessions for the user
525 * The intention is that the named account will never again be usable for
526 * normal login (i.e. there is no way to undo the prevention of access).
528 * @private For use from \\User::newSystemUser only
529 * @param string $username
531 public function preventSessionsForUser( $username ) {
532 $this->preventUsers
[$username] = true;
534 // Instruct the session providers to kill any other sessions too.
535 foreach ( $this->getProviders() as $provider ) {
536 $provider->preventSessionsForUser( $username );
541 * Test if a user is prevented
542 * @private For use from SessionBackend only
543 * @param string $username
546 public function isUserSessionPrevented( $username ) {
547 return !empty( $this->preventUsers
[$username] );
551 * Get the available SessionProviders
552 * @return SessionProvider[]
554 protected function getProviders() {
555 if ( $this->sessionProviders
=== null ) {
556 $this->sessionProviders
= array();
557 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
558 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
559 $provider->setLogger( $this->logger
);
560 $provider->setConfig( $this->config
);
561 $provider->setManager( $this );
562 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
563 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
565 $this->sessionProviders
[(string)$provider] = $provider;
568 return $this->sessionProviders
;
572 * Get a session provider by name
574 * Generally, this will only be used by internal implementation of some
575 * special session-providing mechanism. General purpose code, if it needs
576 * to access a SessionProvider at all, will use Session::getProvider().
578 * @param string $name
579 * @return SessionProvider|null
581 public function getProvider( $name ) {
582 $providers = $this->getProviders();
583 return isset( $providers[$name] ) ?
$providers[$name] : null;
587 * Save all active sessions on shutdown
588 * @private For internal use with register_shutdown_function()
590 public function shutdown() {
591 if ( $this->allSessionBackends
) {
592 $this->logger
->debug( 'Saving all sessions on shutdown' );
593 if ( session_id() !== '' ) {
594 // @codeCoverageIgnoreStart
595 session_write_close();
597 // @codeCoverageIgnoreEnd
598 foreach ( $this->allSessionBackends
as $backend ) {
599 $backend->save( true );
605 * Fetch the SessionInfo(s) for a request
606 * @param WebRequest $request
607 * @return SessionInfo|null
609 private function getSessionInfoForRequest( WebRequest
$request ) {
610 // Call all providers to fetch "the" session
612 foreach ( $this->getProviders() as $provider ) {
613 $info = $provider->provideSessionInfo( $request );
617 if ( $info->getProvider() !== $provider ) {
618 throw new \
UnexpectedValueException(
619 "$provider returned session info for a different provider: $info"
625 // Sort the SessionInfos. Then find the first one that can be
626 // successfully loaded, and then all the ones after it with the same
628 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
631 $info = array_pop( $infos );
632 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
635 $info = array_pop( $infos );
636 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
637 // We hit a lower priority, stop checking.
640 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
641 // This is going to error out below, but we want to
642 // provide a complete list.
649 if ( count( $retInfos ) > 1 ) {
650 $ex = new \
OverflowException(
651 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
653 $ex->sessionInfos
= $retInfos;
657 return $retInfos ?
$retInfos[0] : null;
661 * Load and verify the session info against the store
663 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
664 * @param WebRequest $request
665 * @return bool Whether the session info matches the stored data (if any)
667 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
668 $key = wfMemcKey( 'MWSession', $info->getId() );
669 $blob = $this->store
->get( $key );
671 $newParams = array();
673 if ( $blob !== false ) {
674 // Sanity check: blob must be an array, if it's saved at all
675 if ( !is_array( $blob ) ) {
676 $this->logger
->warning( 'Session "{session}": Bad data', array(
679 $this->store
->delete( $key );
683 // Sanity check: blob has data and metadata arrays
684 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
685 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
687 $this->logger
->warning( 'Session "{session}": Bad data structure', array(
690 $this->store
->delete( $key );
694 $data = $blob['data'];
695 $metadata = $blob['metadata'];
697 // Sanity check: metadata must be an array and must contain certain
698 // keys, if it's saved at all
699 if ( !array_key_exists( 'userId', $metadata ) ||
700 !array_key_exists( 'userName', $metadata ) ||
701 !array_key_exists( 'userToken', $metadata ) ||
702 !array_key_exists( 'provider', $metadata )
704 $this->logger
->warning( 'Session "{session}": Bad metadata', array(
707 $this->store
->delete( $key );
711 // First, load the provider from metadata, or validate it against the metadata.
712 $provider = $info->getProvider();
713 if ( $provider === null ) {
714 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
716 $this->logger
->warning(
717 'Session "{session}": Unknown provider ' . $metadata['provider'],
722 $this->store
->delete( $key );
725 } elseif ( $metadata['provider'] !== (string)$provider ) {
726 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
727 $metadata['provider'] . ' !== ' . $provider,
734 // Load provider metadata from metadata, or validate it against the metadata
735 $providerMetadata = $info->getProviderMetadata();
736 if ( isset( $metadata['providerMetadata'] ) ) {
737 if ( $providerMetadata === null ) {
738 $newParams['metadata'] = $metadata['providerMetadata'];
741 $newProviderMetadata = $provider->mergeMetadata(
742 $metadata['providerMetadata'], $providerMetadata
744 if ( $newProviderMetadata !== $providerMetadata ) {
745 $newParams['metadata'] = $newProviderMetadata;
747 } catch ( MetadataMergeException
$ex ) {
748 $this->logger
->warning(
749 'Session "{session}": Metadata merge failed: {exception}',
753 ) +
$ex->getContext()
760 // Next, load the user from metadata, or validate it against the metadata.
761 $userInfo = $info->getUserInfo();
763 // For loading, id is preferred to name.
765 if ( $metadata['userId'] ) {
766 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
767 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
768 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
770 $userInfo = UserInfo
::newAnonymous();
772 } catch ( \InvalidArgumentException
$ex ) {
773 $this->logger
->error( 'Session "{session}": {exception}', array(
779 $newParams['userInfo'] = $userInfo;
781 // User validation passes if user ID matches, or if there
782 // is no saved ID and the names match.
783 if ( $metadata['userId'] ) {
784 if ( $metadata['userId'] !== $userInfo->getId() ) {
785 $this->logger
->warning(
786 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
789 'uid_a' => $metadata['userId'],
790 'uid_b' => $userInfo->getId(),
795 // If the user was renamed, probably best to fail here.
796 if ( $metadata['userName'] !== null &&
797 $userInfo->getName() !== $metadata['userName']
799 $this->logger
->warning(
800 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
803 'uname_a' => $metadata['userName'],
804 'uname_b' => $userInfo->getName(),
809 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
810 if ( $metadata['userName'] !== $userInfo->getName() ) {
811 $this->logger
->warning(
812 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
815 'uname_a' => $metadata['userName'],
816 'uname_b' => $userInfo->getName(),
820 } elseif ( !$userInfo->isAnon() ) {
821 // Metadata specifies an anonymous user, but the passed-in
822 // user isn't anonymous.
823 $this->logger
->warning(
824 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
832 // And if we have a token in the metadata, it must match the loaded/provided user.
833 if ( $metadata['userToken'] !== null &&
834 $userInfo->getToken() !== $metadata['userToken']
836 $this->logger
->warning( 'Session "{session}": User token mismatch', array(
841 if ( !$userInfo->isVerified() ) {
842 $newParams['userInfo'] = $userInfo->verified();
845 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
846 $newParams['remembered'] = true;
848 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
849 $newParams['forceHTTPS'] = true;
851 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
852 $newParams['persisted'] = true;
855 if ( !$info->isIdSafe() ) {
856 $newParams['idIsSafe'] = true;
859 // No metadata, so we can't load the provider if one wasn't given.
860 if ( $info->getProvider() === null ) {
861 $this->logger
->warning(
862 'Session "{session}": Null provider and no metadata',
869 // If no user was provided and no metadata, it must be anon.
870 if ( !$info->getUserInfo() ) {
871 if ( $info->getProvider()->canChangeUser() ) {
872 $newParams['userInfo'] = UserInfo
::newAnonymous();
875 'Session "{session}": No user provided and provider cannot set user',
881 } elseif ( !$info->getUserInfo()->isVerified() ) {
882 $this->logger
->warning(
883 'Session "{session}": Unverified user provided and no metadata to auth it',
893 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
894 // The ID doesn't come from the user, so it should be safe
895 // (and if not, nothing we can do about it anyway)
896 $newParams['idIsSafe'] = true;
900 // Construct the replacement SessionInfo, if necessary
902 $newParams['copyFrom'] = $info;
903 $info = new SessionInfo( $info->getPriority(), $newParams );
906 // Allow the provider to check the loaded SessionInfo
907 $providerMetadata = $info->getProviderMetadata();
908 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
911 if ( $providerMetadata !== $info->getProviderMetadata() ) {
912 $info = new SessionInfo( $info->getPriority(), array(
913 'metadata' => $providerMetadata,
918 // Give hooks a chance to abort. Combined with the SessionMetadata
919 // hook, this can allow for tying a session to an IP address or the
921 $reason = 'Hook aborted';
924 array( &$reason, $info, $request, $metadata, $data )
926 $this->logger
->warning( 'Session "{session}": ' . $reason, array(
936 * Create a session corresponding to the passed SessionInfo
937 * @private For use by a SessionProvider that needs to specially create its
939 * @param SessionInfo $info
940 * @param WebRequest $request
943 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
944 $id = $info->getId();
946 if ( !isset( $this->allSessionBackends
[$id] ) ) {
947 if ( !isset( $this->allSessionIds
[$id] ) ) {
948 $this->allSessionIds
[$id] = new SessionId( $id );
950 $backend = new SessionBackend(
951 $this->allSessionIds
[$id],
955 $this->config
->get( 'ObjectCacheSessionExpiry' )
957 $this->allSessionBackends
[$id] = $backend;
958 $delay = $backend->delaySave();
960 $backend = $this->allSessionBackends
[$id];
961 $delay = $backend->delaySave();
962 if ( $info->wasPersisted() ) {
965 if ( $info->wasRemembered() ) {
966 $backend->setRememberUser( true );
970 $request->setSessionId( $backend->getSessionId() );
971 $session = $backend->getSession( $request );
973 if ( !$info->isIdSafe() ) {
977 \ScopedCallback
::consume( $delay );
982 * Deregister a SessionBackend
983 * @private For use from \\MediaWiki\\Session\\SessionBackend only
984 * @param SessionBackend $backend
986 public function deregisterSessionBackend( SessionBackend
$backend ) {
987 $id = $backend->getId();
988 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
989 $this->allSessionBackends
[$id] !== $backend ||
990 $this->allSessionIds
[$id] !== $backend->getSessionId()
992 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
995 unset( $this->allSessionBackends
[$id] );
996 // Explicitly do not unset $this->allSessionIds[$id]
1000 * Change a SessionBackend's ID
1001 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1002 * @param SessionBackend $backend
1004 public function changeBackendId( SessionBackend
$backend ) {
1005 $sessionId = $backend->getSessionId();
1006 $oldId = (string)$sessionId;
1007 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
1008 $this->allSessionBackends
[$oldId] !== $backend ||
1009 $this->allSessionIds
[$oldId] !== $sessionId
1011 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1014 $newId = $this->generateSessionId();
1016 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
1017 $sessionId->setId( $newId );
1018 $this->allSessionBackends
[$newId] = $backend;
1019 $this->allSessionIds
[$newId] = $sessionId;
1023 * Generate a new random session ID
1026 public function generateSessionId() {
1028 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1029 $key = wfMemcKey( 'MWSession', $id );
1030 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
1035 * Call setters on a PHPSessionHandler
1036 * @private Use PhpSessionHandler::install()
1037 * @param PHPSessionHandler $handler
1039 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1040 $handler->setManager( $this, $this->store
, $this->logger
);
1044 * Reset the internal caching for unit testing
1046 public static function resetCache() {
1047 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1048 // @codeCoverageIgnoreStart
1049 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1050 // @codeCoverageIgnoreEnd
1053 self
::$globalSession = null;
1054 self
::$globalSessionRequest = null;