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 = [];
71 /** @var SessionId[] */
72 private $allSessionIds = [];
75 private $preventUsers = [];
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 = [] ) {
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' ) );
171 $this->store
= $store instanceof CachedBagOStuff ?
$store : new CachedBagOStuff( $store );
173 register_shutdown_function( [ $this, 'shutdown' ] );
176 public function setLogger( LoggerInterface
$logger ) {
177 $this->logger
= $logger;
180 public function getSessionForRequest( WebRequest
$request ) {
181 $info = $this->getSessionInfoForRequest( $request );
184 $session = $this->getEmptySession( $request );
186 $session = $this->getSessionFromInfo( $info, $request );
191 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
192 if ( !self
::validateSessionId( $id ) ) {
193 throw new \
InvalidArgumentException( 'Invalid session ID' );
196 $request = new FauxRequest
;
201 // Test this here to provide a better log message for the common case
203 $key = wfMemcKey( 'MWSession', $id );
204 if ( is_array( $this->store
->get( $key ) ) ) {
205 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [ 'id' => $id, 'idIsSafe' => true ] );
206 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
207 $session = $this->getSessionFromInfo( $info, $request );
211 if ( $create && $session === null ) {
214 $session = $this->getEmptySessionInternal( $request, $id );
215 } catch ( \Exception
$ex ) {
216 $this->logger
->error( 'Failed to create empty session: {exception}',
218 'method' => __METHOD__
,
228 public function getEmptySession( WebRequest
$request = null ) {
229 return $this->getEmptySessionInternal( $request );
233 * @see SessionManagerInterface::getEmptySession
234 * @param WebRequest|null $request
235 * @param string|null $id ID to force on the new session
238 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
239 if ( $id !== null ) {
240 if ( !self
::validateSessionId( $id ) ) {
241 throw new \
InvalidArgumentException( 'Invalid session ID' );
244 $key = wfMemcKey( 'MWSession', $id );
245 if ( is_array( $this->store
->get( $key ) ) ) {
246 throw new \
InvalidArgumentException( 'Session ID already exists' );
250 $request = new FauxRequest
;
254 foreach ( $this->getProviders() as $provider ) {
255 $info = $provider->newSessionInfo( $id );
259 if ( $info->getProvider() !== $provider ) {
260 throw new \
UnexpectedValueException(
261 "$provider returned an empty session info for a different provider: $info"
264 if ( $id !== null && $info->getId() !== $id ) {
265 throw new \
UnexpectedValueException(
266 "$provider returned empty session info with a wrong id: " .
267 $info->getId() . ' != ' . $id
270 if ( !$info->isIdSafe() ) {
271 throw new \
UnexpectedValueException(
272 "$provider returned empty session info with id flagged unsafe"
275 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
276 if ( $compare > 0 ) {
279 if ( $compare === 0 ) {
286 // Make sure there's exactly one
287 if ( count( $infos ) > 1 ) {
288 throw new \
UnexpectedValueException(
289 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
291 } elseif ( count( $infos ) < 1 ) {
292 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
295 return $this->getSessionFromInfo( $infos[0], $request );
298 public function getVaryHeaders() {
299 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
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] = [];
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 ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION
!== 'warn' ) {
323 if ( $this->varyCookies
=== null ) {
325 foreach ( $this->getProviders() as $provider ) {
326 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
328 $this->varyCookies
= array_values( array_unique( $cookies ) );
330 return $this->varyCookies
;
334 * Validate a session ID
338 public static function validateSessionId( $id ) {
339 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
343 * @name Internal methods
348 * Auto-create the given user, if necessary
349 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
350 * @note This more properly belongs in AuthManager, but we need it now.
351 * When AuthManager comes, this will be deprecated and will pass-through
352 * to the corresponding AuthManager method.
353 * @param User $user User to auto-create
354 * @return bool Success
356 public static function autoCreateUser( User
$user ) {
359 $logger = self
::singleton()->logger
;
361 // Much of this code is based on that in CentralAuth
363 // Try the local user from the slave DB
364 $localId = User
::idFromName( $user->getName() );
367 // Fetch the user ID from the master, so that we don't try to create the user
368 // when they already exist, due to replication lag
369 // @codeCoverageIgnoreStart
370 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
371 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
372 $flags = User
::READ_LATEST
;
374 // @codeCoverageIgnoreEnd
377 // User exists after all.
378 $user->setId( $localId );
379 $user->loadFromId( $flags );
383 // Denied by AuthPlugin? But ignore AuthPlugin itself.
384 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
385 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
391 // Wiki is read-only?
392 if ( wfReadOnly() ) {
393 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
399 $userName = $user->getName();
401 // Check the session, if we tried to create this user already there's
402 // no point in retrying.
403 $session = self
::getGlobalSession();
404 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
406 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
412 // Is the IP user able to create accounts?
414 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
415 ||
$anon->isBlockedFromCreateAccount()
417 // Blacklist the user to avoid repeated DB queries subsequently
418 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
419 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
426 // Check for validity of username
427 if ( !User
::isCreatableName( $userName ) ) {
428 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
429 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
436 // Give other extensions a chance to stop auto creation.
437 $user->loadDefaults( $userName );
439 if ( !\Hooks
::run( 'AbortAutoAccount', [ $user, &$abortMessage ] ) ) {
440 // In this case we have no way to return the message to the user,
441 // but we can log it.
442 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
443 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
450 // Make sure the name has not been changed
451 if ( $user->getName() !== $userName ) {
454 throw new \
UnexpectedValueException(
455 'AbortAutoAccount hook tried to change the user name'
459 // Ignore warnings about master connections/writes...hard to avoid here
460 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
462 $cache = \ObjectCache
::getLocalClusterInstance();
463 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
464 if ( $cache->get( $backoffKey ) ) {
465 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
471 // Checks passed, create the user...
472 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
473 $logger->info( __METHOD__
. ': creating new user ({username}) - from: {url}',
475 'username' => $userName,
480 // Insert the user into the local DB master
481 $status = $user->addToDatabase();
482 if ( !$status->isOK() ) {
483 // @codeCoverageIgnoreStart
484 // double-check for a race condition (T70012)
485 $id = User
::idFromName( $user->getName(), User
::READ_LATEST
);
487 $logger->info( __METHOD__
. ': tried to autocreate existing user',
489 'username' => $userName,
492 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText(),
494 'username' => $userName,
498 $user->loadFromId( User
::READ_LATEST
);
500 // @codeCoverageIgnoreEnd
502 } catch ( \Exception
$ex ) {
503 // @codeCoverageIgnoreStart
504 $logger->error( __METHOD__
. ': failed with exception {exception}', [
506 'username' => $userName,
508 // Do not keep throwing errors for a while
509 $cache->set( $backoffKey, 1, 600 );
510 // Bubble up error; which should normally trigger DB rollbacks
512 // @codeCoverageIgnoreEnd
517 $wgAuth->initUser( $tmpUser, true );
518 if ( $tmpUser !== $user ) {
519 $logger->warning( __METHOD__
. ': ' .
520 get_class( $wgAuth ) . '::initUser() replaced the user object' );
523 # Notify hooks (e.g. Newuserlog)
524 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ] );
525 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
527 $user->saveSettings();
530 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
532 # Watch user's userpage and talk page
533 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
539 * Prevent future sessions for the user
541 * The intention is that the named account will never again be usable for
542 * normal login (i.e. there is no way to undo the prevention of access).
544 * @private For use from \\User::newSystemUser only
545 * @param string $username
547 public function preventSessionsForUser( $username ) {
548 $this->preventUsers
[$username] = true;
550 // Instruct the session providers to kill any other sessions too.
551 foreach ( $this->getProviders() as $provider ) {
552 $provider->preventSessionsForUser( $username );
557 * Test if a user is prevented
558 * @private For use from SessionBackend only
559 * @param string $username
562 public function isUserSessionPrevented( $username ) {
563 return !empty( $this->preventUsers
[$username] );
567 * Get the available SessionProviders
568 * @return SessionProvider[]
570 protected function getProviders() {
571 if ( $this->sessionProviders
=== null ) {
572 $this->sessionProviders
= [];
573 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
574 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
575 $provider->setLogger( $this->logger
);
576 $provider->setConfig( $this->config
);
577 $provider->setManager( $this );
578 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
579 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
581 $this->sessionProviders
[(string)$provider] = $provider;
584 return $this->sessionProviders
;
588 * Get a session provider by name
590 * Generally, this will only be used by internal implementation of some
591 * special session-providing mechanism. General purpose code, if it needs
592 * to access a SessionProvider at all, will use Session::getProvider().
594 * @param string $name
595 * @return SessionProvider|null
597 public function getProvider( $name ) {
598 $providers = $this->getProviders();
599 return isset( $providers[$name] ) ?
$providers[$name] : null;
603 * Save all active sessions on shutdown
604 * @private For internal use with register_shutdown_function()
606 public function shutdown() {
607 if ( $this->allSessionBackends
) {
608 $this->logger
->debug( 'Saving all sessions on shutdown' );
609 if ( session_id() !== '' ) {
610 // @codeCoverageIgnoreStart
611 session_write_close();
613 // @codeCoverageIgnoreEnd
614 foreach ( $this->allSessionBackends
as $backend ) {
615 $backend->save( true );
621 * Fetch the SessionInfo(s) for a request
622 * @param WebRequest $request
623 * @return SessionInfo|null
625 private function getSessionInfoForRequest( WebRequest
$request ) {
626 // Call all providers to fetch "the" session
628 foreach ( $this->getProviders() as $provider ) {
629 $info = $provider->provideSessionInfo( $request );
633 if ( $info->getProvider() !== $provider ) {
634 throw new \
UnexpectedValueException(
635 "$provider returned session info for a different provider: $info"
641 // Sort the SessionInfos. Then find the first one that can be
642 // successfully loaded, and then all the ones after it with the same
644 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
647 $info = array_pop( $infos );
648 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
651 $info = array_pop( $infos );
652 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
653 // We hit a lower priority, stop checking.
656 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
657 // This is going to error out below, but we want to
658 // provide a complete list.
665 if ( count( $retInfos ) > 1 ) {
666 $ex = new \
OverflowException(
667 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
669 $ex->sessionInfos
= $retInfos;
673 return $retInfos ?
$retInfos[0] : null;
677 * Load and verify the session info against the store
679 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
680 * @param WebRequest $request
681 * @return bool Whether the session info matches the stored data (if any)
683 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
684 $key = wfMemcKey( 'MWSession', $info->getId() );
685 $blob = $this->store
->get( $key );
689 if ( $blob !== false ) {
690 // Sanity check: blob must be an array, if it's saved at all
691 if ( !is_array( $blob ) ) {
692 $this->logger
->warning( 'Session "{session}": Bad data', [
695 $this->store
->delete( $key );
699 // Sanity check: blob has data and metadata arrays
700 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
701 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
703 $this->logger
->warning( 'Session "{session}": Bad data structure', [
706 $this->store
->delete( $key );
710 $data = $blob['data'];
711 $metadata = $blob['metadata'];
713 // Sanity check: metadata must be an array and must contain certain
714 // keys, if it's saved at all
715 if ( !array_key_exists( 'userId', $metadata ) ||
716 !array_key_exists( 'userName', $metadata ) ||
717 !array_key_exists( 'userToken', $metadata ) ||
718 !array_key_exists( 'provider', $metadata )
720 $this->logger
->warning( 'Session "{session}": Bad metadata', [
723 $this->store
->delete( $key );
727 // First, load the provider from metadata, or validate it against the metadata.
728 $provider = $info->getProvider();
729 if ( $provider === null ) {
730 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
732 $this->logger
->warning(
733 'Session "{session}": Unknown provider ' . $metadata['provider'],
738 $this->store
->delete( $key );
741 } elseif ( $metadata['provider'] !== (string)$provider ) {
742 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
743 $metadata['provider'] . ' !== ' . $provider,
750 // Load provider metadata from metadata, or validate it against the metadata
751 $providerMetadata = $info->getProviderMetadata();
752 if ( isset( $metadata['providerMetadata'] ) ) {
753 if ( $providerMetadata === null ) {
754 $newParams['metadata'] = $metadata['providerMetadata'];
757 $newProviderMetadata = $provider->mergeMetadata(
758 $metadata['providerMetadata'], $providerMetadata
760 if ( $newProviderMetadata !== $providerMetadata ) {
761 $newParams['metadata'] = $newProviderMetadata;
763 } catch ( MetadataMergeException
$ex ) {
764 $this->logger
->warning(
765 'Session "{session}": Metadata merge failed: {exception}',
769 ] +
$ex->getContext()
776 // Next, load the user from metadata, or validate it against the metadata.
777 $userInfo = $info->getUserInfo();
779 // For loading, id is preferred to name.
781 if ( $metadata['userId'] ) {
782 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
783 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
784 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
786 $userInfo = UserInfo
::newAnonymous();
788 } catch ( \InvalidArgumentException
$ex ) {
789 $this->logger
->error( 'Session "{session}": {exception}', [
795 $newParams['userInfo'] = $userInfo;
797 // User validation passes if user ID matches, or if there
798 // is no saved ID and the names match.
799 if ( $metadata['userId'] ) {
800 if ( $metadata['userId'] !== $userInfo->getId() ) {
801 $this->logger
->warning(
802 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
805 'uid_a' => $metadata['userId'],
806 'uid_b' => $userInfo->getId(),
811 // If the user was renamed, probably best to fail here.
812 if ( $metadata['userName'] !== null &&
813 $userInfo->getName() !== $metadata['userName']
815 $this->logger
->warning(
816 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
819 'uname_a' => $metadata['userName'],
820 'uname_b' => $userInfo->getName(),
825 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
826 if ( $metadata['userName'] !== $userInfo->getName() ) {
827 $this->logger
->warning(
828 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
831 'uname_a' => $metadata['userName'],
832 'uname_b' => $userInfo->getName(),
836 } elseif ( !$userInfo->isAnon() ) {
837 // Metadata specifies an anonymous user, but the passed-in
838 // user isn't anonymous.
839 $this->logger
->warning(
840 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
848 // And if we have a token in the metadata, it must match the loaded/provided user.
849 if ( $metadata['userToken'] !== null &&
850 $userInfo->getToken() !== $metadata['userToken']
852 $this->logger
->warning( 'Session "{session}": User token mismatch', [
857 if ( !$userInfo->isVerified() ) {
858 $newParams['userInfo'] = $userInfo->verified();
861 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
862 $newParams['remembered'] = true;
864 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
865 $newParams['forceHTTPS'] = true;
867 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
868 $newParams['persisted'] = true;
871 if ( !$info->isIdSafe() ) {
872 $newParams['idIsSafe'] = true;
875 // No metadata, so we can't load the provider if one wasn't given.
876 if ( $info->getProvider() === null ) {
877 $this->logger
->warning(
878 'Session "{session}": Null provider and no metadata',
885 // If no user was provided and no metadata, it must be anon.
886 if ( !$info->getUserInfo() ) {
887 if ( $info->getProvider()->canChangeUser() ) {
888 $newParams['userInfo'] = UserInfo
::newAnonymous();
891 'Session "{session}": No user provided and provider cannot set user',
897 } elseif ( !$info->getUserInfo()->isVerified() ) {
898 $this->logger
->warning(
899 'Session "{session}": Unverified user provided and no metadata to auth it',
909 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
910 // The ID doesn't come from the user, so it should be safe
911 // (and if not, nothing we can do about it anyway)
912 $newParams['idIsSafe'] = true;
916 // Construct the replacement SessionInfo, if necessary
918 $newParams['copyFrom'] = $info;
919 $info = new SessionInfo( $info->getPriority(), $newParams );
922 // Allow the provider to check the loaded SessionInfo
923 $providerMetadata = $info->getProviderMetadata();
924 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
927 if ( $providerMetadata !== $info->getProviderMetadata() ) {
928 $info = new SessionInfo( $info->getPriority(), [
929 'metadata' => $providerMetadata,
934 // Give hooks a chance to abort. Combined with the SessionMetadata
935 // hook, this can allow for tying a session to an IP address or the
937 $reason = 'Hook aborted';
940 [ &$reason, $info, $request, $metadata, $data ]
942 $this->logger
->warning( 'Session "{session}": ' . $reason, [
952 * Create a session corresponding to the passed SessionInfo
953 * @private For use by a SessionProvider that needs to specially create its
955 * @param SessionInfo $info
956 * @param WebRequest $request
959 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
960 if ( defined( 'MW_NO_SESSION' ) ) {
961 if ( MW_NO_SESSION
=== 'warn' ) {
962 // Undocumented safety case for converting existing entry points
963 $this->logger
->error( 'Sessions are supposed to be disabled for this entry point' );
965 throw new \
BadMethodCallException( 'Sessions are disabled for this entry point' );
969 $id = $info->getId();
971 if ( !isset( $this->allSessionBackends
[$id] ) ) {
972 if ( !isset( $this->allSessionIds
[$id] ) ) {
973 $this->allSessionIds
[$id] = new SessionId( $id );
975 $backend = new SessionBackend(
976 $this->allSessionIds
[$id],
980 $this->config
->get( 'ObjectCacheSessionExpiry' )
982 $this->allSessionBackends
[$id] = $backend;
983 $delay = $backend->delaySave();
985 $backend = $this->allSessionBackends
[$id];
986 $delay = $backend->delaySave();
987 if ( $info->wasPersisted() ) {
990 if ( $info->wasRemembered() ) {
991 $backend->setRememberUser( true );
995 $request->setSessionId( $backend->getSessionId() );
996 $session = $backend->getSession( $request );
998 if ( !$info->isIdSafe() ) {
1002 \ScopedCallback
::consume( $delay );
1007 * Deregister a SessionBackend
1008 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1009 * @param SessionBackend $backend
1011 public function deregisterSessionBackend( SessionBackend
$backend ) {
1012 $id = $backend->getId();
1013 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
1014 $this->allSessionBackends
[$id] !== $backend ||
1015 $this->allSessionIds
[$id] !== $backend->getSessionId()
1017 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1020 unset( $this->allSessionBackends
[$id] );
1021 // Explicitly do not unset $this->allSessionIds[$id]
1025 * Change a SessionBackend's ID
1026 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1027 * @param SessionBackend $backend
1029 public function changeBackendId( SessionBackend
$backend ) {
1030 $sessionId = $backend->getSessionId();
1031 $oldId = (string)$sessionId;
1032 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
1033 $this->allSessionBackends
[$oldId] !== $backend ||
1034 $this->allSessionIds
[$oldId] !== $sessionId
1036 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1039 $newId = $this->generateSessionId();
1041 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
1042 $sessionId->setId( $newId );
1043 $this->allSessionBackends
[$newId] = $backend;
1044 $this->allSessionIds
[$newId] = $sessionId;
1048 * Generate a new random session ID
1051 public function generateSessionId() {
1053 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1054 $key = wfMemcKey( 'MWSession', $id );
1055 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
1060 * Call setters on a PHPSessionHandler
1061 * @private Use PhpSessionHandler::install()
1062 * @param PHPSessionHandler $handler
1064 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1065 $handler->setManager( $this, $this->store
, $this->logger
);
1069 * Reset the internal caching for unit testing
1071 public static function resetCache() {
1072 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1073 // @codeCoverageIgnoreStart
1074 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1075 // @codeCoverageIgnoreEnd
1078 self
::$globalSession = null;
1079 self
::$globalSessionRequest = null;