Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / session / SessionManager.php
blob0041450f86540b0a0343867f3d91292dff7c74d2
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 MediaWiki\MediaWikiServices;
27 use MWException;
28 use Psr\Log\LoggerInterface;
29 use BagOStuff;
30 use CachedBagOStuff;
31 use Config;
32 use FauxRequest;
33 use User;
34 use WebRequest;
36 /**
37 * This serves as the entry point to the MediaWiki session handling system.
39 * Most methods here are for internal use by session handling code. Other callers
40 * should only use getGlobalSession and the methods of SessionManagerInterface;
41 * the rest of the functionality is exposed via MediaWiki\Session\Session methods.
43 * To provide custom session handling, implement a MediaWiki\Session\SessionProvider.
45 * @ingroup Session
46 * @since 1.27
47 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
49 final class SessionManager implements SessionManagerInterface {
50 /** @var SessionManager|null */
51 private static $instance = null;
53 /** @var Session|null */
54 private static $globalSession = null;
56 /** @var WebRequest|null */
57 private static $globalSessionRequest = null;
59 /** @var LoggerInterface */
60 private $logger;
62 /** @var Config */
63 private $config;
65 /** @var CachedBagOStuff|null */
66 private $store;
68 /** @var SessionProvider[] */
69 private $sessionProviders = null;
71 /** @var string[] */
72 private $varyCookies = null;
74 /** @var array */
75 private $varyHeaders = null;
77 /** @var SessionBackend[] */
78 private $allSessionBackends = [];
80 /** @var SessionId[] */
81 private $allSessionIds = [];
83 /** @var string[] */
84 private $preventUsers = [];
86 /**
87 * Get the global SessionManager
88 * @return SessionManagerInterface
89 * (really a SessionManager, but this is to make IDEs less confused)
91 public static function singleton() {
92 if ( self::$instance === null ) {
93 self::$instance = new self();
95 return self::$instance;
98 /**
99 * Get the "global" session
101 * If PHP's session_id() has been set, returns that session. Otherwise
102 * returns the session for RequestContext::getMain()->getRequest().
104 * @return Session
106 public static function getGlobalSession() {
107 if ( !PHPSessionHandler::isEnabled() ) {
108 $id = '';
109 } else {
110 $id = session_id();
113 $request = \RequestContext::getMain()->getRequest();
114 if (
115 !self::$globalSession // No global session is set up yet
116 || self::$globalSessionRequest !== $request // The global WebRequest changed
117 || $id !== '' && self::$globalSession->getId() !== $id // Someone messed with session_id()
119 self::$globalSessionRequest = $request;
120 if ( $id === '' ) {
121 // session_id() wasn't used, so fetch the Session from the WebRequest.
122 // We use $request->getSession() instead of $singleton->getSessionForRequest()
123 // because doing the latter would require a public
124 // "$request->getSessionId()" method that would confuse end
125 // users by returning SessionId|null where they'd expect it to
126 // be short for $request->getSession()->getId(), and would
127 // wind up being a duplicate of the code in
128 // $request->getSession() anyway.
129 self::$globalSession = $request->getSession();
130 } else {
131 // Someone used session_id(), so we need to follow suit.
132 // Note this overwrites whatever session might already be
133 // associated with $request with the one for $id.
134 self::$globalSession = self::singleton()->getSessionById( $id, true, $request )
135 ?: $request->getSession();
138 return self::$globalSession;
142 * @param array $options
143 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
144 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
145 * - store: BagOStuff to store session data in.
147 public function __construct( $options = [] ) {
148 if ( isset( $options['config'] ) ) {
149 $this->config = $options['config'];
150 if ( !$this->config instanceof Config ) {
151 throw new \InvalidArgumentException(
152 '$options[\'config\'] must be an instance of Config'
155 } else {
156 $this->config = MediaWikiServices::getInstance()->getMainConfig();
159 if ( isset( $options['logger'] ) ) {
160 if ( !$options['logger'] instanceof LoggerInterface ) {
161 throw new \InvalidArgumentException(
162 '$options[\'logger\'] must be an instance of LoggerInterface'
165 $this->setLogger( $options['logger'] );
166 } else {
167 $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'session' ) );
170 if ( isset( $options['store'] ) ) {
171 if ( !$options['store'] instanceof BagOStuff ) {
172 throw new \InvalidArgumentException(
173 '$options[\'store\'] must be an instance of BagOStuff'
176 $store = $options['store'];
177 } else {
178 $store = \ObjectCache::getInstance( $this->config->get( 'SessionCacheType' ) );
180 $this->store = $store instanceof CachedBagOStuff ? $store : new CachedBagOStuff( $store );
182 register_shutdown_function( [ $this, 'shutdown' ] );
185 public function setLogger( LoggerInterface $logger ) {
186 $this->logger = $logger;
189 public function getSessionForRequest( WebRequest $request ) {
190 $info = $this->getSessionInfoForRequest( $request );
192 if ( !$info ) {
193 $session = $this->getEmptySession( $request );
194 } else {
195 $session = $this->getSessionFromInfo( $info, $request );
197 return $session;
200 public function getSessionById( $id, $create = false, WebRequest $request = null ) {
201 if ( !self::validateSessionId( $id ) ) {
202 throw new \InvalidArgumentException( 'Invalid session ID' );
204 if ( !$request ) {
205 $request = new FauxRequest;
208 $session = null;
209 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [ 'id' => $id, 'idIsSafe' => true ] );
211 // If we already have the backend loaded, use it directly
212 if ( isset( $this->allSessionBackends[$id] ) ) {
213 return $this->getSessionFromInfo( $info, $request );
216 // Test if the session is in storage, and if so try to load it.
217 $key = wfMemcKey( 'MWSession', $id );
218 if ( is_array( $this->store->get( $key ) ) ) {
219 $create = false; // If loading fails, don't bother creating because it probably will fail too.
220 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
221 $session = $this->getSessionFromInfo( $info, $request );
225 if ( $create && $session === null ) {
226 $ex = null;
227 try {
228 $session = $this->getEmptySessionInternal( $request, $id );
229 } catch ( \Exception $ex ) {
230 $this->logger->error( 'Failed to create empty session: {exception}',
232 'method' => __METHOD__,
233 'exception' => $ex,
234 ] );
235 $session = null;
239 return $session;
242 public function getEmptySession( WebRequest $request = null ) {
243 return $this->getEmptySessionInternal( $request );
247 * @see SessionManagerInterface::getEmptySession
248 * @param WebRequest|null $request
249 * @param string|null $id ID to force on the new session
250 * @return Session
252 private function getEmptySessionInternal( WebRequest $request = null, $id = null ) {
253 if ( $id !== null ) {
254 if ( !self::validateSessionId( $id ) ) {
255 throw new \InvalidArgumentException( 'Invalid session ID' );
258 $key = wfMemcKey( 'MWSession', $id );
259 if ( is_array( $this->store->get( $key ) ) ) {
260 throw new \InvalidArgumentException( 'Session ID already exists' );
263 if ( !$request ) {
264 $request = new FauxRequest;
267 $infos = [];
268 foreach ( $this->getProviders() as $provider ) {
269 $info = $provider->newSessionInfo( $id );
270 if ( !$info ) {
271 continue;
273 if ( $info->getProvider() !== $provider ) {
274 throw new \UnexpectedValueException(
275 "$provider returned an empty session info for a different provider: $info"
278 if ( $id !== null && $info->getId() !== $id ) {
279 throw new \UnexpectedValueException(
280 "$provider returned empty session info with a wrong id: " .
281 $info->getId() . ' != ' . $id
284 if ( !$info->isIdSafe() ) {
285 throw new \UnexpectedValueException(
286 "$provider returned empty session info with id flagged unsafe"
289 $compare = $infos ? SessionInfo::compare( $infos[0], $info ) : -1;
290 if ( $compare > 0 ) {
291 continue;
293 if ( $compare === 0 ) {
294 $infos[] = $info;
295 } else {
296 $infos = [ $info ];
300 // Make sure there's exactly one
301 if ( count( $infos ) > 1 ) {
302 throw new \UnexpectedValueException(
303 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
305 } elseif ( count( $infos ) < 1 ) {
306 throw new \UnexpectedValueException( 'No provider could provide an empty session!' );
309 return $this->getSessionFromInfo( $infos[0], $request );
312 public function invalidateSessionsForUser( User $user ) {
313 $user->setToken();
314 $user->saveSettings();
316 $authUser = \MediaWiki\Auth\AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$user ] );
317 if ( $authUser ) {
318 $authUser->resetAuthToken();
321 foreach ( $this->getProviders() as $provider ) {
322 $provider->invalidateSessionsForUser( $user );
326 public function getVaryHeaders() {
327 // @codeCoverageIgnoreStart
328 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
329 return [];
331 // @codeCoverageIgnoreEnd
332 if ( $this->varyHeaders === null ) {
333 $headers = [];
334 foreach ( $this->getProviders() as $provider ) {
335 foreach ( $provider->getVaryHeaders() as $header => $options ) {
336 if ( !isset( $headers[$header] ) ) {
337 $headers[$header] = [];
339 if ( is_array( $options ) ) {
340 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
344 $this->varyHeaders = $headers;
346 return $this->varyHeaders;
349 public function getVaryCookies() {
350 // @codeCoverageIgnoreStart
351 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
352 return [];
354 // @codeCoverageIgnoreEnd
355 if ( $this->varyCookies === null ) {
356 $cookies = [];
357 foreach ( $this->getProviders() as $provider ) {
358 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
360 $this->varyCookies = array_values( array_unique( $cookies ) );
362 return $this->varyCookies;
366 * Validate a session ID
367 * @param string $id
368 * @return bool
370 public static function validateSessionId( $id ) {
371 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
375 * @name Internal methods
376 * @{
380 * Auto-create the given user, if necessary
381 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
382 * @deprecated since 1.27, use MediaWiki\Auth\AuthManager::autoCreateUser instead
383 * @param User $user User to auto-create
384 * @return bool Success
385 * @codeCoverageIgnore
387 public static function autoCreateUser( User $user ) {
388 wfDeprecated( __METHOD__, '1.27' );
389 return \MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
390 $user,
391 \MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
392 false
393 )->isGood();
397 * Prevent future sessions for the user
399 * The intention is that the named account will never again be usable for
400 * normal login (i.e. there is no way to undo the prevention of access).
402 * @private For use from \User::newSystemUser only
403 * @param string $username
405 public function preventSessionsForUser( $username ) {
406 $this->preventUsers[$username] = true;
408 // Instruct the session providers to kill any other sessions too.
409 foreach ( $this->getProviders() as $provider ) {
410 $provider->preventSessionsForUser( $username );
415 * Test if a user is prevented
416 * @private For use from SessionBackend only
417 * @param string $username
418 * @return bool
420 public function isUserSessionPrevented( $username ) {
421 return !empty( $this->preventUsers[$username] );
425 * Get the available SessionProviders
426 * @return SessionProvider[]
428 protected function getProviders() {
429 if ( $this->sessionProviders === null ) {
430 $this->sessionProviders = [];
431 foreach ( $this->config->get( 'SessionProviders' ) as $spec ) {
432 $provider = \ObjectFactory::getObjectFromSpec( $spec );
433 $provider->setLogger( $this->logger );
434 $provider->setConfig( $this->config );
435 $provider->setManager( $this );
436 if ( isset( $this->sessionProviders[(string)$provider] ) ) {
437 throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
439 $this->sessionProviders[(string)$provider] = $provider;
442 return $this->sessionProviders;
446 * Get a session provider by name
448 * Generally, this will only be used by internal implementation of some
449 * special session-providing mechanism. General purpose code, if it needs
450 * to access a SessionProvider at all, will use Session::getProvider().
452 * @param string $name
453 * @return SessionProvider|null
455 public function getProvider( $name ) {
456 $providers = $this->getProviders();
457 return isset( $providers[$name] ) ? $providers[$name] : null;
461 * Save all active sessions on shutdown
462 * @private For internal use with register_shutdown_function()
464 public function shutdown() {
465 if ( $this->allSessionBackends ) {
466 $this->logger->debug( 'Saving all sessions on shutdown' );
467 if ( session_id() !== '' ) {
468 // @codeCoverageIgnoreStart
469 session_write_close();
471 // @codeCoverageIgnoreEnd
472 foreach ( $this->allSessionBackends as $backend ) {
473 $backend->shutdown();
479 * Fetch the SessionInfo(s) for a request
480 * @param WebRequest $request
481 * @return SessionInfo|null
483 private function getSessionInfoForRequest( WebRequest $request ) {
484 // Call all providers to fetch "the" session
485 $infos = [];
486 foreach ( $this->getProviders() as $provider ) {
487 $info = $provider->provideSessionInfo( $request );
488 if ( !$info ) {
489 continue;
491 if ( $info->getProvider() !== $provider ) {
492 throw new \UnexpectedValueException(
493 "$provider returned session info for a different provider: $info"
496 $infos[] = $info;
499 // Sort the SessionInfos. Then find the first one that can be
500 // successfully loaded, and then all the ones after it with the same
501 // priority.
502 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
503 $retInfos = [];
504 while ( $infos ) {
505 $info = array_pop( $infos );
506 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
507 $retInfos[] = $info;
508 while ( $infos ) {
509 $info = array_pop( $infos );
510 if ( SessionInfo::compare( $retInfos[0], $info ) ) {
511 // We hit a lower priority, stop checking.
512 break;
514 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
515 // This is going to error out below, but we want to
516 // provide a complete list.
517 $retInfos[] = $info;
518 } else {
519 // Session load failed, so unpersist it from this request
520 $info->getProvider()->unpersistSession( $request );
523 } else {
524 // Session load failed, so unpersist it from this request
525 $info->getProvider()->unpersistSession( $request );
529 if ( count( $retInfos ) > 1 ) {
530 $ex = new \OverflowException(
531 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
533 $ex->sessionInfos = $retInfos;
534 throw $ex;
537 return $retInfos ? $retInfos[0] : null;
541 * Load and verify the session info against the store
543 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
544 * @param WebRequest $request
545 * @return bool Whether the session info matches the stored data (if any)
547 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
548 $key = wfMemcKey( 'MWSession', $info->getId() );
549 $blob = $this->store->get( $key );
551 // If we got data from the store and the SessionInfo says to force use,
552 // "fail" means to delete the data from the store and retry. Otherwise,
553 // "fail" is just return false.
554 if ( $info->forceUse() && $blob !== false ) {
555 $failHandler = function () use ( $key, &$info, $request ) {
556 $this->store->delete( $key );
557 return $this->loadSessionInfoFromStore( $info, $request );
559 } else {
560 $failHandler = function () {
561 return false;
565 $newParams = [];
567 if ( $blob !== false ) {
568 // Sanity check: blob must be an array, if it's saved at all
569 if ( !is_array( $blob ) ) {
570 $this->logger->warning( 'Session "{session}": Bad data', [
571 'session' => $info,
572 ] );
573 $this->store->delete( $key );
574 return $failHandler();
577 // Sanity check: blob has data and metadata arrays
578 if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
579 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
581 $this->logger->warning( 'Session "{session}": Bad data structure', [
582 'session' => $info,
583 ] );
584 $this->store->delete( $key );
585 return $failHandler();
588 $data = $blob['data'];
589 $metadata = $blob['metadata'];
591 // Sanity check: metadata must be an array and must contain certain
592 // keys, if it's saved at all
593 if ( !array_key_exists( 'userId', $metadata ) ||
594 !array_key_exists( 'userName', $metadata ) ||
595 !array_key_exists( 'userToken', $metadata ) ||
596 !array_key_exists( 'provider', $metadata )
598 $this->logger->warning( 'Session "{session}": Bad metadata', [
599 'session' => $info,
600 ] );
601 $this->store->delete( $key );
602 return $failHandler();
605 // First, load the provider from metadata, or validate it against the metadata.
606 $provider = $info->getProvider();
607 if ( $provider === null ) {
608 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
609 if ( !$provider ) {
610 $this->logger->warning(
611 'Session "{session}": Unknown provider ' . $metadata['provider'],
613 'session' => $info,
616 $this->store->delete( $key );
617 return $failHandler();
619 } elseif ( $metadata['provider'] !== (string)$provider ) {
620 $this->logger->warning( 'Session "{session}": Wrong provider ' .
621 $metadata['provider'] . ' !== ' . $provider,
623 'session' => $info,
624 ] );
625 return $failHandler();
628 // Load provider metadata from metadata, or validate it against the metadata
629 $providerMetadata = $info->getProviderMetadata();
630 if ( isset( $metadata['providerMetadata'] ) ) {
631 if ( $providerMetadata === null ) {
632 $newParams['metadata'] = $metadata['providerMetadata'];
633 } else {
634 try {
635 $newProviderMetadata = $provider->mergeMetadata(
636 $metadata['providerMetadata'], $providerMetadata
638 if ( $newProviderMetadata !== $providerMetadata ) {
639 $newParams['metadata'] = $newProviderMetadata;
641 } catch ( MetadataMergeException $ex ) {
642 $this->logger->warning(
643 'Session "{session}": Metadata merge failed: {exception}',
645 'session' => $info,
646 'exception' => $ex,
647 ] + $ex->getContext()
649 return $failHandler();
654 // Next, load the user from metadata, or validate it against the metadata.
655 $userInfo = $info->getUserInfo();
656 if ( !$userInfo ) {
657 // For loading, id is preferred to name.
658 try {
659 if ( $metadata['userId'] ) {
660 $userInfo = UserInfo::newFromId( $metadata['userId'] );
661 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
662 $userInfo = UserInfo::newFromName( $metadata['userName'] );
663 } else {
664 $userInfo = UserInfo::newAnonymous();
666 } catch ( \InvalidArgumentException $ex ) {
667 $this->logger->error( 'Session "{session}": {exception}', [
668 'session' => $info,
669 'exception' => $ex,
670 ] );
671 return $failHandler();
673 $newParams['userInfo'] = $userInfo;
674 } else {
675 // User validation passes if user ID matches, or if there
676 // is no saved ID and the names match.
677 if ( $metadata['userId'] ) {
678 if ( $metadata['userId'] !== $userInfo->getId() ) {
679 $this->logger->warning(
680 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
682 'session' => $info,
683 'uid_a' => $metadata['userId'],
684 'uid_b' => $userInfo->getId(),
685 ] );
686 return $failHandler();
689 // If the user was renamed, probably best to fail here.
690 if ( $metadata['userName'] !== null &&
691 $userInfo->getName() !== $metadata['userName']
693 $this->logger->warning(
694 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
696 'session' => $info,
697 'uname_a' => $metadata['userName'],
698 'uname_b' => $userInfo->getName(),
699 ] );
700 return $failHandler();
703 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
704 if ( $metadata['userName'] !== $userInfo->getName() ) {
705 $this->logger->warning(
706 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
708 'session' => $info,
709 'uname_a' => $metadata['userName'],
710 'uname_b' => $userInfo->getName(),
711 ] );
712 return $failHandler();
714 } elseif ( !$userInfo->isAnon() ) {
715 // Metadata specifies an anonymous user, but the passed-in
716 // user isn't anonymous.
717 $this->logger->warning(
718 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
720 'session' => $info,
721 ] );
722 return $failHandler();
726 // And if we have a token in the metadata, it must match the loaded/provided user.
727 if ( $metadata['userToken'] !== null &&
728 $userInfo->getToken() !== $metadata['userToken']
730 $this->logger->warning( 'Session "{session}": User token mismatch', [
731 'session' => $info,
732 ] );
733 return $failHandler();
735 if ( !$userInfo->isVerified() ) {
736 $newParams['userInfo'] = $userInfo->verified();
739 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
740 $newParams['remembered'] = true;
742 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
743 $newParams['forceHTTPS'] = true;
745 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
746 $newParams['persisted'] = true;
749 if ( !$info->isIdSafe() ) {
750 $newParams['idIsSafe'] = true;
752 } else {
753 // No metadata, so we can't load the provider if one wasn't given.
754 if ( $info->getProvider() === null ) {
755 $this->logger->warning(
756 'Session "{session}": Null provider and no metadata',
758 'session' => $info,
759 ] );
760 return $failHandler();
763 // If no user was provided and no metadata, it must be anon.
764 if ( !$info->getUserInfo() ) {
765 if ( $info->getProvider()->canChangeUser() ) {
766 $newParams['userInfo'] = UserInfo::newAnonymous();
767 } else {
768 $this->logger->info(
769 'Session "{session}": No user provided and provider cannot set user',
771 'session' => $info,
772 ] );
773 return $failHandler();
775 } elseif ( !$info->getUserInfo()->isVerified() ) {
776 $this->logger->warning(
777 'Session "{session}": Unverified user provided and no metadata to auth it',
779 'session' => $info,
780 ] );
781 return $failHandler();
784 $data = false;
785 $metadata = false;
787 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
788 // The ID doesn't come from the user, so it should be safe
789 // (and if not, nothing we can do about it anyway)
790 $newParams['idIsSafe'] = true;
794 // Construct the replacement SessionInfo, if necessary
795 if ( $newParams ) {
796 $newParams['copyFrom'] = $info;
797 $info = new SessionInfo( $info->getPriority(), $newParams );
800 // Allow the provider to check the loaded SessionInfo
801 $providerMetadata = $info->getProviderMetadata();
802 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
803 return $failHandler();
805 if ( $providerMetadata !== $info->getProviderMetadata() ) {
806 $info = new SessionInfo( $info->getPriority(), [
807 'metadata' => $providerMetadata,
808 'copyFrom' => $info,
809 ] );
812 // Give hooks a chance to abort. Combined with the SessionMetadata
813 // hook, this can allow for tying a session to an IP address or the
814 // like.
815 $reason = 'Hook aborted';
816 if ( !\Hooks::run(
817 'SessionCheckInfo',
818 [ &$reason, $info, $request, $metadata, $data ]
819 ) ) {
820 $this->logger->warning( 'Session "{session}": ' . $reason, [
821 'session' => $info,
822 ] );
823 return $failHandler();
826 return true;
830 * Create a Session corresponding to the passed SessionInfo
831 * @private For use by a SessionProvider that needs to specially create its
832 * own Session. Most session providers won't need this.
833 * @param SessionInfo $info
834 * @param WebRequest $request
835 * @return Session
837 public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
838 // @codeCoverageIgnoreStart
839 if ( defined( 'MW_NO_SESSION' ) ) {
840 if ( MW_NO_SESSION === 'warn' ) {
841 // Undocumented safety case for converting existing entry points
842 $this->logger->error( 'Sessions are supposed to be disabled for this entry point', [
843 'exception' => new \BadMethodCallException( 'Sessions are disabled for this entry point' ),
844 ] );
845 } else {
846 throw new \BadMethodCallException( 'Sessions are disabled for this entry point' );
849 // @codeCoverageIgnoreEnd
851 $id = $info->getId();
853 if ( !isset( $this->allSessionBackends[$id] ) ) {
854 if ( !isset( $this->allSessionIds[$id] ) ) {
855 $this->allSessionIds[$id] = new SessionId( $id );
857 $backend = new SessionBackend(
858 $this->allSessionIds[$id],
859 $info,
860 $this->store,
861 $this->logger,
862 $this->config->get( 'ObjectCacheSessionExpiry' )
864 $this->allSessionBackends[$id] = $backend;
865 $delay = $backend->delaySave();
866 } else {
867 $backend = $this->allSessionBackends[$id];
868 $delay = $backend->delaySave();
869 if ( $info->wasPersisted() ) {
870 $backend->persist();
872 if ( $info->wasRemembered() ) {
873 $backend->setRememberUser( true );
877 $request->setSessionId( $backend->getSessionId() );
878 $session = $backend->getSession( $request );
880 if ( !$info->isIdSafe() ) {
881 $session->resetId();
884 \Wikimedia\ScopedCallback::consume( $delay );
885 return $session;
889 * Deregister a SessionBackend
890 * @private For use from \MediaWiki\Session\SessionBackend only
891 * @param SessionBackend $backend
893 public function deregisterSessionBackend( SessionBackend $backend ) {
894 $id = $backend->getId();
895 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
896 $this->allSessionBackends[$id] !== $backend ||
897 $this->allSessionIds[$id] !== $backend->getSessionId()
899 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
902 unset( $this->allSessionBackends[$id] );
903 // Explicitly do not unset $this->allSessionIds[$id]
907 * Change a SessionBackend's ID
908 * @private For use from \MediaWiki\Session\SessionBackend only
909 * @param SessionBackend $backend
911 public function changeBackendId( SessionBackend $backend ) {
912 $sessionId = $backend->getSessionId();
913 $oldId = (string)$sessionId;
914 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
915 $this->allSessionBackends[$oldId] !== $backend ||
916 $this->allSessionIds[$oldId] !== $sessionId
918 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
921 $newId = $this->generateSessionId();
923 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
924 $sessionId->setId( $newId );
925 $this->allSessionBackends[$newId] = $backend;
926 $this->allSessionIds[$newId] = $sessionId;
930 * Generate a new random session ID
931 * @return string
933 public function generateSessionId() {
934 do {
935 $id = \Wikimedia\base_convert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
936 $key = wfMemcKey( 'MWSession', $id );
937 } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
938 return $id;
942 * Call setters on a PHPSessionHandler
943 * @private Use PhpSessionHandler::install()
944 * @param PHPSessionHandler $handler
946 public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
947 $handler->setManager( $this, $this->store, $this->logger );
951 * Reset the internal caching for unit testing
952 * @protected Unit tests only
954 public static function resetCache() {
955 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
956 // @codeCoverageIgnoreStart
957 throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
958 // @codeCoverageIgnoreEnd
961 self::$globalSession = null;
962 self::$globalSessionRequest = null;
965 /**@}*/