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 BagOStuff|null */
63 /** @var SessionProvider[] */
64 private $sessionProviders = null;
67 private $varyCookies = null;
70 private $varyHeaders = null;
72 /** @var SessionBackend[] */
73 private $allSessionBackends = array();
75 /** @var SessionId[] */
76 private $allSessionIds = array();
79 private $preventUsers = array();
82 * Get the global SessionManager
83 * @return SessionManagerInterface
84 * (really a SessionManager, but this is to make IDEs less confused)
86 public static function singleton() {
87 if ( self
::$instance === null ) {
88 self
::$instance = new self();
90 return self
::$instance;
94 * Get the "global" session
96 * If PHP's session_id() has been set, returns that session. Otherwise
97 * returns the session for RequestContext::getMain()->getRequest().
101 public static function getGlobalSession() {
102 if ( !PHPSessionHandler
::isEnabled() ) {
108 $request = \RequestContext
::getMain()->getRequest();
110 !self
::$globalSession // No global session is set up yet
111 || self
::$globalSessionRequest !== $request // The global WebRequest changed
112 ||
$id !== '' && self
::$globalSession->getId() !== $id // Someone messed with session_id()
114 self
::$globalSessionRequest = $request;
116 // session_id() wasn't used, so fetch the Session from the WebRequest.
117 // We use $request->getSession() instead of $singleton->getSessionForRequest()
118 // because doing the latter would require a public
119 // "$request->getSessionId()" method that would confuse end
120 // users by returning SessionId|null where they'd expect it to
121 // be short for $request->getSession()->getId(), and would
122 // wind up being a duplicate of the code in
123 // $request->getSession() anyway.
124 self
::$globalSession = $request->getSession();
126 // Someone used session_id(), so we need to follow suit.
127 // Note this overwrites whatever session might already be
128 // associated with $request with the one for $id.
129 self
::$globalSession = self
::singleton()->getSessionById( $id, true, $request )
130 ?
: $request->getSession();
133 return self
::$globalSession;
137 * @param array $options
138 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
139 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
140 * - store: BagOStuff to store session data in.
142 public function __construct( $options = array() ) {
143 if ( isset( $options['config'] ) ) {
144 $this->config
= $options['config'];
145 if ( !$this->config
instanceof Config
) {
146 throw new \
InvalidArgumentException(
147 '$options[\'config\'] must be an instance of Config'
151 $this->config
= \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
154 if ( isset( $options['logger'] ) ) {
155 if ( !$options['logger'] instanceof LoggerInterface
) {
156 throw new \
InvalidArgumentException(
157 '$options[\'logger\'] must be an instance of LoggerInterface'
160 $this->setLogger( $options['logger'] );
162 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' ) );
165 $this->tempStore
= new \HashBagOStuff
;
166 if ( isset( $options['store'] ) ) {
167 if ( !$options['store'] instanceof BagOStuff
) {
168 throw new \
InvalidArgumentException(
169 '$options[\'store\'] must be an instance of BagOStuff'
172 $this->permStore
= $options['store'];
174 $this->permStore
= \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
175 $this->permStore
->setLogger( $this->logger
);
178 register_shutdown_function( array( $this, 'shutdown' ) );
181 public function setLogger( LoggerInterface
$logger ) {
182 $this->logger
= $logger;
185 public function getSessionForRequest( WebRequest
$request ) {
186 $info = $this->getSessionInfoForRequest( $request );
189 $session = $this->getEmptySession( $request );
191 $session = $this->getSessionFromInfo( $info, $request );
196 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
197 if ( !self
::validateSessionId( $id ) ) {
198 throw new \
InvalidArgumentException( 'Invalid session ID' );
201 $request = new FauxRequest
;
206 // Test this here to provide a better log message for the common case
208 $key = wfMemcKey( 'MWSession', $id );
209 $existing = $this->tempStore
->get( $key );
210 if ( $existing === false ) {
211 $existing = $this->permStore
->get( $key );
212 if ( $existing !== false ) {
213 $this->tempStore
->set( $key, $existing );
216 if ( is_array( $existing ) ) {
217 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array( 'id' => $id, 'idIsSafe' => true ) );
218 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
219 $session = $this->getSessionFromInfo( $info, $request );
223 if ( $create && $session === null ) {
226 $session = $this->getEmptySessionInternal( $request, $id );
227 } catch ( \Exception
$ex ) {
228 $this->logger
->error( __METHOD__
. ': failed to create empty session: ' .
237 public function getEmptySession( WebRequest
$request = null ) {
238 return $this->getEmptySessionInternal( $request );
242 * @see SessionManagerInterface::getEmptySession
243 * @param WebRequest|null $request
244 * @param string|null $id ID to force on the new session
247 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
248 if ( $id !== null ) {
249 if ( !self
::validateSessionId( $id ) ) {
250 throw new \
InvalidArgumentException( 'Invalid session ID' );
253 $key = wfMemcKey( 'MWSession', $id );
254 $existing = $this->tempStore
->get( $key );
255 if ( $existing === false ) {
256 $existing = $this->permStore
->get( $key );
257 if ( $existing !== false ) {
258 $this->tempStore
->set( $key, $existing );
261 if ( is_array( $existing ) ) {
262 throw new \
InvalidArgumentException( 'Session ID already exists' );
266 $request = new FauxRequest
;
270 foreach ( $this->getProviders() as $provider ) {
271 $info = $provider->newSessionInfo( $id );
275 if ( $info->getProvider() !== $provider ) {
276 throw new \
UnexpectedValueException(
277 "$provider returned an empty session info for a different provider: $info"
280 if ( $id !== null && $info->getId() !== $id ) {
281 throw new \
UnexpectedValueException(
282 "$provider returned empty session info with a wrong id: " .
283 $info->getId() . ' != ' . $id
286 if ( !$info->isIdSafe() ) {
287 throw new \
UnexpectedValueException(
288 "$provider returned empty session info with id flagged unsafe"
291 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
292 if ( $compare > 0 ) {
295 if ( $compare === 0 ) {
298 $infos = array( $info );
302 // Make sure there's exactly one
303 if ( count( $infos ) > 1 ) {
304 throw new \
UnexpectedValueException(
305 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
307 } elseif ( count( $infos ) < 1 ) {
308 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
311 return $this->getSessionFromInfo( $infos[0], $request );
314 public function getVaryHeaders() {
315 if ( $this->varyHeaders
=== null ) {
317 foreach ( $this->getProviders() as $provider ) {
318 foreach ( $provider->getVaryHeaders() as $header => $options ) {
319 if ( !isset( $headers[$header] ) ) {
320 $headers[$header] = array();
322 if ( is_array( $options ) ) {
323 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
327 $this->varyHeaders
= $headers;
329 return $this->varyHeaders
;
332 public function getVaryCookies() {
333 if ( $this->varyCookies
=== null ) {
335 foreach ( $this->getProviders() as $provider ) {
336 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
338 $this->varyCookies
= array_values( array_unique( $cookies ) );
340 return $this->varyCookies
;
344 * Validate a session ID
348 public static function validateSessionId( $id ) {
349 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
353 * @name Internal methods
358 * Auto-create the given user, if necessary
359 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
360 * @note This more properly belongs in AuthManager, but we need it now.
361 * When AuthManager comes, this will be deprecated and will pass-through
362 * to the corresponding AuthManager method.
363 * @param User $user User to auto-create
364 * @return bool Success
366 public static function autoCreateUser( User
$user ) {
369 $logger = self
::singleton()->logger
;
371 // Much of this code is based on that in CentralAuth
373 // Try the local user from the slave DB
374 $localId = User
::idFromName( $user->getName() );
376 // Fetch the user ID from the master, so that we don't try to create the user
377 // when they already exist, due to replication lag
378 // @codeCoverageIgnoreStart
379 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
380 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
382 // @codeCoverageIgnoreEnd
385 // User exists after all.
386 $user->setId( $localId );
391 // Denied by AuthPlugin? But ignore AuthPlugin itself.
392 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
393 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
399 // Wiki is read-only?
400 if ( wfReadOnly() ) {
401 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
407 $userName = $user->getName();
409 // Check the session, if we tried to create this user already there's
410 // no point in retrying.
411 $session = self
::getGlobalSession();
412 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
414 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
420 // Is the IP user able to create accounts?
422 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
423 ||
$anon->isBlockedFromCreateAccount()
425 // Blacklist the user to avoid repeated DB queries subsequently
426 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
427 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
434 // Check for validity of username
435 if ( !User
::isCreatableName( $userName ) ) {
436 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
437 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
444 // Give other extensions a chance to stop auto creation.
445 $user->loadDefaults( $userName );
447 if ( !\Hooks
::run( 'AbortAutoAccount', array( $user, &$abortMessage ) ) ) {
448 // In this case we have no way to return the message to the user,
449 // but we can log it.
450 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
451 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
458 // Make sure the name has not been changed
459 if ( $user->getName() !== $userName ) {
462 throw new \
UnexpectedValueException(
463 'AbortAutoAccount hook tried to change the user name'
467 // Ignore warnings about master connections/writes...hard to avoid here
468 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
470 $cache = \ObjectCache
::getLocalClusterInstance();
471 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
472 if ( $cache->get( $backoffKey ) ) {
473 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
479 // Checks passed, create the user...
480 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
481 $logger->info( __METHOD__
. ": creating new user ($userName) - from: $from" );
484 // Insert the user into the local DB master
485 $status = $user->addToDatabase();
486 if ( !$status->isOK() ) {
487 // @codeCoverageIgnoreStart
488 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText() );
492 // @codeCoverageIgnoreEnd
494 } catch ( \Exception
$ex ) {
495 // @codeCoverageIgnoreStart
496 $logger->error( __METHOD__
. ': failed with exception ' . $ex->getMessage() );
497 // Do not keep throwing errors for a while
498 $cache->set( $backoffKey, 1, 600 );
499 // Bubble up error; which should normally trigger DB rollbacks
501 // @codeCoverageIgnoreEnd
506 $wgAuth->initUser( $tmpUser, true );
507 if ( $tmpUser !== $user ) {
508 $logger->warning( __METHOD__
. ': ' .
509 get_class( $wgAuth ) . '::initUser() replaced the user object' );
512 # Notify hooks (e.g. Newuserlog)
513 \Hooks
::run( 'AuthPluginAutoCreate', array( $user ) );
514 \Hooks
::run( 'LocalUserCreated', array( $user, true ) );
516 $user->saveSettings();
519 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
521 # Watch user's userpage and talk page
522 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
528 * Prevent future sessions for the user
530 * The intention is that the named account will never again be usable for
531 * normal login (i.e. there is no way to undo the prevention of access).
533 * @private For use from \\User::newSystemUser only
534 * @param string $username
536 public function preventSessionsForUser( $username ) {
537 $this->preventUsers
[$username] = true;
539 // Instruct the session providers to kill any other sessions too.
540 foreach ( $this->getProviders() as $provider ) {
541 $provider->preventSessionsForUser( $username );
546 * Test if a user is prevented
547 * @private For use from SessionBackend only
548 * @param string $username
551 public function isUserSessionPrevented( $username ) {
552 return !empty( $this->preventUsers
[$username] );
556 * Get the available SessionProviders
557 * @return SessionProvider[]
559 protected function getProviders() {
560 if ( $this->sessionProviders
=== null ) {
561 $this->sessionProviders
= array();
562 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
563 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
564 $provider->setLogger( $this->logger
);
565 $provider->setConfig( $this->config
);
566 $provider->setManager( $this );
567 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
568 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
570 $this->sessionProviders
[(string)$provider] = $provider;
573 return $this->sessionProviders
;
577 * Get a session provider by name
579 * Generally, this will only be used by internal implementation of some
580 * special session-providing mechanism. General purpose code, if it needs
581 * to access a SessionProvider at all, will use Session::getProvider().
583 * @param string $name
584 * @return SessionProvider|null
586 public function getProvider( $name ) {
587 $providers = $this->getProviders();
588 return isset( $providers[$name] ) ?
$providers[$name] : null;
592 * Save all active sessions on shutdown
593 * @private For internal use with register_shutdown_function()
595 public function shutdown() {
596 if ( $this->allSessionBackends
) {
597 $this->logger
->debug( 'Saving all sessions on shutdown' );
598 if ( session_id() !== '' ) {
599 // @codeCoverageIgnoreStart
600 session_write_close();
602 // @codeCoverageIgnoreEnd
603 foreach ( $this->allSessionBackends
as $backend ) {
604 $backend->save( true );
610 * Fetch the SessionInfo(s) for a request
611 * @param WebRequest $request
612 * @return SessionInfo|null
614 private function getSessionInfoForRequest( WebRequest
$request ) {
615 // Call all providers to fetch "the" session
617 foreach ( $this->getProviders() as $provider ) {
618 $info = $provider->provideSessionInfo( $request );
622 if ( $info->getProvider() !== $provider ) {
623 throw new \
UnexpectedValueException(
624 "$provider returned session info for a different provider: $info"
630 // Sort the SessionInfos. Then find the first one that can be
631 // successfully loaded, and then all the ones after it with the same
633 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
636 $info = array_pop( $infos );
637 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
640 $info = array_pop( $infos );
641 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
642 // We hit a lower priority, stop checking.
645 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
646 // This is going to error out below, but we want to
647 // provide a complete list.
654 if ( count( $retInfos ) > 1 ) {
655 $ex = new \
OverflowException(
656 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
658 $ex->sessionInfos
= $retInfos;
662 return $retInfos ?
$retInfos[0] : null;
666 * Load and verify the session info against the store
668 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
669 * @param WebRequest $request
670 * @return bool Whether the session info matches the stored data (if any)
672 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
673 $key = wfMemcKey( 'MWSession', $info->getId() );
674 $blob = $this->tempStore
->get( $key );
675 if ( $blob === false ) {
676 $blob = $this->permStore
->get( $key );
677 if ( $blob !== false ) {
678 $this->tempStore
->set( $key, $blob );
682 $newParams = array();
684 if ( $blob !== false ) {
685 // Sanity check: blob must be an array, if it's saved at all
686 if ( !is_array( $blob ) ) {
687 $this->logger
->warning( "Session $info: Bad data" );
688 $this->tempStore
->delete( $key );
689 $this->permStore
->delete( $key );
693 // Sanity check: blob has data and metadata arrays
694 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
695 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
697 $this->logger
->warning( "Session $info: Bad data structure" );
698 $this->tempStore
->delete( $key );
699 $this->permStore
->delete( $key );
703 $data = $blob['data'];
704 $metadata = $blob['metadata'];
706 // Sanity check: metadata must be an array and must contain certain
707 // keys, if it's saved at all
708 if ( !array_key_exists( 'userId', $metadata ) ||
709 !array_key_exists( 'userName', $metadata ) ||
710 !array_key_exists( 'userToken', $metadata ) ||
711 !array_key_exists( 'provider', $metadata )
713 $this->logger
->warning( "Session $info: Bad metadata" );
714 $this->tempStore
->delete( $key );
715 $this->permStore
->delete( $key );
719 // First, load the provider from metadata, or validate it against the metadata.
720 $provider = $info->getProvider();
721 if ( $provider === null ) {
722 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
724 $this->logger
->warning( "Session $info: Unknown provider, " . $metadata['provider'] );
725 $this->tempStore
->delete( $key );
726 $this->permStore
->delete( $key );
729 } elseif ( $metadata['provider'] !== (string)$provider ) {
730 $this->logger
->warning( "Session $info: Wrong provider, " .
731 $metadata['provider'] . ' !== ' . $provider );
735 // Load provider metadata from metadata, or validate it against the metadata
736 $providerMetadata = $info->getProviderMetadata();
737 if ( isset( $metadata['providerMetadata'] ) ) {
738 if ( $providerMetadata === null ) {
739 $newParams['metadata'] = $metadata['providerMetadata'];
742 $newProviderMetadata = $provider->mergeMetadata(
743 $metadata['providerMetadata'], $providerMetadata
745 if ( $newProviderMetadata !== $providerMetadata ) {
746 $newParams['metadata'] = $newProviderMetadata;
748 } catch ( \UnexpectedValueException
$ex ) {
749 $this->logger
->warning( "Session $info: Metadata merge failed: " . $ex->getMessage() );
755 // Next, load the user from metadata, or validate it against the metadata.
756 $userInfo = $info->getUserInfo();
758 // For loading, id is preferred to name.
760 if ( $metadata['userId'] ) {
761 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
762 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
763 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
765 $userInfo = UserInfo
::newAnonymous();
767 } catch ( \InvalidArgumentException
$ex ) {
768 $this->logger
->error( "Session $info: " . $ex->getMessage() );
771 $newParams['userInfo'] = $userInfo;
773 // User validation passes if user ID matches, or if there
774 // is no saved ID and the names match.
775 if ( $metadata['userId'] ) {
776 if ( $metadata['userId'] !== $userInfo->getId() ) {
777 $this->logger
->warning( "Session $info: User ID mismatch, " .
778 $metadata['userId'] . ' !== ' . $userInfo->getId() );
782 // If the user was renamed, probably best to fail here.
783 if ( $metadata['userName'] !== null &&
784 $userInfo->getName() !== $metadata['userName']
786 $this->logger
->warning( "Session $info: User ID matched but name didn't (rename?), " .
787 $metadata['userName'] . ' !== ' . $userInfo->getName() );
791 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
792 if ( $metadata['userName'] !== $userInfo->getName() ) {
793 $this->logger
->warning( "Session $info: User name mismatch, " .
794 $metadata['userName'] . ' !== ' . $userInfo->getName() );
797 } elseif ( !$userInfo->isAnon() ) {
798 // Metadata specifies an anonymous user, but the passed-in
799 // user isn't anonymous.
800 $this->logger
->warning(
801 "Session $info: Metadata has an anonymous user, " .
802 'but a non-anon user was provided'
808 // And if we have a token in the metadata, it must match the loaded/provided user.
809 if ( $metadata['userToken'] !== null &&
810 $userInfo->getToken() !== $metadata['userToken']
812 $this->logger
->warning( "Session $info: User token mismatch" );
815 if ( !$userInfo->isVerified() ) {
816 $newParams['userInfo'] = $userInfo->verified();
819 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
820 $newParams['remembered'] = true;
822 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
823 $newParams['forceHTTPS'] = true;
825 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
826 $newParams['persisted'] = true;
829 if ( !$info->isIdSafe() ) {
830 $newParams['idIsSafe'] = true;
833 // No metadata, so we can't load the provider if one wasn't given.
834 if ( $info->getProvider() === null ) {
835 $this->logger
->warning( "Session $info: Null provider and no metadata" );
839 // If no user was provided and no metadata, it must be anon.
840 if ( !$info->getUserInfo() ) {
841 if ( $info->getProvider()->canChangeUser() ) {
842 $newParams['userInfo'] = UserInfo
::newAnonymous();
845 "Session $info: No user provided and provider cannot set user"
849 } elseif ( !$info->getUserInfo()->isVerified() ) {
850 $this->logger
->warning(
851 "Session $info: Unverified user provided and no metadata to auth it"
859 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
860 // The ID doesn't come from the user, so it should be safe
861 // (and if not, nothing we can do about it anyway)
862 $newParams['idIsSafe'] = true;
866 // Construct the replacement SessionInfo, if necessary
868 $newParams['copyFrom'] = $info;
869 $info = new SessionInfo( $info->getPriority(), $newParams );
872 // Allow the provider to check the loaded SessionInfo
873 $providerMetadata = $info->getProviderMetadata();
874 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
877 if ( $providerMetadata !== $info->getProviderMetadata() ) {
878 $info = new SessionInfo( $info->getPriority(), array(
879 'metadata' => $providerMetadata,
884 // Give hooks a chance to abort. Combined with the SessionMetadata
885 // hook, this can allow for tying a session to an IP address or the
887 $reason = 'Hook aborted';
890 array( &$reason, $info, $request, $metadata, $data )
892 $this->logger
->warning( "Session $info: $reason" );
900 * Create a session corresponding to the passed SessionInfo
901 * @private For use by a SessionProvider that needs to specially create its
903 * @param SessionInfo $info
904 * @param WebRequest $request
907 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
908 $id = $info->getId();
910 if ( !isset( $this->allSessionBackends
[$id] ) ) {
911 if ( !isset( $this->allSessionIds
[$id] ) ) {
912 $this->allSessionIds
[$id] = new SessionId( $id );
914 $backend = new SessionBackend(
915 $this->allSessionIds
[$id],
920 $this->config
->get( 'ObjectCacheSessionExpiry' )
922 $this->allSessionBackends
[$id] = $backend;
923 $delay = $backend->delaySave();
925 $backend = $this->allSessionBackends
[$id];
926 $delay = $backend->delaySave();
927 if ( $info->wasPersisted() ) {
930 if ( $info->wasRemembered() ) {
931 $backend->setRememberUser( true );
935 $request->setSessionId( $backend->getSessionId() );
936 $session = $backend->getSession( $request );
938 if ( !$info->isIdSafe() ) {
942 \ScopedCallback
::consume( $delay );
947 * Deregister a SessionBackend
948 * @private For use from \\MediaWiki\\Session\\SessionBackend only
949 * @param SessionBackend $backend
951 public function deregisterSessionBackend( SessionBackend
$backend ) {
952 $id = $backend->getId();
953 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
954 $this->allSessionBackends
[$id] !== $backend ||
955 $this->allSessionIds
[$id] !== $backend->getSessionId()
957 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
960 unset( $this->allSessionBackends
[$id] );
961 // Explicitly do not unset $this->allSessionIds[$id]
965 * Change a SessionBackend's ID
966 * @private For use from \\MediaWiki\\Session\\SessionBackend only
967 * @param SessionBackend $backend
969 public function changeBackendId( SessionBackend
$backend ) {
970 $sessionId = $backend->getSessionId();
971 $oldId = (string)$sessionId;
972 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
973 $this->allSessionBackends
[$oldId] !== $backend ||
974 $this->allSessionIds
[$oldId] !== $sessionId
976 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
979 $newId = $this->generateSessionId();
981 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
982 $sessionId->setId( $newId );
983 $this->allSessionBackends
[$newId] = $backend;
984 $this->allSessionIds
[$newId] = $sessionId;
988 * Generate a new random session ID
991 public function generateSessionId() {
993 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
994 $key = wfMemcKey( 'MWSession', $id );
995 } while ( isset( $this->allSessionIds
[$id] ) ||
996 is_array( $this->tempStore
->get( $key ) ) ||
is_array( $this->permStore
->get( $key ) )
1002 * Call setters on a PHPSessionHandler
1003 * @private Use PhpSessionHandler::install()
1004 * @param PHPSessionHandler $handler
1006 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1007 $handler->setManager( $this, $this->permStore
, $this->logger
);
1011 * Reset the internal caching for unit testing
1013 public static function resetCache() {
1014 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1015 // @codeCoverageIgnoreStart
1016 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1017 // @codeCoverageIgnoreEnd
1020 self
::$globalSession = null;
1021 self
::$globalSessionRequest = null;