9 use DateFormatterFactory
;
10 use EventRelayerGroup
;
14 use IBufferingStatsdDataFactory
;
15 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface
;
16 use MediaWiki\Http\HttpRequestFactory
;
17 use MediaWiki\Permissions\PermissionManager
;
18 use MediaWiki\Preferences\PreferencesFactory
;
19 use MediaWiki\Shell\CommandFactory
;
20 use MediaWiki\Revision\RevisionRenderer
;
21 use MediaWiki\Revision\SlotRoleRegistry
;
22 use MediaWiki\Special\SpecialPageFactory
;
23 use MediaWiki\Storage\BlobStore
;
24 use MediaWiki\Storage\BlobStoreFactory
;
25 use MediaWiki\Storage\NameTableStore
;
26 use MediaWiki\Storage\NameTableStoreFactory
;
27 use MediaWiki\Revision\RevisionFactory
;
28 use MediaWiki\Revision\RevisionLookup
;
29 use MediaWiki\Revision\RevisionStore
;
30 use OldRevisionImporter
;
31 use MediaWiki\Revision\RevisionStoreFactory
;
32 use UploadRevisionImporter
;
33 use Wikimedia\Rdbms\LBFactory
;
35 use Wikimedia\Rdbms\LoadBalancer
;
36 use MediaHandlerFactory
;
37 use MediaWiki\Config\ConfigRepository
;
38 use MediaWiki\Linker\LinkRenderer
;
39 use MediaWiki\Linker\LinkRendererFactory
;
51 use SearchEngineConfig
;
52 use SearchEngineFactory
;
55 use WatchedItemStoreInterface
;
56 use WatchedItemQueryService
;
60 use VirtualRESTServiceClient
;
61 use Wikimedia\Services\SalvageableService
;
62 use Wikimedia\Services\ServiceContainer
;
63 use Wikimedia\Services\NoSuchServiceException
;
64 use MediaWiki\Interwiki\InterwikiLookup
;
68 * Service locator for MediaWiki core services.
70 * This program is free software; you can redistribute it and/or modify
71 * it under the terms of the GNU General Public License as published by
72 * the Free Software Foundation; either version 2 of the License, or
73 * (at your option) any later version.
75 * This program is distributed in the hope that it will be useful,
76 * but WITHOUT ANY WARRANTY; without even the implied warranty of
77 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
78 * GNU General Public License for more details.
80 * You should have received a copy of the GNU General Public License along
81 * with this program; if not, write to the Free Software Foundation, Inc.,
82 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
83 * http://www.gnu.org/copyleft/gpl.html
91 * MediaWikiServices is the service locator for the application scope of MediaWiki.
92 * Its implemented as a simple configurable DI container.
93 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
94 * the network of service objects that defines MediaWiki's application logic.
95 * It acts as an entry point to MediaWiki's dependency injection mechanism.
97 * Services are defined in the "wiring" array passed to the constructor,
98 * or by calling defineService().
100 * @see docs/injection.txt for an overview of using dependency injection in the
101 * MediaWiki code base.
103 class MediaWikiServices
extends ServiceContainer
{
106 * @var MediaWikiServices|null
108 private static $instance = null;
111 * Returns the global default instance of the top level service locator.
115 * The default instance is initialized using the service instantiator functions
116 * defined in ServiceWiring.php.
118 * @note This should only be called by static functions! The instance returned here
119 * should not be passed around! Objects that need access to a service should have
120 * that service injected into the constructor, never a service locator!
122 * @return MediaWikiServices
124 public static function getInstance() {
125 if ( self
::$instance === null ) {
126 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
127 // but some information from the global scope has to be injected here,
128 // even if it's just a file name or database credentials to load
129 // configuration from.
130 $bootstrapConfig = new GlobalVarConfig();
131 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
134 return self
::$instance;
138 * Replaces the global MediaWikiServices instance.
142 * @note This is for use in PHPUnit tests only!
144 * @throws MWException if called outside of PHPUnit tests.
146 * @param MediaWikiServices $services The new MediaWikiServices object.
148 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
150 public static function forceGlobalInstance( MediaWikiServices
$services ) {
151 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
152 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
155 $old = self
::getInstance();
156 self
::$instance = $services;
162 * Creates a new instance of MediaWikiServices and sets it as the global default
163 * instance. getInstance() will return a different MediaWikiServices object
164 * after every call to resetGlobalInstance().
168 * @warning This should not be used during normal operation. It is intended for use
169 * when the configuration has changed significantly since bootstrap time, e.g.
170 * during the installation process or during testing.
172 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
173 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
174 * any of the services managed by MediaWikiServices exist. If any service objects
175 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
176 * with the operation of the services managed by the new MediaWikiServices.
177 * Operating with a mix of services created by the old and the new
178 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
179 * Any class implementing LAZY LOADING is especially prone to this problem,
180 * since instances would typically retain a reference to a storage layer service.
182 * @see forceGlobalInstance()
183 * @see resetGlobalInstance()
184 * @see resetBetweenTest()
186 * @param Config|null $bootstrapConfig The Config object to be registered as the
187 * 'BootstrapConfig' service. This has to contain at least the information
188 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
189 * config of the old instance of MediaWikiServices will be re-used. If there
190 * was no previous instance, a new GlobalVarConfig object will be used to
191 * bootstrap the services.
193 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
194 * See SalvageableService for details.
196 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
197 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
200 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
201 if ( self
::$instance === null ) {
202 // no global instance yet, nothing to reset
206 self
::failIfResetNotAllowed( __METHOD__
);
208 if ( $bootstrapConfig === null ) {
209 $bootstrapConfig = self
::$instance->getBootstrapConfig();
212 $oldInstance = self
::$instance;
214 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
215 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
217 if ( $quick === 'quick' ) {
218 self
::$instance->salvage( $oldInstance );
220 $oldInstance->destroy();
225 * Salvages the state of any salvageable service instances in $other.
227 * @note $other will have been destroyed when salvage() returns.
229 * @param MediaWikiServices $other
231 private function salvage( self
$other ) {
232 foreach ( $this->getServiceNames() as $name ) {
233 // The service could be new in the new instance and not registered in the
234 // other instance (e.g. an extension that was loaded after the instantiation of
235 // the other instance. Skip this service in this case. See T143974
237 $oldService = $other->peekService( $name );
238 } catch ( NoSuchServiceException
$e ) {
242 if ( $oldService instanceof SalvageableService
) {
243 /** @var SalvageableService $newService */
244 $newService = $this->getService( $name );
245 $newService->salvage( $oldService );
253 * Creates a new MediaWikiServices instance and initializes it according to the
254 * given $bootstrapConfig. In particular, all wiring files defined in the
255 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
257 * @param Config|null $bootstrapConfig The Config object to be registered as the
258 * 'BootstrapConfig' service.
260 * @param string $loadWiring set this to 'load' to load the wiring files specified
261 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
263 * @return MediaWikiServices
264 * @throws MWException
265 * @throws \FatalError
267 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
268 $instance = new self( $bootstrapConfig );
270 // Load the default wiring from the specified files.
271 if ( $loadWiring === 'load' ) {
272 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
273 $instance->loadWiringFiles( $wiringFiles );
276 // Provide a traditional hook point to allow extensions to configure services.
277 Hooks
::run( 'MediaWikiServices', [ $instance ] );
283 * Disables all storage layer services. After calling this, any attempt to access the
284 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
289 * @warning This is intended for extreme situations only and should never be used
290 * while serving normal web requests. Legitimate use cases for this method include
291 * the installation process. Test fixtures may also use this, if the fixture relies
294 * @see resetGlobalInstance()
295 * @see resetChildProcessServices()
297 public static function disableStorageBackend() {
298 // TODO: also disable some Caches, JobQueues, etc
299 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
300 $services = self
::getInstance();
302 foreach ( $destroy as $name ) {
303 $services->disableService( $name );
306 ObjectCache
::clear();
310 * Resets any services that may have become stale after a child process
311 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
312 * to call this method from the parent process.
316 * @note This is intended for use in the context of process forking only!
318 * @see resetGlobalInstance()
319 * @see disableStorageBackend()
321 public static function resetChildProcessServices() {
322 // NOTE: for now, just reset everything. Since we don't know the interdependencies
323 // between services, we can't do this more selectively at this time.
324 self
::resetGlobalInstance();
326 // Child, reseed because there is no bug in PHP:
327 // https://bugs.php.net/bug.php?id=42465
328 mt_srand( getmypid() );
332 * Resets the given service for testing purposes.
336 * @warning This is generally unsafe! Other services may still retain references
337 * to the stale service instance, leading to failures and inconsistencies. Subclasses
338 * may use this method to reset specific services under specific instances, but
339 * it should not be exposed to application logic.
341 * @note With proper dependency injection used throughout the codebase, this method
342 * should not be needed. It is provided to allow tests that pollute global service
343 * instances to clean up.
345 * @param string $name
346 * @param bool $destroy Whether the service instance should be destroyed if it exists.
347 * When set to false, any existing service instance will effectively be detached
348 * from the container.
350 * @throws MWException if called outside of PHPUnit tests.
352 public function resetServiceForTesting( $name, $destroy = true ) {
353 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
354 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
357 $this->resetService( $name, $destroy );
361 * Convenience method that throws an exception unless it is called during a phase in which
362 * resetting of global services is allowed. In general, services should not be reset
363 * individually, since that may introduce inconsistencies.
367 * This method will throw an exception if:
369 * - self::$resetInProgress is false (to allow all services to be reset together
370 * via resetGlobalInstance)
371 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
372 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
374 * This method is intended to be used to safeguard against accidentally resetting
375 * global service instances that are not yet managed by MediaWikiServices. It is
376 * defined here in the MediaWikiServices services class to have a central place
377 * for managing service bootstrapping and resetting.
379 * @param string $method the name of the caller method, as given by __METHOD__.
381 * @throws MWException if called outside bootstrap mode.
383 * @see resetGlobalInstance()
384 * @see forceGlobalInstance()
385 * @see disableStorageBackend()
387 public static function failIfResetNotAllowed( $method ) {
388 if ( !defined( 'MW_PHPUNIT_TEST' )
389 && !defined( 'MW_PARSER_TEST' )
390 && !defined( 'MEDIAWIKI_INSTALL' )
391 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
392 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
394 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
399 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
400 * This has to contain at least the information needed to set up the 'ConfigFactory'
403 public function __construct( Config
$config ) {
404 parent
::__construct();
406 // Register the given Config object as the bootstrap config service.
407 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
412 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
416 * @return ActorMigration
418 public function getActorMigration() {
419 return $this->getService( 'ActorMigration' );
426 public function getBlobStore() {
427 return $this->getService( '_SqlBlobStore' );
432 * @return BlobStoreFactory
434 public function getBlobStoreFactory() {
435 return $this->getService( 'BlobStoreFactory' );
439 * Returns the Config object containing the bootstrap configuration.
440 * Bootstrap configuration would typically include database credentials
441 * and other information that may be needed before the ConfigFactory
442 * service can be instantiated.
444 * @note This should only be used during bootstrapping, in particular
445 * when creating the MainConfig service. Application logic should
446 * use getMainConfig() to get a Config instances.
451 public function getBootstrapConfig() {
452 return $this->getService( 'BootstrapConfig' );
457 * @return NameTableStore
459 public function getChangeTagDefStore() {
460 return $this->getService( 'NameTableStoreFactory' )->getChangeTagDef();
465 * @return CommentStore
467 public function getCommentStore() {
468 return $this->getService( 'CommentStore' );
473 * @return ConfigFactory
475 public function getConfigFactory() {
476 return $this->getService( 'ConfigFactory' );
481 * @return ConfigRepository
483 public function getConfigRepository() {
484 return $this->getService( 'ConfigRepository' );
489 * @return \ConfiguredReadOnlyMode
491 public function getConfiguredReadOnlyMode() {
492 return $this->getService( 'ConfiguredReadOnlyMode' );
499 public function getContentLanguage() {
500 return $this->getService( 'ContentLanguage' );
505 * @return NameTableStore
507 public function getContentModelStore() {
508 return $this->getService( 'NameTableStoreFactory' )->getContentModels();
515 public function getCryptHKDF() {
516 return $this->getService( 'CryptHKDF' );
521 * @return DateFormatterFactory
523 public function getDateFormatterFactory() {
524 return $this->getService( 'DateFormatterFactory' );
529 * @return LoadBalancer The main DB load balancer for the local wiki.
531 public function getDBLoadBalancer() {
532 return $this->getService( 'DBLoadBalancer' );
539 public function getDBLoadBalancerFactory() {
540 return $this->getService( 'DBLoadBalancerFactory' );
545 * @return EventRelayerGroup
547 public function getEventRelayerGroup() {
548 return $this->getService( 'EventRelayerGroup' );
553 * @return \ExternalStoreFactory
555 public function getExternalStoreFactory() {
556 return $this->getService( 'ExternalStoreFactory' );
561 * @return GenderCache
563 public function getGenderCache() {
564 return $this->getService( 'GenderCache' );
569 * @return HttpRequestFactory
571 public function getHttpRequestFactory() {
572 return $this->getService( 'HttpRequestFactory' );
577 * @return InterwikiLookup
579 public function getInterwikiLookup() {
580 return $this->getService( 'InterwikiLookup' );
587 public function getLinkCache() {
588 return $this->getService( 'LinkCache' );
592 * LinkRenderer instance that can be used
593 * if no custom options are needed
596 * @return LinkRenderer
598 public function getLinkRenderer() {
599 return $this->getService( 'LinkRenderer' );
604 * @return LinkRendererFactory
606 public function getLinkRendererFactory() {
607 return $this->getService( 'LinkRendererFactory' );
614 public function getLocalServerObjectCache() {
615 return $this->getService( 'LocalServerObjectCache' );
620 * @return MagicWordFactory
622 public function getMagicWordFactory() {
623 return $this->getService( 'MagicWordFactory' );
627 * Returns the Config object that provides configuration for MediaWiki core.
628 * This may or may not be the same object that is returned by getBootstrapConfig().
633 public function getMainConfig() {
634 return $this->getService( 'MainConfig' );
641 public function getMainObjectStash() {
642 return $this->getService( 'MainObjectStash' );
647 * @return \WANObjectCache
649 public function getMainWANObjectCache() {
650 return $this->getService( 'MainWANObjectCache' );
655 * @return MediaHandlerFactory
657 public function getMediaHandlerFactory() {
658 return $this->getService( 'MediaHandlerFactory' );
663 * @return MimeAnalyzer
665 public function getMimeAnalyzer() {
666 return $this->getService( 'MimeAnalyzer' );
671 * @return NamespaceInfo
673 public function getNamespaceInfo() : NamespaceInfo
{
674 return $this->getService( 'NamespaceInfo' );
679 * @return NameTableStoreFactory
681 public function getNameTableStoreFactory() {
682 return $this->getService( 'NameTableStoreFactory' );
687 * @return OldRevisionImporter
689 public function getOldRevisionImporter() {
690 return $this->getService( 'OldRevisionImporter' );
697 public function getParser() {
698 return $this->getService( 'Parser' );
703 * @return ParserCache
705 public function getParserCache() {
706 return $this->getService( 'ParserCache' );
711 * @return ParserFactory
713 public function getParserFactory() {
714 return $this->getService( 'ParserFactory' );
719 * @return PasswordFactory
721 public function getPasswordFactory() {
722 return $this->getService( 'PasswordFactory' );
727 * @return StatsdDataFactoryInterface
729 public function getPerDbNameStatsdDataFactory() {
730 return $this->getService( 'PerDbNameStatsdDataFactory' );
735 * @return PermissionManager
737 public function getPermissionManager() {
738 return $this->getService( 'PermissionManager' );
743 * @return PreferencesFactory
745 public function getPreferencesFactory() {
746 return $this->getService( 'PreferencesFactory' );
751 * @return ProxyLookup
753 public function getProxyLookup() {
754 return $this->getService( 'ProxyLookup' );
759 * @return \ReadOnlyMode
761 public function getReadOnlyMode() {
762 return $this->getService( 'ReadOnlyMode' );
767 * @return ResourceLoader
769 public function getResourceLoader() {
770 return $this->getService( 'ResourceLoader' );
775 * @return RevisionFactory
777 public function getRevisionFactory() {
778 return $this->getService( 'RevisionFactory' );
783 * @return RevisionLookup
785 public function getRevisionLookup() {
786 return $this->getService( 'RevisionLookup' );
791 * @return RevisionRenderer
793 public function getRevisionRenderer() {
794 return $this->getService( 'RevisionRenderer' );
799 * @return RevisionStore
801 public function getRevisionStore() {
802 return $this->getService( 'RevisionStore' );
807 * @return RevisionStoreFactory
809 public function getRevisionStoreFactory() {
810 return $this->getService( 'RevisionStoreFactory' );
815 * @return SearchEngine
817 public function newSearchEngine() {
818 // New engine object every time, since they keep state
819 return $this->getService( 'SearchEngineFactory' )->create();
824 * @return SearchEngineConfig
826 public function getSearchEngineConfig() {
827 return $this->getService( 'SearchEngineConfig' );
832 * @return SearchEngineFactory
834 public function getSearchEngineFactory() {
835 return $this->getService( 'SearchEngineFactory' );
840 * @return CommandFactory
842 public function getShellCommandFactory() {
843 return $this->getService( 'ShellCommandFactory' );
850 public function getSiteLookup() {
851 return $this->getService( 'SiteLookup' );
858 public function getSiteStore() {
859 return $this->getService( 'SiteStore' );
864 * @return SkinFactory
866 public function getSkinFactory() {
867 return $this->getService( 'SkinFactory' );
872 * @return SlotRoleRegistry
874 public function getSlotRoleRegistry() {
875 return $this->getService( 'SlotRoleRegistry' );
880 * @return NameTableStore
882 public function getSlotRoleStore() {
883 return $this->getService( 'NameTableStoreFactory' )->getSlotRoles();
888 * @return SpecialPageFactory
890 public function getSpecialPageFactory() : SpecialPageFactory
{
891 return $this->getService( 'SpecialPageFactory' );
896 * @return IBufferingStatsdDataFactory
898 public function getStatsdDataFactory() {
899 return $this->getService( 'StatsdDataFactory' );
904 * @return TitleFormatter
906 public function getTitleFormatter() {
907 return $this->getService( 'TitleFormatter' );
912 * @return TitleParser
914 public function getTitleParser() {
915 return $this->getService( 'TitleParser' );
920 * @return UploadRevisionImporter
922 public function getUploadRevisionImporter() {
923 return $this->getService( 'UploadRevisionImporter' );
928 * @return VirtualRESTServiceClient
930 public function getVirtualRESTServiceClient() {
931 return $this->getService( 'VirtualRESTServiceClient' );
936 * @return WatchedItemQueryService
938 public function getWatchedItemQueryService() {
939 return $this->getService( 'WatchedItemQueryService' );
944 * @return WatchedItemStoreInterface
946 public function getWatchedItemStore() {
947 return $this->getService( 'WatchedItemStore' );
952 * @return \OldRevisionImporter
954 public function getWikiRevisionOldRevisionImporter() {
955 return $this->getService( 'OldRevisionImporter' );
960 * @return \OldRevisionImporter
962 public function getWikiRevisionOldRevisionImporterNoUpdates() {
963 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
968 * @return \UploadRevisionImporter
970 public function getWikiRevisionUploadImporter() {
971 return $this->getService( 'UploadRevisionImporter' );