10 use DateFormatterFactory
;
11 use EventRelayerGroup
;
15 use IBufferingStatsdDataFactory
;
16 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface
;
17 use MediaWiki\Block\BlockManager
;
18 use MediaWiki\Block\BlockRestrictionStore
;
19 use MediaWiki\FileBackend\FSFile\TempFSFileFactory
;
20 use MediaWiki\Http\HttpRequestFactory
;
21 use MediaWiki\Page\MovePageFactory
;
22 use MediaWiki\Permissions\PermissionManager
;
23 use MediaWiki\Preferences\PreferencesFactory
;
24 use MediaWiki\Revision\RevisionRenderer
;
25 use MediaWiki\Revision\SlotRoleRegistry
;
26 use MediaWiki\Shell\CommandFactory
;
27 use MediaWiki\Special\SpecialPageFactory
;
28 use MediaWiki\Storage\BlobStore
;
29 use MediaWiki\Storage\BlobStoreFactory
;
30 use MediaWiki\Storage\NameTableStore
;
31 use MediaWiki\Storage\NameTableStoreFactory
;
32 use MediaWiki\Revision\RevisionFactory
;
33 use MediaWiki\Revision\RevisionLookup
;
34 use MediaWiki\Revision\RevisionStore
;
35 use OldRevisionImporter
;
36 use MediaWiki\Revision\RevisionStoreFactory
;
37 use UploadRevisionImporter
;
38 use Wikimedia\Rdbms\ILoadBalancer
;
40 use MediaHandlerFactory
;
41 use MediaWiki\Config\ConfigRepository
;
42 use MediaWiki\Linker\LinkRenderer
;
43 use MediaWiki\Linker\LinkRendererFactory
;
57 use SearchEngineConfig
;
58 use SearchEngineFactory
;
61 use WatchedItemStoreInterface
;
62 use WatchedItemQueryService
;
66 use VirtualRESTServiceClient
;
67 use Wikimedia\ObjectFactory
;
68 use Wikimedia\Rdbms\LBFactory
;
69 use Wikimedia\Services\SalvageableService
;
70 use Wikimedia\Services\ServiceContainer
;
71 use Wikimedia\Services\NoSuchServiceException
;
72 use MediaWiki\Interwiki\InterwikiLookup
;
74 use MediaWiki\Storage\PageEditStash
;
77 * Service locator for MediaWiki core services.
79 * This program is free software; you can redistribute it and/or modify
80 * it under the terms of the GNU General Public License as published by
81 * the Free Software Foundation; either version 2 of the License, or
82 * (at your option) any later version.
84 * This program is distributed in the hope that it will be useful,
85 * but WITHOUT ANY WARRANTY; without even the implied warranty of
86 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
87 * GNU General Public License for more details.
89 * You should have received a copy of the GNU General Public License along
90 * with this program; if not, write to the Free Software Foundation, Inc.,
91 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
92 * http://www.gnu.org/copyleft/gpl.html
100 * MediaWikiServices is the service locator for the application scope of MediaWiki.
101 * Its implemented as a simple configurable DI container.
102 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
103 * the network of service objects that defines MediaWiki's application logic.
104 * It acts as an entry point to MediaWiki's dependency injection mechanism.
106 * Services are defined in the "wiring" array passed to the constructor,
107 * or by calling defineService().
109 * @see docs/injection.txt for an overview of using dependency injection in the
110 * MediaWiki code base.
112 class MediaWikiServices
extends ServiceContainer
{
115 * @var MediaWikiServices|null
117 private static $instance = null;
120 * Returns the global default instance of the top level service locator.
124 * The default instance is initialized using the service instantiator functions
125 * defined in ServiceWiring.php.
127 * @note This should only be called by static functions! The instance returned here
128 * should not be passed around! Objects that need access to a service should have
129 * that service injected into the constructor, never a service locator!
131 * @return MediaWikiServices
133 public static function getInstance() {
134 if ( self
::$instance === null ) {
135 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
136 // but some information from the global scope has to be injected here,
137 // even if it's just a file name or database credentials to load
138 // configuration from.
139 $bootstrapConfig = new GlobalVarConfig();
140 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
143 return self
::$instance;
147 * Replaces the global MediaWikiServices instance.
151 * @note This is for use in PHPUnit tests only!
153 * @throws MWException if called outside of PHPUnit tests.
155 * @param MediaWikiServices $services The new MediaWikiServices object.
157 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
159 public static function forceGlobalInstance( MediaWikiServices
$services ) {
160 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
161 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
164 $old = self
::getInstance();
165 self
::$instance = $services;
171 * Creates a new instance of MediaWikiServices and sets it as the global default
172 * instance. getInstance() will return a different MediaWikiServices object
173 * after every call to resetGlobalInstance().
177 * @warning This should not be used during normal operation. It is intended for use
178 * when the configuration has changed significantly since bootstrap time, e.g.
179 * during the installation process or during testing.
181 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
182 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
183 * any of the services managed by MediaWikiServices exist. If any service objects
184 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
185 * with the operation of the services managed by the new MediaWikiServices.
186 * Operating with a mix of services created by the old and the new
187 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
188 * Any class implementing LAZY LOADING is especially prone to this problem,
189 * since instances would typically retain a reference to a storage layer service.
191 * @see forceGlobalInstance()
192 * @see resetGlobalInstance()
193 * @see resetBetweenTest()
195 * @param Config|null $bootstrapConfig The Config object to be registered as the
196 * 'BootstrapConfig' service. This has to contain at least the information
197 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
198 * config of the old instance of MediaWikiServices will be re-used. If there
199 * was no previous instance, a new GlobalVarConfig object will be used to
200 * bootstrap the services.
202 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
203 * See SalvageableService for details.
205 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
206 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
209 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
210 if ( self
::$instance === null ) {
211 // no global instance yet, nothing to reset
215 self
::failIfResetNotAllowed( __METHOD__
);
217 if ( $bootstrapConfig === null ) {
218 $bootstrapConfig = self
::$instance->getBootstrapConfig();
221 $oldInstance = self
::$instance;
223 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
224 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
226 if ( $quick === 'quick' ) {
227 self
::$instance->salvage( $oldInstance );
229 $oldInstance->destroy();
233 /** @noinspection PhpDocSignatureInspection */
236 * Salvages the state of any salvageable service instances in $other.
238 * @note $other will have been destroyed when salvage() returns.
240 * @param MediaWikiServices $other
242 private function salvage( self
$other ) {
243 foreach ( $this->getServiceNames() as $name ) {
244 // The service could be new in the new instance and not registered in the
245 // other instance (e.g. an extension that was loaded after the instantiation of
246 // the other instance. Skip this service in this case. See T143974
248 $oldService = $other->peekService( $name );
249 } catch ( NoSuchServiceException
$e ) {
253 if ( $oldService instanceof SalvageableService
) {
254 /** @var SalvageableService $newService */
255 $newService = $this->getService( $name );
256 $newService->salvage( $oldService );
264 * Creates a new MediaWikiServices instance and initializes it according to the
265 * given $bootstrapConfig. In particular, all wiring files defined in the
266 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
268 * @param Config|null $bootstrapConfig The Config object to be registered as the
269 * 'BootstrapConfig' service.
271 * @param string $loadWiring set this to 'load' to load the wiring files specified
272 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
274 * @return MediaWikiServices
275 * @throws MWException
276 * @throws \FatalError
278 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
279 $instance = new self( $bootstrapConfig );
281 // Load the default wiring from the specified files.
282 if ( $loadWiring === 'load' ) {
283 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
284 $instance->loadWiringFiles( $wiringFiles );
287 // Provide a traditional hook point to allow extensions to configure services.
288 Hooks
::run( 'MediaWikiServices', [ $instance ] );
294 * Disables all storage layer services. After calling this, any attempt to access the
295 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
300 * @warning This is intended for extreme situations only and should never be used
301 * while serving normal web requests. Legitimate use cases for this method include
302 * the installation process. Test fixtures may also use this, if the fixture relies
305 * @see resetGlobalInstance()
306 * @see resetChildProcessServices()
308 public static function disableStorageBackend() {
309 // TODO: also disable some Caches, JobQueues, etc
310 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
311 $services = self
::getInstance();
313 foreach ( $destroy as $name ) {
314 $services->disableService( $name );
317 ObjectCache
::clear();
321 * Resets any services that may have become stale after a child process
322 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
323 * to call this method from the parent process.
327 * @note This is intended for use in the context of process forking only!
329 * @see resetGlobalInstance()
330 * @see disableStorageBackend()
332 public static function resetChildProcessServices() {
333 // NOTE: for now, just reset everything. Since we don't know the interdependencies
334 // between services, we can't do this more selectively at this time.
335 self
::resetGlobalInstance();
337 // Child, reseed because there is no bug in PHP:
338 // https://bugs.php.net/bug.php?id=42465
339 mt_srand( getmypid() );
343 * Resets the given service for testing purposes.
347 * @warning This is generally unsafe! Other services may still retain references
348 * to the stale service instance, leading to failures and inconsistencies. Subclasses
349 * may use this method to reset specific services under specific instances, but
350 * it should not be exposed to application logic.
352 * @note With proper dependency injection used throughout the codebase, this method
353 * should not be needed. It is provided to allow tests that pollute global service
354 * instances to clean up.
356 * @param string $name
357 * @param bool $destroy Whether the service instance should be destroyed if it exists.
358 * When set to false, any existing service instance will effectively be detached
359 * from the container.
361 * @throws MWException if called outside of PHPUnit tests.
363 public function resetServiceForTesting( $name, $destroy = true ) {
364 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
365 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
368 $this->resetService( $name, $destroy );
372 * Convenience method that throws an exception unless it is called during a phase in which
373 * resetting of global services is allowed. In general, services should not be reset
374 * individually, since that may introduce inconsistencies.
378 * This method will throw an exception if:
380 * - self::$resetInProgress is false (to allow all services to be reset together
381 * via resetGlobalInstance)
382 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
383 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
385 * This method is intended to be used to safeguard against accidentally resetting
386 * global service instances that are not yet managed by MediaWikiServices. It is
387 * defined here in the MediaWikiServices services class to have a central place
388 * for managing service bootstrapping and resetting.
390 * @param string $method the name of the caller method, as given by __METHOD__.
392 * @throws MWException if called outside bootstrap mode.
394 * @see resetGlobalInstance()
395 * @see forceGlobalInstance()
396 * @see disableStorageBackend()
398 public static function failIfResetNotAllowed( $method ) {
399 if ( !defined( 'MW_PHPUNIT_TEST' )
400 && !defined( 'MW_PARSER_TEST' )
401 && !defined( 'MEDIAWIKI_INSTALL' )
402 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
403 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
405 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
410 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
411 * This has to contain at least the information needed to set up the 'ConfigFactory'
414 public function __construct( Config
$config ) {
415 parent
::__construct();
417 // Register the given Config object as the bootstrap config service.
418 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
423 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
427 * @return ActorMigration
429 public function getActorMigration() {
430 return $this->getService( 'ActorMigration' );
435 * @return BadFileLookup
437 public function getBadFileLookup() : BadFileLookup
{
438 return $this->getService( 'BadFileLookup' );
445 public function getBlobStore() {
446 return $this->getService( '_SqlBlobStore' );
451 * @return BlobStoreFactory
453 public function getBlobStoreFactory() {
454 return $this->getService( 'BlobStoreFactory' );
459 * @return BlockManager
461 public function getBlockManager() : BlockManager
{
462 return $this->getService( 'BlockManager' );
467 * @return BlockRestrictionStore
469 public function getBlockRestrictionStore() : BlockRestrictionStore
{
470 return $this->getService( 'BlockRestrictionStore' );
474 * Returns the Config object containing the bootstrap configuration.
475 * Bootstrap configuration would typically include database credentials
476 * and other information that may be needed before the ConfigFactory
477 * service can be instantiated.
479 * @note This should only be used during bootstrapping, in particular
480 * when creating the MainConfig service. Application logic should
481 * use getMainConfig() to get a Config instances.
486 public function getBootstrapConfig() {
487 return $this->getService( 'BootstrapConfig' );
492 * @return NameTableStore
494 public function getChangeTagDefStore() {
495 return $this->getService( 'NameTableStoreFactory' )->getChangeTagDef();
500 * @return CommentStore
502 public function getCommentStore() {
503 return $this->getService( 'CommentStore' );
508 * @return ConfigFactory
510 public function getConfigFactory() {
511 return $this->getService( 'ConfigFactory' );
516 * @return ConfigRepository
518 public function getConfigRepository() {
519 return $this->getService( 'ConfigRepository' );
524 * @return \ConfiguredReadOnlyMode
526 public function getConfiguredReadOnlyMode() {
527 return $this->getService( 'ConfiguredReadOnlyMode' );
534 public function getContentLanguage() {
535 return $this->getService( 'ContentLanguage' );
540 * @return NameTableStore
542 public function getContentModelStore() {
543 return $this->getService( 'NameTableStoreFactory' )->getContentModels();
550 public function getCryptHKDF() {
551 return $this->getService( 'CryptHKDF' );
556 * @return DateFormatterFactory
558 public function getDateFormatterFactory() {
559 return $this->getService( 'DateFormatterFactory' );
564 * @return ILoadBalancer The main DB load balancer for the local wiki.
566 public function getDBLoadBalancer() {
567 return $this->getService( 'DBLoadBalancer' );
574 public function getDBLoadBalancerFactory() {
575 return $this->getService( 'DBLoadBalancerFactory' );
580 * @return EventRelayerGroup
582 public function getEventRelayerGroup() {
583 return $this->getService( 'EventRelayerGroup' );
588 * @return \ExternalStoreAccess
590 public function getExternalStoreAccess() {
591 return $this->getService( 'ExternalStoreAccess' );
596 * @return \ExternalStoreFactory
598 public function getExternalStoreFactory() {
599 return $this->getService( 'ExternalStoreFactory' );
604 * @return GenderCache
606 public function getGenderCache() {
607 return $this->getService( 'GenderCache' );
612 * @return HttpRequestFactory
614 public function getHttpRequestFactory() {
615 return $this->getService( 'HttpRequestFactory' );
620 * @return InterwikiLookup
622 public function getInterwikiLookup() {
623 return $this->getService( 'InterwikiLookup' );
630 public function getLinkCache() {
631 return $this->getService( 'LinkCache' );
635 * LinkRenderer instance that can be used
636 * if no custom options are needed
639 * @return LinkRenderer
641 public function getLinkRenderer() {
642 return $this->getService( 'LinkRenderer' );
647 * @return LinkRendererFactory
649 public function getLinkRendererFactory() {
650 return $this->getService( 'LinkRendererFactory' );
657 public function getLocalServerObjectCache() {
658 return $this->getService( 'LocalServerObjectCache' );
663 * @return MagicWordFactory
665 public function getMagicWordFactory() {
666 return $this->getService( 'MagicWordFactory' );
670 * Returns the Config object that provides configuration for MediaWiki core.
671 * This may or may not be the same object that is returned by getBootstrapConfig().
676 public function getMainConfig() {
677 return $this->getService( 'MainConfig' );
684 public function getMainObjectStash() {
685 return $this->getService( 'MainObjectStash' );
690 * @return \WANObjectCache
692 public function getMainWANObjectCache() {
693 return $this->getService( 'MainWANObjectCache' );
698 * @return MediaHandlerFactory
700 public function getMediaHandlerFactory() {
701 return $this->getService( 'MediaHandlerFactory' );
706 * @return MessageCache
708 public function getMessageCache() : MessageCache
{
709 return $this->getService( 'MessageCache' );
714 * @return MimeAnalyzer
716 public function getMimeAnalyzer() {
717 return $this->getService( 'MimeAnalyzer' );
722 * @return MovePageFactory
724 public function getMovePageFactory() : MovePageFactory
{
725 return $this->getService( 'MovePageFactory' );
730 * @return NamespaceInfo
732 public function getNamespaceInfo() : NamespaceInfo
{
733 return $this->getService( 'NamespaceInfo' );
738 * @return NameTableStoreFactory
740 public function getNameTableStoreFactory() {
741 return $this->getService( 'NameTableStoreFactory' );
745 * ObjectFactory is intended for instantiating "handlers" from declarative definitions,
746 * such as Action API modules, special pages, or REST API handlers.
749 * @return ObjectFactory
751 public function getObjectFactory() {
752 return $this->getService( 'ObjectFactory' );
757 * @return OldRevisionImporter
759 public function getOldRevisionImporter() {
760 return $this->getService( 'OldRevisionImporter' );
764 * @return PageEditStash
767 public function getPageEditStash() {
768 return $this->getService( 'PageEditStash' );
775 public function getParser() {
776 return $this->getService( 'Parser' );
781 * @return ParserCache
783 public function getParserCache() {
784 return $this->getService( 'ParserCache' );
789 * @return ParserFactory
791 public function getParserFactory() {
792 return $this->getService( 'ParserFactory' );
797 * @return PasswordFactory
799 public function getPasswordFactory() {
800 return $this->getService( 'PasswordFactory' );
805 * @return StatsdDataFactoryInterface
807 public function getPerDbNameStatsdDataFactory() {
808 return $this->getService( 'PerDbNameStatsdDataFactory' );
813 * @return PermissionManager
815 public function getPermissionManager() {
816 return $this->getService( 'PermissionManager' );
821 * @return PreferencesFactory
823 public function getPreferencesFactory() {
824 return $this->getService( 'PreferencesFactory' );
829 * @return ProxyLookup
831 public function getProxyLookup() {
832 return $this->getService( 'ProxyLookup' );
837 * @return \ReadOnlyMode
839 public function getReadOnlyMode() {
840 return $this->getService( 'ReadOnlyMode' );
847 public function getRepoGroup() : RepoGroup
{
848 return $this->getService( 'RepoGroup' );
853 * @return ResourceLoader
855 public function getResourceLoader() {
856 return $this->getService( 'ResourceLoader' );
861 * @return RevisionFactory
863 public function getRevisionFactory() {
864 return $this->getService( 'RevisionFactory' );
869 * @return RevisionLookup
871 public function getRevisionLookup() {
872 return $this->getService( 'RevisionLookup' );
877 * @return RevisionRenderer
879 public function getRevisionRenderer() {
880 return $this->getService( 'RevisionRenderer' );
885 * @return RevisionStore
887 public function getRevisionStore() {
888 return $this->getService( 'RevisionStore' );
893 * @return RevisionStoreFactory
895 public function getRevisionStoreFactory() {
896 return $this->getService( 'RevisionStoreFactory' );
901 * @return SearchEngine
903 public function newSearchEngine() {
904 // New engine object every time, since they keep state
905 return $this->getService( 'SearchEngineFactory' )->create();
910 * @return SearchEngineConfig
912 public function getSearchEngineConfig() {
913 return $this->getService( 'SearchEngineConfig' );
918 * @return SearchEngineFactory
920 public function getSearchEngineFactory() {
921 return $this->getService( 'SearchEngineFactory' );
926 * @return CommandFactory
928 public function getShellCommandFactory() {
929 return $this->getService( 'ShellCommandFactory' );
936 public function getSiteLookup() {
937 return $this->getService( 'SiteLookup' );
944 public function getSiteStore() {
945 return $this->getService( 'SiteStore' );
950 * @return SkinFactory
952 public function getSkinFactory() {
953 return $this->getService( 'SkinFactory' );
958 * @return SlotRoleRegistry
960 public function getSlotRoleRegistry() {
961 return $this->getService( 'SlotRoleRegistry' );
966 * @return NameTableStore
968 public function getSlotRoleStore() {
969 return $this->getService( 'NameTableStoreFactory' )->getSlotRoles();
974 * @return SpecialPageFactory
976 public function getSpecialPageFactory() : SpecialPageFactory
{
977 return $this->getService( 'SpecialPageFactory' );
982 * @return IBufferingStatsdDataFactory
984 public function getStatsdDataFactory() {
985 return $this->getService( 'StatsdDataFactory' );
990 * @return TempFSFileFactory
992 public function getTempFSFileFactory() : TempFSFileFactory
{
993 return $this->getService( 'TempFSFileFactory' );
998 * @return TitleFormatter
1000 public function getTitleFormatter() {
1001 return $this->getService( 'TitleFormatter' );
1006 * @return TitleParser
1008 public function getTitleParser() {
1009 return $this->getService( 'TitleParser' );
1014 * @return UploadRevisionImporter
1016 public function getUploadRevisionImporter() {
1017 return $this->getService( 'UploadRevisionImporter' );
1022 * @return VirtualRESTServiceClient
1024 public function getVirtualRESTServiceClient() {
1025 return $this->getService( 'VirtualRESTServiceClient' );
1030 * @return WatchedItemQueryService
1032 public function getWatchedItemQueryService() {
1033 return $this->getService( 'WatchedItemQueryService' );
1038 * @return WatchedItemStoreInterface
1040 public function getWatchedItemStore() {
1041 return $this->getService( 'WatchedItemStore' );
1046 * @return \OldRevisionImporter
1048 public function getWikiRevisionOldRevisionImporter() {
1049 return $this->getService( 'OldRevisionImporter' );
1054 * @return \OldRevisionImporter
1056 public function getWikiRevisionOldRevisionImporterNoUpdates() {
1057 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
1062 * @return \UploadRevisionImporter
1064 public function getWikiRevisionUploadImporter() {
1065 return $this->getService( 'UploadRevisionImporter' );