10 use EventRelayerGroup
;
14 use IBufferingStatsdDataFactory
;
15 use MediaWiki\Http\HttpRequestFactory
;
16 use MediaWiki\Preferences\PreferencesFactory
;
17 use MediaWiki\Shell\CommandFactory
;
18 use MediaWiki\Special\SpecialPageFactory
;
19 use MediaWiki\Storage\BlobStore
;
20 use MediaWiki\Storage\BlobStoreFactory
;
21 use MediaWiki\Storage\NameTableStore
;
22 use MediaWiki\Storage\RevisionFactory
;
23 use MediaWiki\Storage\RevisionLookup
;
24 use MediaWiki\Storage\RevisionStore
;
25 use OldRevisionImporter
;
26 use MediaWiki\Storage\RevisionStoreFactory
;
27 use UploadRevisionImporter
;
28 use Wikimedia\Rdbms\LBFactory
;
30 use Wikimedia\Rdbms\LoadBalancer
;
31 use MediaHandlerFactory
;
32 use MediaWiki\Config\ConfigRepository
;
33 use MediaWiki\Linker\LinkRenderer
;
34 use MediaWiki\Linker\LinkRendererFactory
;
35 use MediaWiki\Services\SalvageableService
;
36 use MediaWiki\Services\ServiceContainer
;
37 use MediaWiki\Services\NoSuchServiceException
;
47 use SearchEngineConfig
;
48 use SearchEngineFactory
;
51 use WatchedItemStoreInterface
;
52 use WatchedItemQueryService
;
56 use VirtualRESTServiceClient
;
57 use MediaWiki\Interwiki\InterwikiLookup
;
61 * Service locator for MediaWiki core services.
63 * This program is free software; you can redistribute it and/or modify
64 * it under the terms of the GNU General Public License as published by
65 * the Free Software Foundation; either version 2 of the License, or
66 * (at your option) any later version.
68 * This program is distributed in the hope that it will be useful,
69 * but WITHOUT ANY WARRANTY; without even the implied warranty of
70 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
71 * GNU General Public License for more details.
73 * You should have received a copy of the GNU General Public License along
74 * with this program; if not, write to the Free Software Foundation, Inc.,
75 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
76 * http://www.gnu.org/copyleft/gpl.html
84 * MediaWikiServices is the service locator for the application scope of MediaWiki.
85 * Its implemented as a simple configurable DI container.
86 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
87 * the network of service objects that defines MediaWiki's application logic.
88 * It acts as an entry point to MediaWiki's dependency injection mechanism.
90 * Services are defined in the "wiring" array passed to the constructor,
91 * or by calling defineService().
93 * @see docs/injection.txt for an overview of using dependency injection in the
94 * MediaWiki code base.
96 class MediaWikiServices
extends ServiceContainer
{
99 * @var MediaWikiServices|null
101 private static $instance = null;
104 * Returns the global default instance of the top level service locator.
108 * The default instance is initialized using the service instantiator functions
109 * defined in ServiceWiring.php.
111 * @note This should only be called by static functions! The instance returned here
112 * should not be passed around! Objects that need access to a service should have
113 * that service injected into the constructor, never a service locator!
115 * @return MediaWikiServices
117 public static function getInstance() {
118 if ( self
::$instance === null ) {
119 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
120 // but some information from the global scope has to be injected here,
121 // even if it's just a file name or database credentials to load
122 // configuration from.
123 $bootstrapConfig = new GlobalVarConfig();
124 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
127 return self
::$instance;
131 * Replaces the global MediaWikiServices instance.
135 * @note This is for use in PHPUnit tests only!
137 * @throws MWException if called outside of PHPUnit tests.
139 * @param MediaWikiServices $services The new MediaWikiServices object.
141 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
143 public static function forceGlobalInstance( MediaWikiServices
$services ) {
144 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
145 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
148 $old = self
::getInstance();
149 self
::$instance = $services;
155 * Creates a new instance of MediaWikiServices and sets it as the global default
156 * instance. getInstance() will return a different MediaWikiServices object
157 * after every call to resetGlobalInstance().
161 * @warning This should not be used during normal operation. It is intended for use
162 * when the configuration has changed significantly since bootstrap time, e.g.
163 * during the installation process or during testing.
165 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
166 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
167 * any of the services managed by MediaWikiServices exist. If any service objects
168 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
169 * with the operation of the services managed by the new MediaWikiServices.
170 * Operating with a mix of services created by the old and the new
171 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
172 * Any class implementing LAZY LOADING is especially prone to this problem,
173 * since instances would typically retain a reference to a storage layer service.
175 * @see forceGlobalInstance()
176 * @see resetGlobalInstance()
177 * @see resetBetweenTest()
179 * @param Config|null $bootstrapConfig The Config object to be registered as the
180 * 'BootstrapConfig' service. This has to contain at least the information
181 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
182 * config of the old instance of MediaWikiServices will be re-used. If there
183 * was no previous instance, a new GlobalVarConfig object will be used to
184 * bootstrap the services.
186 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
187 * See SalvageableService for details.
189 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
190 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
193 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
194 if ( self
::$instance === null ) {
195 // no global instance yet, nothing to reset
199 self
::failIfResetNotAllowed( __METHOD__
);
201 if ( $bootstrapConfig === null ) {
202 $bootstrapConfig = self
::$instance->getBootstrapConfig();
205 $oldInstance = self
::$instance;
207 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
208 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
210 if ( $quick === 'quick' ) {
211 self
::$instance->salvage( $oldInstance );
213 $oldInstance->destroy();
218 * Salvages the state of any salvageable service instances in $other.
220 * @note $other will have been destroyed when salvage() returns.
222 * @param MediaWikiServices $other
224 private function salvage( self
$other ) {
225 foreach ( $this->getServiceNames() as $name ) {
226 // The service could be new in the new instance and not registered in the
227 // other instance (e.g. an extension that was loaded after the instantiation of
228 // the other instance. Skip this service in this case. See T143974
230 $oldService = $other->peekService( $name );
231 } catch ( NoSuchServiceException
$e ) {
235 if ( $oldService instanceof SalvageableService
) {
236 /** @var SalvageableService $newService */
237 $newService = $this->getService( $name );
238 $newService->salvage( $oldService );
246 * Creates a new MediaWikiServices instance and initializes it according to the
247 * given $bootstrapConfig. In particular, all wiring files defined in the
248 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
250 * @param Config|null $bootstrapConfig The Config object to be registered as the
251 * 'BootstrapConfig' service.
253 * @param string $loadWiring set this to 'load' to load the wiring files specified
254 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
256 * @return MediaWikiServices
257 * @throws MWException
258 * @throws \FatalError
260 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
261 $instance = new self( $bootstrapConfig );
263 // Load the default wiring from the specified files.
264 if ( $loadWiring === 'load' ) {
265 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
266 $instance->loadWiringFiles( $wiringFiles );
269 // Provide a traditional hook point to allow extensions to configure services.
270 Hooks
::run( 'MediaWikiServices', [ $instance ] );
276 * Disables all storage layer services. After calling this, any attempt to access the
277 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
282 * @warning This is intended for extreme situations only and should never be used
283 * while serving normal web requests. Legitimate use cases for this method include
284 * the installation process. Test fixtures may also use this, if the fixture relies
287 * @see resetGlobalInstance()
288 * @see resetChildProcessServices()
290 public static function disableStorageBackend() {
291 // TODO: also disable some Caches, JobQueues, etc
292 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
293 $services = self
::getInstance();
295 foreach ( $destroy as $name ) {
296 $services->disableService( $name );
299 ObjectCache
::clear();
303 * Resets any services that may have become stale after a child process
304 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
305 * to call this method from the parent process.
309 * @note This is intended for use in the context of process forking only!
311 * @see resetGlobalInstance()
312 * @see disableStorageBackend()
314 public static function resetChildProcessServices() {
315 // NOTE: for now, just reset everything. Since we don't know the interdependencies
316 // between services, we can't do this more selectively at this time.
317 self
::resetGlobalInstance();
319 // Child, reseed because there is no bug in PHP:
320 // https://bugs.php.net/bug.php?id=42465
321 mt_srand( getmypid() );
325 * Resets the given service for testing purposes.
329 * @warning This is generally unsafe! Other services may still retain references
330 * to the stale service instance, leading to failures and inconsistencies. Subclasses
331 * may use this method to reset specific services under specific instances, but
332 * it should not be exposed to application logic.
334 * @note With proper dependency injection used throughout the codebase, this method
335 * should not be needed. It is provided to allow tests that pollute global service
336 * instances to clean up.
338 * @param string $name
339 * @param bool $destroy Whether the service instance should be destroyed if it exists.
340 * When set to false, any existing service instance will effectively be detached
341 * from the container.
343 * @throws MWException if called outside of PHPUnit tests.
345 public function resetServiceForTesting( $name, $destroy = true ) {
346 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
347 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
350 $this->resetService( $name, $destroy );
354 * Convenience method that throws an exception unless it is called during a phase in which
355 * resetting of global services is allowed. In general, services should not be reset
356 * individually, since that may introduce inconsistencies.
360 * This method will throw an exception if:
362 * - self::$resetInProgress is false (to allow all services to be reset together
363 * via resetGlobalInstance)
364 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
365 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
367 * This method is intended to be used to safeguard against accidentally resetting
368 * global service instances that are not yet managed by MediaWikiServices. It is
369 * defined here in the MediaWikiServices services class to have a central place
370 * for managing service bootstrapping and resetting.
372 * @param string $method the name of the caller method, as given by __METHOD__.
374 * @throws MWException if called outside bootstrap mode.
376 * @see resetGlobalInstance()
377 * @see forceGlobalInstance()
378 * @see disableStorageBackend()
380 public static function failIfResetNotAllowed( $method ) {
381 if ( !defined( 'MW_PHPUNIT_TEST' )
382 && !defined( 'MW_PARSER_TEST' )
383 && !defined( 'MEDIAWIKI_INSTALL' )
384 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
385 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
387 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
392 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
393 * This has to contain at least the information needed to set up the 'ConfigFactory'
396 public function __construct( Config
$config ) {
397 parent
::__construct();
399 // Register the given Config object as the bootstrap config service.
400 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
405 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
409 * @return ActorMigration
411 public function getActorMigration() {
412 return $this->getService( 'ActorMigration' );
419 public function getBlobStore() {
420 return $this->getService( '_SqlBlobStore' );
425 * @return BlobStoreFactory
427 public function getBlobStoreFactory() {
428 return $this->getService( 'BlobStoreFactory' );
432 * Returns the Config object containing the bootstrap configuration.
433 * Bootstrap configuration would typically include database credentials
434 * and other information that may be needed before the ConfigFactory
435 * service can be instantiated.
437 * @note This should only be used during bootstrapping, in particular
438 * when creating the MainConfig service. Application logic should
439 * use getMainConfig() to get a Config instances.
444 public function getBootstrapConfig() {
445 return $this->getService( 'BootstrapConfig' );
450 * @return NameTableStore
452 public function getChangeTagDefStore() {
453 return $this->getService( 'ChangeTagDefStore' );
458 * @return CommentStore
460 public function getCommentStore() {
461 return $this->getService( 'CommentStore' );
466 * @return ConfigFactory
468 public function getConfigFactory() {
469 return $this->getService( 'ConfigFactory' );
474 * @return ConfigRepository
476 public function getConfigRepository() {
477 return $this->getService( 'ConfigRepository' );
482 * @return \ConfiguredReadOnlyMode
484 public function getConfiguredReadOnlyMode() {
485 return $this->getService( 'ConfiguredReadOnlyMode' );
492 public function getContentLanguage() {
493 return $this->getService( 'ContentLanguage' );
498 * @return NameTableStore
500 public function getContentModelStore() {
501 return $this->getService( 'ContentModelStore' );
508 public function getCryptHKDF() {
509 return $this->getService( 'CryptHKDF' );
514 * @deprecated since 1.32, use random_bytes()/random_int()
517 public function getCryptRand() {
518 return $this->getService( 'CryptRand' );
523 * @return LoadBalancer The main DB load balancer for the local wiki.
525 public function getDBLoadBalancer() {
526 return $this->getService( 'DBLoadBalancer' );
533 public function getDBLoadBalancerFactory() {
534 return $this->getService( 'DBLoadBalancerFactory' );
539 * @return EventRelayerGroup
541 public function getEventRelayerGroup() {
542 return $this->getService( 'EventRelayerGroup' );
547 * @return \ExternalStoreFactory
549 public function getExternalStoreFactory() {
550 return $this->getService( 'ExternalStoreFactory' );
555 * @return GenderCache
557 public function getGenderCache() {
558 return $this->getService( 'GenderCache' );
563 * @return HttpRequestFactory
565 public function getHttpRequestFactory() {
566 return $this->getService( 'HttpRequestFactory' );
571 * @return InterwikiLookup
573 public function getInterwikiLookup() {
574 return $this->getService( 'InterwikiLookup' );
581 public function getLinkCache() {
582 return $this->getService( 'LinkCache' );
586 * LinkRenderer instance that can be used
587 * if no custom options are needed
590 * @return LinkRenderer
592 public function getLinkRenderer() {
593 return $this->getService( 'LinkRenderer' );
598 * @return LinkRendererFactory
600 public function getLinkRendererFactory() {
601 return $this->getService( 'LinkRendererFactory' );
608 public function getLocalServerObjectCache() {
609 return $this->getService( 'LocalServerObjectCache' );
614 * @return MagicWordFactory
616 public function getMagicWordFactory() {
617 return $this->getService( 'MagicWordFactory' );
621 * Returns the Config object that provides configuration for MediaWiki core.
622 * This may or may not be the same object that is returned by getBootstrapConfig().
627 public function getMainConfig() {
628 return $this->getService( 'MainConfig' );
635 public function getMainObjectStash() {
636 return $this->getService( 'MainObjectStash' );
641 * @return \WANObjectCache
643 public function getMainWANObjectCache() {
644 return $this->getService( 'MainWANObjectCache' );
649 * @return MediaHandlerFactory
651 public function getMediaHandlerFactory() {
652 return $this->getService( 'MediaHandlerFactory' );
657 * @return MimeAnalyzer
659 public function getMimeAnalyzer() {
660 return $this->getService( 'MimeAnalyzer' );
665 * @return OldRevisionImporter
667 public function getOldRevisionImporter() {
668 return $this->getService( 'OldRevisionImporter' );
675 public function getParser() {
676 return $this->getService( 'Parser' );
681 * @return ParserCache
683 public function getParserCache() {
684 return $this->getService( 'ParserCache' );
689 * @return ParserFactory
691 public function getParserFactory() {
692 return $this->getService( 'ParserFactory' );
697 * @return PasswordFactory
699 public function getPasswordFactory() {
700 return $this->getService( 'PasswordFactory' );
705 * @return IBufferingStatsdDataFactory
707 public function getPerDbNameStatsdDataFactory() {
708 return $this->getService( 'PerDbNameStatsdDataFactory' );
713 * @return PreferencesFactory
715 public function getPreferencesFactory() {
716 return $this->getService( 'PreferencesFactory' );
721 * @return ProxyLookup
723 public function getProxyLookup() {
724 return $this->getService( 'ProxyLookup' );
729 * @return \ReadOnlyMode
731 public function getReadOnlyMode() {
732 return $this->getService( 'ReadOnlyMode' );
737 * @return RevisionFactory
739 public function getRevisionFactory() {
740 return $this->getService( 'RevisionFactory' );
745 * @return RevisionLookup
747 public function getRevisionLookup() {
748 return $this->getService( 'RevisionLookup' );
753 * @return RevisionStore
755 public function getRevisionStore() {
756 return $this->getService( 'RevisionStore' );
761 * @return RevisionStoreFactory
763 public function getRevisionStoreFactory() {
764 return $this->getService( 'RevisionStoreFactory' );
769 * @return SearchEngine
771 public function newSearchEngine() {
772 // New engine object every time, since they keep state
773 return $this->getService( 'SearchEngineFactory' )->create();
778 * @return SearchEngineConfig
780 public function getSearchEngineConfig() {
781 return $this->getService( 'SearchEngineConfig' );
786 * @return SearchEngineFactory
788 public function getSearchEngineFactory() {
789 return $this->getService( 'SearchEngineFactory' );
794 * @return CommandFactory
796 public function getShellCommandFactory() {
797 return $this->getService( 'ShellCommandFactory' );
804 public function getSiteLookup() {
805 return $this->getService( 'SiteLookup' );
812 public function getSiteStore() {
813 return $this->getService( 'SiteStore' );
818 * @return SkinFactory
820 public function getSkinFactory() {
821 return $this->getService( 'SkinFactory' );
826 * @return NameTableStore
828 public function getSlotRoleStore() {
829 return $this->getService( 'SlotRoleStore' );
834 * @return SpecialPageFactory
836 public function getSpecialPageFactory() : SpecialPageFactory
{
837 return $this->getService( 'SpecialPageFactory' );
842 * @return IBufferingStatsdDataFactory
844 public function getStatsdDataFactory() {
845 return $this->getService( 'StatsdDataFactory' );
850 * @return TitleFormatter
852 public function getTitleFormatter() {
853 return $this->getService( 'TitleFormatter' );
858 * @return TitleParser
860 public function getTitleParser() {
861 return $this->getService( 'TitleParser' );
866 * @return UploadRevisionImporter
868 public function getUploadRevisionImporter() {
869 return $this->getService( 'UploadRevisionImporter' );
874 * @return VirtualRESTServiceClient
876 public function getVirtualRESTServiceClient() {
877 return $this->getService( 'VirtualRESTServiceClient' );
882 * @return WatchedItemQueryService
884 public function getWatchedItemQueryService() {
885 return $this->getService( 'WatchedItemQueryService' );
890 * @return WatchedItemStoreInterface
892 public function getWatchedItemStore() {
893 return $this->getService( 'WatchedItemStore' );
898 * @return \OldRevisionImporter
900 public function getWikiRevisionOldRevisionImporter() {
901 return $this->getService( 'OldRevisionImporter' );
906 * @return \OldRevisionImporter
908 public function getWikiRevisionOldRevisionImporterNoUpdates() {
909 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
914 * @return \UploadRevisionImporter
916 public function getWikiRevisionUploadImporter() {
917 return $this->getService( 'UploadRevisionImporter' );