28use Psr\Log\LoggerInterface;
92 if ( self::$instance ===
null ) {
93 self::$instance =
new self();
113 $request = \RequestContext::getMain()->getRequest();
115 !self::$globalSession
116 || self::$globalSessionRequest !==
$request
117 || $id !==
'' && self::$globalSession->getId() !== $id
119 self::$globalSessionRequest =
$request;
129 self::$globalSession =
$request->getSession();
148 if ( isset(
$options[
'config'] ) ) {
150 if ( !$this->config instanceof
Config ) {
151 throw new \InvalidArgumentException(
152 '$options[\'config\'] must be an instance of Config'
159 if ( isset(
$options[
'logger'] ) ) {
160 if ( !
$options[
'logger'] instanceof LoggerInterface ) {
161 throw new \InvalidArgumentException(
162 '$options[\'logger\'] must be an instance of LoggerInterface'
172 throw new \InvalidArgumentException(
173 '$options[\'store\'] must be an instance of BagOStuff'
178 $store = \ObjectCache::getInstance( $this->config->get(
'SessionCacheType' ) );
182 register_shutdown_function( [ $this,
'shutdown' ] );
201 if ( !self::validateSessionId( $id ) ) {
202 throw new \InvalidArgumentException(
'Invalid session ID' );
212 if ( isset( $this->allSessionBackends[$id] ) ) {
217 $key = $this->store->makeKey(
'MWSession', $id );
218 if ( is_array( $this->store->get( $key ) ) ) {
225 if ( $create && $session ===
null ) {
229 }
catch ( \Exception $ex ) {
230 $this->logger->error(
'Failed to create empty session: {exception}',
232 'method' => __METHOD__,
253 if ( $id !==
null ) {
254 if ( !self::validateSessionId( $id ) ) {
255 throw new \InvalidArgumentException(
'Invalid session ID' );
258 $key = $this->store->makeKey(
'MWSession', $id );
259 if ( is_array( $this->store->get( $key ) ) ) {
260 throw new \InvalidArgumentException(
'Session ID already exists' );
269 $info = $provider->newSessionInfo( $id );
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"
290 if ( $compare > 0 ) {
293 if ( $compare === 0 ) {
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!' );
314 $user->saveSettings();
316 $authUser = \MediaWiki\Auth\AuthManager::callLegacyAuthPlugin(
'getUserInstance', [ &$user ] );
318 $authUser->resetAuthToken();
322 $provider->invalidateSessionsForUser( $user );
328 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
332 if ( $this->varyHeaders ===
null ) {
336 if ( !isset( $headers[
$header] ) ) {
344 $this->varyHeaders = $headers;
351 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
355 if ( $this->varyCookies ===
null ) {
358 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
360 $this->varyCookies = array_values( array_unique( $cookies ) );
371 return is_string( $id ) && preg_match(
'/^[a-zA-Z0-9_-]{32,}$/', $id );
389 return \MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
391 \
MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
410 $provider->preventSessionsForUser(
$username );
421 return !empty( $this->preventUsers[
$username] );
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;
457 return isset( $providers[$name] ) ? $providers[
$name] :
null;
465 if ( $this->allSessionBackends ) {
466 $this->logger->debug(
'Saving all sessions on shutdown' );
467 if ( session_id() !==
'' ) {
469 session_write_close();
472 foreach ( $this->allSessionBackends as $backend ) {
473 $backend->shutdown();
487 $info = $provider->provideSessionInfo(
$request );
491 if ( $info->getProvider() !== $provider ) {
492 throw new \UnexpectedValueException(
493 "$provider returned session info for a different provider: $info"
502 usort( $infos,
'MediaWiki\\Session\\SessionInfo::compare' );
505 $info = array_pop( $infos );
509 $info = array_pop( $infos );
520 $info->getProvider()->unpersistSession(
$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;
537 return $retInfos ? $retInfos[0] :
null;
548 $key = $this->store->makeKey(
'MWSession', $info->
getId() );
549 $blob = $this->store->get( $key );
555 $failHandler =
function () use ( $key, &$info,
$request ) {
556 $this->store->delete( $key );
560 $failHandler =
function () {
567 if (
$blob !==
false ) {
569 if ( !is_array(
$blob ) ) {
570 $this->logger->warning(
'Session "{session}": Bad data', [
573 $this->store->delete( $key );
574 return $failHandler();
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', [
584 $this->store->delete( $key );
585 return $failHandler();
588 $data =
$blob[
'data'];
589 $metadata =
$blob[
'metadata'];
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', [
601 $this->store->delete( $key );
602 return $failHandler();
607 if ( $provider ===
null ) {
608 $newParams[
'provider'] = $provider = $this->
getProvider( $metadata[
'provider'] );
610 $this->logger->warning(
611 'Session "{session}": Unknown provider ' . $metadata[
'provider'],
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,
625 return $failHandler();
630 if ( isset( $metadata[
'providerMetadata'] ) ) {
631 if ( $providerMetadata ===
null ) {
632 $newParams[
'metadata'] = $metadata[
'providerMetadata'];
635 $newProviderMetadata = $provider->mergeMetadata(
636 $metadata[
'providerMetadata'], $providerMetadata
638 if ( $newProviderMetadata !== $providerMetadata ) {
639 $newParams[
'metadata'] = $newProviderMetadata;
642 $this->logger->warning(
643 'Session "{session}": Metadata merge failed: {exception}',
647 ] + $ex->getContext()
649 return $failHandler();
659 if ( $metadata[
'userId'] ) {
661 } elseif ( $metadata[
'userName'] !==
null ) {
666 }
catch ( \InvalidArgumentException $ex ) {
667 $this->logger->error(
'Session "{session}": {exception}', [
671 return $failHandler();
673 $newParams[
'userInfo'] = $userInfo;
677 if ( $metadata[
'userId'] ) {
678 if ( $metadata[
'userId'] !== $userInfo->getId() ) {
679 $this->logger->warning(
680 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
683 'uid_a' => $metadata[
'userId'],
684 'uid_b' => $userInfo->
getId(),
686 return $failHandler();
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}',
697 'uname_a' => $metadata[
'userName'],
698 'uname_b' => $userInfo->getName(),
700 return $failHandler();
703 } elseif ( $metadata[
'userName'] !==
null ) {
704 if ( $metadata[
'userName'] !== $userInfo->getName() ) {
705 $this->logger->warning(
706 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
709 'uname_a' => $metadata[
'userName'],
710 'uname_b' => $userInfo->getName(),
712 return $failHandler();
714 } elseif ( !$userInfo->isAnon() ) {
717 $this->logger->warning(
718 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
722 return $failHandler();
727 if ( $metadata[
'userToken'] !==
null &&
728 $userInfo->getToken() !== $metadata[
'userToken']
730 $this->logger->warning(
'Session "{session}": User token mismatch', [
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;
750 $newParams[
'idIsSafe'] =
true;
755 $this->logger->warning(
756 'Session "{session}": Null provider and no metadata',
760 return $failHandler();
769 'Session "{session}": No user provided and provider cannot set user',
773 return $failHandler();
778 'Session "{session}": Unverified user provided and no metadata to auth it',
782 return $failHandler();
791 $newParams[
'idIsSafe'] =
true;
797 $newParams[
'copyFrom'] = $info;
804 return $failHandler();
808 'metadata' => $providerMetadata,
816 $reason =
'Hook aborted';
819 [ &$reason, $info,
$request, $metadata, $data ]
821 $this->logger->warning(
'Session "{session}": ' . $reason, [
824 return $failHandler();
840 if ( defined(
'MW_NO_SESSION' ) ) {
843 $this->logger->error(
'Sessions are supposed to be disabled for this entry point', [
844 'exception' =>
new \BadMethodCallException(
'Sessions are disabled for this entry point' ),
847 throw new \BadMethodCallException(
'Sessions are disabled for this entry point' );
852 $id = $info->
getId();
854 if ( !isset( $this->allSessionBackends[$id] ) ) {
855 if ( !isset( $this->allSessionIds[$id] ) ) {
856 $this->allSessionIds[$id] =
new SessionId( $id );
859 $this->allSessionIds[$id],
863 $this->config->get(
'ObjectCacheSessionExpiry' )
865 $this->allSessionBackends[$id] = $backend;
866 $delay = $backend->delaySave();
868 $backend = $this->allSessionBackends[$id];
869 $delay = $backend->delaySave();
874 $backend->setRememberUser(
true );
878 $request->setSessionId( $backend->getSessionId() );
879 $session = $backend->getSession(
$request );
885 \Wikimedia\ScopedCallback::consume( $delay );
895 $id = $backend->
getId();
896 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
897 $this->allSessionBackends[$id] !== $backend ||
900 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
903 unset( $this->allSessionBackends[$id] );
914 $oldId = (
string)$sessionId;
915 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
916 $this->allSessionBackends[$oldId] !== $backend ||
917 $this->allSessionIds[$oldId] !== $sessionId
919 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
924 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
925 $sessionId->setId( $newId );
926 $this->allSessionBackends[$newId] = $backend;
927 $this->allSessionIds[$newId] = $sessionId;
937 $key = $this->store->makeKey(
'MWSession', $id );
938 }
while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
948 $handler->setManager( $this, $this->store, $this->logger );
956 if ( !defined(
'MW_PHPUNIT_TEST' ) ) {
958 throw new MWException( __METHOD__ .
' may only be called from unit tests!' );
962 self::$globalSession =
null;
963 self::$globalSessionRequest =
null;
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
interface is intended to be more or less compatible with the PHP memcached client.
Wrapper around a BagOStuff that caches data in memory.
WebRequest clone which takes values from a provided array.
static generateHex( $chars, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in hexadecimal string format.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
this hook is for auditing only or null if authentication failed before getting that far $username
Allows to change the fields on the form that will be generated $name
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Interface for configuration instances.