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
;
49 use SearchEngineConfig
;
50 use SearchEngineFactory
;
53 use WatchedItemStoreInterface
;
54 use WatchedItemQueryService
;
58 use VirtualRESTServiceClient
;
59 use Wikimedia\Services\SalvageableService
;
60 use Wikimedia\Services\ServiceContainer
;
61 use Wikimedia\Services\NoSuchServiceException
;
62 use MediaWiki\Interwiki\InterwikiLookup
;
66 * Service locator for MediaWiki core services.
68 * This program is free software; you can redistribute it and/or modify
69 * it under the terms of the GNU General Public License as published by
70 * the Free Software Foundation; either version 2 of the License, or
71 * (at your option) any later version.
73 * This program is distributed in the hope that it will be useful,
74 * but WITHOUT ANY WARRANTY; without even the implied warranty of
75 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
76 * GNU General Public License for more details.
78 * You should have received a copy of the GNU General Public License along
79 * with this program; if not, write to the Free Software Foundation, Inc.,
80 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
81 * http://www.gnu.org/copyleft/gpl.html
89 * MediaWikiServices is the service locator for the application scope of MediaWiki.
90 * Its implemented as a simple configurable DI container.
91 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
92 * the network of service objects that defines MediaWiki's application logic.
93 * It acts as an entry point to MediaWiki's dependency injection mechanism.
95 * Services are defined in the "wiring" array passed to the constructor,
96 * or by calling defineService().
98 * @see docs/injection.txt for an overview of using dependency injection in the
99 * MediaWiki code base.
101 class MediaWikiServices
extends ServiceContainer
{
104 * @var MediaWikiServices|null
106 private static $instance = null;
109 * Returns the global default instance of the top level service locator.
113 * The default instance is initialized using the service instantiator functions
114 * defined in ServiceWiring.php.
116 * @note This should only be called by static functions! The instance returned here
117 * should not be passed around! Objects that need access to a service should have
118 * that service injected into the constructor, never a service locator!
120 * @return MediaWikiServices
122 public static function getInstance() {
123 if ( self
::$instance === null ) {
124 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
125 // but some information from the global scope has to be injected here,
126 // even if it's just a file name or database credentials to load
127 // configuration from.
128 $bootstrapConfig = new GlobalVarConfig();
129 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
132 return self
::$instance;
136 * Replaces the global MediaWikiServices instance.
140 * @note This is for use in PHPUnit tests only!
142 * @throws MWException if called outside of PHPUnit tests.
144 * @param MediaWikiServices $services The new MediaWikiServices object.
146 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
148 public static function forceGlobalInstance( MediaWikiServices
$services ) {
149 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
150 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
153 $old = self
::getInstance();
154 self
::$instance = $services;
160 * Creates a new instance of MediaWikiServices and sets it as the global default
161 * instance. getInstance() will return a different MediaWikiServices object
162 * after every call to resetGlobalInstance().
166 * @warning This should not be used during normal operation. It is intended for use
167 * when the configuration has changed significantly since bootstrap time, e.g.
168 * during the installation process or during testing.
170 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
171 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
172 * any of the services managed by MediaWikiServices exist. If any service objects
173 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
174 * with the operation of the services managed by the new MediaWikiServices.
175 * Operating with a mix of services created by the old and the new
176 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
177 * Any class implementing LAZY LOADING is especially prone to this problem,
178 * since instances would typically retain a reference to a storage layer service.
180 * @see forceGlobalInstance()
181 * @see resetGlobalInstance()
182 * @see resetBetweenTest()
184 * @param Config|null $bootstrapConfig The Config object to be registered as the
185 * 'BootstrapConfig' service. This has to contain at least the information
186 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
187 * config of the old instance of MediaWikiServices will be re-used. If there
188 * was no previous instance, a new GlobalVarConfig object will be used to
189 * bootstrap the services.
191 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
192 * See SalvageableService for details.
194 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
195 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
198 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
199 if ( self
::$instance === null ) {
200 // no global instance yet, nothing to reset
204 self
::failIfResetNotAllowed( __METHOD__
);
206 if ( $bootstrapConfig === null ) {
207 $bootstrapConfig = self
::$instance->getBootstrapConfig();
210 $oldInstance = self
::$instance;
212 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
213 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
215 if ( $quick === 'quick' ) {
216 self
::$instance->salvage( $oldInstance );
218 $oldInstance->destroy();
223 * Salvages the state of any salvageable service instances in $other.
225 * @note $other will have been destroyed when salvage() returns.
227 * @param MediaWikiServices $other
229 private function salvage( self
$other ) {
230 foreach ( $this->getServiceNames() as $name ) {
231 // The service could be new in the new instance and not registered in the
232 // other instance (e.g. an extension that was loaded after the instantiation of
233 // the other instance. Skip this service in this case. See T143974
235 $oldService = $other->peekService( $name );
236 } catch ( NoSuchServiceException
$e ) {
240 if ( $oldService instanceof SalvageableService
) {
241 /** @var SalvageableService $newService */
242 $newService = $this->getService( $name );
243 $newService->salvage( $oldService );
251 * Creates a new MediaWikiServices instance and initializes it according to the
252 * given $bootstrapConfig. In particular, all wiring files defined in the
253 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
255 * @param Config|null $bootstrapConfig The Config object to be registered as the
256 * 'BootstrapConfig' service.
258 * @param string $loadWiring set this to 'load' to load the wiring files specified
259 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
261 * @return MediaWikiServices
262 * @throws MWException
263 * @throws \FatalError
265 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
266 $instance = new self( $bootstrapConfig );
268 // Load the default wiring from the specified files.
269 if ( $loadWiring === 'load' ) {
270 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
271 $instance->loadWiringFiles( $wiringFiles );
274 // Provide a traditional hook point to allow extensions to configure services.
275 Hooks
::run( 'MediaWikiServices', [ $instance ] );
281 * Disables all storage layer services. After calling this, any attempt to access the
282 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
287 * @warning This is intended for extreme situations only and should never be used
288 * while serving normal web requests. Legitimate use cases for this method include
289 * the installation process. Test fixtures may also use this, if the fixture relies
292 * @see resetGlobalInstance()
293 * @see resetChildProcessServices()
295 public static function disableStorageBackend() {
296 // TODO: also disable some Caches, JobQueues, etc
297 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
298 $services = self
::getInstance();
300 foreach ( $destroy as $name ) {
301 $services->disableService( $name );
304 ObjectCache
::clear();
308 * Resets any services that may have become stale after a child process
309 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
310 * to call this method from the parent process.
314 * @note This is intended for use in the context of process forking only!
316 * @see resetGlobalInstance()
317 * @see disableStorageBackend()
319 public static function resetChildProcessServices() {
320 // NOTE: for now, just reset everything. Since we don't know the interdependencies
321 // between services, we can't do this more selectively at this time.
322 self
::resetGlobalInstance();
324 // Child, reseed because there is no bug in PHP:
325 // https://bugs.php.net/bug.php?id=42465
326 mt_srand( getmypid() );
330 * Resets the given service for testing purposes.
334 * @warning This is generally unsafe! Other services may still retain references
335 * to the stale service instance, leading to failures and inconsistencies. Subclasses
336 * may use this method to reset specific services under specific instances, but
337 * it should not be exposed to application logic.
339 * @note With proper dependency injection used throughout the codebase, this method
340 * should not be needed. It is provided to allow tests that pollute global service
341 * instances to clean up.
343 * @param string $name
344 * @param bool $destroy Whether the service instance should be destroyed if it exists.
345 * When set to false, any existing service instance will effectively be detached
346 * from the container.
348 * @throws MWException if called outside of PHPUnit tests.
350 public function resetServiceForTesting( $name, $destroy = true ) {
351 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
352 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
355 $this->resetService( $name, $destroy );
359 * Convenience method that throws an exception unless it is called during a phase in which
360 * resetting of global services is allowed. In general, services should not be reset
361 * individually, since that may introduce inconsistencies.
365 * This method will throw an exception if:
367 * - self::$resetInProgress is false (to allow all services to be reset together
368 * via resetGlobalInstance)
369 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
370 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
372 * This method is intended to be used to safeguard against accidentally resetting
373 * global service instances that are not yet managed by MediaWikiServices. It is
374 * defined here in the MediaWikiServices services class to have a central place
375 * for managing service bootstrapping and resetting.
377 * @param string $method the name of the caller method, as given by __METHOD__.
379 * @throws MWException if called outside bootstrap mode.
381 * @see resetGlobalInstance()
382 * @see forceGlobalInstance()
383 * @see disableStorageBackend()
385 public static function failIfResetNotAllowed( $method ) {
386 if ( !defined( 'MW_PHPUNIT_TEST' )
387 && !defined( 'MW_PARSER_TEST' )
388 && !defined( 'MEDIAWIKI_INSTALL' )
389 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
390 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
392 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
397 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
398 * This has to contain at least the information needed to set up the 'ConfigFactory'
401 public function __construct( Config
$config ) {
402 parent
::__construct();
404 // Register the given Config object as the bootstrap config service.
405 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
410 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
414 * @return ActorMigration
416 public function getActorMigration() {
417 return $this->getService( 'ActorMigration' );
424 public function getBlobStore() {
425 return $this->getService( '_SqlBlobStore' );
430 * @return BlobStoreFactory
432 public function getBlobStoreFactory() {
433 return $this->getService( 'BlobStoreFactory' );
437 * Returns the Config object containing the bootstrap configuration.
438 * Bootstrap configuration would typically include database credentials
439 * and other information that may be needed before the ConfigFactory
440 * service can be instantiated.
442 * @note This should only be used during bootstrapping, in particular
443 * when creating the MainConfig service. Application logic should
444 * use getMainConfig() to get a Config instances.
449 public function getBootstrapConfig() {
450 return $this->getService( 'BootstrapConfig' );
455 * @return NameTableStore
457 public function getChangeTagDefStore() {
458 return $this->getService( 'NameTableStoreFactory' )->getChangeTagDef();
463 * @return CommentStore
465 public function getCommentStore() {
466 return $this->getService( 'CommentStore' );
471 * @return ConfigFactory
473 public function getConfigFactory() {
474 return $this->getService( 'ConfigFactory' );
479 * @return ConfigRepository
481 public function getConfigRepository() {
482 return $this->getService( 'ConfigRepository' );
487 * @return \ConfiguredReadOnlyMode
489 public function getConfiguredReadOnlyMode() {
490 return $this->getService( 'ConfiguredReadOnlyMode' );
497 public function getContentLanguage() {
498 return $this->getService( 'ContentLanguage' );
503 * @return NameTableStore
505 public function getContentModelStore() {
506 return $this->getService( 'NameTableStoreFactory' )->getContentModels();
513 public function getCryptHKDF() {
514 return $this->getService( 'CryptHKDF' );
519 * @deprecated since 1.32, use random_bytes()/random_int()
522 public function getCryptRand() {
523 wfDeprecated( __METHOD__
, '1.32' );
524 return $this->getService( 'CryptRand' );
529 * @return LoadBalancer The main DB load balancer for the local wiki.
531 public function getDBLoadBalancer() {
532 return $this->getService( 'DBLoadBalancer' );
539 public function getDBLoadBalancerFactory() {
540 return $this->getService( 'DBLoadBalancerFactory' );
545 * @return EventRelayerGroup
547 public function getEventRelayerGroup() {
548 return $this->getService( 'EventRelayerGroup' );
553 * @return \ExternalStoreFactory
555 public function getExternalStoreFactory() {
556 return $this->getService( 'ExternalStoreFactory' );
561 * @return GenderCache
563 public function getGenderCache() {
564 return $this->getService( 'GenderCache' );
569 * @return HttpRequestFactory
571 public function getHttpRequestFactory() {
572 return $this->getService( 'HttpRequestFactory' );
577 * @return InterwikiLookup
579 public function getInterwikiLookup() {
580 return $this->getService( 'InterwikiLookup' );
587 public function getLinkCache() {
588 return $this->getService( 'LinkCache' );
592 * LinkRenderer instance that can be used
593 * if no custom options are needed
596 * @return LinkRenderer
598 public function getLinkRenderer() {
599 return $this->getService( 'LinkRenderer' );
604 * @return LinkRendererFactory
606 public function getLinkRendererFactory() {
607 return $this->getService( 'LinkRendererFactory' );
614 public function getLocalServerObjectCache() {
615 return $this->getService( 'LocalServerObjectCache' );
620 * @return MagicWordFactory
622 public function getMagicWordFactory() {
623 return $this->getService( 'MagicWordFactory' );
627 * Returns the Config object that provides configuration for MediaWiki core.
628 * This may or may not be the same object that is returned by getBootstrapConfig().
633 public function getMainConfig() {
634 return $this->getService( 'MainConfig' );
641 public function getMainObjectStash() {
642 return $this->getService( 'MainObjectStash' );
647 * @return \WANObjectCache
649 public function getMainWANObjectCache() {
650 return $this->getService( 'MainWANObjectCache' );
655 * @return MediaHandlerFactory
657 public function getMediaHandlerFactory() {
658 return $this->getService( 'MediaHandlerFactory' );
663 * @return MimeAnalyzer
665 public function getMimeAnalyzer() {
666 return $this->getService( 'MimeAnalyzer' );
671 * @return NameTableStoreFactory
673 public function getNameTableStoreFactory() {
674 return $this->getService( 'NameTableStoreFactory' );
678 * @return OldRevisionImporter
680 public function getOldRevisionImporter() {
681 return $this->getService( 'OldRevisionImporter' );
688 public function getParser() {
689 return $this->getService( 'Parser' );
694 * @return ParserCache
696 public function getParserCache() {
697 return $this->getService( 'ParserCache' );
702 * @return ParserFactory
704 public function getParserFactory() {
705 return $this->getService( 'ParserFactory' );
710 * @return PasswordFactory
712 public function getPasswordFactory() {
713 return $this->getService( 'PasswordFactory' );
718 * @return StatsdDataFactoryInterface
720 public function getPerDbNameStatsdDataFactory() {
721 return $this->getService( 'PerDbNameStatsdDataFactory' );
726 * @return PreferencesFactory
728 public function getPreferencesFactory() {
729 return $this->getService( 'PreferencesFactory' );
734 * @return ProxyLookup
736 public function getProxyLookup() {
737 return $this->getService( 'ProxyLookup' );
742 * @return \ReadOnlyMode
744 public function getReadOnlyMode() {
745 return $this->getService( 'ReadOnlyMode' );
750 * @return ResourceLoader
752 public function getResourceLoader() {
753 return $this->getService( 'ResourceLoader' );
758 * @return RevisionFactory
760 public function getRevisionFactory() {
761 return $this->getService( 'RevisionFactory' );
766 * @return RevisionLookup
768 public function getRevisionLookup() {
769 return $this->getService( 'RevisionLookup' );
774 * @return RevisionRenderer
776 public function getRevisionRenderer() {
777 return $this->getService( 'RevisionRenderer' );
782 * @return RevisionStore
784 public function getRevisionStore() {
785 return $this->getService( 'RevisionStore' );
790 * @return RevisionStoreFactory
792 public function getRevisionStoreFactory() {
793 return $this->getService( 'RevisionStoreFactory' );
798 * @return SearchEngine
800 public function newSearchEngine() {
801 // New engine object every time, since they keep state
802 return $this->getService( 'SearchEngineFactory' )->create();
807 * @return SearchEngineConfig
809 public function getSearchEngineConfig() {
810 return $this->getService( 'SearchEngineConfig' );
815 * @return SearchEngineFactory
817 public function getSearchEngineFactory() {
818 return $this->getService( 'SearchEngineFactory' );
823 * @return CommandFactory
825 public function getShellCommandFactory() {
826 return $this->getService( 'ShellCommandFactory' );
833 public function getSiteLookup() {
834 return $this->getService( 'SiteLookup' );
841 public function getSiteStore() {
842 return $this->getService( 'SiteStore' );
847 * @return SkinFactory
849 public function getSkinFactory() {
850 return $this->getService( 'SkinFactory' );
855 * @return SlotRoleRegistry
857 public function getSlotRoleRegistry() {
858 return $this->getService( 'SlotRoleRegistry' );
863 * @return NameTableStore
865 public function getSlotRoleStore() {
866 return $this->getService( 'NameTableStoreFactory' )->getSlotRoles();
871 * @return SpecialPageFactory
873 public function getSpecialPageFactory() : SpecialPageFactory
{
874 return $this->getService( 'SpecialPageFactory' );
879 * @return IBufferingStatsdDataFactory
881 public function getStatsdDataFactory() {
882 return $this->getService( 'StatsdDataFactory' );
887 * @return TitleFormatter
889 public function getTitleFormatter() {
890 return $this->getService( 'TitleFormatter' );
895 * @return TitleParser
897 public function getTitleParser() {
898 return $this->getService( 'TitleParser' );
903 * @return UploadRevisionImporter
905 public function getUploadRevisionImporter() {
906 return $this->getService( 'UploadRevisionImporter' );
911 * @return VirtualRESTServiceClient
913 public function getVirtualRESTServiceClient() {
914 return $this->getService( 'VirtualRESTServiceClient' );
919 * @return WatchedItemQueryService
921 public function getWatchedItemQueryService() {
922 return $this->getService( 'WatchedItemQueryService' );
927 * @return WatchedItemStoreInterface
929 public function getWatchedItemStore() {
930 return $this->getService( 'WatchedItemStore' );
935 * @return \OldRevisionImporter
937 public function getWikiRevisionOldRevisionImporter() {
938 return $this->getService( 'OldRevisionImporter' );
943 * @return \OldRevisionImporter
945 public function getWikiRevisionOldRevisionImporterNoUpdates() {
946 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
951 * @return \UploadRevisionImporter
953 public function getWikiRevisionUploadImporter() {
954 return $this->getService( 'UploadRevisionImporter' );