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
;
23 use Wikimedia\Message\IMessageFormatterFactory
;
24 use MediaWiki\Page\MovePageFactory
;
25 use MediaWiki\Permissions\PermissionManager
;
26 use MediaWiki\Preferences\PreferencesFactory
;
27 use MediaWiki\Revision\RevisionRenderer
;
28 use MediaWiki\Revision\SlotRoleRegistry
;
29 use MediaWiki\Shell\CommandFactory
;
30 use MediaWiki\Special\SpecialPageFactory
;
31 use MediaWiki\Storage\BlobStore
;
32 use MediaWiki\Storage\BlobStoreFactory
;
33 use MediaWiki\Storage\NameTableStore
;
34 use MediaWiki\Storage\NameTableStoreFactory
;
35 use MediaWiki\Revision\RevisionFactory
;
36 use MediaWiki\Revision\RevisionLookup
;
37 use MediaWiki\Revision\RevisionStore
;
38 use OldRevisionImporter
;
39 use MediaWiki\Revision\RevisionStoreFactory
;
40 use UploadRevisionImporter
;
41 use Wikimedia\Rdbms\ILoadBalancer
;
43 use MediaHandlerFactory
;
44 use MediaWiki\Config\ConfigRepository
;
45 use MediaWiki\Linker\LinkRenderer
;
46 use MediaWiki\Linker\LinkRendererFactory
;
60 use SearchEngineConfig
;
61 use SearchEngineFactory
;
64 use WatchedItemStoreInterface
;
65 use WatchedItemQueryService
;
69 use VirtualRESTServiceClient
;
70 use Wikimedia\ObjectFactory
;
71 use Wikimedia\Rdbms\LBFactory
;
72 use Wikimedia\Services\SalvageableService
;
73 use Wikimedia\Services\ServiceContainer
;
74 use Wikimedia\Services\NoSuchServiceException
;
75 use MediaWiki\Interwiki\InterwikiLookup
;
77 use MediaWiki\Storage\PageEditStash
;
80 * Service locator for MediaWiki core services.
82 * This program is free software; you can redistribute it and/or modify
83 * it under the terms of the GNU General Public License as published by
84 * the Free Software Foundation; either version 2 of the License, or
85 * (at your option) any later version.
87 * This program is distributed in the hope that it will be useful,
88 * but WITHOUT ANY WARRANTY; without even the implied warranty of
89 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
90 * GNU General Public License for more details.
92 * You should have received a copy of the GNU General Public License along
93 * with this program; if not, write to the Free Software Foundation, Inc.,
94 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
95 * http://www.gnu.org/copyleft/gpl.html
103 * MediaWikiServices is the service locator for the application scope of MediaWiki.
104 * Its implemented as a simple configurable DI container.
105 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
106 * the network of service objects that defines MediaWiki's application logic.
107 * It acts as an entry point to MediaWiki's dependency injection mechanism.
109 * Services are defined in the "wiring" array passed to the constructor,
110 * or by calling defineService().
112 * @see docs/injection.txt for an overview of using dependency injection in the
113 * MediaWiki code base.
115 class MediaWikiServices
extends ServiceContainer
{
118 * @var MediaWikiServices|null
120 private static $instance = null;
123 * Returns the global default instance of the top level service locator.
127 * The default instance is initialized using the service instantiator functions
128 * defined in ServiceWiring.php.
130 * @note This should only be called by static functions! The instance returned here
131 * should not be passed around! Objects that need access to a service should have
132 * that service injected into the constructor, never a service locator!
134 * @return MediaWikiServices
136 public static function getInstance() {
137 if ( self
::$instance === null ) {
138 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
139 // but some information from the global scope has to be injected here,
140 // even if it's just a file name or database credentials to load
141 // configuration from.
142 $bootstrapConfig = new GlobalVarConfig();
143 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
146 return self
::$instance;
150 * Replaces the global MediaWikiServices instance.
154 * @note This is for use in PHPUnit tests only!
156 * @throws MWException if called outside of PHPUnit tests.
158 * @param MediaWikiServices $services The new MediaWikiServices object.
160 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
162 public static function forceGlobalInstance( MediaWikiServices
$services ) {
163 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
164 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
167 $old = self
::getInstance();
168 self
::$instance = $services;
174 * Creates a new instance of MediaWikiServices and sets it as the global default
175 * instance. getInstance() will return a different MediaWikiServices object
176 * after every call to resetGlobalInstance().
180 * @warning This should not be used during normal operation. It is intended for use
181 * when the configuration has changed significantly since bootstrap time, e.g.
182 * during the installation process or during testing.
184 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
185 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
186 * any of the services managed by MediaWikiServices exist. If any service objects
187 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
188 * with the operation of the services managed by the new MediaWikiServices.
189 * Operating with a mix of services created by the old and the new
190 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
191 * Any class implementing LAZY LOADING is especially prone to this problem,
192 * since instances would typically retain a reference to a storage layer service.
194 * @see forceGlobalInstance()
195 * @see resetGlobalInstance()
196 * @see resetBetweenTest()
198 * @param Config|null $bootstrapConfig The Config object to be registered as the
199 * 'BootstrapConfig' service. This has to contain at least the information
200 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
201 * config of the old instance of MediaWikiServices will be re-used. If there
202 * was no previous instance, a new GlobalVarConfig object will be used to
203 * bootstrap the services.
205 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
206 * See SalvageableService for details.
208 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
209 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
212 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
213 if ( self
::$instance === null ) {
214 // no global instance yet, nothing to reset
218 self
::failIfResetNotAllowed( __METHOD__
);
220 if ( $bootstrapConfig === null ) {
221 $bootstrapConfig = self
::$instance->getBootstrapConfig();
224 $oldInstance = self
::$instance;
226 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
227 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
229 if ( $quick === 'quick' ) {
230 self
::$instance->salvage( $oldInstance );
232 $oldInstance->destroy();
236 /** @noinspection PhpDocSignatureInspection */
239 * Salvages the state of any salvageable service instances in $other.
241 * @note $other will have been destroyed when salvage() returns.
243 * @param MediaWikiServices $other
245 private function salvage( self
$other ) {
246 foreach ( $this->getServiceNames() as $name ) {
247 // The service could be new in the new instance and not registered in the
248 // other instance (e.g. an extension that was loaded after the instantiation of
249 // the other instance. Skip this service in this case. See T143974
251 $oldService = $other->peekService( $name );
252 } catch ( NoSuchServiceException
$e ) {
256 if ( $oldService instanceof SalvageableService
) {
257 /** @var SalvageableService $newService */
258 $newService = $this->getService( $name );
259 $newService->salvage( $oldService );
267 * Creates a new MediaWikiServices instance and initializes it according to the
268 * given $bootstrapConfig. In particular, all wiring files defined in the
269 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
271 * @param Config|null $bootstrapConfig The Config object to be registered as the
272 * 'BootstrapConfig' service.
274 * @param string $loadWiring set this to 'load' to load the wiring files specified
275 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
277 * @return MediaWikiServices
278 * @throws MWException
279 * @throws \FatalError
281 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
282 $instance = new self( $bootstrapConfig );
284 // Load the default wiring from the specified files.
285 if ( $loadWiring === 'load' ) {
286 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
287 $instance->loadWiringFiles( $wiringFiles );
290 // Provide a traditional hook point to allow extensions to configure services.
291 Hooks
::run( 'MediaWikiServices', [ $instance ] );
297 * Disables all storage layer services. After calling this, any attempt to access the
298 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
303 * @warning This is intended for extreme situations only and should never be used
304 * while serving normal web requests. Legitimate use cases for this method include
305 * the installation process. Test fixtures may also use this, if the fixture relies
308 * @see resetGlobalInstance()
309 * @see resetChildProcessServices()
311 public static function disableStorageBackend() {
312 // TODO: also disable some Caches, JobQueues, etc
313 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
314 $services = self
::getInstance();
316 foreach ( $destroy as $name ) {
317 $services->disableService( $name );
320 ObjectCache
::clear();
324 * Resets any services that may have become stale after a child process
325 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
326 * to call this method from the parent process.
330 * @note This is intended for use in the context of process forking only!
332 * @see resetGlobalInstance()
333 * @see disableStorageBackend()
335 public static function resetChildProcessServices() {
336 // NOTE: for now, just reset everything. Since we don't know the interdependencies
337 // between services, we can't do this more selectively at this time.
338 self
::resetGlobalInstance();
340 // Child, reseed because there is no bug in PHP:
341 // https://bugs.php.net/bug.php?id=42465
342 mt_srand( getmypid() );
346 * Resets the given service for testing purposes.
350 * @warning This is generally unsafe! Other services may still retain references
351 * to the stale service instance, leading to failures and inconsistencies. Subclasses
352 * may use this method to reset specific services under specific instances, but
353 * it should not be exposed to application logic.
355 * @note With proper dependency injection used throughout the codebase, this method
356 * should not be needed. It is provided to allow tests that pollute global service
357 * instances to clean up.
359 * @param string $name
360 * @param bool $destroy Whether the service instance should be destroyed if it exists.
361 * When set to false, any existing service instance will effectively be detached
362 * from the container.
364 * @throws MWException if called outside of PHPUnit tests.
366 public function resetServiceForTesting( $name, $destroy = true ) {
367 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
368 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
371 $this->resetService( $name, $destroy );
375 * Convenience method that throws an exception unless it is called during a phase in which
376 * resetting of global services is allowed. In general, services should not be reset
377 * individually, since that may introduce inconsistencies.
381 * This method will throw an exception if:
383 * - self::$resetInProgress is false (to allow all services to be reset together
384 * via resetGlobalInstance)
385 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
386 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
388 * This method is intended to be used to safeguard against accidentally resetting
389 * global service instances that are not yet managed by MediaWikiServices. It is
390 * defined here in the MediaWikiServices services class to have a central place
391 * for managing service bootstrapping and resetting.
393 * @param string $method the name of the caller method, as given by __METHOD__.
395 * @throws MWException if called outside bootstrap mode.
397 * @see resetGlobalInstance()
398 * @see forceGlobalInstance()
399 * @see disableStorageBackend()
401 public static function failIfResetNotAllowed( $method ) {
402 if ( !defined( 'MW_PHPUNIT_TEST' )
403 && !defined( 'MW_PARSER_TEST' )
404 && !defined( 'MEDIAWIKI_INSTALL' )
405 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
406 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
408 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
413 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
414 * This has to contain at least the information needed to set up the 'ConfigFactory'
417 public function __construct( Config
$config ) {
418 parent
::__construct();
420 // Register the given Config object as the bootstrap config service.
421 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
426 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
430 * @return ActorMigration
432 public function getActorMigration() {
433 return $this->getService( 'ActorMigration' );
438 * @return BadFileLookup
440 public function getBadFileLookup() : BadFileLookup
{
441 return $this->getService( 'BadFileLookup' );
448 public function getBlobStore() {
449 return $this->getService( '_SqlBlobStore' );
454 * @return BlobStoreFactory
456 public function getBlobStoreFactory() {
457 return $this->getService( 'BlobStoreFactory' );
462 * @return BlockManager
464 public function getBlockManager() : BlockManager
{
465 return $this->getService( 'BlockManager' );
470 * @return BlockRestrictionStore
472 public function getBlockRestrictionStore() : BlockRestrictionStore
{
473 return $this->getService( 'BlockRestrictionStore' );
477 * Returns the Config object containing the bootstrap configuration.
478 * Bootstrap configuration would typically include database credentials
479 * and other information that may be needed before the ConfigFactory
480 * service can be instantiated.
482 * @note This should only be used during bootstrapping, in particular
483 * when creating the MainConfig service. Application logic should
484 * use getMainConfig() to get a Config instances.
489 public function getBootstrapConfig() {
490 return $this->getService( 'BootstrapConfig' );
495 * @return NameTableStore
497 public function getChangeTagDefStore() {
498 return $this->getService( 'NameTableStoreFactory' )->getChangeTagDef();
503 * @return CommentStore
505 public function getCommentStore() {
506 return $this->getService( 'CommentStore' );
511 * @return ConfigFactory
513 public function getConfigFactory() {
514 return $this->getService( 'ConfigFactory' );
519 * @return ConfigRepository
521 public function getConfigRepository() {
522 return $this->getService( 'ConfigRepository' );
527 * @return \ConfiguredReadOnlyMode
529 public function getConfiguredReadOnlyMode() {
530 return $this->getService( 'ConfiguredReadOnlyMode' );
537 public function getContentLanguage() {
538 return $this->getService( 'ContentLanguage' );
543 * @return NameTableStore
545 public function getContentModelStore() {
546 return $this->getService( 'NameTableStoreFactory' )->getContentModels();
553 public function getCryptHKDF() {
554 return $this->getService( 'CryptHKDF' );
559 * @return DateFormatterFactory
561 public function getDateFormatterFactory() {
562 return $this->getService( 'DateFormatterFactory' );
567 * @return ILoadBalancer The main DB load balancer for the local wiki.
569 public function getDBLoadBalancer() {
570 return $this->getService( 'DBLoadBalancer' );
577 public function getDBLoadBalancerFactory() {
578 return $this->getService( 'DBLoadBalancerFactory' );
583 * @return EventRelayerGroup
585 public function getEventRelayerGroup() {
586 return $this->getService( 'EventRelayerGroup' );
591 * @return \ExternalStoreAccess
593 public function getExternalStoreAccess() {
594 return $this->getService( 'ExternalStoreAccess' );
599 * @return \ExternalStoreFactory
601 public function getExternalStoreFactory() {
602 return $this->getService( 'ExternalStoreFactory' );
607 * @return GenderCache
609 public function getGenderCache() {
610 return $this->getService( 'GenderCache' );
615 * @return HttpRequestFactory
617 public function getHttpRequestFactory() {
618 return $this->getService( 'HttpRequestFactory' );
623 * @return InterwikiLookup
625 public function getInterwikiLookup() {
626 return $this->getService( 'InterwikiLookup' );
633 public function getLinkCache() {
634 return $this->getService( 'LinkCache' );
638 * LinkRenderer instance that can be used
639 * if no custom options are needed
642 * @return LinkRenderer
644 public function getLinkRenderer() {
645 return $this->getService( 'LinkRenderer' );
650 * @return LinkRendererFactory
652 public function getLinkRendererFactory() {
653 return $this->getService( 'LinkRendererFactory' );
660 public function getLocalServerObjectCache() {
661 return $this->getService( 'LocalServerObjectCache' );
666 * @return LockManagerGroupFactory
668 public function getLockManagerGroupFactory() : LockManagerGroupFactory
{
669 return $this->getService( 'LockManagerGroupFactory' );
674 * @return MagicWordFactory
676 public function getMagicWordFactory() {
677 return $this->getService( 'MagicWordFactory' );
681 * Returns the Config object that provides configuration for MediaWiki core.
682 * This may or may not be the same object that is returned by getBootstrapConfig().
687 public function getMainConfig() {
688 return $this->getService( 'MainConfig' );
695 public function getMainObjectStash() {
696 return $this->getService( 'MainObjectStash' );
701 * @return \WANObjectCache
703 public function getMainWANObjectCache() {
704 return $this->getService( 'MainWANObjectCache' );
709 * @return MediaHandlerFactory
711 public function getMediaHandlerFactory() {
712 return $this->getService( 'MediaHandlerFactory' );
717 * @return MessageCache
719 public function getMessageCache() : MessageCache
{
720 return $this->getService( 'MessageCache' );
725 * @return IMessageFormatterFactory
727 public function getMessageFormatterFactory() {
728 return $this->getService( 'MessageFormatterFactory' );
733 * @return MimeAnalyzer
735 public function getMimeAnalyzer() {
736 return $this->getService( 'MimeAnalyzer' );
741 * @return MovePageFactory
743 public function getMovePageFactory() : MovePageFactory
{
744 return $this->getService( 'MovePageFactory' );
749 * @return NamespaceInfo
751 public function getNamespaceInfo() : NamespaceInfo
{
752 return $this->getService( 'NamespaceInfo' );
757 * @return NameTableStoreFactory
759 public function getNameTableStoreFactory() {
760 return $this->getService( 'NameTableStoreFactory' );
764 * ObjectFactory is intended for instantiating "handlers" from declarative definitions,
765 * such as Action API modules, special pages, or REST API handlers.
768 * @return ObjectFactory
770 public function getObjectFactory() {
771 return $this->getService( 'ObjectFactory' );
776 * @return OldRevisionImporter
778 public function getOldRevisionImporter() {
779 return $this->getService( 'OldRevisionImporter' );
783 * @return PageEditStash
786 public function getPageEditStash() {
787 return $this->getService( 'PageEditStash' );
794 public function getParser() {
795 return $this->getService( 'Parser' );
800 * @return ParserCache
802 public function getParserCache() {
803 return $this->getService( 'ParserCache' );
808 * @return ParserFactory
810 public function getParserFactory() {
811 return $this->getService( 'ParserFactory' );
816 * @return PasswordFactory
818 public function getPasswordFactory() {
819 return $this->getService( 'PasswordFactory' );
824 * @return PasswordReset
826 public function getPasswordReset() : PasswordReset
{
827 return $this->getService( 'PasswordReset' );
832 * @return StatsdDataFactoryInterface
834 public function getPerDbNameStatsdDataFactory() {
835 return $this->getService( 'PerDbNameStatsdDataFactory' );
840 * @return PermissionManager
842 public function getPermissionManager() {
843 return $this->getService( 'PermissionManager' );
848 * @return PreferencesFactory
850 public function getPreferencesFactory() {
851 return $this->getService( 'PreferencesFactory' );
856 * @return ProxyLookup
858 public function getProxyLookup() {
859 return $this->getService( 'ProxyLookup' );
864 * @return \ReadOnlyMode
866 public function getReadOnlyMode() {
867 return $this->getService( 'ReadOnlyMode' );
874 public function getRepoGroup() : RepoGroup
{
875 return $this->getService( 'RepoGroup' );
880 * @return ResourceLoader
882 public function getResourceLoader() {
883 return $this->getService( 'ResourceLoader' );
888 * @return RevisionFactory
890 public function getRevisionFactory() {
891 return $this->getService( 'RevisionFactory' );
896 * @return RevisionLookup
898 public function getRevisionLookup() {
899 return $this->getService( 'RevisionLookup' );
904 * @return RevisionRenderer
906 public function getRevisionRenderer() {
907 return $this->getService( 'RevisionRenderer' );
912 * @return RevisionStore
914 public function getRevisionStore() {
915 return $this->getService( 'RevisionStore' );
920 * @return RevisionStoreFactory
922 public function getRevisionStoreFactory() {
923 return $this->getService( 'RevisionStoreFactory' );
928 * @return SearchEngine
930 public function newSearchEngine() {
931 // New engine object every time, since they keep state
932 return $this->getService( 'SearchEngineFactory' )->create();
937 * @return SearchEngineConfig
939 public function getSearchEngineConfig() {
940 return $this->getService( 'SearchEngineConfig' );
945 * @return SearchEngineFactory
947 public function getSearchEngineFactory() {
948 return $this->getService( 'SearchEngineFactory' );
953 * @return CommandFactory
955 public function getShellCommandFactory() {
956 return $this->getService( 'ShellCommandFactory' );
963 public function getSiteLookup() {
964 return $this->getService( 'SiteLookup' );
971 public function getSiteStore() {
972 return $this->getService( 'SiteStore' );
977 * @return SkinFactory
979 public function getSkinFactory() {
980 return $this->getService( 'SkinFactory' );
985 * @return SlotRoleRegistry
987 public function getSlotRoleRegistry() {
988 return $this->getService( 'SlotRoleRegistry' );
993 * @return NameTableStore
995 public function getSlotRoleStore() {
996 return $this->getService( 'NameTableStoreFactory' )->getSlotRoles();
1001 * @return SpecialPageFactory
1003 public function getSpecialPageFactory() : SpecialPageFactory
{
1004 return $this->getService( 'SpecialPageFactory' );
1009 * @return IBufferingStatsdDataFactory
1011 public function getStatsdDataFactory() {
1012 return $this->getService( 'StatsdDataFactory' );
1017 * @return TempFSFileFactory
1019 public function getTempFSFileFactory() : TempFSFileFactory
{
1020 return $this->getService( 'TempFSFileFactory' );
1025 * @return TitleFormatter
1027 public function getTitleFormatter() {
1028 return $this->getService( 'TitleFormatter' );
1033 * @return TitleParser
1035 public function getTitleParser() {
1036 return $this->getService( 'TitleParser' );
1041 * @return UploadRevisionImporter
1043 public function getUploadRevisionImporter() {
1044 return $this->getService( 'UploadRevisionImporter' );
1049 * @return VirtualRESTServiceClient
1051 public function getVirtualRESTServiceClient() {
1052 return $this->getService( 'VirtualRESTServiceClient' );
1057 * @return WatchedItemQueryService
1059 public function getWatchedItemQueryService() {
1060 return $this->getService( 'WatchedItemQueryService' );
1065 * @return WatchedItemStoreInterface
1067 public function getWatchedItemStore() {
1068 return $this->getService( 'WatchedItemStore' );
1073 * @return \OldRevisionImporter
1075 public function getWikiRevisionOldRevisionImporter() {
1076 return $this->getService( 'OldRevisionImporter' );
1081 * @return \OldRevisionImporter
1083 public function getWikiRevisionOldRevisionImporterNoUpdates() {
1084 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
1089 * @return \UploadRevisionImporter
1091 public function getWikiRevisionUploadImporter() {
1092 return $this->getService( 'UploadRevisionImporter' );