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\Special\SpecialPageFactory
;
21 use MediaWiki\Storage\BlobStore
;
22 use MediaWiki\Storage\BlobStoreFactory
;
23 use MediaWiki\Storage\NameTableStore
;
24 use MediaWiki\Storage\NameTableStoreFactory
;
25 use MediaWiki\Storage\RevisionFactory
;
26 use MediaWiki\Storage\RevisionLookup
;
27 use MediaWiki\Storage\RevisionStore
;
28 use OldRevisionImporter
;
29 use MediaWiki\Storage\RevisionStoreFactory
;
30 use UploadRevisionImporter
;
31 use Wikimedia\Rdbms\LBFactory
;
33 use Wikimedia\Rdbms\LoadBalancer
;
34 use MediaHandlerFactory
;
35 use MediaWiki\Config\ConfigRepository
;
36 use MediaWiki\Linker\LinkRenderer
;
37 use MediaWiki\Linker\LinkRendererFactory
;
38 use MediaWiki\Services\SalvageableService
;
39 use MediaWiki\Services\ServiceContainer
;
40 use MediaWiki\Services\NoSuchServiceException
;
50 use SearchEngineConfig
;
51 use SearchEngineFactory
;
54 use WatchedItemStoreInterface
;
55 use WatchedItemQueryService
;
59 use VirtualRESTServiceClient
;
60 use MediaWiki\Interwiki\InterwikiLookup
;
64 * Service locator for MediaWiki core services.
66 * This program is free software; you can redistribute it and/or modify
67 * it under the terms of the GNU General Public License as published by
68 * the Free Software Foundation; either version 2 of the License, or
69 * (at your option) any later version.
71 * This program is distributed in the hope that it will be useful,
72 * but WITHOUT ANY WARRANTY; without even the implied warranty of
73 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
74 * GNU General Public License for more details.
76 * You should have received a copy of the GNU General Public License along
77 * with this program; if not, write to the Free Software Foundation, Inc.,
78 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
79 * http://www.gnu.org/copyleft/gpl.html
87 * MediaWikiServices is the service locator for the application scope of MediaWiki.
88 * Its implemented as a simple configurable DI container.
89 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
90 * the network of service objects that defines MediaWiki's application logic.
91 * It acts as an entry point to MediaWiki's dependency injection mechanism.
93 * Services are defined in the "wiring" array passed to the constructor,
94 * or by calling defineService().
96 * @see docs/injection.txt for an overview of using dependency injection in the
97 * MediaWiki code base.
99 class MediaWikiServices
extends ServiceContainer
{
102 * @var MediaWikiServices|null
104 private static $instance = null;
107 * Returns the global default instance of the top level service locator.
111 * The default instance is initialized using the service instantiator functions
112 * defined in ServiceWiring.php.
114 * @note This should only be called by static functions! The instance returned here
115 * should not be passed around! Objects that need access to a service should have
116 * that service injected into the constructor, never a service locator!
118 * @return MediaWikiServices
120 public static function getInstance() {
121 if ( self
::$instance === null ) {
122 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
123 // but some information from the global scope has to be injected here,
124 // even if it's just a file name or database credentials to load
125 // configuration from.
126 $bootstrapConfig = new GlobalVarConfig();
127 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
130 return self
::$instance;
134 * Replaces the global MediaWikiServices instance.
138 * @note This is for use in PHPUnit tests only!
140 * @throws MWException if called outside of PHPUnit tests.
142 * @param MediaWikiServices $services The new MediaWikiServices object.
144 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
146 public static function forceGlobalInstance( MediaWikiServices
$services ) {
147 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
148 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
151 $old = self
::getInstance();
152 self
::$instance = $services;
158 * Creates a new instance of MediaWikiServices and sets it as the global default
159 * instance. getInstance() will return a different MediaWikiServices object
160 * after every call to resetGlobalInstance().
164 * @warning This should not be used during normal operation. It is intended for use
165 * when the configuration has changed significantly since bootstrap time, e.g.
166 * during the installation process or during testing.
168 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
169 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
170 * any of the services managed by MediaWikiServices exist. If any service objects
171 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
172 * with the operation of the services managed by the new MediaWikiServices.
173 * Operating with a mix of services created by the old and the new
174 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
175 * Any class implementing LAZY LOADING is especially prone to this problem,
176 * since instances would typically retain a reference to a storage layer service.
178 * @see forceGlobalInstance()
179 * @see resetGlobalInstance()
180 * @see resetBetweenTest()
182 * @param Config|null $bootstrapConfig The Config object to be registered as the
183 * 'BootstrapConfig' service. This has to contain at least the information
184 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
185 * config of the old instance of MediaWikiServices will be re-used. If there
186 * was no previous instance, a new GlobalVarConfig object will be used to
187 * bootstrap the services.
189 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
190 * See SalvageableService for details.
192 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
193 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
196 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
197 if ( self
::$instance === null ) {
198 // no global instance yet, nothing to reset
202 self
::failIfResetNotAllowed( __METHOD__
);
204 if ( $bootstrapConfig === null ) {
205 $bootstrapConfig = self
::$instance->getBootstrapConfig();
208 $oldInstance = self
::$instance;
210 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
211 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
213 if ( $quick === 'quick' ) {
214 self
::$instance->salvage( $oldInstance );
216 $oldInstance->destroy();
221 * Salvages the state of any salvageable service instances in $other.
223 * @note $other will have been destroyed when salvage() returns.
225 * @param MediaWikiServices $other
227 private function salvage( self
$other ) {
228 foreach ( $this->getServiceNames() as $name ) {
229 // The service could be new in the new instance and not registered in the
230 // other instance (e.g. an extension that was loaded after the instantiation of
231 // the other instance. Skip this service in this case. See T143974
233 $oldService = $other->peekService( $name );
234 } catch ( NoSuchServiceException
$e ) {
238 if ( $oldService instanceof SalvageableService
) {
239 /** @var SalvageableService $newService */
240 $newService = $this->getService( $name );
241 $newService->salvage( $oldService );
249 * Creates a new MediaWikiServices instance and initializes it according to the
250 * given $bootstrapConfig. In particular, all wiring files defined in the
251 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
253 * @param Config|null $bootstrapConfig The Config object to be registered as the
254 * 'BootstrapConfig' service.
256 * @param string $loadWiring set this to 'load' to load the wiring files specified
257 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
259 * @return MediaWikiServices
260 * @throws MWException
261 * @throws \FatalError
263 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
264 $instance = new self( $bootstrapConfig );
266 // Load the default wiring from the specified files.
267 if ( $loadWiring === 'load' ) {
268 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
269 $instance->loadWiringFiles( $wiringFiles );
272 // Provide a traditional hook point to allow extensions to configure services.
273 Hooks
::run( 'MediaWikiServices', [ $instance ] );
279 * Disables all storage layer services. After calling this, any attempt to access the
280 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
285 * @warning This is intended for extreme situations only and should never be used
286 * while serving normal web requests. Legitimate use cases for this method include
287 * the installation process. Test fixtures may also use this, if the fixture relies
290 * @see resetGlobalInstance()
291 * @see resetChildProcessServices()
293 public static function disableStorageBackend() {
294 // TODO: also disable some Caches, JobQueues, etc
295 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
296 $services = self
::getInstance();
298 foreach ( $destroy as $name ) {
299 $services->disableService( $name );
302 ObjectCache
::clear();
306 * Resets any services that may have become stale after a child process
307 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
308 * to call this method from the parent process.
312 * @note This is intended for use in the context of process forking only!
314 * @see resetGlobalInstance()
315 * @see disableStorageBackend()
317 public static function resetChildProcessServices() {
318 // NOTE: for now, just reset everything. Since we don't know the interdependencies
319 // between services, we can't do this more selectively at this time.
320 self
::resetGlobalInstance();
322 // Child, reseed because there is no bug in PHP:
323 // https://bugs.php.net/bug.php?id=42465
324 mt_srand( getmypid() );
328 * Resets the given service for testing purposes.
332 * @warning This is generally unsafe! Other services may still retain references
333 * to the stale service instance, leading to failures and inconsistencies. Subclasses
334 * may use this method to reset specific services under specific instances, but
335 * it should not be exposed to application logic.
337 * @note With proper dependency injection used throughout the codebase, this method
338 * should not be needed. It is provided to allow tests that pollute global service
339 * instances to clean up.
341 * @param string $name
342 * @param bool $destroy Whether the service instance should be destroyed if it exists.
343 * When set to false, any existing service instance will effectively be detached
344 * from the container.
346 * @throws MWException if called outside of PHPUnit tests.
348 public function resetServiceForTesting( $name, $destroy = true ) {
349 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
350 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
353 $this->resetService( $name, $destroy );
357 * Convenience method that throws an exception unless it is called during a phase in which
358 * resetting of global services is allowed. In general, services should not be reset
359 * individually, since that may introduce inconsistencies.
363 * This method will throw an exception if:
365 * - self::$resetInProgress is false (to allow all services to be reset together
366 * via resetGlobalInstance)
367 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
368 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
370 * This method is intended to be used to safeguard against accidentally resetting
371 * global service instances that are not yet managed by MediaWikiServices. It is
372 * defined here in the MediaWikiServices services class to have a central place
373 * for managing service bootstrapping and resetting.
375 * @param string $method the name of the caller method, as given by __METHOD__.
377 * @throws MWException if called outside bootstrap mode.
379 * @see resetGlobalInstance()
380 * @see forceGlobalInstance()
381 * @see disableStorageBackend()
383 public static function failIfResetNotAllowed( $method ) {
384 if ( !defined( 'MW_PHPUNIT_TEST' )
385 && !defined( 'MW_PARSER_TEST' )
386 && !defined( 'MEDIAWIKI_INSTALL' )
387 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
388 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
390 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
395 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
396 * This has to contain at least the information needed to set up the 'ConfigFactory'
399 public function __construct( Config
$config ) {
400 parent
::__construct();
402 // Register the given Config object as the bootstrap config service.
403 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
408 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
412 * @return ActorMigration
414 public function getActorMigration() {
415 return $this->getService( 'ActorMigration' );
422 public function getBlobStore() {
423 return $this->getService( '_SqlBlobStore' );
428 * @return BlobStoreFactory
430 public function getBlobStoreFactory() {
431 return $this->getService( 'BlobStoreFactory' );
435 * Returns the Config object containing the bootstrap configuration.
436 * Bootstrap configuration would typically include database credentials
437 * and other information that may be needed before the ConfigFactory
438 * service can be instantiated.
440 * @note This should only be used during bootstrapping, in particular
441 * when creating the MainConfig service. Application logic should
442 * use getMainConfig() to get a Config instances.
447 public function getBootstrapConfig() {
448 return $this->getService( 'BootstrapConfig' );
453 * @return NameTableStore
455 public function getChangeTagDefStore() {
456 return $this->getService( 'NameTableStoreFactory' )->getChangeTagDef();
461 * @return CommentStore
463 public function getCommentStore() {
464 return $this->getService( 'CommentStore' );
469 * @return ConfigFactory
471 public function getConfigFactory() {
472 return $this->getService( 'ConfigFactory' );
477 * @return ConfigRepository
479 public function getConfigRepository() {
480 return $this->getService( 'ConfigRepository' );
485 * @return \ConfiguredReadOnlyMode
487 public function getConfiguredReadOnlyMode() {
488 return $this->getService( 'ConfiguredReadOnlyMode' );
495 public function getContentLanguage() {
496 return $this->getService( 'ContentLanguage' );
501 * @return NameTableStore
503 public function getContentModelStore() {
504 return $this->getService( 'NameTableStoreFactory' )->getContentModels();
511 public function getCryptHKDF() {
512 return $this->getService( 'CryptHKDF' );
517 * @deprecated since 1.32, use random_bytes()/random_int()
520 public function getCryptRand() {
521 return $this->getService( 'CryptRand' );
526 * @return LoadBalancer The main DB load balancer for the local wiki.
528 public function getDBLoadBalancer() {
529 return $this->getService( 'DBLoadBalancer' );
536 public function getDBLoadBalancerFactory() {
537 return $this->getService( 'DBLoadBalancerFactory' );
542 * @return EventRelayerGroup
544 public function getEventRelayerGroup() {
545 return $this->getService( 'EventRelayerGroup' );
550 * @return \ExternalStoreFactory
552 public function getExternalStoreFactory() {
553 return $this->getService( 'ExternalStoreFactory' );
558 * @return GenderCache
560 public function getGenderCache() {
561 return $this->getService( 'GenderCache' );
566 * @return HttpRequestFactory
568 public function getHttpRequestFactory() {
569 return $this->getService( 'HttpRequestFactory' );
574 * @return InterwikiLookup
576 public function getInterwikiLookup() {
577 return $this->getService( 'InterwikiLookup' );
584 public function getLinkCache() {
585 return $this->getService( 'LinkCache' );
589 * LinkRenderer instance that can be used
590 * if no custom options are needed
593 * @return LinkRenderer
595 public function getLinkRenderer() {
596 return $this->getService( 'LinkRenderer' );
601 * @return LinkRendererFactory
603 public function getLinkRendererFactory() {
604 return $this->getService( 'LinkRendererFactory' );
611 public function getLocalServerObjectCache() {
612 return $this->getService( 'LocalServerObjectCache' );
617 * @return MagicWordFactory
619 public function getMagicWordFactory() {
620 return $this->getService( 'MagicWordFactory' );
624 * Returns the Config object that provides configuration for MediaWiki core.
625 * This may or may not be the same object that is returned by getBootstrapConfig().
630 public function getMainConfig() {
631 return $this->getService( 'MainConfig' );
638 public function getMainObjectStash() {
639 return $this->getService( 'MainObjectStash' );
644 * @return \WANObjectCache
646 public function getMainWANObjectCache() {
647 return $this->getService( 'MainWANObjectCache' );
652 * @return MediaHandlerFactory
654 public function getMediaHandlerFactory() {
655 return $this->getService( 'MediaHandlerFactory' );
660 * @return MimeAnalyzer
662 public function getMimeAnalyzer() {
663 return $this->getService( 'MimeAnalyzer' );
668 * @return NameTableStoreFactory
670 public function getNameTableStoreFactory() {
671 return $this->getService( 'NameTableStoreFactory' );
675 * @return OldRevisionImporter
677 public function getOldRevisionImporter() {
678 return $this->getService( 'OldRevisionImporter' );
685 public function getParser() {
686 return $this->getService( 'Parser' );
691 * @return ParserCache
693 public function getParserCache() {
694 return $this->getService( 'ParserCache' );
699 * @return ParserFactory
701 public function getParserFactory() {
702 return $this->getService( 'ParserFactory' );
707 * @return PasswordFactory
709 public function getPasswordFactory() {
710 return $this->getService( 'PasswordFactory' );
715 * @return StatsdDataFactoryInterface
717 public function getPerDbNameStatsdDataFactory() {
718 return $this->getService( 'PerDbNameStatsdDataFactory' );
723 * @return PreferencesFactory
725 public function getPreferencesFactory() {
726 return $this->getService( 'PreferencesFactory' );
731 * @return ProxyLookup
733 public function getProxyLookup() {
734 return $this->getService( 'ProxyLookup' );
739 * @return \ReadOnlyMode
741 public function getReadOnlyMode() {
742 return $this->getService( 'ReadOnlyMode' );
747 * @return RevisionFactory
749 public function getRevisionFactory() {
750 return $this->getService( 'RevisionFactory' );
755 * @return RevisionLookup
757 public function getRevisionLookup() {
758 return $this->getService( 'RevisionLookup' );
763 * @return RevisionRenderer
765 public function getRevisionRenderer() {
766 return $this->getService( 'RevisionRenderer' );
771 * @return RevisionStore
773 public function getRevisionStore() {
774 return $this->getService( 'RevisionStore' );
779 * @return RevisionStoreFactory
781 public function getRevisionStoreFactory() {
782 return $this->getService( 'RevisionStoreFactory' );
787 * @return SearchEngine
789 public function newSearchEngine() {
790 // New engine object every time, since they keep state
791 return $this->getService( 'SearchEngineFactory' )->create();
796 * @return SearchEngineConfig
798 public function getSearchEngineConfig() {
799 return $this->getService( 'SearchEngineConfig' );
804 * @return SearchEngineFactory
806 public function getSearchEngineFactory() {
807 return $this->getService( 'SearchEngineFactory' );
812 * @return CommandFactory
814 public function getShellCommandFactory() {
815 return $this->getService( 'ShellCommandFactory' );
822 public function getSiteLookup() {
823 return $this->getService( 'SiteLookup' );
830 public function getSiteStore() {
831 return $this->getService( 'SiteStore' );
836 * @return SkinFactory
838 public function getSkinFactory() {
839 return $this->getService( 'SkinFactory' );
844 * @return NameTableStore
846 public function getSlotRoleStore() {
847 return $this->getService( 'NameTableStoreFactory' )->getSlotRoles();
852 * @return SpecialPageFactory
854 public function getSpecialPageFactory() : SpecialPageFactory
{
855 return $this->getService( 'SpecialPageFactory' );
860 * @return IBufferingStatsdDataFactory
862 public function getStatsdDataFactory() {
863 return $this->getService( 'StatsdDataFactory' );
868 * @return TitleFormatter
870 public function getTitleFormatter() {
871 return $this->getService( 'TitleFormatter' );
876 * @return TitleParser
878 public function getTitleParser() {
879 return $this->getService( 'TitleParser' );
884 * @return UploadRevisionImporter
886 public function getUploadRevisionImporter() {
887 return $this->getService( 'UploadRevisionImporter' );
892 * @return VirtualRESTServiceClient
894 public function getVirtualRESTServiceClient() {
895 return $this->getService( 'VirtualRESTServiceClient' );
900 * @return WatchedItemQueryService
902 public function getWatchedItemQueryService() {
903 return $this->getService( 'WatchedItemQueryService' );
908 * @return WatchedItemStoreInterface
910 public function getWatchedItemStore() {
911 return $this->getService( 'WatchedItemStore' );
916 * @return \OldRevisionImporter
918 public function getWikiRevisionOldRevisionImporter() {
919 return $this->getService( 'OldRevisionImporter' );
924 * @return \OldRevisionImporter
926 public function getWikiRevisionOldRevisionImporterNoUpdates() {
927 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
932 * @return \UploadRevisionImporter
934 public function getWikiRevisionUploadImporter() {
935 return $this->getService( 'UploadRevisionImporter' );