10 use EventRelayerGroup
;
14 use IBufferingStatsdDataFactory
;
15 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface
;
16 use MediaWiki\Http\HttpRequestFactory
;
17 use MediaWiki\Permissions\PermissionManager
;
18 use MediaWiki\Preferences\PreferencesFactory
;
19 use MediaWiki\Shell\CommandFactory
;
20 use MediaWiki\Revision\RevisionRenderer
;
21 use MediaWiki\Revision\SlotRoleRegistry
;
22 use MediaWiki\Special\SpecialPageFactory
;
23 use MediaWiki\Storage\BlobStore
;
24 use MediaWiki\Storage\BlobStoreFactory
;
25 use MediaWiki\Storage\NameTableStore
;
26 use MediaWiki\Storage\NameTableStoreFactory
;
27 use MediaWiki\Revision\RevisionFactory
;
28 use MediaWiki\Revision\RevisionLookup
;
29 use MediaWiki\Revision\RevisionStore
;
30 use OldRevisionImporter
;
31 use MediaWiki\Revision\RevisionStoreFactory
;
32 use UploadRevisionImporter
;
33 use Wikimedia\Rdbms\LBFactory
;
35 use Wikimedia\Rdbms\LoadBalancer
;
36 use MediaHandlerFactory
;
37 use MediaWiki\Config\ConfigRepository
;
38 use MediaWiki\Linker\LinkRenderer
;
39 use MediaWiki\Linker\LinkRendererFactory
;
50 use SearchEngineConfig
;
51 use SearchEngineFactory
;
54 use WatchedItemStoreInterface
;
55 use WatchedItemQueryService
;
59 use VirtualRESTServiceClient
;
60 use Wikimedia\Services\SalvageableService
;
61 use Wikimedia\Services\ServiceContainer
;
62 use Wikimedia\Services\NoSuchServiceException
;
63 use MediaWiki\Interwiki\InterwikiLookup
;
67 * Service locator for MediaWiki core services.
69 * This program is free software; you can redistribute it and/or modify
70 * it under the terms of the GNU General Public License as published by
71 * the Free Software Foundation; either version 2 of the License, or
72 * (at your option) any later version.
74 * This program is distributed in the hope that it will be useful,
75 * but WITHOUT ANY WARRANTY; without even the implied warranty of
76 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
77 * GNU General Public License for more details.
79 * You should have received a copy of the GNU General Public License along
80 * with this program; if not, write to the Free Software Foundation, Inc.,
81 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
82 * http://www.gnu.org/copyleft/gpl.html
90 * MediaWikiServices is the service locator for the application scope of MediaWiki.
91 * Its implemented as a simple configurable DI container.
92 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
93 * the network of service objects that defines MediaWiki's application logic.
94 * It acts as an entry point to MediaWiki's dependency injection mechanism.
96 * Services are defined in the "wiring" array passed to the constructor,
97 * or by calling defineService().
99 * @see docs/injection.txt for an overview of using dependency injection in the
100 * MediaWiki code base.
102 class MediaWikiServices
extends ServiceContainer
{
105 * @var MediaWikiServices|null
107 private static $instance = null;
110 * Returns the global default instance of the top level service locator.
114 * The default instance is initialized using the service instantiator functions
115 * defined in ServiceWiring.php.
117 * @note This should only be called by static functions! The instance returned here
118 * should not be passed around! Objects that need access to a service should have
119 * that service injected into the constructor, never a service locator!
121 * @return MediaWikiServices
123 public static function getInstance() {
124 if ( self
::$instance === null ) {
125 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
126 // but some information from the global scope has to be injected here,
127 // even if it's just a file name or database credentials to load
128 // configuration from.
129 $bootstrapConfig = new GlobalVarConfig();
130 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
133 return self
::$instance;
137 * Replaces the global MediaWikiServices instance.
141 * @note This is for use in PHPUnit tests only!
143 * @throws MWException if called outside of PHPUnit tests.
145 * @param MediaWikiServices $services The new MediaWikiServices object.
147 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
149 public static function forceGlobalInstance( MediaWikiServices
$services ) {
150 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
151 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
154 $old = self
::getInstance();
155 self
::$instance = $services;
161 * Creates a new instance of MediaWikiServices and sets it as the global default
162 * instance. getInstance() will return a different MediaWikiServices object
163 * after every call to resetGlobalInstance().
167 * @warning This should not be used during normal operation. It is intended for use
168 * when the configuration has changed significantly since bootstrap time, e.g.
169 * during the installation process or during testing.
171 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
172 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
173 * any of the services managed by MediaWikiServices exist. If any service objects
174 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
175 * with the operation of the services managed by the new MediaWikiServices.
176 * Operating with a mix of services created by the old and the new
177 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
178 * Any class implementing LAZY LOADING is especially prone to this problem,
179 * since instances would typically retain a reference to a storage layer service.
181 * @see forceGlobalInstance()
182 * @see resetGlobalInstance()
183 * @see resetBetweenTest()
185 * @param Config|null $bootstrapConfig The Config object to be registered as the
186 * 'BootstrapConfig' service. This has to contain at least the information
187 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
188 * config of the old instance of MediaWikiServices will be re-used. If there
189 * was no previous instance, a new GlobalVarConfig object will be used to
190 * bootstrap the services.
192 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
193 * See SalvageableService for details.
195 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
196 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
199 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
200 if ( self
::$instance === null ) {
201 // no global instance yet, nothing to reset
205 self
::failIfResetNotAllowed( __METHOD__
);
207 if ( $bootstrapConfig === null ) {
208 $bootstrapConfig = self
::$instance->getBootstrapConfig();
211 $oldInstance = self
::$instance;
213 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
214 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
216 if ( $quick === 'quick' ) {
217 self
::$instance->salvage( $oldInstance );
219 $oldInstance->destroy();
224 * Salvages the state of any salvageable service instances in $other.
226 * @note $other will have been destroyed when salvage() returns.
228 * @param MediaWikiServices $other
230 private function salvage( self
$other ) {
231 foreach ( $this->getServiceNames() as $name ) {
232 // The service could be new in the new instance and not registered in the
233 // other instance (e.g. an extension that was loaded after the instantiation of
234 // the other instance. Skip this service in this case. See T143974
236 $oldService = $other->peekService( $name );
237 } catch ( NoSuchServiceException
$e ) {
241 if ( $oldService instanceof SalvageableService
) {
242 /** @var SalvageableService $newService */
243 $newService = $this->getService( $name );
244 $newService->salvage( $oldService );
252 * Creates a new MediaWikiServices instance and initializes it according to the
253 * given $bootstrapConfig. In particular, all wiring files defined in the
254 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
256 * @param Config|null $bootstrapConfig The Config object to be registered as the
257 * 'BootstrapConfig' service.
259 * @param string $loadWiring set this to 'load' to load the wiring files specified
260 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
262 * @return MediaWikiServices
263 * @throws MWException
264 * @throws \FatalError
266 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
267 $instance = new self( $bootstrapConfig );
269 // Load the default wiring from the specified files.
270 if ( $loadWiring === 'load' ) {
271 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
272 $instance->loadWiringFiles( $wiringFiles );
275 // Provide a traditional hook point to allow extensions to configure services.
276 Hooks
::run( 'MediaWikiServices', [ $instance ] );
282 * Disables all storage layer services. After calling this, any attempt to access the
283 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
288 * @warning This is intended for extreme situations only and should never be used
289 * while serving normal web requests. Legitimate use cases for this method include
290 * the installation process. Test fixtures may also use this, if the fixture relies
293 * @see resetGlobalInstance()
294 * @see resetChildProcessServices()
296 public static function disableStorageBackend() {
297 // TODO: also disable some Caches, JobQueues, etc
298 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
299 $services = self
::getInstance();
301 foreach ( $destroy as $name ) {
302 $services->disableService( $name );
305 ObjectCache
::clear();
309 * Resets any services that may have become stale after a child process
310 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
311 * to call this method from the parent process.
315 * @note This is intended for use in the context of process forking only!
317 * @see resetGlobalInstance()
318 * @see disableStorageBackend()
320 public static function resetChildProcessServices() {
321 // NOTE: for now, just reset everything. Since we don't know the interdependencies
322 // between services, we can't do this more selectively at this time.
323 self
::resetGlobalInstance();
325 // Child, reseed because there is no bug in PHP:
326 // https://bugs.php.net/bug.php?id=42465
327 mt_srand( getmypid() );
331 * Resets the given service for testing purposes.
335 * @warning This is generally unsafe! Other services may still retain references
336 * to the stale service instance, leading to failures and inconsistencies. Subclasses
337 * may use this method to reset specific services under specific instances, but
338 * it should not be exposed to application logic.
340 * @note With proper dependency injection used throughout the codebase, this method
341 * should not be needed. It is provided to allow tests that pollute global service
342 * instances to clean up.
344 * @param string $name
345 * @param bool $destroy Whether the service instance should be destroyed if it exists.
346 * When set to false, any existing service instance will effectively be detached
347 * from the container.
349 * @throws MWException if called outside of PHPUnit tests.
351 public function resetServiceForTesting( $name, $destroy = true ) {
352 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
353 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
356 $this->resetService( $name, $destroy );
360 * Convenience method that throws an exception unless it is called during a phase in which
361 * resetting of global services is allowed. In general, services should not be reset
362 * individually, since that may introduce inconsistencies.
366 * This method will throw an exception if:
368 * - self::$resetInProgress is false (to allow all services to be reset together
369 * via resetGlobalInstance)
370 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
371 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
373 * This method is intended to be used to safeguard against accidentally resetting
374 * global service instances that are not yet managed by MediaWikiServices. It is
375 * defined here in the MediaWikiServices services class to have a central place
376 * for managing service bootstrapping and resetting.
378 * @param string $method the name of the caller method, as given by __METHOD__.
380 * @throws MWException if called outside bootstrap mode.
382 * @see resetGlobalInstance()
383 * @see forceGlobalInstance()
384 * @see disableStorageBackend()
386 public static function failIfResetNotAllowed( $method ) {
387 if ( !defined( 'MW_PHPUNIT_TEST' )
388 && !defined( 'MW_PARSER_TEST' )
389 && !defined( 'MEDIAWIKI_INSTALL' )
390 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
391 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
393 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
398 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
399 * This has to contain at least the information needed to set up the 'ConfigFactory'
402 public function __construct( Config
$config ) {
403 parent
::__construct();
405 // Register the given Config object as the bootstrap config service.
406 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
411 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
415 * @return ActorMigration
417 public function getActorMigration() {
418 return $this->getService( 'ActorMigration' );
425 public function getBlobStore() {
426 return $this->getService( '_SqlBlobStore' );
431 * @return BlobStoreFactory
433 public function getBlobStoreFactory() {
434 return $this->getService( 'BlobStoreFactory' );
438 * Returns the Config object containing the bootstrap configuration.
439 * Bootstrap configuration would typically include database credentials
440 * and other information that may be needed before the ConfigFactory
441 * service can be instantiated.
443 * @note This should only be used during bootstrapping, in particular
444 * when creating the MainConfig service. Application logic should
445 * use getMainConfig() to get a Config instances.
450 public function getBootstrapConfig() {
451 return $this->getService( 'BootstrapConfig' );
456 * @return NameTableStore
458 public function getChangeTagDefStore() {
459 return $this->getService( 'NameTableStoreFactory' )->getChangeTagDef();
464 * @return CommentStore
466 public function getCommentStore() {
467 return $this->getService( 'CommentStore' );
472 * @return ConfigFactory
474 public function getConfigFactory() {
475 return $this->getService( 'ConfigFactory' );
480 * @return ConfigRepository
482 public function getConfigRepository() {
483 return $this->getService( 'ConfigRepository' );
488 * @return \ConfiguredReadOnlyMode
490 public function getConfiguredReadOnlyMode() {
491 return $this->getService( 'ConfiguredReadOnlyMode' );
498 public function getContentLanguage() {
499 return $this->getService( 'ContentLanguage' );
504 * @return NameTableStore
506 public function getContentModelStore() {
507 return $this->getService( 'NameTableStoreFactory' )->getContentModels();
514 public function getCryptHKDF() {
515 return $this->getService( 'CryptHKDF' );
520 * @deprecated since 1.32, use random_bytes()/random_int()
523 public function getCryptRand() {
524 wfDeprecated( __METHOD__
, '1.32' );
525 return $this->getService( 'CryptRand' );
530 * @return LoadBalancer The main DB load balancer for the local wiki.
532 public function getDBLoadBalancer() {
533 return $this->getService( 'DBLoadBalancer' );
540 public function getDBLoadBalancerFactory() {
541 return $this->getService( 'DBLoadBalancerFactory' );
546 * @return EventRelayerGroup
548 public function getEventRelayerGroup() {
549 return $this->getService( 'EventRelayerGroup' );
554 * @return \ExternalStoreFactory
556 public function getExternalStoreFactory() {
557 return $this->getService( 'ExternalStoreFactory' );
562 * @return GenderCache
564 public function getGenderCache() {
565 return $this->getService( 'GenderCache' );
570 * @return HttpRequestFactory
572 public function getHttpRequestFactory() {
573 return $this->getService( 'HttpRequestFactory' );
578 * @return InterwikiLookup
580 public function getInterwikiLookup() {
581 return $this->getService( 'InterwikiLookup' );
588 public function getLinkCache() {
589 return $this->getService( 'LinkCache' );
593 * LinkRenderer instance that can be used
594 * if no custom options are needed
597 * @return LinkRenderer
599 public function getLinkRenderer() {
600 return $this->getService( 'LinkRenderer' );
605 * @return LinkRendererFactory
607 public function getLinkRendererFactory() {
608 return $this->getService( 'LinkRendererFactory' );
615 public function getLocalServerObjectCache() {
616 return $this->getService( 'LocalServerObjectCache' );
621 * @return MagicWordFactory
623 public function getMagicWordFactory() {
624 return $this->getService( 'MagicWordFactory' );
628 * Returns the Config object that provides configuration for MediaWiki core.
629 * This may or may not be the same object that is returned by getBootstrapConfig().
634 public function getMainConfig() {
635 return $this->getService( 'MainConfig' );
642 public function getMainObjectStash() {
643 return $this->getService( 'MainObjectStash' );
648 * @return \WANObjectCache
650 public function getMainWANObjectCache() {
651 return $this->getService( 'MainWANObjectCache' );
656 * @return MediaHandlerFactory
658 public function getMediaHandlerFactory() {
659 return $this->getService( 'MediaHandlerFactory' );
664 * @return MimeAnalyzer
666 public function getMimeAnalyzer() {
667 return $this->getService( 'MimeAnalyzer' );
672 * @return NameTableStoreFactory
674 public function getNameTableStoreFactory() {
675 return $this->getService( 'NameTableStoreFactory' );
679 * @return OldRevisionImporter
681 public function getOldRevisionImporter() {
682 return $this->getService( 'OldRevisionImporter' );
689 public function getParser() {
690 return $this->getService( 'Parser' );
695 * @return ParserCache
697 public function getParserCache() {
698 return $this->getService( 'ParserCache' );
703 * @return ParserFactory
705 public function getParserFactory() {
706 return $this->getService( 'ParserFactory' );
711 * @return PasswordFactory
713 public function getPasswordFactory() {
714 return $this->getService( 'PasswordFactory' );
719 * @return StatsdDataFactoryInterface
721 public function getPerDbNameStatsdDataFactory() {
722 return $this->getService( 'PerDbNameStatsdDataFactory' );
727 * @return PermissionManager
729 public function getPermissionManager() {
730 return $this->getService( 'PermissionManager' );
735 * @return PreferencesFactory
737 public function getPreferencesFactory() {
738 return $this->getService( 'PreferencesFactory' );
743 * @return ProxyLookup
745 public function getProxyLookup() {
746 return $this->getService( 'ProxyLookup' );
751 * @return \ReadOnlyMode
753 public function getReadOnlyMode() {
754 return $this->getService( 'ReadOnlyMode' );
759 * @return ResourceLoader
761 public function getResourceLoader() {
762 return $this->getService( 'ResourceLoader' );
767 * @return RevisionFactory
769 public function getRevisionFactory() {
770 return $this->getService( 'RevisionFactory' );
775 * @return RevisionLookup
777 public function getRevisionLookup() {
778 return $this->getService( 'RevisionLookup' );
783 * @return RevisionRenderer
785 public function getRevisionRenderer() {
786 return $this->getService( 'RevisionRenderer' );
791 * @return RevisionStore
793 public function getRevisionStore() {
794 return $this->getService( 'RevisionStore' );
799 * @return RevisionStoreFactory
801 public function getRevisionStoreFactory() {
802 return $this->getService( 'RevisionStoreFactory' );
807 * @return SearchEngine
809 public function newSearchEngine() {
810 // New engine object every time, since they keep state
811 return $this->getService( 'SearchEngineFactory' )->create();
816 * @return SearchEngineConfig
818 public function getSearchEngineConfig() {
819 return $this->getService( 'SearchEngineConfig' );
824 * @return SearchEngineFactory
826 public function getSearchEngineFactory() {
827 return $this->getService( 'SearchEngineFactory' );
832 * @return CommandFactory
834 public function getShellCommandFactory() {
835 return $this->getService( 'ShellCommandFactory' );
842 public function getSiteLookup() {
843 return $this->getService( 'SiteLookup' );
850 public function getSiteStore() {
851 return $this->getService( 'SiteStore' );
856 * @return SkinFactory
858 public function getSkinFactory() {
859 return $this->getService( 'SkinFactory' );
864 * @return SlotRoleRegistry
866 public function getSlotRoleRegistry() {
867 return $this->getService( 'SlotRoleRegistry' );
872 * @return NameTableStore
874 public function getSlotRoleStore() {
875 return $this->getService( 'NameTableStoreFactory' )->getSlotRoles();
880 * @return SpecialPageFactory
882 public function getSpecialPageFactory() : SpecialPageFactory
{
883 return $this->getService( 'SpecialPageFactory' );
888 * @return IBufferingStatsdDataFactory
890 public function getStatsdDataFactory() {
891 return $this->getService( 'StatsdDataFactory' );
896 * @return TitleFormatter
898 public function getTitleFormatter() {
899 return $this->getService( 'TitleFormatter' );
904 * @return TitleParser
906 public function getTitleParser() {
907 return $this->getService( 'TitleParser' );
912 * @return UploadRevisionImporter
914 public function getUploadRevisionImporter() {
915 return $this->getService( 'UploadRevisionImporter' );
920 * @return VirtualRESTServiceClient
922 public function getVirtualRESTServiceClient() {
923 return $this->getService( 'VirtualRESTServiceClient' );
928 * @return WatchedItemQueryService
930 public function getWatchedItemQueryService() {
931 return $this->getService( 'WatchedItemQueryService' );
936 * @return WatchedItemStoreInterface
938 public function getWatchedItemStore() {
939 return $this->getService( 'WatchedItemStore' );
944 * @return \OldRevisionImporter
946 public function getWikiRevisionOldRevisionImporter() {
947 return $this->getService( 'OldRevisionImporter' );
952 * @return \OldRevisionImporter
954 public function getWikiRevisionOldRevisionImporterNoUpdates() {
955 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
960 * @return \UploadRevisionImporter
962 public function getWikiRevisionUploadImporter() {
963 return $this->getService( 'UploadRevisionImporter' );