Go to the documentation of this file.
28 use Psr\Log\LoggerInterface;
92 if ( self::$instance ===
null ) {
93 self::$instance =
new self();
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'
182 register_shutdown_function( [ $this,
'shutdown' ] );
201 if ( !self::validateSessionId( $id ) ) {
202 throw new \InvalidArgumentException(
'Invalid session ID' );
212 if ( isset( $this->allSessionBackends[$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' );
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();
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 ) {
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;
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}',
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;
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;
938 }
while ( isset( $this->allSessionIds[$id] ) || is_array( $this->
store->get( $key ) ) );
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;
WebRequest clone which takes values from a provided array.
error also a ContextSource you ll probably need to make sure the header is varied on $request
processing should stop and the error should be shown to the user * false
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
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 account $user
interface is intended to be more or less compatible with the PHP memcached client.
static generateHex( $chars, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in hexadecimal string format.
Allows to change the fields on the form that will be generated $name
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
Interface for configuration instances.
wfMemcKey()
Make a cache key for the local wiki.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
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
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
Wrapper around a BagOStuff that caches data in memory.
static getObjectFromSpec( $spec)
Instantiate an object based on a specification array.
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
static getMain()
Static methods.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
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
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 MediaWikiServices
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
this hook is for auditing only or null if authentication failed before getting that far $username
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup 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
the array() calling protocol came about after MediaWiki 1.4rc1.