10 use EventRelayerGroup
;
14 use IBufferingStatsdDataFactory
;
15 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface
;
16 use MediaWiki\Http\HttpRequestFactory
;
17 use MediaWiki\Preferences\PreferencesFactory
;
18 use MediaWiki\Shell\CommandFactory
;
19 use MediaWiki\Revision\RevisionRenderer
;
20 use MediaWiki\Revision\SlotRoleRegistry
;
21 use MediaWiki\Special\SpecialPageFactory
;
22 use MediaWiki\Storage\BlobStore
;
23 use MediaWiki\Storage\BlobStoreFactory
;
24 use MediaWiki\Storage\NameTableStore
;
25 use MediaWiki\Storage\NameTableStoreFactory
;
26 use MediaWiki\Revision\RevisionFactory
;
27 use MediaWiki\Revision\RevisionLookup
;
28 use MediaWiki\Revision\RevisionStore
;
29 use OldRevisionImporter
;
30 use MediaWiki\Revision\RevisionStoreFactory
;
31 use UploadRevisionImporter
;
32 use Wikimedia\Rdbms\LBFactory
;
34 use Wikimedia\Rdbms\LoadBalancer
;
35 use MediaHandlerFactory
;
36 use MediaWiki\Config\ConfigRepository
;
37 use MediaWiki\Linker\LinkRenderer
;
38 use MediaWiki\Linker\LinkRendererFactory
;
48 use SearchEngineConfig
;
49 use SearchEngineFactory
;
52 use WatchedItemStoreInterface
;
53 use WatchedItemQueryService
;
57 use VirtualRESTServiceClient
;
58 use Wikimedia\Services\SalvageableService
;
59 use Wikimedia\Services\ServiceContainer
;
60 use Wikimedia\Services\NoSuchServiceException
;
61 use MediaWiki\Interwiki\InterwikiLookup
;
65 * Service locator for MediaWiki core services.
67 * This program is free software; you can redistribute it and/or modify
68 * it under the terms of the GNU General Public License as published by
69 * the Free Software Foundation; either version 2 of the License, or
70 * (at your option) any later version.
72 * This program is distributed in the hope that it will be useful,
73 * but WITHOUT ANY WARRANTY; without even the implied warranty of
74 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
75 * GNU General Public License for more details.
77 * You should have received a copy of the GNU General Public License along
78 * with this program; if not, write to the Free Software Foundation, Inc.,
79 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
80 * http://www.gnu.org/copyleft/gpl.html
88 * MediaWikiServices is the service locator for the application scope of MediaWiki.
89 * Its implemented as a simple configurable DI container.
90 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
91 * the network of service objects that defines MediaWiki's application logic.
92 * It acts as an entry point to MediaWiki's dependency injection mechanism.
94 * Services are defined in the "wiring" array passed to the constructor,
95 * or by calling defineService().
97 * @see docs/injection.txt for an overview of using dependency injection in the
98 * MediaWiki code base.
100 class MediaWikiServices
extends ServiceContainer
{
103 * @var MediaWikiServices|null
105 private static $instance = null;
108 * Returns the global default instance of the top level service locator.
112 * The default instance is initialized using the service instantiator functions
113 * defined in ServiceWiring.php.
115 * @note This should only be called by static functions! The instance returned here
116 * should not be passed around! Objects that need access to a service should have
117 * that service injected into the constructor, never a service locator!
119 * @return MediaWikiServices
121 public static function getInstance() {
122 if ( self
::$instance === null ) {
123 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
124 // but some information from the global scope has to be injected here,
125 // even if it's just a file name or database credentials to load
126 // configuration from.
127 $bootstrapConfig = new GlobalVarConfig();
128 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
131 return self
::$instance;
135 * Replaces the global MediaWikiServices instance.
139 * @note This is for use in PHPUnit tests only!
141 * @throws MWException if called outside of PHPUnit tests.
143 * @param MediaWikiServices $services The new MediaWikiServices object.
145 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
147 public static function forceGlobalInstance( MediaWikiServices
$services ) {
148 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
149 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
152 $old = self
::getInstance();
153 self
::$instance = $services;
159 * Creates a new instance of MediaWikiServices and sets it as the global default
160 * instance. getInstance() will return a different MediaWikiServices object
161 * after every call to resetGlobalInstance().
165 * @warning This should not be used during normal operation. It is intended for use
166 * when the configuration has changed significantly since bootstrap time, e.g.
167 * during the installation process or during testing.
169 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
170 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
171 * any of the services managed by MediaWikiServices exist. If any service objects
172 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
173 * with the operation of the services managed by the new MediaWikiServices.
174 * Operating with a mix of services created by the old and the new
175 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
176 * Any class implementing LAZY LOADING is especially prone to this problem,
177 * since instances would typically retain a reference to a storage layer service.
179 * @see forceGlobalInstance()
180 * @see resetGlobalInstance()
181 * @see resetBetweenTest()
183 * @param Config|null $bootstrapConfig The Config object to be registered as the
184 * 'BootstrapConfig' service. This has to contain at least the information
185 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
186 * config of the old instance of MediaWikiServices will be re-used. If there
187 * was no previous instance, a new GlobalVarConfig object will be used to
188 * bootstrap the services.
190 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
191 * See SalvageableService for details.
193 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
194 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
197 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
198 if ( self
::$instance === null ) {
199 // no global instance yet, nothing to reset
203 self
::failIfResetNotAllowed( __METHOD__
);
205 if ( $bootstrapConfig === null ) {
206 $bootstrapConfig = self
::$instance->getBootstrapConfig();
209 $oldInstance = self
::$instance;
211 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
212 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
214 if ( $quick === 'quick' ) {
215 self
::$instance->salvage( $oldInstance );
217 $oldInstance->destroy();
222 * Salvages the state of any salvageable service instances in $other.
224 * @note $other will have been destroyed when salvage() returns.
226 * @param MediaWikiServices $other
228 private function salvage( self
$other ) {
229 foreach ( $this->getServiceNames() as $name ) {
230 // The service could be new in the new instance and not registered in the
231 // other instance (e.g. an extension that was loaded after the instantiation of
232 // the other instance. Skip this service in this case. See T143974
234 $oldService = $other->peekService( $name );
235 } catch ( NoSuchServiceException
$e ) {
239 if ( $oldService instanceof SalvageableService
) {
240 /** @var SalvageableService $newService */
241 $newService = $this->getService( $name );
242 $newService->salvage( $oldService );
250 * Creates a new MediaWikiServices instance and initializes it according to the
251 * given $bootstrapConfig. In particular, all wiring files defined in the
252 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
254 * @param Config|null $bootstrapConfig The Config object to be registered as the
255 * 'BootstrapConfig' service.
257 * @param string $loadWiring set this to 'load' to load the wiring files specified
258 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
260 * @return MediaWikiServices
261 * @throws MWException
262 * @throws \FatalError
264 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
265 $instance = new self( $bootstrapConfig );
267 // Load the default wiring from the specified files.
268 if ( $loadWiring === 'load' ) {
269 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
270 $instance->loadWiringFiles( $wiringFiles );
273 // Provide a traditional hook point to allow extensions to configure services.
274 Hooks
::run( 'MediaWikiServices', [ $instance ] );
280 * Disables all storage layer services. After calling this, any attempt to access the
281 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
286 * @warning This is intended for extreme situations only and should never be used
287 * while serving normal web requests. Legitimate use cases for this method include
288 * the installation process. Test fixtures may also use this, if the fixture relies
291 * @see resetGlobalInstance()
292 * @see resetChildProcessServices()
294 public static function disableStorageBackend() {
295 // TODO: also disable some Caches, JobQueues, etc
296 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
297 $services = self
::getInstance();
299 foreach ( $destroy as $name ) {
300 $services->disableService( $name );
303 ObjectCache
::clear();
307 * Resets any services that may have become stale after a child process
308 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
309 * to call this method from the parent process.
313 * @note This is intended for use in the context of process forking only!
315 * @see resetGlobalInstance()
316 * @see disableStorageBackend()
318 public static function resetChildProcessServices() {
319 // NOTE: for now, just reset everything. Since we don't know the interdependencies
320 // between services, we can't do this more selectively at this time.
321 self
::resetGlobalInstance();
323 // Child, reseed because there is no bug in PHP:
324 // https://bugs.php.net/bug.php?id=42465
325 mt_srand( getmypid() );
329 * Resets the given service for testing purposes.
333 * @warning This is generally unsafe! Other services may still retain references
334 * to the stale service instance, leading to failures and inconsistencies. Subclasses
335 * may use this method to reset specific services under specific instances, but
336 * it should not be exposed to application logic.
338 * @note With proper dependency injection used throughout the codebase, this method
339 * should not be needed. It is provided to allow tests that pollute global service
340 * instances to clean up.
342 * @param string $name
343 * @param bool $destroy Whether the service instance should be destroyed if it exists.
344 * When set to false, any existing service instance will effectively be detached
345 * from the container.
347 * @throws MWException if called outside of PHPUnit tests.
349 public function resetServiceForTesting( $name, $destroy = true ) {
350 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
351 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
354 $this->resetService( $name, $destroy );
358 * Convenience method that throws an exception unless it is called during a phase in which
359 * resetting of global services is allowed. In general, services should not be reset
360 * individually, since that may introduce inconsistencies.
364 * This method will throw an exception if:
366 * - self::$resetInProgress is false (to allow all services to be reset together
367 * via resetGlobalInstance)
368 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
369 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
371 * This method is intended to be used to safeguard against accidentally resetting
372 * global service instances that are not yet managed by MediaWikiServices. It is
373 * defined here in the MediaWikiServices services class to have a central place
374 * for managing service bootstrapping and resetting.
376 * @param string $method the name of the caller method, as given by __METHOD__.
378 * @throws MWException if called outside bootstrap mode.
380 * @see resetGlobalInstance()
381 * @see forceGlobalInstance()
382 * @see disableStorageBackend()
384 public static function failIfResetNotAllowed( $method ) {
385 if ( !defined( 'MW_PHPUNIT_TEST' )
386 && !defined( 'MW_PARSER_TEST' )
387 && !defined( 'MEDIAWIKI_INSTALL' )
388 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
389 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
391 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
396 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
397 * This has to contain at least the information needed to set up the 'ConfigFactory'
400 public function __construct( Config
$config ) {
401 parent
::__construct();
403 // Register the given Config object as the bootstrap config service.
404 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
409 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
413 * @return ActorMigration
415 public function getActorMigration() {
416 return $this->getService( 'ActorMigration' );
423 public function getBlobStore() {
424 return $this->getService( '_SqlBlobStore' );
429 * @return BlobStoreFactory
431 public function getBlobStoreFactory() {
432 return $this->getService( 'BlobStoreFactory' );
436 * Returns the Config object containing the bootstrap configuration.
437 * Bootstrap configuration would typically include database credentials
438 * and other information that may be needed before the ConfigFactory
439 * service can be instantiated.
441 * @note This should only be used during bootstrapping, in particular
442 * when creating the MainConfig service. Application logic should
443 * use getMainConfig() to get a Config instances.
448 public function getBootstrapConfig() {
449 return $this->getService( 'BootstrapConfig' );
454 * @return NameTableStore
456 public function getChangeTagDefStore() {
457 return $this->getService( 'NameTableStoreFactory' )->getChangeTagDef();
462 * @return CommentStore
464 public function getCommentStore() {
465 return $this->getService( 'CommentStore' );
470 * @return ConfigFactory
472 public function getConfigFactory() {
473 return $this->getService( 'ConfigFactory' );
478 * @return ConfigRepository
480 public function getConfigRepository() {
481 return $this->getService( 'ConfigRepository' );
486 * @return \ConfiguredReadOnlyMode
488 public function getConfiguredReadOnlyMode() {
489 return $this->getService( 'ConfiguredReadOnlyMode' );
496 public function getContentLanguage() {
497 return $this->getService( 'ContentLanguage' );
502 * @return NameTableStore
504 public function getContentModelStore() {
505 return $this->getService( 'NameTableStoreFactory' )->getContentModels();
512 public function getCryptHKDF() {
513 return $this->getService( 'CryptHKDF' );
518 * @deprecated since 1.32, use random_bytes()/random_int()
521 public function getCryptRand() {
522 wfDeprecated( __METHOD__
, '1.32' );
523 return $this->getService( 'CryptRand' );
528 * @return LoadBalancer The main DB load balancer for the local wiki.
530 public function getDBLoadBalancer() {
531 return $this->getService( 'DBLoadBalancer' );
538 public function getDBLoadBalancerFactory() {
539 return $this->getService( 'DBLoadBalancerFactory' );
544 * @return EventRelayerGroup
546 public function getEventRelayerGroup() {
547 return $this->getService( 'EventRelayerGroup' );
552 * @return \ExternalStoreFactory
554 public function getExternalStoreFactory() {
555 return $this->getService( 'ExternalStoreFactory' );
560 * @return GenderCache
562 public function getGenderCache() {
563 return $this->getService( 'GenderCache' );
568 * @return HttpRequestFactory
570 public function getHttpRequestFactory() {
571 return $this->getService( 'HttpRequestFactory' );
576 * @return InterwikiLookup
578 public function getInterwikiLookup() {
579 return $this->getService( 'InterwikiLookup' );
586 public function getLinkCache() {
587 return $this->getService( 'LinkCache' );
591 * LinkRenderer instance that can be used
592 * if no custom options are needed
595 * @return LinkRenderer
597 public function getLinkRenderer() {
598 return $this->getService( 'LinkRenderer' );
603 * @return LinkRendererFactory
605 public function getLinkRendererFactory() {
606 return $this->getService( 'LinkRendererFactory' );
613 public function getLocalServerObjectCache() {
614 return $this->getService( 'LocalServerObjectCache' );
619 * @return MagicWordFactory
621 public function getMagicWordFactory() {
622 return $this->getService( 'MagicWordFactory' );
626 * Returns the Config object that provides configuration for MediaWiki core.
627 * This may or may not be the same object that is returned by getBootstrapConfig().
632 public function getMainConfig() {
633 return $this->getService( 'MainConfig' );
640 public function getMainObjectStash() {
641 return $this->getService( 'MainObjectStash' );
646 * @return \WANObjectCache
648 public function getMainWANObjectCache() {
649 return $this->getService( 'MainWANObjectCache' );
654 * @return MediaHandlerFactory
656 public function getMediaHandlerFactory() {
657 return $this->getService( 'MediaHandlerFactory' );
662 * @return MimeAnalyzer
664 public function getMimeAnalyzer() {
665 return $this->getService( 'MimeAnalyzer' );
670 * @return NameTableStoreFactory
672 public function getNameTableStoreFactory() {
673 return $this->getService( 'NameTableStoreFactory' );
677 * @return OldRevisionImporter
679 public function getOldRevisionImporter() {
680 return $this->getService( 'OldRevisionImporter' );
687 public function getParser() {
688 return $this->getService( 'Parser' );
693 * @return ParserCache
695 public function getParserCache() {
696 return $this->getService( 'ParserCache' );
701 * @return ParserFactory
703 public function getParserFactory() {
704 return $this->getService( 'ParserFactory' );
709 * @return PasswordFactory
711 public function getPasswordFactory() {
712 return $this->getService( 'PasswordFactory' );
717 * @return StatsdDataFactoryInterface
719 public function getPerDbNameStatsdDataFactory() {
720 return $this->getService( 'PerDbNameStatsdDataFactory' );
725 * @return PreferencesFactory
727 public function getPreferencesFactory() {
728 return $this->getService( 'PreferencesFactory' );
733 * @return ProxyLookup
735 public function getProxyLookup() {
736 return $this->getService( 'ProxyLookup' );
741 * @return \ReadOnlyMode
743 public function getReadOnlyMode() {
744 return $this->getService( 'ReadOnlyMode' );
749 * @return RevisionFactory
751 public function getRevisionFactory() {
752 return $this->getService( 'RevisionFactory' );
757 * @return RevisionLookup
759 public function getRevisionLookup() {
760 return $this->getService( 'RevisionLookup' );
765 * @return RevisionRenderer
767 public function getRevisionRenderer() {
768 return $this->getService( 'RevisionRenderer' );
773 * @return RevisionStore
775 public function getRevisionStore() {
776 return $this->getService( 'RevisionStore' );
781 * @return RevisionStoreFactory
783 public function getRevisionStoreFactory() {
784 return $this->getService( 'RevisionStoreFactory' );
789 * @return SearchEngine
791 public function newSearchEngine() {
792 // New engine object every time, since they keep state
793 return $this->getService( 'SearchEngineFactory' )->create();
798 * @return SearchEngineConfig
800 public function getSearchEngineConfig() {
801 return $this->getService( 'SearchEngineConfig' );
806 * @return SearchEngineFactory
808 public function getSearchEngineFactory() {
809 return $this->getService( 'SearchEngineFactory' );
814 * @return CommandFactory
816 public function getShellCommandFactory() {
817 return $this->getService( 'ShellCommandFactory' );
824 public function getSiteLookup() {
825 return $this->getService( 'SiteLookup' );
832 public function getSiteStore() {
833 return $this->getService( 'SiteStore' );
838 * @return SkinFactory
840 public function getSkinFactory() {
841 return $this->getService( 'SkinFactory' );
846 * @return SlotRoleRegistry
848 public function getSlotRoleRegistry() {
849 return $this->getService( 'SlotRoleRegistry' );
854 * @return NameTableStore
856 public function getSlotRoleStore() {
857 return $this->getService( 'NameTableStoreFactory' )->getSlotRoles();
862 * @return SpecialPageFactory
864 public function getSpecialPageFactory() : SpecialPageFactory
{
865 return $this->getService( 'SpecialPageFactory' );
870 * @return IBufferingStatsdDataFactory
872 public function getStatsdDataFactory() {
873 return $this->getService( 'StatsdDataFactory' );
878 * @return TitleFormatter
880 public function getTitleFormatter() {
881 return $this->getService( 'TitleFormatter' );
886 * @return TitleParser
888 public function getTitleParser() {
889 return $this->getService( 'TitleParser' );
894 * @return UploadRevisionImporter
896 public function getUploadRevisionImporter() {
897 return $this->getService( 'UploadRevisionImporter' );
902 * @return VirtualRESTServiceClient
904 public function getVirtualRESTServiceClient() {
905 return $this->getService( 'VirtualRESTServiceClient' );
910 * @return WatchedItemQueryService
912 public function getWatchedItemQueryService() {
913 return $this->getService( 'WatchedItemQueryService' );
918 * @return WatchedItemStoreInterface
920 public function getWatchedItemStore() {
921 return $this->getService( 'WatchedItemStore' );
926 * @return \OldRevisionImporter
928 public function getWikiRevisionOldRevisionImporter() {
929 return $this->getService( 'OldRevisionImporter' );
934 * @return \OldRevisionImporter
936 public function getWikiRevisionOldRevisionImporterNoUpdates() {
937 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
942 * @return \UploadRevisionImporter
944 public function getWikiRevisionUploadImporter() {
945 return $this->getService( 'UploadRevisionImporter' );