SessionManager: Change behavior of getSessionById()
[mediawiki.git] / includes / session / SessionManager.php
blob0e4546885a4d16be5b8166f49036177da2d270c1
1 <?php
2 /**
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
20 * @file
21 * @ingroup Session
24 namespace MediaWiki\Session;
26 use Psr\Log\LoggerInterface;
27 use BagOStuff;
28 use Config;
29 use FauxRequest;
30 use Language;
31 use Message;
32 use User;
33 use WebRequest;
35 /**
36 * This serves as the entry point to the MediaWiki session handling system.
38 * @ingroup Session
39 * @since 1.27
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 */
52 private $logger;
54 /** @var Config */
55 private $config;
57 /** @var BagOStuff|null */
58 private $store;
60 /** @var SessionProvider[] */
61 private $sessionProviders = null;
63 /** @var string[] */
64 private $varyCookies = null;
66 /** @var array */
67 private $varyHeaders = null;
69 /** @var SessionBackend[] */
70 private $allSessionBackends = array();
72 /** @var SessionId[] */
73 private $allSessionIds = array();
75 /** @var string[] */
76 private $preventUsers = array();
78 /**
79 * Get the global SessionManager
80 * @return SessionManagerInterface
81 * (really a SessionManager, but this is to make IDEs less confused)
83 public static function singleton() {
84 if ( self::$instance === null ) {
85 self::$instance = new self();
87 return self::$instance;
90 /**
91 * Get the "global" session
93 * If PHP's session_id() has been set, returns that session. Otherwise
94 * returns the session for RequestContext::getMain()->getRequest().
96 * @return Session
98 public static function getGlobalSession() {
99 if ( !PHPSessionHandler::isEnabled() ) {
100 $id = '';
101 } else {
102 $id = session_id();
105 $request = \RequestContext::getMain()->getRequest();
106 if (
107 !self::$globalSession // No global session is set up yet
108 || self::$globalSessionRequest !== $request // The global WebRequest changed
109 || $id !== '' && self::$globalSession->getId() !== $id // Someone messed with session_id()
111 self::$globalSessionRequest = $request;
112 if ( $id === '' ) {
113 // session_id() wasn't used, so fetch the Session from the WebRequest.
114 // We use $request->getSession() instead of $singleton->getSessionForRequest()
115 // because doing the latter would require a public
116 // "$request->getSessionId()" method that would confuse end
117 // users by returning SessionId|null where they'd expect it to
118 // be short for $request->getSession()->getId(), and would
119 // wind up being a duplicate of the code in
120 // $request->getSession() anyway.
121 self::$globalSession = $request->getSession();
122 } else {
123 // Someone used session_id(), so we need to follow suit.
124 // Note this overwrites whatever session might already be
125 // associated with $request with the one for $id.
126 self::$globalSession = self::singleton()->getSessionById( $id, true, $request )
127 ?: $request->getSession();
130 return self::$globalSession;
134 * @param array $options
135 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
136 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
137 * - store: BagOStuff to store session data in.
139 public function __construct( $options = array() ) {
140 if ( isset( $options['config'] ) ) {
141 $this->config = $options['config'];
142 if ( !$this->config instanceof Config ) {
143 throw new \InvalidArgumentException(
144 '$options[\'config\'] must be an instance of Config'
147 } else {
148 $this->config = \ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
151 if ( isset( $options['logger'] ) ) {
152 if ( !$options['logger'] instanceof LoggerInterface ) {
153 throw new \InvalidArgumentException(
154 '$options[\'logger\'] must be an instance of LoggerInterface'
157 $this->setLogger( $options['logger'] );
158 } else {
159 $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'session' ) );
162 if ( isset( $options['store'] ) ) {
163 if ( !$options['store'] instanceof BagOStuff ) {
164 throw new \InvalidArgumentException(
165 '$options[\'store\'] must be an instance of BagOStuff'
168 $this->store = $options['store'];
169 } else {
170 $this->store = \ObjectCache::getInstance( $this->config->get( 'SessionCacheType' ) );
171 $this->store->setLogger( $this->logger );
174 register_shutdown_function( array( $this, 'shutdown' ) );
177 public function setLogger( LoggerInterface $logger ) {
178 $this->logger = $logger;
181 public function getPersistedSessionId( WebRequest $request ) {
182 $info = $this->getSessionInfoForRequest( $request );
183 if ( $info && $info->wasPersisted() ) {
184 return $info->getId();
185 } else {
186 return null;
190 public function getSessionForRequest( WebRequest $request ) {
191 $info = $this->getSessionInfoForRequest( $request );
193 if ( !$info ) {
194 $session = $this->getEmptySession( $request );
195 } else {
196 $session = $this->getSessionFromInfo( $info, $request );
198 return $session;
201 public function getSessionById( $id, $create = false, WebRequest $request = null ) {
202 if ( !self::validateSessionId( $id ) ) {
203 throw new \InvalidArgumentException( 'Invalid session ID' );
205 if ( !$request ) {
206 $request = new FauxRequest;
209 $session = null;
211 // Test this here to provide a better log message for the common case
212 // of "no such ID"
213 $key = wfMemcKey( 'MWSession', $id );
214 if ( is_array( $this->store->get( $key ) ) ) {
215 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array( 'id' => $id, 'idIsSafe' => true ) );
216 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
217 $session = $this->getSessionFromInfo( $info, $request );
221 if ( $create && $session === null ) {
222 $ex = null;
223 try {
224 $session = $this->getEmptySessionInternal( $request, $id );
225 } catch ( \Exception $ex ) {
226 $this->logger->error( __METHOD__ . ': failed to create empty session: ' .
227 $ex->getMessage() );
228 $session = null;
232 return $session;
235 public function getEmptySession( WebRequest $request = null ) {
236 return $this->getEmptySessionInternal( $request );
240 * @see SessionManagerInterface::getEmptySession
241 * @param WebRequest|null $request
242 * @param string|null $id ID to force on the new session
243 * @return Session
245 private function getEmptySessionInternal( WebRequest $request = null, $id = null ) {
246 if ( $id !== null ) {
247 if ( !self::validateSessionId( $id ) ) {
248 throw new \InvalidArgumentException( 'Invalid session ID' );
251 $key = wfMemcKey( 'MWSession', $id );
252 if ( is_array( $this->store->get( $key ) ) ) {
253 throw new \InvalidArgumentException( 'Session ID already exists' );
256 if ( !$request ) {
257 $request = new FauxRequest;
260 $infos = array();
261 foreach ( $this->getProviders() as $provider ) {
262 $info = $provider->newSessionInfo( $id );
263 if ( !$info ) {
264 continue;
266 if ( $info->getProvider() !== $provider ) {
267 throw new \UnexpectedValueException(
268 "$provider returned an empty session info for a different provider: $info"
271 if ( $id !== null && $info->getId() !== $id ) {
272 throw new \UnexpectedValueException(
273 "$provider returned empty session info with a wrong id: " .
274 $info->getId() . ' != ' . $id
277 if ( !$info->isIdSafe() ) {
278 throw new \UnexpectedValueException(
279 "$provider returned empty session info with id flagged unsafe"
282 $compare = $infos ? SessionInfo::compare( $infos[0], $info ) : -1;
283 if ( $compare > 0 ) {
284 continue;
286 if ( $compare === 0 ) {
287 $infos[] = $info;
288 } else {
289 $infos = array( $info );
293 // Make sure there's exactly one
294 if ( count( $infos ) > 1 ) {
295 throw new \UnexpectedValueException(
296 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
298 } elseif ( count( $infos ) < 1 ) {
299 throw new \UnexpectedValueException( 'No provider could provide an empty session!' );
302 return $this->getSessionFromInfo( $infos[0], $request );
305 public function getVaryHeaders() {
306 if ( $this->varyHeaders === null ) {
307 $headers = array();
308 foreach ( $this->getProviders() as $provider ) {
309 foreach ( $provider->getVaryHeaders() as $header => $options ) {
310 if ( !isset( $headers[$header] ) ) {
311 $headers[$header] = array();
313 if ( is_array( $options ) ) {
314 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
318 $this->varyHeaders = $headers;
320 return $this->varyHeaders;
323 public function getVaryCookies() {
324 if ( $this->varyCookies === null ) {
325 $cookies = array();
326 foreach ( $this->getProviders() as $provider ) {
327 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
329 $this->varyCookies = array_values( array_unique( $cookies ) );
331 return $this->varyCookies;
335 * Validate a session ID
336 * @param string $id
337 * @return bool
339 public static function validateSessionId( $id ) {
340 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
344 * @name Internal methods
345 * @{
349 * Auto-create the given user, if necessary
350 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
351 * @note This more properly belongs in AuthManager, but we need it now.
352 * When AuthManager comes, this will be deprecated and will pass-through
353 * to the corresponding AuthManager method.
354 * @param User $user User to auto-create
355 * @return bool Success
357 public static function autoCreateUser( User $user ) {
358 global $wgAuth;
360 $logger = self::singleton()->logger;
362 // Much of this code is based on that in CentralAuth
364 // Try the local user from the slave DB
365 $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 );
373 // @codeCoverageIgnoreEnd
375 if ( $localId ) {
376 // User exists after all.
377 $user->setId( $localId );
378 $user->loadFromId();
379 return false;
382 // Denied by AuthPlugin? But ignore AuthPlugin itself.
383 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
384 $logger->debug( __METHOD__ . ': denied by AuthPlugin' );
385 $user->setId( 0 );
386 $user->loadFromId();
387 return false;
390 // Wiki is read-only?
391 if ( wfReadOnly() ) {
392 $logger->debug( __METHOD__ . ': denied by wfReadOnly()' );
393 $user->setId( 0 );
394 $user->loadFromId();
395 return false;
398 $userName = $user->getName();
400 // Check the session, if we tried to create this user already there's
401 // no point in retrying.
402 $session = self::getGlobalSession();
403 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
404 if ( $reason ) {
405 $logger->debug( __METHOD__ . ": blacklisted in session ($reason)" );
406 $user->setId( 0 );
407 $user->loadFromId();
408 return false;
411 // Is the IP user able to create accounts?
412 $anon = new User;
413 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
414 || $anon->isBlockedFromCreateAccount()
416 // Blacklist the user to avoid repeated DB queries subsequently
417 $logger->debug( __METHOD__ . ': user is blocked from this wiki, blacklisting' );
418 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
419 $session->persist();
420 $user->setId( 0 );
421 $user->loadFromId();
422 return false;
425 // Check for validity of username
426 if ( !User::isCreatableName( $userName ) ) {
427 $logger->debug( __METHOD__ . ': Invalid username, blacklisting' );
428 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
429 $session->persist();
430 $user->setId( 0 );
431 $user->loadFromId();
432 return false;
435 // Give other extensions a chance to stop auto creation.
436 $user->loadDefaults( $userName );
437 $abortMessage = '';
438 if ( !\Hooks::run( 'AbortAutoAccount', array( $user, &$abortMessage ) ) ) {
439 // In this case we have no way to return the message to the user,
440 // but we can log it.
441 $logger->debug( __METHOD__ . ": denied by hook: $abortMessage" );
442 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
443 $session->persist();
444 $user->setId( 0 );
445 $user->loadFromId();
446 return false;
449 // Make sure the name has not been changed
450 if ( $user->getName() !== $userName ) {
451 $user->setId( 0 );
452 $user->loadFromId();
453 throw new \UnexpectedValueException(
454 'AbortAutoAccount hook tried to change the user name'
458 // Ignore warnings about master connections/writes...hard to avoid here
459 \Profiler::instance()->getTransactionProfiler()->resetExpectations();
461 $cache = \ObjectCache::getLocalClusterInstance();
462 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
463 if ( $cache->get( $backoffKey ) ) {
464 $logger->debug( __METHOD__ . ': denied by prior creation attempt failures' );
465 $user->setId( 0 );
466 $user->loadFromId();
467 return false;
470 // Checks passed, create the user...
471 $from = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : 'CLI';
472 $logger->info( __METHOD__ . ": creating new user ($userName) - from: $from" );
474 try {
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() );
480 $user->setId( 0 );
481 $user->loadFromId();
482 return false;
483 // @codeCoverageIgnoreEnd
485 } catch ( \Exception $ex ) {
486 // @codeCoverageIgnoreStart
487 $logger->error( __METHOD__ . ': failed with exception ' . $ex->getMessage() );
488 // Do not keep throwing errors for a while
489 $cache->set( $backoffKey, 1, 600 );
490 // Bubble up error; which should normally trigger DB rollbacks
491 throw $ex;
492 // @codeCoverageIgnoreEnd
495 # Notify hooks (e.g. Newuserlog)
496 \Hooks::run( 'AuthPluginAutoCreate', array( $user ) );
497 \Hooks::run( 'LocalUserCreated', array( $user, true ) );
499 # Update user count
500 \DeferredUpdates::addUpdate( new \SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
502 # Watch user's userpage and talk page
503 $user->addWatch( $user->getUserPage(), \WatchedItem::IGNORE_USER_RIGHTS );
505 return true;
509 * Prevent future sessions for the user
511 * The intention is that the named account will never again be usable for
512 * normal login (i.e. there is no way to undo the prevention of access).
514 * @private For use from \\User::newSystemUser only
515 * @param string $username
517 public function preventSessionsForUser( $username ) {
518 $this->preventUsers[$username] = true;
520 // Reset the user's token to kill existing sessions
521 $user = User::newFromName( $username );
522 if ( $user && $user->getToken() ) {
523 $user->setToken( true );
524 $user->saveSettings();
527 // Instruct the session providers to kill any other sessions too.
528 foreach ( $this->getProviders() as $provider ) {
529 $provider->preventSessionsForUser( $username );
534 * Test if a user is prevented
535 * @private For use from SessionBackend only
536 * @param string $username
537 * @return bool
539 public function isUserSessionPrevented( $username ) {
540 return !empty( $this->preventUsers[$username] );
544 * Get the available SessionProviders
545 * @return SessionProvider[]
547 protected function getProviders() {
548 if ( $this->sessionProviders === null ) {
549 $this->sessionProviders = array();
550 foreach ( $this->config->get( 'SessionProviders' ) as $spec ) {
551 $provider = \ObjectFactory::getObjectFromSpec( $spec );
552 $provider->setLogger( $this->logger );
553 $provider->setConfig( $this->config );
554 $provider->setManager( $this );
555 if ( isset( $this->sessionProviders[(string)$provider] ) ) {
556 throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
558 $this->sessionProviders[(string)$provider] = $provider;
561 return $this->sessionProviders;
565 * Get a session provider by name
567 * Generally, this will only be used by internal implementation of some
568 * special session-providing mechanism. General purpose code, if it needs
569 * to access a SessionProvider at all, will use Session::getProvider().
571 * @param string $name
572 * @return SessionProvider|null
574 public function getProvider( $name ) {
575 $providers = $this->getProviders();
576 return isset( $providers[$name] ) ? $providers[$name] : null;
580 * Save all active sessions on shutdown
581 * @private For internal use with register_shutdown_function()
583 public function shutdown() {
584 if ( $this->allSessionBackends ) {
585 $this->logger->debug( 'Saving all sessions on shutdown' );
586 if ( session_id() !== '' ) {
587 // @codeCoverageIgnoreStart
588 session_write_close();
590 // @codeCoverageIgnoreEnd
591 foreach ( $this->allSessionBackends as $backend ) {
592 $backend->save( true );
598 * Fetch the SessionInfo(s) for a request
599 * @param WebRequest $request
600 * @return SessionInfo|null
602 private function getSessionInfoForRequest( WebRequest $request ) {
603 // Call all providers to fetch "the" session
604 $infos = array();
605 foreach ( $this->getProviders() as $provider ) {
606 $info = $provider->provideSessionInfo( $request );
607 if ( !$info ) {
608 continue;
610 if ( $info->getProvider() !== $provider ) {
611 throw new \UnexpectedValueException(
612 "$provider returned session info for a different provider: $info"
615 $infos[] = $info;
618 // Sort the SessionInfos. Then find the first one that can be
619 // successfully loaded, and then all the ones after it with the same
620 // priority.
621 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
622 $retInfos = array();
623 while ( $infos ) {
624 $info = array_pop( $infos );
625 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
626 $retInfos[] = $info;
627 while ( $infos ) {
628 $info = array_pop( $infos );
629 if ( SessionInfo::compare( $retInfos[0], $info ) ) {
630 // We hit a lower priority, stop checking.
631 break;
633 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
634 // This is going to error out below, but we want to
635 // provide a complete list.
636 $retInfos[] = $info;
642 if ( count( $retInfos ) > 1 ) {
643 $ex = new \OverflowException(
644 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
646 $ex->sessionInfos = $retInfos;
647 throw $ex;
650 return $retInfos ? $retInfos[0] : null;
654 * Load and verify the session info against the store
656 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
657 * @param WebRequest $request
658 * @return bool Whether the session info matches the stored data (if any)
660 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
661 $key = wfMemcKey( 'MWSession', $info->getId() );
662 $blob = $this->store->get( $key );
664 $newParams = array();
666 if ( $blob !== false ) {
667 // Sanity check: blob must be an array, if it's saved at all
668 if ( !is_array( $blob ) ) {
669 $this->logger->warning( "Session $info: Bad data" );
670 $this->store->delete( $key );
671 return false;
674 // Sanity check: blob has data and metadata arrays
675 if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
676 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
678 $this->logger->warning( "Session $info: Bad data structure" );
679 $this->store->delete( $key );
680 return false;
683 $data = $blob['data'];
684 $metadata = $blob['metadata'];
686 // Sanity check: metadata must be an array and must contain certain
687 // keys, if it's saved at all
688 if ( !array_key_exists( 'userId', $metadata ) ||
689 !array_key_exists( 'userName', $metadata ) ||
690 !array_key_exists( 'userToken', $metadata ) ||
691 !array_key_exists( 'provider', $metadata )
693 $this->logger->warning( "Session $info: Bad metadata" );
694 $this->store->delete( $key );
695 return false;
698 // First, load the provider from metadata, or validate it against the metadata.
699 $provider = $info->getProvider();
700 if ( $provider === null ) {
701 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
702 if ( !$provider ) {
703 $this->logger->warning( "Session $info: Unknown provider, " . $metadata['provider'] );
704 $this->store->delete( $key );
705 return false;
707 } elseif ( $metadata['provider'] !== (string)$provider ) {
708 $this->logger->warning( "Session $info: Wrong provider, " .
709 $metadata['provider'] . ' !== ' . $provider );
710 return false;
713 // Load provider metadata from metadata, or validate it against the metadata
714 $providerMetadata = $info->getProviderMetadata();
715 if ( isset( $metadata['providerMetadata'] ) ) {
716 if ( $providerMetadata === null ) {
717 $newParams['metadata'] = $metadata['providerMetadata'];
718 } else {
719 try {
720 $newProviderMetadata = $provider->mergeMetadata(
721 $metadata['providerMetadata'], $providerMetadata
723 if ( $newProviderMetadata !== $providerMetadata ) {
724 $newParams['metadata'] = $newProviderMetadata;
726 } catch ( \UnexpectedValueException $ex ) {
727 $this->logger->warning( "Session $info: Metadata merge failed: " . $ex->getMessage() );
728 return false;
733 // Next, load the user from metadata, or validate it against the metadata.
734 $userInfo = $info->getUserInfo();
735 if ( !$userInfo ) {
736 // For loading, id is preferred to name.
737 try {
738 if ( $metadata['userId'] ) {
739 $userInfo = UserInfo::newFromId( $metadata['userId'] );
740 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
741 $userInfo = UserInfo::newFromName( $metadata['userName'] );
742 } else {
743 $userInfo = UserInfo::newAnonymous();
745 } catch ( \InvalidArgumentException $ex ) {
746 $this->logger->error( "Session $info: " . $ex->getMessage() );
747 return false;
749 $newParams['userInfo'] = $userInfo;
750 } else {
751 // User validation passes if user ID matches, or if there
752 // is no saved ID and the names match.
753 if ( $metadata['userId'] ) {
754 if ( $metadata['userId'] !== $userInfo->getId() ) {
755 $this->logger->warning( "Session $info: User ID mismatch, " .
756 $metadata['userId'] . ' !== ' . $userInfo->getId() );
757 return false;
760 // If the user was renamed, probably best to fail here.
761 if ( $metadata['userName'] !== null &&
762 $userInfo->getName() !== $metadata['userName']
764 $this->logger->warning( "Session $info: User ID matched but name didn't (rename?), " .
765 $metadata['userName'] . ' !== ' . $userInfo->getName() );
766 return false;
769 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
770 if ( $metadata['userName'] !== $userInfo->getName() ) {
771 $this->logger->warning( "Session $info: User name mismatch, " .
772 $metadata['userName'] . ' !== ' . $userInfo->getName() );
773 return false;
775 } elseif ( !$userInfo->isAnon() ) {
776 // Metadata specifies an anonymous user, but the passed-in
777 // user isn't anonymous.
778 $this->logger->warning(
779 "Session $info: Metadata has an anonymous user, " .
780 'but a non-anon user was provided'
782 return false;
786 // And if we have a token in the metadata, it must match the loaded/provided user.
787 if ( $metadata['userToken'] !== null &&
788 $userInfo->getToken() !== $metadata['userToken']
790 $this->logger->warning( "Session $info: User token mismatch" );
791 return false;
793 if ( !$userInfo->isVerified() ) {
794 $newParams['userInfo'] = $userInfo->verified();
797 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
798 $newParams['remembered'] = true;
800 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
801 $newParams['forceHTTPS'] = true;
804 if ( !$info->isIdSafe() ) {
805 $newParams['idIsSafe'] = true;
807 } else {
808 // No metadata, so we can't load the provider if one wasn't given.
809 if ( $info->getProvider() === null ) {
810 $this->logger->warning( "Session $info: Null provider and no metadata" );
811 return false;
814 // If no user was provided and no metadata, it must be anon.
815 if ( !$info->getUserInfo() ) {
816 if ( $info->getProvider()->canChangeUser() ) {
817 $newParams['userInfo'] = UserInfo::newAnonymous();
818 } else {
819 $this->logger->info(
820 "Session $info: No user provided and provider cannot set user"
822 return false;
824 } elseif ( !$info->getUserInfo()->isVerified() ) {
825 $this->logger->warning(
826 "Session $info: Unverified user provided and no metadata to auth it"
828 return false;
831 $data = false;
832 $metadata = false;
834 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
835 // The ID doesn't come from the user, so it should be safe
836 // (and if not, nothing we can do about it anyway)
837 $newParams['idIsSafe'] = true;
841 // Construct the replacement SessionInfo, if necessary
842 if ( $newParams ) {
843 $newParams['copyFrom'] = $info;
844 $info = new SessionInfo( $info->getPriority(), $newParams );
847 // Allow the provider to check the loaded SessionInfo
848 $providerMetadata = $info->getProviderMetadata();
849 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
850 return false;
852 if ( $providerMetadata !== $info->getProviderMetadata() ) {
853 $info = new SessionInfo( $info->getPriority(), array(
854 'metadata' => $providerMetadata,
855 'copyFrom' => $info,
856 ) );
859 // Give hooks a chance to abort. Combined with the SessionMetadata
860 // hook, this can allow for tying a session to an IP address or the
861 // like.
862 $reason = 'Hook aborted';
863 if ( !\Hooks::run(
864 'SessionCheckInfo',
865 array( &$reason, $info, $request, $metadata, $data )
866 ) ) {
867 $this->logger->warning( "Session $info: $reason" );
868 return false;
871 return true;
875 * Create a session corresponding to the passed SessionInfo
876 * @private For use by a SessionProvider that needs to specially create its
877 * own session.
878 * @param SessionInfo $info
879 * @param WebRequest $request
880 * @return Session
882 public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
883 $id = $info->getId();
885 if ( !isset( $this->allSessionBackends[$id] ) ) {
886 if ( !isset( $this->allSessionIds[$id] ) ) {
887 $this->allSessionIds[$id] = new SessionId( $id );
889 $backend = new SessionBackend(
890 $this->allSessionIds[$id],
891 $info,
892 $this->store,
893 $this->logger,
894 $this->config->get( 'ObjectCacheSessionExpiry' )
896 $this->allSessionBackends[$id] = $backend;
897 $delay = $backend->delaySave();
898 } else {
899 $backend = $this->allSessionBackends[$id];
900 $delay = $backend->delaySave();
901 if ( $info->wasPersisted() ) {
902 $backend->persist();
904 if ( $info->wasRemembered() ) {
905 $backend->setRememberUser( true );
909 $request->setSessionId( $backend->getSessionId() );
910 $session = $backend->getSession( $request );
912 if ( !$info->isIdSafe() ) {
913 $session->resetId();
916 \ScopedCallback::consume( $delay );
917 return $session;
921 * Deregister a SessionBackend
922 * @private For use from \\MediaWiki\\Session\\SessionBackend only
923 * @param SessionBackend $backend
925 public function deregisterSessionBackend( SessionBackend $backend ) {
926 $id = $backend->getId();
927 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
928 $this->allSessionBackends[$id] !== $backend ||
929 $this->allSessionIds[$id] !== $backend->getSessionId()
931 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
934 unset( $this->allSessionBackends[$id] );
935 // Explicitly do not unset $this->allSessionIds[$id]
939 * Change a SessionBackend's ID
940 * @private For use from \\MediaWiki\\Session\\SessionBackend only
941 * @param SessionBackend $backend
943 public function changeBackendId( SessionBackend $backend ) {
944 $sessionId = $backend->getSessionId();
945 $oldId = (string)$sessionId;
946 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
947 $this->allSessionBackends[$oldId] !== $backend ||
948 $this->allSessionIds[$oldId] !== $sessionId
950 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
953 $newId = $this->generateSessionId();
955 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
956 $sessionId->setId( $newId );
957 $this->allSessionBackends[$newId] = $backend;
958 $this->allSessionIds[$newId] = $sessionId;
962 * Generate a new random session ID
963 * @return string
965 public function generateSessionId() {
966 do {
967 $id = wfBaseConvert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
968 $key = wfMemcKey( 'MWSession', $id );
969 } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
970 return $id;
974 * Call setters on a PHPSessionHandler
975 * @private Use PhpSessionHandler::install()
976 * @param PHPSessionHandler $handler
978 public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
979 $handler->setManager( $this, $this->store, $this->logger );
983 * Reset the internal caching for unit testing
985 public static function resetCache() {
986 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
987 // @codeCoverageIgnoreStart
988 throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
989 // @codeCoverageIgnoreEnd
992 self::$globalSession = null;
993 self::$globalSessionRequest = null;
996 /**@}*/