24 namespace MediaWiki\Session;
27 use Psr\Log\LoggerInterface;
84 if ( self::$instance === null ) {
85 self::$instance =
new self();
87 return self::$instance;
107 !self::$globalSession
108 || self::$globalSessionRequest !==
$request
109 || $id !==
'' && self::$globalSession->getId() !== $id
111 self::$globalSessionRequest =
$request;
121 self::$globalSession =
$request->getSession();
126 self::$globalSession = self::singleton()->getSessionById( $id,
true,
$request )
130 return self::$globalSession;
140 if ( isset(
$options[
'config'] ) ) {
142 if ( !$this->config instanceof
Config ) {
143 throw new \InvalidArgumentException(
144 '$options[\'config\'] must be an instance of Config'
151 if ( isset(
$options[
'logger'] ) ) {
152 if ( !
$options[
'logger'] instanceof LoggerInterface ) {
153 throw new \InvalidArgumentException(
154 '$options[\'logger\'] must be an instance of LoggerInterface'
164 throw new \InvalidArgumentException(
165 '$options[\'store\'] must be an instance of BagOStuff'
174 register_shutdown_function( [ $this,
'shutdown' ] );
193 if ( !self::validateSessionId( $id ) ) {
194 throw new \InvalidArgumentException(
'Invalid session ID' );
204 if ( isset( $this->allSessionBackends[$id] ) ) {
210 if ( is_array( $this->
store->get( $key ) ) ) {
217 if ( $create && $session === null ) {
221 }
catch ( \Exception $ex ) {
222 $this->logger->error(
'Failed to create empty session: {exception}',
224 'method' => __METHOD__,
245 if ( $id !== null ) {
246 if ( !self::validateSessionId( $id ) ) {
247 throw new \InvalidArgumentException(
'Invalid session ID' );
251 if ( is_array( $this->
store->get( $key ) ) ) {
252 throw new \InvalidArgumentException(
'Session ID already exists' );
261 $info = $provider->newSessionInfo( $id );
265 if ( $info->getProvider() !== $provider ) {
266 throw new \UnexpectedValueException(
267 "$provider returned an empty session info for a different provider: $info"
270 if ( $id !== null && $info->getId() !== $id ) {
271 throw new \UnexpectedValueException(
272 "$provider returned empty session info with a wrong id: " .
273 $info->getId() .
' != ' . $id
276 if ( !$info->isIdSafe() ) {
277 throw new \UnexpectedValueException(
278 "$provider returned empty session info with id flagged unsafe"
282 if ( $compare > 0 ) {
285 if ( $compare === 0 ) {
293 if ( count( $infos ) > 1 ) {
294 throw new \UnexpectedValueException(
295 'Multiple empty sessions tied for top priority: ' . implode(
', ', $infos )
297 } elseif ( count( $infos ) < 1 ) {
298 throw new \UnexpectedValueException(
'No provider could provide an empty session!' );
310 $authUser->resetAuthToken();
314 $provider->invalidateSessionsForUser( $user );
320 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
324 if ( $this->varyHeaders === null ) {
327 foreach ( $provider->getVaryHeaders()
as $header =>
$options ) {
328 if ( !isset( $headers[$header] ) ) {
329 $headers[$header] = [];
332 $headers[$header] = array_unique( array_merge( $headers[$header],
$options ) );
336 $this->varyHeaders = $headers;
343 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
347 if ( $this->varyCookies === null ) {
350 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
352 $this->varyCookies = array_values( array_unique( $cookies ) );
363 return is_string( $id ) && preg_match(
'/^[a-zA-Z0-9_-]{32,}$/', $id );
382 if ( !$wgDisableAuthManager ) {
384 return \MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
386 \
MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
392 $logger = self::singleton()->logger;
403 if ( !$localId &&
wfGetLB()->getReaderIndex() != 0 ) {
411 $user->
setId( $localId );
417 if ( get_class( $wgAuth ) !==
'AuthPlugin' && !$wgAuth->autoCreate() ) {
418 $logger->debug( __METHOD__ .
': denied by AuthPlugin' );
426 $logger->debug( __METHOD__ .
': denied by wfReadOnly()' );
436 $session = self::getGlobalSession();
437 $reason = $session->get(
'MWSession::AutoCreateBlacklist' );
439 $logger->debug( __METHOD__ .
": blacklisted in session ($reason)" );
447 if ( !$anon->isAllowedAny(
'createaccount',
'autocreateaccount' )
448 || $anon->isBlockedFromCreateAccount()
451 $logger->debug( __METHOD__ .
': user is blocked from this wiki, blacklisting' );
452 $session->set(
'MWSession::AutoCreateBlacklist',
'blocked', 600 );
461 $logger->debug( __METHOD__ .
': Invalid username, blacklisting' );
462 $session->set(
'MWSession::AutoCreateBlacklist',
'invalid username', 600 );
472 if ( !\
Hooks::run(
'AbortAutoAccount', [ $user, &$abortMessage ] ) ) {
475 $logger->debug( __METHOD__ .
": denied by hook: $abortMessage" );
476 $session->set(
'MWSession::AutoCreateBlacklist',
"hook aborted: $abortMessage", 600 );
484 if ( $user->
getName() !== $userName ) {
487 throw new \UnexpectedValueException(
488 'AbortAutoAccount hook tried to change the user name'
496 $backoffKey =
wfMemcKey(
'MWSession',
'autocreate-failed', md5( $userName ) );
497 if (
$cache->get( $backoffKey ) ) {
498 $logger->debug( __METHOD__ .
': denied by prior creation attempt failures' );
505 $from = isset( $_SERVER[
'REQUEST_URI'] ) ? $_SERVER[
'REQUEST_URI'] :
'CLI';
506 $logger->info( __METHOD__ .
': creating new user ({username}) - from: {url}',
508 'username' => $userName,
520 $logger->info( __METHOD__ .
': tried to autocreate existing user',
522 'username' => $userName,
526 __METHOD__ .
': failed with message ' .
$status->getWikiText(
false,
false,
'en' ),
528 'username' => $userName,
537 }
catch ( \Exception $ex ) {
539 $logger->error( __METHOD__ .
': failed with exception {exception}', [
541 'username' => $userName,
544 $cache->set( $backoffKey, 1, 600 );
553 $wgAuth->initUser( $tmpUser,
true );
554 if ( $tmpUser !== $user ) {
555 $logger->warning( __METHOD__ .
': ' .
556 get_class( $wgAuth ) .
'::initUser() replaced the user object' );
560 # Notify hooks (e.g. Newuserlog)
562 \Hooks::run(
'LocalUserCreated', [ $user,
true ] );
569 # Watch user's userpage and talk page
589 $provider->preventSessionsForUser(
$username );
600 return !empty( $this->preventUsers[
$username] );
608 if ( $this->sessionProviders === null ) {
609 $this->sessionProviders = [];
610 foreach ( $this->config->get(
'SessionProviders' )
as $spec ) {
612 $provider->setLogger( $this->logger );
613 $provider->setConfig( $this->config );
614 $provider->setManager( $this );
615 if ( isset( $this->sessionProviders[(
string)$provider] ) ) {
616 throw new \UnexpectedValueException(
"Duplicate provider name \"$provider\"" );
618 $this->sessionProviders[(
string)$provider] = $provider;
636 return isset( $providers[
$name] ) ? $providers[
$name] : null;
644 if ( $this->allSessionBackends ) {
645 $this->logger->debug(
'Saving all sessions on shutdown' );
646 if ( session_id() !==
'' ) {
648 session_write_close();
651 foreach ( $this->allSessionBackends
as $backend ) {
652 $backend->shutdown();
666 $info = $provider->provideSessionInfo( $request );
670 if ( $info->getProvider() !== $provider ) {
671 throw new \UnexpectedValueException(
672 "$provider returned session info for a different provider: $info"
681 usort( $infos,
'MediaWiki\\Session\\SessionInfo::compare' );
684 $info = array_pop( $infos );
688 $info = array_pop( $infos );
699 $info->getProvider()->unpersistSession( $request );
704 $info->getProvider()->unpersistSession( $request );
708 if ( count( $retInfos ) > 1 ) {
709 $ex = new \OverflowException(
710 'Multiple sessions for this request tied for top priority: ' . implode(
', ', $retInfos )
712 $ex->sessionInfos = $retInfos;
716 return $retInfos ? $retInfos[0] : null;
734 $failHandler =
function ()
use ( $key, &$info, $request ) {
735 $this->
store->delete( $key );
739 $failHandler =
function () {
746 if ( $blob !==
false ) {
748 if ( !is_array( $blob ) ) {
749 $this->logger->warning(
'Session "{session}": Bad data', [
752 $this->
store->delete( $key );
753 return $failHandler();
757 if ( !isset( $blob[
'data'] ) || !is_array( $blob[
'data'] ) ||
758 !isset( $blob[
'metadata'] ) || !is_array( $blob[
'metadata'] )
760 $this->logger->warning(
'Session "{session}": Bad data structure', [
763 $this->
store->delete( $key );
764 return $failHandler();
767 $data = $blob[
'data'];
768 $metadata = $blob[
'metadata'];
772 if ( !array_key_exists(
'userId', $metadata ) ||
773 !array_key_exists(
'userName', $metadata ) ||
774 !array_key_exists(
'userToken', $metadata ) ||
775 !array_key_exists(
'provider', $metadata )
777 $this->logger->warning(
'Session "{session}": Bad metadata', [
780 $this->
store->delete( $key );
781 return $failHandler();
786 if ( $provider === null ) {
787 $newParams[
'provider'] = $provider = $this->
getProvider( $metadata[
'provider'] );
789 $this->logger->warning(
790 'Session "{session}": Unknown provider ' . $metadata[
'provider'],
795 $this->
store->delete( $key );
796 return $failHandler();
798 } elseif ( $metadata[
'provider'] !== (
string)$provider ) {
799 $this->logger->warning(
'Session "{session}": Wrong provider ' .
800 $metadata[
'provider'] .
' !== ' . $provider,
804 return $failHandler();
809 if ( isset( $metadata[
'providerMetadata'] ) ) {
810 if ( $providerMetadata === null ) {
811 $newParams[
'metadata'] = $metadata[
'providerMetadata'];
814 $newProviderMetadata = $provider->mergeMetadata(
815 $metadata[
'providerMetadata'], $providerMetadata
817 if ( $newProviderMetadata !== $providerMetadata ) {
818 $newParams[
'metadata'] = $newProviderMetadata;
821 $this->logger->warning(
822 'Session "{session}": Metadata merge failed: {exception}',
828 return $failHandler();
838 if ( $metadata[
'userId'] ) {
840 } elseif ( $metadata[
'userName'] !== null ) {
845 }
catch ( \InvalidArgumentException $ex ) {
846 $this->logger->error(
'Session "{session}": {exception}', [
850 return $failHandler();
852 $newParams[
'userInfo'] = $userInfo;
856 if ( $metadata[
'userId'] ) {
857 if ( $metadata[
'userId'] !== $userInfo->getId() ) {
858 $this->logger->warning(
859 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
862 'uid_a' => $metadata[
'userId'],
863 'uid_b' => $userInfo->
getId(),
865 return $failHandler();
869 if ( $metadata[
'userName'] !== null &&
870 $userInfo->getName() !== $metadata[
'userName']
872 $this->logger->warning(
873 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
876 'uname_a' => $metadata[
'userName'],
877 'uname_b' => $userInfo->getName(),
879 return $failHandler();
882 } elseif ( $metadata[
'userName'] !== null ) {
883 if ( $metadata[
'userName'] !== $userInfo->getName() ) {
884 $this->logger->warning(
885 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
888 'uname_a' => $metadata[
'userName'],
889 'uname_b' => $userInfo->getName(),
891 return $failHandler();
893 } elseif ( !$userInfo->isAnon() ) {
896 $this->logger->warning(
897 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
901 return $failHandler();
906 if ( $metadata[
'userToken'] !== null &&
907 $userInfo->getToken() !== $metadata[
'userToken']
909 $this->logger->warning(
'Session "{session}": User token mismatch', [
912 return $failHandler();
914 if ( !$userInfo->isVerified() ) {
915 $newParams[
'userInfo'] = $userInfo->verified();
918 if ( !empty( $metadata[
'remember'] ) && !$info->
wasRemembered() ) {
919 $newParams[
'remembered'] =
true;
921 if ( !empty( $metadata[
'forceHTTPS'] ) && !$info->
forceHTTPS() ) {
922 $newParams[
'forceHTTPS'] =
true;
924 if ( !empty( $metadata[
'persisted'] ) && !$info->
wasPersisted() ) {
925 $newParams[
'persisted'] =
true;
929 $newParams[
'idIsSafe'] =
true;
934 $this->logger->warning(
935 'Session "{session}": Null provider and no metadata',
939 return $failHandler();
948 'Session "{session}": No user provided and provider cannot set user',
952 return $failHandler();
955 $this->logger->warning(
956 'Session "{session}": Unverified user provided and no metadata to auth it',
960 return $failHandler();
969 $newParams[
'idIsSafe'] =
true;
975 $newParams[
'copyFrom'] = $info;
981 if ( !$info->
getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
982 return $failHandler();
986 'metadata' => $providerMetadata,
994 $reason =
'Hook aborted';
997 [ &$reason, $info, $request, $metadata, $data ]
999 $this->logger->warning(
'Session "{session}": ' . $reason, [
1002 return $failHandler();
1018 if ( defined(
'MW_NO_SESSION' ) ) {
1021 $this->logger->error(
'Sessions are supposed to be disabled for this entry point', [
1022 'exception' =>
new \BadMethodCallException(
'Sessions are disabled for this entry point' ),
1025 throw new \BadMethodCallException(
'Sessions are disabled for this entry point' );
1030 $id = $info->
getId();
1032 if ( !isset( $this->allSessionBackends[$id] ) ) {
1033 if ( !isset( $this->allSessionIds[$id] ) ) {
1034 $this->allSessionIds[$id] =
new SessionId( $id );
1037 $this->allSessionIds[$id],
1041 $this->config->get(
'ObjectCacheSessionExpiry' )
1043 $this->allSessionBackends[$id] = $backend;
1046 $backend = $this->allSessionBackends[$id];
1047 $delay = $backend->delaySave();
1049 $backend->persist();
1052 $backend->setRememberUser(
true );
1057 $session = $backend->getSession( $request );
1060 $session->resetId();
1073 $id = $backend->
getId();
1074 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
1075 $this->allSessionBackends[$id] !== $backend ||
1078 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
1081 unset( $this->allSessionBackends[$id] );
1092 $oldId = (
string)$sessionId;
1093 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
1094 $this->allSessionBackends[$oldId] !== $backend ||
1095 $this->allSessionIds[$oldId] !== $sessionId
1097 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
1102 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
1103 $sessionId->setId( $newId );
1104 $this->allSessionBackends[$newId] = $backend;
1105 $this->allSessionIds[$newId] = $sessionId;
1116 }
while ( isset( $this->allSessionIds[$id] ) || is_array( $this->
store->get( $key ) ) );
1133 if ( !defined(
'MW_PHPUNIT_TEST' ) ) {
1135 throw new MWException( __METHOD__ .
' may only be called from unit tests!' );
1139 self::$globalSession = null;
1140 self::$globalSessionRequest = null;
static getObjectFromSpec($spec)
Instantiate an object based on a specification array.
saveSettings()
Save this user's settings into the database.
processing should stop and the error should be shown to the user * false
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static instance()
Singleton.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
static getInstance($id)
Get a cached instance of the specified type of cache object.
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
static getLocalClusterInstance()
Get the main cluster-local cache object.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
$wgAuth $wgAuth
Authentication plugin.
when a variable name is used in a it is silently declared as a new local masking the global
setToken($token=false)
Set the random token (used for persistent authentication) Called from loadDefaults() among other plac...
getName()
Get the user name, or the IP of an anonymous user.
MediaWiki s SiteStore can be cached and stored in a flat in a json format If the SiteStore is frequently the file cache may provide a performance benefit over a database store
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
loadDefaults($name=false)
Set cached properties to default.
interface is intended to be more or less compatible with the PHP memcached client.
wfGetLB($wiki=false)
Get a load balancer object.
wfReadOnly()
Check whether the wiki is in read-only mode.
static getMain()
Static methods.
Interface for configuration instances.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Class for handling updates to the site_stats table.
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static addUpdate(DeferrableUpdate $update, $type=self::POSTSEND)
Add an update to the deferred list.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
setSessionId(SessionId $sessionId)
Set the session for this request.
static getDefaultInstance()
setId($v)
Set the user and reload all fields according to a given ID.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
this hook is for auditing only or null if authentication failed before getting that far $username
error also a ContextSource you ll probably need to make sure the header is varied on $request
addToDatabase()
Add this existing user object to the database.
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...
$wgDisableAuthManager
Disable AuthManager.
static isCreatableName($name)
Usernames which fail to pass this function will be blocked from new account registrations, but may be used internally either by batch processes or by user accounts which have already been created.
getUserPage()
Get this user's personal page title.
static idFromName($name, $flags=self::READ_NORMAL)
Get database id given a user name.
Wrapper around a BagOStuff that caches data in memory.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
static consume(ScopedCallback &$sc=null)
Trigger a scoped callback and destroy it.
wfMemcKey()
Make a cache key for the local wiki.
loadFromId($flags=self::READ_NORMAL)
Load user table data, given mId has already been set.
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
addWatch($title, $checkRights=self::CHECK_USER_RIGHTS)
Watch an article.
Allows to change the fields on the form that will be generated $name