28use Psr\Log\LoggerInterface;
35use Wikimedia\ObjectFactory;
93 if ( self::$instance ===
null ) {
94 self::$instance =
new self();
114 $request = \RequestContext::getMain()->getRequest();
116 !self::$globalSession
117 || self::$globalSessionRequest !==
$request
118 || $id !==
'' && self::$globalSession->getId() !== $id
120 self::$globalSessionRequest =
$request;
130 self::$globalSession =
$request->getSession();
149 if ( isset(
$options[
'config'] ) ) {
151 if ( !$this->config instanceof
Config ) {
152 throw new \InvalidArgumentException(
153 '$options[\'config\'] must be an instance of Config'
160 if ( isset(
$options[
'logger'] ) ) {
161 if ( !
$options[
'logger'] instanceof LoggerInterface ) {
162 throw new \InvalidArgumentException(
163 '$options[\'logger\'] must be an instance of LoggerInterface'
173 throw new \InvalidArgumentException(
174 '$options[\'store\'] must be an instance of BagOStuff'
179 $store = \ObjectCache::getInstance( $this->config->get(
'SessionCacheType' ) );
183 register_shutdown_function( [ $this,
'shutdown' ] );
202 if ( !self::validateSessionId( $id ) ) {
203 throw new \InvalidArgumentException(
'Invalid session ID' );
213 if ( isset( $this->allSessionBackends[$id] ) ) {
218 $key = $this->store->makeKey(
'MWSession', $id );
219 if ( is_array( $this->store->get( $key ) ) ) {
226 if ( $create && $session ===
null ) {
230 }
catch ( \Exception $ex ) {
231 $this->logger->error(
'Failed to create empty session: {exception}',
233 'method' => __METHOD__,
254 if ( $id !==
null ) {
255 if ( !self::validateSessionId( $id ) ) {
256 throw new \InvalidArgumentException(
'Invalid session ID' );
259 $key = $this->store->makeKey(
'MWSession', $id );
260 if ( is_array( $this->store->get( $key ) ) ) {
261 throw new \InvalidArgumentException(
'Session ID already exists' );
270 $info = $provider->newSessionInfo( $id );
274 if ( $info->getProvider() !== $provider ) {
275 throw new \UnexpectedValueException(
276 "$provider returned an empty session info for a different provider: $info"
279 if ( $id !==
null && $info->getId() !== $id ) {
280 throw new \UnexpectedValueException(
281 "$provider returned empty session info with a wrong id: " .
282 $info->getId() .
' != ' . $id
285 if ( !$info->isIdSafe() ) {
286 throw new \UnexpectedValueException(
287 "$provider returned empty session info with id flagged unsafe"
291 if ( $compare > 0 ) {
294 if ( $compare === 0 ) {
302 if ( count( $infos ) > 1 ) {
303 throw new \UnexpectedValueException(
304 'Multiple empty sessions tied for top priority: ' . implode(
', ', $infos )
306 } elseif ( count( $infos ) < 1 ) {
307 throw new \UnexpectedValueException(
'No provider could provide an empty session!' );
315 $user->saveSettings();
318 $provider->invalidateSessionsForUser(
$user );
324 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
328 if ( $this->varyHeaders ===
null ) {
332 if ( !isset( $headers[
$header] ) ) {
340 $this->varyHeaders = $headers;
347 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
351 if ( $this->varyCookies ===
null ) {
354 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
356 $this->varyCookies = array_values( array_unique( $cookies ) );
367 return is_string( $id ) && preg_match(
'/^[a-zA-Z0-9_-]{32,}$/', $id );
389 $provider->preventSessionsForUser(
$username );
400 return !empty( $this->preventUsers[
$username] );
408 if ( $this->sessionProviders ===
null ) {
409 $this->sessionProviders = [];
410 foreach ( $this->config->get(
'SessionProviders' )
as $spec ) {
411 $provider = ObjectFactory::getObjectFromSpec( $spec );
412 $provider->setLogger( $this->logger );
413 $provider->setConfig( $this->config );
414 $provider->setManager( $this );
415 if ( isset( $this->sessionProviders[(
string)$provider] ) ) {
416 throw new \UnexpectedValueException(
"Duplicate provider name \"$provider\"" );
418 $this->sessionProviders[(
string)$provider] = $provider;
436 return $providers[
$name] ??
null;
444 if ( $this->allSessionBackends ) {
445 $this->logger->debug(
'Saving all sessions on shutdown' );
446 if ( session_id() !==
'' ) {
448 session_write_close();
451 foreach ( $this->allSessionBackends
as $backend ) {
452 $backend->shutdown();
466 $info = $provider->provideSessionInfo(
$request );
470 if ( $info->getProvider() !== $provider ) {
471 throw new \UnexpectedValueException(
472 "$provider returned session info for a different provider: $info"
481 usort( $infos,
'MediaWiki\\Session\\SessionInfo::compare' );
484 $info = array_pop( $infos );
488 $info = array_pop( $infos );
499 $info->getProvider()->unpersistSession(
$request );
504 $info->getProvider()->unpersistSession(
$request );
508 if ( count( $retInfos ) > 1 ) {
509 $ex = new \OverflowException(
510 'Multiple sessions for this request tied for top priority: ' . implode(
', ', $retInfos )
512 $ex->sessionInfos = $retInfos;
516 return $retInfos ? $retInfos[0] :
null;
527 $key = $this->store->makeKey(
'MWSession', $info->
getId() );
528 $blob = $this->store->get( $key );
534 $failHandler =
function ()
use ( $key, &$info,
$request ) {
535 $this->store->delete( $key );
539 $failHandler =
function () {
546 if (
$blob !==
false ) {
548 if ( !is_array(
$blob ) ) {
549 $this->logger->warning(
'Session "{session}": Bad data', [
552 $this->store->delete( $key );
553 return $failHandler();
557 if ( !isset(
$blob[
'data'] ) || !is_array(
$blob[
'data'] ) ||
558 !isset(
$blob[
'metadata'] ) || !is_array(
$blob[
'metadata'] )
560 $this->logger->warning(
'Session "{session}": Bad data structure', [
563 $this->store->delete( $key );
564 return $failHandler();
568 $metadata =
$blob[
'metadata'];
572 if ( !array_key_exists(
'userId', $metadata ) ||
573 !array_key_exists(
'userName', $metadata ) ||
574 !array_key_exists(
'userToken', $metadata ) ||
575 !array_key_exists(
'provider', $metadata )
577 $this->logger->warning(
'Session "{session}": Bad metadata', [
580 $this->store->delete( $key );
581 return $failHandler();
586 if ( $provider ===
null ) {
587 $newParams[
'provider'] = $provider = $this->
getProvider( $metadata[
'provider'] );
589 $this->logger->warning(
590 'Session "{session}": Unknown provider ' . $metadata[
'provider'],
595 $this->store->delete( $key );
596 return $failHandler();
598 } elseif ( $metadata[
'provider'] !== (
string)$provider ) {
599 $this->logger->warning(
'Session "{session}": Wrong provider ' .
600 $metadata[
'provider'] .
' !== ' . $provider,
604 return $failHandler();
609 if ( isset( $metadata[
'providerMetadata'] ) ) {
610 if ( $providerMetadata ===
null ) {
611 $newParams[
'metadata'] = $metadata[
'providerMetadata'];
614 $newProviderMetadata = $provider->mergeMetadata(
615 $metadata[
'providerMetadata'], $providerMetadata
617 if ( $newProviderMetadata !== $providerMetadata ) {
618 $newParams[
'metadata'] = $newProviderMetadata;
621 $this->logger->warning(
622 'Session "{session}": Metadata merge failed: {exception}',
628 return $failHandler();
638 if ( $metadata[
'userId'] ) {
640 } elseif ( $metadata[
'userName'] !==
null ) {
645 }
catch ( \InvalidArgumentException $ex ) {
646 $this->logger->error(
'Session "{session}": {exception}', [
650 return $failHandler();
652 $newParams[
'userInfo'] = $userInfo;
656 if ( $metadata[
'userId'] ) {
657 if ( $metadata[
'userId'] !== $userInfo->getId() ) {
658 $this->logger->warning(
659 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
662 'uid_a' => $metadata[
'userId'],
663 'uid_b' => $userInfo->
getId(),
665 return $failHandler();
669 if ( $metadata[
'userName'] !==
null &&
670 $userInfo->getName() !== $metadata[
'userName']
672 $this->logger->warning(
673 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
676 'uname_a' => $metadata[
'userName'],
677 'uname_b' => $userInfo->getName(),
679 return $failHandler();
682 } elseif ( $metadata[
'userName'] !==
null ) {
683 if ( $metadata[
'userName'] !== $userInfo->getName() ) {
684 $this->logger->warning(
685 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
688 'uname_a' => $metadata[
'userName'],
689 'uname_b' => $userInfo->getName(),
691 return $failHandler();
693 } elseif ( !$userInfo->isAnon() ) {
696 $this->logger->warning(
697 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
701 return $failHandler();
706 if ( $metadata[
'userToken'] !==
null &&
707 $userInfo->getToken() !== $metadata[
'userToken']
709 $this->logger->warning(
'Session "{session}": User token mismatch', [
712 return $failHandler();
714 if ( !$userInfo->isVerified() ) {
715 $newParams[
'userInfo'] = $userInfo->verified();
718 if ( !empty( $metadata[
'remember'] ) && !$info->
wasRemembered() ) {
719 $newParams[
'remembered'] =
true;
721 if ( !empty( $metadata[
'forceHTTPS'] ) && !$info->
forceHTTPS() ) {
722 $newParams[
'forceHTTPS'] =
true;
724 if ( !empty( $metadata[
'persisted'] ) && !$info->
wasPersisted() ) {
725 $newParams[
'persisted'] =
true;
729 $newParams[
'idIsSafe'] =
true;
734 $this->logger->warning(
735 'Session "{session}": Null provider and no metadata',
739 return $failHandler();
748 'Session "{session}": No user provided and provider cannot set user',
752 return $failHandler();
757 'Session "{session}": Unverified user provided and no metadata to auth it',
761 return $failHandler();
770 $newParams[
'idIsSafe'] =
true;
776 $newParams[
'copyFrom'] = $info;
783 return $failHandler();
787 'metadata' => $providerMetadata,
795 $reason =
'Hook aborted';
800 $this->logger->warning(
'Session "{session}": ' . $reason, [
803 return $failHandler();
819 if ( defined(
'MW_NO_SESSION' ) ) {
822 $this->logger->error(
'Sessions are supposed to be disabled for this entry point', [
823 'exception' =>
new \BadMethodCallException(
'Sessions are disabled for this entry point' ),
826 throw new \BadMethodCallException(
'Sessions are disabled for this entry point' );
831 $id = $info->
getId();
833 if ( !isset( $this->allSessionBackends[$id] ) ) {
834 if ( !isset( $this->allSessionIds[$id] ) ) {
835 $this->allSessionIds[$id] =
new SessionId( $id );
838 $this->allSessionIds[$id],
842 $this->config->get(
'ObjectCacheSessionExpiry' )
844 $this->allSessionBackends[$id] = $backend;
845 $delay = $backend->delaySave();
847 $backend = $this->allSessionBackends[$id];
848 $delay = $backend->delaySave();
853 $backend->setRememberUser(
true );
857 $request->setSessionId( $backend->getSessionId() );
858 $session = $backend->getSession(
$request );
864 \Wikimedia\ScopedCallback::consume( $delay );
874 $id = $backend->
getId();
875 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
876 $this->allSessionBackends[$id] !== $backend ||
879 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
882 unset( $this->allSessionBackends[$id] );
893 $oldId = (
string)$sessionId;
894 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
895 $this->allSessionBackends[$oldId] !== $backend ||
896 $this->allSessionIds[$oldId] !== $sessionId
898 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
903 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
904 $sessionId->setId( $newId );
905 $this->allSessionBackends[$newId] = $backend;
906 $this->allSessionIds[$newId] = $sessionId;
916 $key = $this->store->makeKey(
'MWSession', $id );
917 }
while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
927 $handler->setManager( $this, $this->store, $this->logger );
935 if ( !defined(
'MW_PHPUNIT_TEST' ) ) {
937 throw new MWException( __METHOD__ .
' may only be called from unit tests!' );
941 self::$globalSession =
null;
942 self::$globalSessionRequest =
null;
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Class representing a cache/ephemeral data store.
Wrapper around a BagOStuff that caches data in memory.
WebRequest clone which takes values from a provided array.
static generateHex( $chars)
Generate a run of 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...
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
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
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
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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
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
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 $username
return true to allow those checks to and false if checking is done & $user
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.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))