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( 'Failed to create empty session: {exception}',
221 'method' => __METHOD__
,
231 public function getEmptySession( WebRequest
$request = null ) {
232 return $this->getEmptySessionInternal( $request );
236 * @see SessionManagerInterface::getEmptySession
237 * @param WebRequest|null $request
238 * @param string|null $id ID to force on the new session
241 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
242 if ( $id !== null ) {
243 if ( !self
::validateSessionId( $id ) ) {
244 throw new \
InvalidArgumentException( 'Invalid session ID' );
247 $key = wfMemcKey( 'MWSession', $id );
248 if ( is_array( $this->store
->get( $key ) ) ) {
249 throw new \
InvalidArgumentException( 'Session ID already exists' );
253 $request = new FauxRequest
;
257 foreach ( $this->getProviders() as $provider ) {
258 $info = $provider->newSessionInfo( $id );
262 if ( $info->getProvider() !== $provider ) {
263 throw new \
UnexpectedValueException(
264 "$provider returned an empty session info for a different provider: $info"
267 if ( $id !== null && $info->getId() !== $id ) {
268 throw new \
UnexpectedValueException(
269 "$provider returned empty session info with a wrong id: " .
270 $info->getId() . ' != ' . $id
273 if ( !$info->isIdSafe() ) {
274 throw new \
UnexpectedValueException(
275 "$provider returned empty session info with id flagged unsafe"
278 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
279 if ( $compare > 0 ) {
282 if ( $compare === 0 ) {
285 $infos = array( $info );
289 // Make sure there's exactly one
290 if ( count( $infos ) > 1 ) {
291 throw new \
UnexpectedValueException(
292 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
294 } elseif ( count( $infos ) < 1 ) {
295 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
298 return $this->getSessionFromInfo( $infos[0], $request );
301 public function getVaryHeaders() {
302 if ( $this->varyHeaders
=== null ) {
304 foreach ( $this->getProviders() as $provider ) {
305 foreach ( $provider->getVaryHeaders() as $header => $options ) {
306 if ( !isset( $headers[$header] ) ) {
307 $headers[$header] = array();
309 if ( is_array( $options ) ) {
310 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
314 $this->varyHeaders
= $headers;
316 return $this->varyHeaders
;
319 public function getVaryCookies() {
320 if ( $this->varyCookies
=== null ) {
322 foreach ( $this->getProviders() as $provider ) {
323 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
325 $this->varyCookies
= array_values( array_unique( $cookies ) );
327 return $this->varyCookies
;
331 * Validate a session ID
335 public static function validateSessionId( $id ) {
336 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
340 * @name Internal methods
345 * Auto-create the given user, if necessary
346 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
347 * @note This more properly belongs in AuthManager, but we need it now.
348 * When AuthManager comes, this will be deprecated and will pass-through
349 * to the corresponding AuthManager method.
350 * @param User $user User to auto-create
351 * @return bool Success
353 public static function autoCreateUser( User
$user ) {
356 $logger = self
::singleton()->logger
;
358 // Much of this code is based on that in CentralAuth
360 // Try the local user from the slave DB
361 $localId = User
::idFromName( $user->getName() );
363 // Fetch the user ID from the master, so that we don't try to create the user
364 // when they already exist, due to replication lag
365 // @codeCoverageIgnoreStart
366 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
367 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
369 // @codeCoverageIgnoreEnd
372 // User exists after all.
373 $user->setId( $localId );
378 // Denied by AuthPlugin? But ignore AuthPlugin itself.
379 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
380 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
386 // Wiki is read-only?
387 if ( wfReadOnly() ) {
388 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
394 $userName = $user->getName();
396 // Check the session, if we tried to create this user already there's
397 // no point in retrying.
398 $session = self
::getGlobalSession();
399 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
401 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
407 // Is the IP user able to create accounts?
409 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
410 ||
$anon->isBlockedFromCreateAccount()
412 // Blacklist the user to avoid repeated DB queries subsequently
413 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
414 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
421 // Check for validity of username
422 if ( !User
::isCreatableName( $userName ) ) {
423 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
424 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
431 // Give other extensions a chance to stop auto creation.
432 $user->loadDefaults( $userName );
434 if ( !\Hooks
::run( 'AbortAutoAccount', array( $user, &$abortMessage ) ) ) {
435 // In this case we have no way to return the message to the user,
436 // but we can log it.
437 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
438 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
445 // Make sure the name has not been changed
446 if ( $user->getName() !== $userName ) {
449 throw new \
UnexpectedValueException(
450 'AbortAutoAccount hook tried to change the user name'
454 // Ignore warnings about master connections/writes...hard to avoid here
455 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
457 $cache = \ObjectCache
::getLocalClusterInstance();
458 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
459 if ( $cache->get( $backoffKey ) ) {
460 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
466 // Checks passed, create the user...
467 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
468 $logger->info( __METHOD__
. ': creating new user ({username}) - from: {url}',
470 'username' => $userName,
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(),
481 'username' => $userName,
486 // @codeCoverageIgnoreEnd
488 } catch ( \Exception
$ex ) {
489 // @codeCoverageIgnoreStart
490 $logger->error( __METHOD__
. ': failed with exception {exception}', array(
492 'username' => $userName,
494 // Do not keep throwing errors for a while
495 $cache->set( $backoffKey, 1, 600 );
496 // Bubble up error; which should normally trigger DB rollbacks
498 // @codeCoverageIgnoreEnd
503 $wgAuth->initUser( $tmpUser, true );
504 if ( $tmpUser !== $user ) {
505 $logger->warning( __METHOD__
. ': ' .
506 get_class( $wgAuth ) . '::initUser() replaced the user object' );
509 # Notify hooks (e.g. Newuserlog)
510 \Hooks
::run( 'AuthPluginAutoCreate', array( $user ) );
511 \Hooks
::run( 'LocalUserCreated', array( $user, true ) );
513 $user->saveSettings();
516 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
518 # Watch user's userpage and talk page
519 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
525 * Prevent future sessions for the user
527 * The intention is that the named account will never again be usable for
528 * normal login (i.e. there is no way to undo the prevention of access).
530 * @private For use from \\User::newSystemUser only
531 * @param string $username
533 public function preventSessionsForUser( $username ) {
534 $this->preventUsers
[$username] = true;
536 // Instruct the session providers to kill any other sessions too.
537 foreach ( $this->getProviders() as $provider ) {
538 $provider->preventSessionsForUser( $username );
543 * Test if a user is prevented
544 * @private For use from SessionBackend only
545 * @param string $username
548 public function isUserSessionPrevented( $username ) {
549 return !empty( $this->preventUsers
[$username] );
553 * Get the available SessionProviders
554 * @return SessionProvider[]
556 protected function getProviders() {
557 if ( $this->sessionProviders
=== null ) {
558 $this->sessionProviders
= array();
559 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
560 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
561 $provider->setLogger( $this->logger
);
562 $provider->setConfig( $this->config
);
563 $provider->setManager( $this );
564 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
565 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
567 $this->sessionProviders
[(string)$provider] = $provider;
570 return $this->sessionProviders
;
574 * Get a session provider by name
576 * Generally, this will only be used by internal implementation of some
577 * special session-providing mechanism. General purpose code, if it needs
578 * to access a SessionProvider at all, will use Session::getProvider().
580 * @param string $name
581 * @return SessionProvider|null
583 public function getProvider( $name ) {
584 $providers = $this->getProviders();
585 return isset( $providers[$name] ) ?
$providers[$name] : null;
589 * Save all active sessions on shutdown
590 * @private For internal use with register_shutdown_function()
592 public function shutdown() {
593 if ( $this->allSessionBackends
) {
594 $this->logger
->debug( 'Saving all sessions on shutdown' );
595 if ( session_id() !== '' ) {
596 // @codeCoverageIgnoreStart
597 session_write_close();
599 // @codeCoverageIgnoreEnd
600 foreach ( $this->allSessionBackends
as $backend ) {
601 $backend->save( true );
607 * Fetch the SessionInfo(s) for a request
608 * @param WebRequest $request
609 * @return SessionInfo|null
611 private function getSessionInfoForRequest( WebRequest
$request ) {
612 // Call all providers to fetch "the" session
614 foreach ( $this->getProviders() as $provider ) {
615 $info = $provider->provideSessionInfo( $request );
619 if ( $info->getProvider() !== $provider ) {
620 throw new \
UnexpectedValueException(
621 "$provider returned session info for a different provider: $info"
627 // Sort the SessionInfos. Then find the first one that can be
628 // successfully loaded, and then all the ones after it with the same
630 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
633 $info = array_pop( $infos );
634 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
637 $info = array_pop( $infos );
638 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
639 // We hit a lower priority, stop checking.
642 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
643 // This is going to error out below, but we want to
644 // provide a complete list.
651 if ( count( $retInfos ) > 1 ) {
652 $ex = new \
OverflowException(
653 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
655 $ex->sessionInfos
= $retInfos;
659 return $retInfos ?
$retInfos[0] : null;
663 * Load and verify the session info against the store
665 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
666 * @param WebRequest $request
667 * @return bool Whether the session info matches the stored data (if any)
669 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
670 $key = wfMemcKey( 'MWSession', $info->getId() );
671 $blob = $this->store
->get( $key );
673 $newParams = array();
675 if ( $blob !== false ) {
676 // Sanity check: blob must be an array, if it's saved at all
677 if ( !is_array( $blob ) ) {
678 $this->logger
->warning( 'Session "{session}": Bad data', array(
681 $this->store
->delete( $key );
685 // Sanity check: blob has data and metadata arrays
686 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
687 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
689 $this->logger
->warning( 'Session "{session}": Bad data structure', array(
692 $this->store
->delete( $key );
696 $data = $blob['data'];
697 $metadata = $blob['metadata'];
699 // Sanity check: metadata must be an array and must contain certain
700 // keys, if it's saved at all
701 if ( !array_key_exists( 'userId', $metadata ) ||
702 !array_key_exists( 'userName', $metadata ) ||
703 !array_key_exists( 'userToken', $metadata ) ||
704 !array_key_exists( 'provider', $metadata )
706 $this->logger
->warning( 'Session "{session}": Bad metadata', array(
709 $this->store
->delete( $key );
713 // First, load the provider from metadata, or validate it against the metadata.
714 $provider = $info->getProvider();
715 if ( $provider === null ) {
716 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
718 $this->logger
->warning(
719 'Session "{session}": Unknown provider ' . $metadata['provider'],
724 $this->store
->delete( $key );
727 } elseif ( $metadata['provider'] !== (string)$provider ) {
728 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
729 $metadata['provider'] . ' !== ' . $provider,
736 // Load provider metadata from metadata, or validate it against the metadata
737 $providerMetadata = $info->getProviderMetadata();
738 if ( isset( $metadata['providerMetadata'] ) ) {
739 if ( $providerMetadata === null ) {
740 $newParams['metadata'] = $metadata['providerMetadata'];
743 $newProviderMetadata = $provider->mergeMetadata(
744 $metadata['providerMetadata'], $providerMetadata
746 if ( $newProviderMetadata !== $providerMetadata ) {
747 $newParams['metadata'] = $newProviderMetadata;
749 } catch ( \UnexpectedValueException
$ex ) {
750 $this->logger
->warning(
751 'Session "{session}": Metadata merge failed: {exception}',
761 // Next, load the user from metadata, or validate it against the metadata.
762 $userInfo = $info->getUserInfo();
764 // For loading, id is preferred to name.
766 if ( $metadata['userId'] ) {
767 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
768 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
769 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
771 $userInfo = UserInfo
::newAnonymous();
773 } catch ( \InvalidArgumentException
$ex ) {
774 $this->logger
->error( 'Session "{session}": {exception}', array(
780 $newParams['userInfo'] = $userInfo;
782 // User validation passes if user ID matches, or if there
783 // is no saved ID and the names match.
784 if ( $metadata['userId'] ) {
785 if ( $metadata['userId'] !== $userInfo->getId() ) {
786 $this->logger
->warning(
787 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
790 'uid_a' => $metadata['userId'],
791 'uid_b' => $userInfo->getId(),
796 // If the user was renamed, probably best to fail here.
797 if ( $metadata['userName'] !== null &&
798 $userInfo->getName() !== $metadata['userName']
800 $this->logger
->warning(
801 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
804 'uname_a' => $metadata['userName'],
805 'uname_b' => $userInfo->getName(),
810 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
811 if ( $metadata['userName'] !== $userInfo->getName() ) {
812 $this->logger
->warning(
813 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
816 'uname_a' => $metadata['userName'],
817 'uname_b' => $userInfo->getName(),
821 } elseif ( !$userInfo->isAnon() ) {
822 // Metadata specifies an anonymous user, but the passed-in
823 // user isn't anonymous.
824 $this->logger
->warning(
825 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
833 // And if we have a token in the metadata, it must match the loaded/provided user.
834 if ( $metadata['userToken'] !== null &&
835 $userInfo->getToken() !== $metadata['userToken']
837 $this->logger
->warning( 'Session "{session}": User token mismatch', array(
842 if ( !$userInfo->isVerified() ) {
843 $newParams['userInfo'] = $userInfo->verified();
846 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
847 $newParams['remembered'] = true;
849 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
850 $newParams['forceHTTPS'] = true;
852 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
853 $newParams['persisted'] = true;
856 if ( !$info->isIdSafe() ) {
857 $newParams['idIsSafe'] = true;
860 // No metadata, so we can't load the provider if one wasn't given.
861 if ( $info->getProvider() === null ) {
862 $this->logger
->warning(
863 'Session "{session}": Null provider and no metadata',
870 // If no user was provided and no metadata, it must be anon.
871 if ( !$info->getUserInfo() ) {
872 if ( $info->getProvider()->canChangeUser() ) {
873 $newParams['userInfo'] = UserInfo
::newAnonymous();
876 'Session "{session}": No user provided and provider cannot set user',
882 } elseif ( !$info->getUserInfo()->isVerified() ) {
883 $this->logger
->warning(
884 'Session "{session}": Unverified user provided and no metadata to auth it',
894 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
895 // The ID doesn't come from the user, so it should be safe
896 // (and if not, nothing we can do about it anyway)
897 $newParams['idIsSafe'] = true;
901 // Construct the replacement SessionInfo, if necessary
903 $newParams['copyFrom'] = $info;
904 $info = new SessionInfo( $info->getPriority(), $newParams );
907 // Allow the provider to check the loaded SessionInfo
908 $providerMetadata = $info->getProviderMetadata();
909 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
912 if ( $providerMetadata !== $info->getProviderMetadata() ) {
913 $info = new SessionInfo( $info->getPriority(), array(
914 'metadata' => $providerMetadata,
919 // Give hooks a chance to abort. Combined with the SessionMetadata
920 // hook, this can allow for tying a session to an IP address or the
922 $reason = 'Hook aborted';
925 array( &$reason, $info, $request, $metadata, $data )
927 $this->logger
->warning( 'Session "{session}": ' . $reason, array(
937 * Create a session corresponding to the passed SessionInfo
938 * @private For use by a SessionProvider that needs to specially create its
940 * @param SessionInfo $info
941 * @param WebRequest $request
944 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
945 $id = $info->getId();
947 if ( !isset( $this->allSessionBackends
[$id] ) ) {
948 if ( !isset( $this->allSessionIds
[$id] ) ) {
949 $this->allSessionIds
[$id] = new SessionId( $id );
951 $backend = new SessionBackend(
952 $this->allSessionIds
[$id],
956 $this->config
->get( 'ObjectCacheSessionExpiry' )
958 $this->allSessionBackends
[$id] = $backend;
959 $delay = $backend->delaySave();
961 $backend = $this->allSessionBackends
[$id];
962 $delay = $backend->delaySave();
963 if ( $info->wasPersisted() ) {
966 if ( $info->wasRemembered() ) {
967 $backend->setRememberUser( true );
971 $request->setSessionId( $backend->getSessionId() );
972 $session = $backend->getSession( $request );
974 if ( !$info->isIdSafe() ) {
978 \ScopedCallback
::consume( $delay );
983 * Deregister a SessionBackend
984 * @private For use from \\MediaWiki\\Session\\SessionBackend only
985 * @param SessionBackend $backend
987 public function deregisterSessionBackend( SessionBackend
$backend ) {
988 $id = $backend->getId();
989 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
990 $this->allSessionBackends
[$id] !== $backend ||
991 $this->allSessionIds
[$id] !== $backend->getSessionId()
993 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
996 unset( $this->allSessionBackends
[$id] );
997 // Explicitly do not unset $this->allSessionIds[$id]
1001 * Change a SessionBackend's ID
1002 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1003 * @param SessionBackend $backend
1005 public function changeBackendId( SessionBackend
$backend ) {
1006 $sessionId = $backend->getSessionId();
1007 $oldId = (string)$sessionId;
1008 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
1009 $this->allSessionBackends
[$oldId] !== $backend ||
1010 $this->allSessionIds
[$oldId] !== $sessionId
1012 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1015 $newId = $this->generateSessionId();
1017 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
1018 $sessionId->setId( $newId );
1019 $this->allSessionBackends
[$newId] = $backend;
1020 $this->allSessionIds
[$newId] = $sessionId;
1024 * Generate a new random session ID
1027 public function generateSessionId() {
1029 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1030 $key = wfMemcKey( 'MWSession', $id );
1031 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
1036 * Call setters on a PHPSessionHandler
1037 * @private Use PhpSessionHandler::install()
1038 * @param PHPSessionHandler $handler
1040 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1041 $handler->setManager( $this, $this->store
, $this->logger
);
1045 * Reset the internal caching for unit testing
1047 public static function resetCache() {
1048 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1049 // @codeCoverageIgnoreStart
1050 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1051 // @codeCoverageIgnoreEnd
1054 self
::$globalSession = null;
1055 self
::$globalSessionRequest = null;