10 use EventRelayerGroup
;
14 use IBufferingStatsdDataFactory
;
15 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface
;
16 use MediaWiki\Http\HttpRequestFactory
;
17 use MediaWiki\Preferences\PreferencesFactory
;
18 use MediaWiki\Shell\CommandFactory
;
19 use MediaWiki\Special\SpecialPageFactory
;
20 use MediaWiki\Storage\BlobStore
;
21 use MediaWiki\Storage\BlobStoreFactory
;
22 use MediaWiki\Storage\NameTableStore
;
23 use MediaWiki\Storage\RevisionFactory
;
24 use MediaWiki\Storage\RevisionLookup
;
25 use MediaWiki\Storage\RevisionStore
;
26 use OldRevisionImporter
;
27 use MediaWiki\Storage\RevisionStoreFactory
;
28 use UploadRevisionImporter
;
29 use Wikimedia\Rdbms\LBFactory
;
31 use Wikimedia\Rdbms\LoadBalancer
;
32 use MediaHandlerFactory
;
33 use MediaWiki\Config\ConfigRepository
;
34 use MediaWiki\Linker\LinkRenderer
;
35 use MediaWiki\Linker\LinkRendererFactory
;
36 use MediaWiki\Services\SalvageableService
;
37 use MediaWiki\Services\ServiceContainer
;
38 use MediaWiki\Services\NoSuchServiceException
;
48 use SearchEngineConfig
;
49 use SearchEngineFactory
;
52 use WatchedItemStoreInterface
;
53 use WatchedItemQueryService
;
57 use VirtualRESTServiceClient
;
58 use MediaWiki\Interwiki\InterwikiLookup
;
62 * Service locator for MediaWiki core services.
64 * This program is free software; you can redistribute it and/or modify
65 * it under the terms of the GNU General Public License as published by
66 * the Free Software Foundation; either version 2 of the License, or
67 * (at your option) any later version.
69 * This program is distributed in the hope that it will be useful,
70 * but WITHOUT ANY WARRANTY; without even the implied warranty of
71 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
72 * GNU General Public License for more details.
74 * You should have received a copy of the GNU General Public License along
75 * with this program; if not, write to the Free Software Foundation, Inc.,
76 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
77 * http://www.gnu.org/copyleft/gpl.html
85 * MediaWikiServices is the service locator for the application scope of MediaWiki.
86 * Its implemented as a simple configurable DI container.
87 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
88 * the network of service objects that defines MediaWiki's application logic.
89 * It acts as an entry point to MediaWiki's dependency injection mechanism.
91 * Services are defined in the "wiring" array passed to the constructor,
92 * or by calling defineService().
94 * @see docs/injection.txt for an overview of using dependency injection in the
95 * MediaWiki code base.
97 class MediaWikiServices
extends ServiceContainer
{
100 * @var MediaWikiServices|null
102 private static $instance = null;
105 * Returns the global default instance of the top level service locator.
109 * The default instance is initialized using the service instantiator functions
110 * defined in ServiceWiring.php.
112 * @note This should only be called by static functions! The instance returned here
113 * should not be passed around! Objects that need access to a service should have
114 * that service injected into the constructor, never a service locator!
116 * @return MediaWikiServices
118 public static function getInstance() {
119 if ( self
::$instance === null ) {
120 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
121 // but some information from the global scope has to be injected here,
122 // even if it's just a file name or database credentials to load
123 // configuration from.
124 $bootstrapConfig = new GlobalVarConfig();
125 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
128 return self
::$instance;
132 * Replaces the global MediaWikiServices instance.
136 * @note This is for use in PHPUnit tests only!
138 * @throws MWException if called outside of PHPUnit tests.
140 * @param MediaWikiServices $services The new MediaWikiServices object.
142 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
144 public static function forceGlobalInstance( MediaWikiServices
$services ) {
145 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
146 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
149 $old = self
::getInstance();
150 self
::$instance = $services;
156 * Creates a new instance of MediaWikiServices and sets it as the global default
157 * instance. getInstance() will return a different MediaWikiServices object
158 * after every call to resetGlobalInstance().
162 * @warning This should not be used during normal operation. It is intended for use
163 * when the configuration has changed significantly since bootstrap time, e.g.
164 * during the installation process or during testing.
166 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
167 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
168 * any of the services managed by MediaWikiServices exist. If any service objects
169 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
170 * with the operation of the services managed by the new MediaWikiServices.
171 * Operating with a mix of services created by the old and the new
172 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
173 * Any class implementing LAZY LOADING is especially prone to this problem,
174 * since instances would typically retain a reference to a storage layer service.
176 * @see forceGlobalInstance()
177 * @see resetGlobalInstance()
178 * @see resetBetweenTest()
180 * @param Config|null $bootstrapConfig The Config object to be registered as the
181 * 'BootstrapConfig' service. This has to contain at least the information
182 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
183 * config of the old instance of MediaWikiServices will be re-used. If there
184 * was no previous instance, a new GlobalVarConfig object will be used to
185 * bootstrap the services.
187 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
188 * See SalvageableService for details.
190 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
191 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
194 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
195 if ( self
::$instance === null ) {
196 // no global instance yet, nothing to reset
200 self
::failIfResetNotAllowed( __METHOD__
);
202 if ( $bootstrapConfig === null ) {
203 $bootstrapConfig = self
::$instance->getBootstrapConfig();
206 $oldInstance = self
::$instance;
208 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
209 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
211 if ( $quick === 'quick' ) {
212 self
::$instance->salvage( $oldInstance );
214 $oldInstance->destroy();
219 * Salvages the state of any salvageable service instances in $other.
221 * @note $other will have been destroyed when salvage() returns.
223 * @param MediaWikiServices $other
225 private function salvage( self
$other ) {
226 foreach ( $this->getServiceNames() as $name ) {
227 // The service could be new in the new instance and not registered in the
228 // other instance (e.g. an extension that was loaded after the instantiation of
229 // the other instance. Skip this service in this case. See T143974
231 $oldService = $other->peekService( $name );
232 } catch ( NoSuchServiceException
$e ) {
236 if ( $oldService instanceof SalvageableService
) {
237 /** @var SalvageableService $newService */
238 $newService = $this->getService( $name );
239 $newService->salvage( $oldService );
247 * Creates a new MediaWikiServices instance and initializes it according to the
248 * given $bootstrapConfig. In particular, all wiring files defined in the
249 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
251 * @param Config|null $bootstrapConfig The Config object to be registered as the
252 * 'BootstrapConfig' service.
254 * @param string $loadWiring set this to 'load' to load the wiring files specified
255 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
257 * @return MediaWikiServices
258 * @throws MWException
259 * @throws \FatalError
261 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
262 $instance = new self( $bootstrapConfig );
264 // Load the default wiring from the specified files.
265 if ( $loadWiring === 'load' ) {
266 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
267 $instance->loadWiringFiles( $wiringFiles );
270 // Provide a traditional hook point to allow extensions to configure services.
271 Hooks
::run( 'MediaWikiServices', [ $instance ] );
277 * Disables all storage layer services. After calling this, any attempt to access the
278 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
283 * @warning This is intended for extreme situations only and should never be used
284 * while serving normal web requests. Legitimate use cases for this method include
285 * the installation process. Test fixtures may also use this, if the fixture relies
288 * @see resetGlobalInstance()
289 * @see resetChildProcessServices()
291 public static function disableStorageBackend() {
292 // TODO: also disable some Caches, JobQueues, etc
293 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
294 $services = self
::getInstance();
296 foreach ( $destroy as $name ) {
297 $services->disableService( $name );
300 ObjectCache
::clear();
304 * Resets any services that may have become stale after a child process
305 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
306 * to call this method from the parent process.
310 * @note This is intended for use in the context of process forking only!
312 * @see resetGlobalInstance()
313 * @see disableStorageBackend()
315 public static function resetChildProcessServices() {
316 // NOTE: for now, just reset everything. Since we don't know the interdependencies
317 // between services, we can't do this more selectively at this time.
318 self
::resetGlobalInstance();
320 // Child, reseed because there is no bug in PHP:
321 // https://bugs.php.net/bug.php?id=42465
322 mt_srand( getmypid() );
326 * Resets the given service for testing purposes.
330 * @warning This is generally unsafe! Other services may still retain references
331 * to the stale service instance, leading to failures and inconsistencies. Subclasses
332 * may use this method to reset specific services under specific instances, but
333 * it should not be exposed to application logic.
335 * @note With proper dependency injection used throughout the codebase, this method
336 * should not be needed. It is provided to allow tests that pollute global service
337 * instances to clean up.
339 * @param string $name
340 * @param bool $destroy Whether the service instance should be destroyed if it exists.
341 * When set to false, any existing service instance will effectively be detached
342 * from the container.
344 * @throws MWException if called outside of PHPUnit tests.
346 public function resetServiceForTesting( $name, $destroy = true ) {
347 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
348 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
351 $this->resetService( $name, $destroy );
355 * Convenience method that throws an exception unless it is called during a phase in which
356 * resetting of global services is allowed. In general, services should not be reset
357 * individually, since that may introduce inconsistencies.
361 * This method will throw an exception if:
363 * - self::$resetInProgress is false (to allow all services to be reset together
364 * via resetGlobalInstance)
365 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
366 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
368 * This method is intended to be used to safeguard against accidentally resetting
369 * global service instances that are not yet managed by MediaWikiServices. It is
370 * defined here in the MediaWikiServices services class to have a central place
371 * for managing service bootstrapping and resetting.
373 * @param string $method the name of the caller method, as given by __METHOD__.
375 * @throws MWException if called outside bootstrap mode.
377 * @see resetGlobalInstance()
378 * @see forceGlobalInstance()
379 * @see disableStorageBackend()
381 public static function failIfResetNotAllowed( $method ) {
382 if ( !defined( 'MW_PHPUNIT_TEST' )
383 && !defined( 'MW_PARSER_TEST' )
384 && !defined( 'MEDIAWIKI_INSTALL' )
385 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
386 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
388 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
393 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
394 * This has to contain at least the information needed to set up the 'ConfigFactory'
397 public function __construct( Config
$config ) {
398 parent
::__construct();
400 // Register the given Config object as the bootstrap config service.
401 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
406 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
410 * @return ActorMigration
412 public function getActorMigration() {
413 return $this->getService( 'ActorMigration' );
420 public function getBlobStore() {
421 return $this->getService( '_SqlBlobStore' );
426 * @return BlobStoreFactory
428 public function getBlobStoreFactory() {
429 return $this->getService( 'BlobStoreFactory' );
433 * Returns the Config object containing the bootstrap configuration.
434 * Bootstrap configuration would typically include database credentials
435 * and other information that may be needed before the ConfigFactory
436 * service can be instantiated.
438 * @note This should only be used during bootstrapping, in particular
439 * when creating the MainConfig service. Application logic should
440 * use getMainConfig() to get a Config instances.
445 public function getBootstrapConfig() {
446 return $this->getService( 'BootstrapConfig' );
451 * @return NameTableStore
453 public function getChangeTagDefStore() {
454 return $this->getService( 'ChangeTagDefStore' );
459 * @return CommentStore
461 public function getCommentStore() {
462 return $this->getService( 'CommentStore' );
467 * @return ConfigFactory
469 public function getConfigFactory() {
470 return $this->getService( 'ConfigFactory' );
475 * @return ConfigRepository
477 public function getConfigRepository() {
478 return $this->getService( 'ConfigRepository' );
483 * @return \ConfiguredReadOnlyMode
485 public function getConfiguredReadOnlyMode() {
486 return $this->getService( 'ConfiguredReadOnlyMode' );
493 public function getContentLanguage() {
494 return $this->getService( 'ContentLanguage' );
499 * @return NameTableStore
501 public function getContentModelStore() {
502 return $this->getService( 'ContentModelStore' );
509 public function getCryptHKDF() {
510 return $this->getService( 'CryptHKDF' );
515 * @deprecated since 1.32, use random_bytes()/random_int()
518 public function getCryptRand() {
519 return $this->getService( 'CryptRand' );
524 * @return LoadBalancer The main DB load balancer for the local wiki.
526 public function getDBLoadBalancer() {
527 return $this->getService( 'DBLoadBalancer' );
534 public function getDBLoadBalancerFactory() {
535 return $this->getService( 'DBLoadBalancerFactory' );
540 * @return EventRelayerGroup
542 public function getEventRelayerGroup() {
543 return $this->getService( 'EventRelayerGroup' );
548 * @return \ExternalStoreFactory
550 public function getExternalStoreFactory() {
551 return $this->getService( 'ExternalStoreFactory' );
556 * @return GenderCache
558 public function getGenderCache() {
559 return $this->getService( 'GenderCache' );
564 * @return HttpRequestFactory
566 public function getHttpRequestFactory() {
567 return $this->getService( 'HttpRequestFactory' );
572 * @return InterwikiLookup
574 public function getInterwikiLookup() {
575 return $this->getService( 'InterwikiLookup' );
582 public function getLinkCache() {
583 return $this->getService( 'LinkCache' );
587 * LinkRenderer instance that can be used
588 * if no custom options are needed
591 * @return LinkRenderer
593 public function getLinkRenderer() {
594 return $this->getService( 'LinkRenderer' );
599 * @return LinkRendererFactory
601 public function getLinkRendererFactory() {
602 return $this->getService( 'LinkRendererFactory' );
609 public function getLocalServerObjectCache() {
610 return $this->getService( 'LocalServerObjectCache' );
615 * @return MagicWordFactory
617 public function getMagicWordFactory() {
618 return $this->getService( 'MagicWordFactory' );
622 * Returns the Config object that provides configuration for MediaWiki core.
623 * This may or may not be the same object that is returned by getBootstrapConfig().
628 public function getMainConfig() {
629 return $this->getService( 'MainConfig' );
636 public function getMainObjectStash() {
637 return $this->getService( 'MainObjectStash' );
642 * @return \WANObjectCache
644 public function getMainWANObjectCache() {
645 return $this->getService( 'MainWANObjectCache' );
650 * @return MediaHandlerFactory
652 public function getMediaHandlerFactory() {
653 return $this->getService( 'MediaHandlerFactory' );
658 * @return MimeAnalyzer
660 public function getMimeAnalyzer() {
661 return $this->getService( 'MimeAnalyzer' );
666 * @return OldRevisionImporter
668 public function getOldRevisionImporter() {
669 return $this->getService( 'OldRevisionImporter' );
676 public function getParser() {
677 return $this->getService( 'Parser' );
682 * @return ParserCache
684 public function getParserCache() {
685 return $this->getService( 'ParserCache' );
690 * @return ParserFactory
692 public function getParserFactory() {
693 return $this->getService( 'ParserFactory' );
698 * @return PasswordFactory
700 public function getPasswordFactory() {
701 return $this->getService( 'PasswordFactory' );
706 * @return StatsdDataFactoryInterface
708 public function getPerDbNameStatsdDataFactory() {
709 return $this->getService( 'PerDbNameStatsdDataFactory' );
714 * @return PreferencesFactory
716 public function getPreferencesFactory() {
717 return $this->getService( 'PreferencesFactory' );
722 * @return ProxyLookup
724 public function getProxyLookup() {
725 return $this->getService( 'ProxyLookup' );
730 * @return \ReadOnlyMode
732 public function getReadOnlyMode() {
733 return $this->getService( 'ReadOnlyMode' );
738 * @return RevisionFactory
740 public function getRevisionFactory() {
741 return $this->getService( 'RevisionFactory' );
746 * @return RevisionLookup
748 public function getRevisionLookup() {
749 return $this->getService( 'RevisionLookup' );
754 * @return RevisionStore
756 public function getRevisionStore() {
757 return $this->getService( 'RevisionStore' );
762 * @return RevisionStoreFactory
764 public function getRevisionStoreFactory() {
765 return $this->getService( 'RevisionStoreFactory' );
770 * @return SearchEngine
772 public function newSearchEngine() {
773 // New engine object every time, since they keep state
774 return $this->getService( 'SearchEngineFactory' )->create();
779 * @return SearchEngineConfig
781 public function getSearchEngineConfig() {
782 return $this->getService( 'SearchEngineConfig' );
787 * @return SearchEngineFactory
789 public function getSearchEngineFactory() {
790 return $this->getService( 'SearchEngineFactory' );
795 * @return CommandFactory
797 public function getShellCommandFactory() {
798 return $this->getService( 'ShellCommandFactory' );
805 public function getSiteLookup() {
806 return $this->getService( 'SiteLookup' );
813 public function getSiteStore() {
814 return $this->getService( 'SiteStore' );
819 * @return SkinFactory
821 public function getSkinFactory() {
822 return $this->getService( 'SkinFactory' );
827 * @return NameTableStore
829 public function getSlotRoleStore() {
830 return $this->getService( 'SlotRoleStore' );
835 * @return SpecialPageFactory
837 public function getSpecialPageFactory() : SpecialPageFactory
{
838 return $this->getService( 'SpecialPageFactory' );
843 * @return IBufferingStatsdDataFactory
845 public function getStatsdDataFactory() {
846 return $this->getService( 'StatsdDataFactory' );
851 * @return TitleFormatter
853 public function getTitleFormatter() {
854 return $this->getService( 'TitleFormatter' );
859 * @return TitleParser
861 public function getTitleParser() {
862 return $this->getService( 'TitleParser' );
867 * @return UploadRevisionImporter
869 public function getUploadRevisionImporter() {
870 return $this->getService( 'UploadRevisionImporter' );
875 * @return VirtualRESTServiceClient
877 public function getVirtualRESTServiceClient() {
878 return $this->getService( 'VirtualRESTServiceClient' );
883 * @return WatchedItemQueryService
885 public function getWatchedItemQueryService() {
886 return $this->getService( 'WatchedItemQueryService' );
891 * @return WatchedItemStoreInterface
893 public function getWatchedItemStore() {
894 return $this->getService( 'WatchedItemStore' );
899 * @return \OldRevisionImporter
901 public function getWikiRevisionOldRevisionImporter() {
902 return $this->getService( 'OldRevisionImporter' );
907 * @return \OldRevisionImporter
909 public function getWikiRevisionOldRevisionImporterNoUpdates() {
910 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
915 * @return \UploadRevisionImporter
917 public function getWikiRevisionUploadImporter() {
918 return $this->getService( 'UploadRevisionImporter' );