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\FileBackend\LockManager\LockManagerGroupFactory
;
21 use MediaWiki\Http\HttpRequestFactory
;
22 use MediaWiki\Page\MovePageFactory
;
23 use MediaWiki\Permissions\PermissionManager
;
24 use MediaWiki\Preferences\PreferencesFactory
;
25 use MediaWiki\Revision\RevisionRenderer
;
26 use MediaWiki\Revision\SlotRoleRegistry
;
27 use MediaWiki\Shell\CommandFactory
;
28 use MediaWiki\Special\SpecialPageFactory
;
29 use MediaWiki\Storage\BlobStore
;
30 use MediaWiki\Storage\BlobStoreFactory
;
31 use MediaWiki\Storage\NameTableStore
;
32 use MediaWiki\Storage\NameTableStoreFactory
;
33 use MediaWiki\Revision\RevisionFactory
;
34 use MediaWiki\Revision\RevisionLookup
;
35 use MediaWiki\Revision\RevisionStore
;
36 use OldRevisionImporter
;
37 use MediaWiki\Revision\RevisionStoreFactory
;
38 use UploadRevisionImporter
;
39 use Wikimedia\Rdbms\ILoadBalancer
;
41 use MediaHandlerFactory
;
42 use MediaWiki\Config\ConfigRepository
;
43 use MediaWiki\Linker\LinkRenderer
;
44 use MediaWiki\Linker\LinkRendererFactory
;
58 use SearchEngineConfig
;
59 use SearchEngineFactory
;
62 use WatchedItemStoreInterface
;
63 use WatchedItemQueryService
;
67 use VirtualRESTServiceClient
;
68 use Wikimedia\ObjectFactory
;
69 use Wikimedia\Rdbms\LBFactory
;
70 use Wikimedia\Services\SalvageableService
;
71 use Wikimedia\Services\ServiceContainer
;
72 use Wikimedia\Services\NoSuchServiceException
;
73 use MediaWiki\Interwiki\InterwikiLookup
;
75 use MediaWiki\Storage\PageEditStash
;
78 * Service locator for MediaWiki core services.
80 * This program is free software; you can redistribute it and/or modify
81 * it under the terms of the GNU General Public License as published by
82 * the Free Software Foundation; either version 2 of the License, or
83 * (at your option) any later version.
85 * This program is distributed in the hope that it will be useful,
86 * but WITHOUT ANY WARRANTY; without even the implied warranty of
87 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
88 * GNU General Public License for more details.
90 * You should have received a copy of the GNU General Public License along
91 * with this program; if not, write to the Free Software Foundation, Inc.,
92 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
93 * http://www.gnu.org/copyleft/gpl.html
101 * MediaWikiServices is the service locator for the application scope of MediaWiki.
102 * Its implemented as a simple configurable DI container.
103 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
104 * the network of service objects that defines MediaWiki's application logic.
105 * It acts as an entry point to MediaWiki's dependency injection mechanism.
107 * Services are defined in the "wiring" array passed to the constructor,
108 * or by calling defineService().
110 * @see docs/injection.txt for an overview of using dependency injection in the
111 * MediaWiki code base.
113 class MediaWikiServices
extends ServiceContainer
{
116 * @var MediaWikiServices|null
118 private static $instance = null;
121 * Returns the global default instance of the top level service locator.
125 * The default instance is initialized using the service instantiator functions
126 * defined in ServiceWiring.php.
128 * @note This should only be called by static functions! The instance returned here
129 * should not be passed around! Objects that need access to a service should have
130 * that service injected into the constructor, never a service locator!
132 * @return MediaWikiServices
134 public static function getInstance() {
135 if ( self
::$instance === null ) {
136 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
137 // but some information from the global scope has to be injected here,
138 // even if it's just a file name or database credentials to load
139 // configuration from.
140 $bootstrapConfig = new GlobalVarConfig();
141 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
144 return self
::$instance;
148 * Replaces the global MediaWikiServices instance.
152 * @note This is for use in PHPUnit tests only!
154 * @throws MWException if called outside of PHPUnit tests.
156 * @param MediaWikiServices $services The new MediaWikiServices object.
158 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
160 public static function forceGlobalInstance( MediaWikiServices
$services ) {
161 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
162 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
165 $old = self
::getInstance();
166 self
::$instance = $services;
172 * Creates a new instance of MediaWikiServices and sets it as the global default
173 * instance. getInstance() will return a different MediaWikiServices object
174 * after every call to resetGlobalInstance().
178 * @warning This should not be used during normal operation. It is intended for use
179 * when the configuration has changed significantly since bootstrap time, e.g.
180 * during the installation process or during testing.
182 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
183 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
184 * any of the services managed by MediaWikiServices exist. If any service objects
185 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
186 * with the operation of the services managed by the new MediaWikiServices.
187 * Operating with a mix of services created by the old and the new
188 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
189 * Any class implementing LAZY LOADING is especially prone to this problem,
190 * since instances would typically retain a reference to a storage layer service.
192 * @see forceGlobalInstance()
193 * @see resetGlobalInstance()
194 * @see resetBetweenTest()
196 * @param Config|null $bootstrapConfig The Config object to be registered as the
197 * 'BootstrapConfig' service. This has to contain at least the information
198 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
199 * config of the old instance of MediaWikiServices will be re-used. If there
200 * was no previous instance, a new GlobalVarConfig object will be used to
201 * bootstrap the services.
203 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
204 * See SalvageableService for details.
206 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
207 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
210 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
211 if ( self
::$instance === null ) {
212 // no global instance yet, nothing to reset
216 self
::failIfResetNotAllowed( __METHOD__
);
218 if ( $bootstrapConfig === null ) {
219 $bootstrapConfig = self
::$instance->getBootstrapConfig();
222 $oldInstance = self
::$instance;
224 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
225 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
227 if ( $quick === 'quick' ) {
228 self
::$instance->salvage( $oldInstance );
230 $oldInstance->destroy();
234 /** @noinspection PhpDocSignatureInspection */
237 * Salvages the state of any salvageable service instances in $other.
239 * @note $other will have been destroyed when salvage() returns.
241 * @param MediaWikiServices $other
243 private function salvage( self
$other ) {
244 foreach ( $this->getServiceNames() as $name ) {
245 // The service could be new in the new instance and not registered in the
246 // other instance (e.g. an extension that was loaded after the instantiation of
247 // the other instance. Skip this service in this case. See T143974
249 $oldService = $other->peekService( $name );
250 } catch ( NoSuchServiceException
$e ) {
254 if ( $oldService instanceof SalvageableService
) {
255 /** @var SalvageableService $newService */
256 $newService = $this->getService( $name );
257 $newService->salvage( $oldService );
265 * Creates a new MediaWikiServices instance and initializes it according to the
266 * given $bootstrapConfig. In particular, all wiring files defined in the
267 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
269 * @param Config|null $bootstrapConfig The Config object to be registered as the
270 * 'BootstrapConfig' service.
272 * @param string $loadWiring set this to 'load' to load the wiring files specified
273 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
275 * @return MediaWikiServices
276 * @throws MWException
277 * @throws \FatalError
279 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
280 $instance = new self( $bootstrapConfig );
282 // Load the default wiring from the specified files.
283 if ( $loadWiring === 'load' ) {
284 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
285 $instance->loadWiringFiles( $wiringFiles );
288 // Provide a traditional hook point to allow extensions to configure services.
289 Hooks
::run( 'MediaWikiServices', [ $instance ] );
295 * Disables all storage layer services. After calling this, any attempt to access the
296 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
301 * @warning This is intended for extreme situations only and should never be used
302 * while serving normal web requests. Legitimate use cases for this method include
303 * the installation process. Test fixtures may also use this, if the fixture relies
306 * @see resetGlobalInstance()
307 * @see resetChildProcessServices()
309 public static function disableStorageBackend() {
310 // TODO: also disable some Caches, JobQueues, etc
311 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
312 $services = self
::getInstance();
314 foreach ( $destroy as $name ) {
315 $services->disableService( $name );
318 ObjectCache
::clear();
322 * Resets any services that may have become stale after a child process
323 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
324 * to call this method from the parent process.
328 * @note This is intended for use in the context of process forking only!
330 * @see resetGlobalInstance()
331 * @see disableStorageBackend()
333 public static function resetChildProcessServices() {
334 // NOTE: for now, just reset everything. Since we don't know the interdependencies
335 // between services, we can't do this more selectively at this time.
336 self
::resetGlobalInstance();
338 // Child, reseed because there is no bug in PHP:
339 // https://bugs.php.net/bug.php?id=42465
340 mt_srand( getmypid() );
344 * Resets the given service for testing purposes.
348 * @warning This is generally unsafe! Other services may still retain references
349 * to the stale service instance, leading to failures and inconsistencies. Subclasses
350 * may use this method to reset specific services under specific instances, but
351 * it should not be exposed to application logic.
353 * @note With proper dependency injection used throughout the codebase, this method
354 * should not be needed. It is provided to allow tests that pollute global service
355 * instances to clean up.
357 * @param string $name
358 * @param bool $destroy Whether the service instance should be destroyed if it exists.
359 * When set to false, any existing service instance will effectively be detached
360 * from the container.
362 * @throws MWException if called outside of PHPUnit tests.
364 public function resetServiceForTesting( $name, $destroy = true ) {
365 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
366 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
369 $this->resetService( $name, $destroy );
373 * Convenience method that throws an exception unless it is called during a phase in which
374 * resetting of global services is allowed. In general, services should not be reset
375 * individually, since that may introduce inconsistencies.
379 * This method will throw an exception if:
381 * - self::$resetInProgress is false (to allow all services to be reset together
382 * via resetGlobalInstance)
383 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
384 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
386 * This method is intended to be used to safeguard against accidentally resetting
387 * global service instances that are not yet managed by MediaWikiServices. It is
388 * defined here in the MediaWikiServices services class to have a central place
389 * for managing service bootstrapping and resetting.
391 * @param string $method the name of the caller method, as given by __METHOD__.
393 * @throws MWException if called outside bootstrap mode.
395 * @see resetGlobalInstance()
396 * @see forceGlobalInstance()
397 * @see disableStorageBackend()
399 public static function failIfResetNotAllowed( $method ) {
400 if ( !defined( 'MW_PHPUNIT_TEST' )
401 && !defined( 'MW_PARSER_TEST' )
402 && !defined( 'MEDIAWIKI_INSTALL' )
403 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
404 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
406 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
411 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
412 * This has to contain at least the information needed to set up the 'ConfigFactory'
415 public function __construct( Config
$config ) {
416 parent
::__construct();
418 // Register the given Config object as the bootstrap config service.
419 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
424 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
428 * @return ActorMigration
430 public function getActorMigration() {
431 return $this->getService( 'ActorMigration' );
436 * @return BadFileLookup
438 public function getBadFileLookup() : BadFileLookup
{
439 return $this->getService( 'BadFileLookup' );
446 public function getBlobStore() {
447 return $this->getService( '_SqlBlobStore' );
452 * @return BlobStoreFactory
454 public function getBlobStoreFactory() {
455 return $this->getService( 'BlobStoreFactory' );
460 * @return BlockManager
462 public function getBlockManager() : BlockManager
{
463 return $this->getService( 'BlockManager' );
468 * @return BlockRestrictionStore
470 public function getBlockRestrictionStore() : BlockRestrictionStore
{
471 return $this->getService( 'BlockRestrictionStore' );
475 * Returns the Config object containing the bootstrap configuration.
476 * Bootstrap configuration would typically include database credentials
477 * and other information that may be needed before the ConfigFactory
478 * service can be instantiated.
480 * @note This should only be used during bootstrapping, in particular
481 * when creating the MainConfig service. Application logic should
482 * use getMainConfig() to get a Config instances.
487 public function getBootstrapConfig() {
488 return $this->getService( 'BootstrapConfig' );
493 * @return NameTableStore
495 public function getChangeTagDefStore() {
496 return $this->getService( 'NameTableStoreFactory' )->getChangeTagDef();
501 * @return CommentStore
503 public function getCommentStore() {
504 return $this->getService( 'CommentStore' );
509 * @return ConfigFactory
511 public function getConfigFactory() {
512 return $this->getService( 'ConfigFactory' );
517 * @return ConfigRepository
519 public function getConfigRepository() {
520 return $this->getService( 'ConfigRepository' );
525 * @return \ConfiguredReadOnlyMode
527 public function getConfiguredReadOnlyMode() {
528 return $this->getService( 'ConfiguredReadOnlyMode' );
535 public function getContentLanguage() {
536 return $this->getService( 'ContentLanguage' );
541 * @return NameTableStore
543 public function getContentModelStore() {
544 return $this->getService( 'NameTableStoreFactory' )->getContentModels();
551 public function getCryptHKDF() {
552 return $this->getService( 'CryptHKDF' );
557 * @return DateFormatterFactory
559 public function getDateFormatterFactory() {
560 return $this->getService( 'DateFormatterFactory' );
565 * @return ILoadBalancer The main DB load balancer for the local wiki.
567 public function getDBLoadBalancer() {
568 return $this->getService( 'DBLoadBalancer' );
575 public function getDBLoadBalancerFactory() {
576 return $this->getService( 'DBLoadBalancerFactory' );
581 * @return EventRelayerGroup
583 public function getEventRelayerGroup() {
584 return $this->getService( 'EventRelayerGroup' );
589 * @return \ExternalStoreAccess
591 public function getExternalStoreAccess() {
592 return $this->getService( 'ExternalStoreAccess' );
597 * @return \ExternalStoreFactory
599 public function getExternalStoreFactory() {
600 return $this->getService( 'ExternalStoreFactory' );
605 * @return GenderCache
607 public function getGenderCache() {
608 return $this->getService( 'GenderCache' );
613 * @return HttpRequestFactory
615 public function getHttpRequestFactory() {
616 return $this->getService( 'HttpRequestFactory' );
621 * @return InterwikiLookup
623 public function getInterwikiLookup() {
624 return $this->getService( 'InterwikiLookup' );
631 public function getLinkCache() {
632 return $this->getService( 'LinkCache' );
636 * LinkRenderer instance that can be used
637 * if no custom options are needed
640 * @return LinkRenderer
642 public function getLinkRenderer() {
643 return $this->getService( 'LinkRenderer' );
648 * @return LinkRendererFactory
650 public function getLinkRendererFactory() {
651 return $this->getService( 'LinkRendererFactory' );
658 public function getLocalServerObjectCache() {
659 return $this->getService( 'LocalServerObjectCache' );
664 * @return LockManagerGroupFactory
666 public function getLockManagerGroupFactory() : LockManagerGroupFactory
{
667 return $this->getService( 'LockManagerGroupFactory' );
672 * @return MagicWordFactory
674 public function getMagicWordFactory() {
675 return $this->getService( 'MagicWordFactory' );
679 * Returns the Config object that provides configuration for MediaWiki core.
680 * This may or may not be the same object that is returned by getBootstrapConfig().
685 public function getMainConfig() {
686 return $this->getService( 'MainConfig' );
693 public function getMainObjectStash() {
694 return $this->getService( 'MainObjectStash' );
699 * @return \WANObjectCache
701 public function getMainWANObjectCache() {
702 return $this->getService( 'MainWANObjectCache' );
707 * @return MediaHandlerFactory
709 public function getMediaHandlerFactory() {
710 return $this->getService( 'MediaHandlerFactory' );
715 * @return MessageCache
717 public function getMessageCache() : MessageCache
{
718 return $this->getService( 'MessageCache' );
723 * @return MimeAnalyzer
725 public function getMimeAnalyzer() {
726 return $this->getService( 'MimeAnalyzer' );
731 * @return MovePageFactory
733 public function getMovePageFactory() : MovePageFactory
{
734 return $this->getService( 'MovePageFactory' );
739 * @return NamespaceInfo
741 public function getNamespaceInfo() : NamespaceInfo
{
742 return $this->getService( 'NamespaceInfo' );
747 * @return NameTableStoreFactory
749 public function getNameTableStoreFactory() {
750 return $this->getService( 'NameTableStoreFactory' );
754 * ObjectFactory is intended for instantiating "handlers" from declarative definitions,
755 * such as Action API modules, special pages, or REST API handlers.
758 * @return ObjectFactory
760 public function getObjectFactory() {
761 return $this->getService( 'ObjectFactory' );
766 * @return OldRevisionImporter
768 public function getOldRevisionImporter() {
769 return $this->getService( 'OldRevisionImporter' );
773 * @return PageEditStash
776 public function getPageEditStash() {
777 return $this->getService( 'PageEditStash' );
784 public function getParser() {
785 return $this->getService( 'Parser' );
790 * @return ParserCache
792 public function getParserCache() {
793 return $this->getService( 'ParserCache' );
798 * @return ParserFactory
800 public function getParserFactory() {
801 return $this->getService( 'ParserFactory' );
806 * @return PasswordFactory
808 public function getPasswordFactory() {
809 return $this->getService( 'PasswordFactory' );
814 * @return StatsdDataFactoryInterface
816 public function getPerDbNameStatsdDataFactory() {
817 return $this->getService( 'PerDbNameStatsdDataFactory' );
822 * @return PermissionManager
824 public function getPermissionManager() {
825 return $this->getService( 'PermissionManager' );
830 * @return PreferencesFactory
832 public function getPreferencesFactory() {
833 return $this->getService( 'PreferencesFactory' );
838 * @return ProxyLookup
840 public function getProxyLookup() {
841 return $this->getService( 'ProxyLookup' );
846 * @return \ReadOnlyMode
848 public function getReadOnlyMode() {
849 return $this->getService( 'ReadOnlyMode' );
856 public function getRepoGroup() : RepoGroup
{
857 return $this->getService( 'RepoGroup' );
862 * @return ResourceLoader
864 public function getResourceLoader() {
865 return $this->getService( 'ResourceLoader' );
870 * @return RevisionFactory
872 public function getRevisionFactory() {
873 return $this->getService( 'RevisionFactory' );
878 * @return RevisionLookup
880 public function getRevisionLookup() {
881 return $this->getService( 'RevisionLookup' );
886 * @return RevisionRenderer
888 public function getRevisionRenderer() {
889 return $this->getService( 'RevisionRenderer' );
894 * @return RevisionStore
896 public function getRevisionStore() {
897 return $this->getService( 'RevisionStore' );
902 * @return RevisionStoreFactory
904 public function getRevisionStoreFactory() {
905 return $this->getService( 'RevisionStoreFactory' );
910 * @return SearchEngine
912 public function newSearchEngine() {
913 // New engine object every time, since they keep state
914 return $this->getService( 'SearchEngineFactory' )->create();
919 * @return SearchEngineConfig
921 public function getSearchEngineConfig() {
922 return $this->getService( 'SearchEngineConfig' );
927 * @return SearchEngineFactory
929 public function getSearchEngineFactory() {
930 return $this->getService( 'SearchEngineFactory' );
935 * @return CommandFactory
937 public function getShellCommandFactory() {
938 return $this->getService( 'ShellCommandFactory' );
945 public function getSiteLookup() {
946 return $this->getService( 'SiteLookup' );
953 public function getSiteStore() {
954 return $this->getService( 'SiteStore' );
959 * @return SkinFactory
961 public function getSkinFactory() {
962 return $this->getService( 'SkinFactory' );
967 * @return SlotRoleRegistry
969 public function getSlotRoleRegistry() {
970 return $this->getService( 'SlotRoleRegistry' );
975 * @return NameTableStore
977 public function getSlotRoleStore() {
978 return $this->getService( 'NameTableStoreFactory' )->getSlotRoles();
983 * @return SpecialPageFactory
985 public function getSpecialPageFactory() : SpecialPageFactory
{
986 return $this->getService( 'SpecialPageFactory' );
991 * @return IBufferingStatsdDataFactory
993 public function getStatsdDataFactory() {
994 return $this->getService( 'StatsdDataFactory' );
999 * @return TempFSFileFactory
1001 public function getTempFSFileFactory() : TempFSFileFactory
{
1002 return $this->getService( 'TempFSFileFactory' );
1007 * @return TitleFormatter
1009 public function getTitleFormatter() {
1010 return $this->getService( 'TitleFormatter' );
1015 * @return TitleParser
1017 public function getTitleParser() {
1018 return $this->getService( 'TitleParser' );
1023 * @return UploadRevisionImporter
1025 public function getUploadRevisionImporter() {
1026 return $this->getService( 'UploadRevisionImporter' );
1031 * @return VirtualRESTServiceClient
1033 public function getVirtualRESTServiceClient() {
1034 return $this->getService( 'VirtualRESTServiceClient' );
1039 * @return WatchedItemQueryService
1041 public function getWatchedItemQueryService() {
1042 return $this->getService( 'WatchedItemQueryService' );
1047 * @return WatchedItemStoreInterface
1049 public function getWatchedItemStore() {
1050 return $this->getService( 'WatchedItemStore' );
1055 * @return \OldRevisionImporter
1057 public function getWikiRevisionOldRevisionImporter() {
1058 return $this->getService( 'OldRevisionImporter' );
1063 * @return \OldRevisionImporter
1065 public function getWikiRevisionOldRevisionImporterNoUpdates() {
1066 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
1071 * @return \UploadRevisionImporter
1073 public function getWikiRevisionUploadImporter() {
1074 return $this->getService( 'UploadRevisionImporter' );