API: Some raw message cleanup
[mediawiki.git] / includes / MediaWikiServices.php
blob49891dfd5e63936d87cc5a335359bfc61cd052f1
1 <?php
2 namespace MediaWiki;
4 use Config;
5 use ConfigFactory;
6 use EventRelayerGroup;
7 use GenderCache;
8 use GlobalVarConfig;
9 use Hooks;
10 use LBFactory;
11 use LinkCache;
12 use Liuggio\StatsdClient\Factory\StatsdDataFactory;
13 use LoadBalancer;
14 use MediaHandlerFactory;
15 use MediaWiki\Linker\LinkRenderer;
16 use MediaWiki\Linker\LinkRendererFactory;
17 use MediaWiki\Services\SalvageableService;
18 use MediaWiki\Services\ServiceContainer;
19 use MWException;
20 use ObjectCache;
21 use SearchEngine;
22 use SearchEngineConfig;
23 use SearchEngineFactory;
24 use SiteLookup;
25 use SiteStore;
26 use WatchedItemStore;
27 use WatchedItemQueryService;
28 use SkinFactory;
29 use TitleFormatter;
30 use TitleParser;
31 use VirtualRESTServiceClient;
32 use MediaWiki\Interwiki\InterwikiLookup;
34 /**
35 * Service locator for MediaWiki core services.
37 * This program is free software; you can redistribute it and/or modify
38 * it under the terms of the GNU General Public License as published by
39 * the Free Software Foundation; either version 2 of the License, or
40 * (at your option) any later version.
42 * This program is distributed in the hope that it will be useful,
43 * but WITHOUT ANY WARRANTY; without even the implied warranty of
44 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
45 * GNU General Public License for more details.
47 * You should have received a copy of the GNU General Public License along
48 * with this program; if not, write to the Free Software Foundation, Inc.,
49 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
50 * http://www.gnu.org/copyleft/gpl.html
52 * @file
54 * @since 1.27
57 /**
58 * MediaWikiServices is the service locator for the application scope of MediaWiki.
59 * Its implemented as a simple configurable DI container.
60 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
61 * the network of service objects that defines MediaWiki's application logic.
62 * It acts as an entry point to MediaWiki's dependency injection mechanism.
64 * Services are defined in the "wiring" array passed to the constructor,
65 * or by calling defineService().
67 * @see docs/injection.txt for an overview of using dependency injection in the
68 * MediaWiki code base.
70 class MediaWikiServices extends ServiceContainer {
72 /**
73 * @var MediaWikiServices|null
75 private static $instance = null;
77 /**
78 * Returns the global default instance of the top level service locator.
80 * @since 1.27
82 * The default instance is initialized using the service instantiator functions
83 * defined in ServiceWiring.php.
85 * @note This should only be called by static functions! The instance returned here
86 * should not be passed around! Objects that need access to a service should have
87 * that service injected into the constructor, never a service locator!
89 * @return MediaWikiServices
91 public static function getInstance() {
92 if ( self::$instance === null ) {
93 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
94 // but some information from the global scope has to be injected here,
95 // even if it's just a file name or database credentials to load
96 // configuration from.
97 $bootstrapConfig = new GlobalVarConfig();
98 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
101 return self::$instance;
105 * Replaces the global MediaWikiServices instance.
107 * @since 1.28
109 * @note This is for use in PHPUnit tests only!
111 * @throws MWException if called outside of PHPUnit tests.
113 * @param MediaWikiServices $services The new MediaWikiServices object.
115 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
117 public static function forceGlobalInstance( MediaWikiServices $services ) {
118 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
119 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
122 $old = self::getInstance();
123 self::$instance = $services;
125 return $old;
129 * Creates a new instance of MediaWikiServices and sets it as the global default
130 * instance. getInstance() will return a different MediaWikiServices object
131 * after every call to resetGlobalInstance().
133 * @since 1.28
135 * @warning This should not be used during normal operation. It is intended for use
136 * when the configuration has changed significantly since bootstrap time, e.g.
137 * during the installation process or during testing.
139 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
140 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
141 * any of the services managed by MediaWikiServices exist. If any service objects
142 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
143 * with the operation of the services managed by the new MediaWikiServices.
144 * Operating with a mix of services created by the old and the new
145 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
146 * Any class implementing LAZY LOADING is especially prone to this problem,
147 * since instances would typically retain a reference to a storage layer service.
149 * @see forceGlobalInstance()
150 * @see resetGlobalInstance()
151 * @see resetBetweenTest()
153 * @param Config|null $bootstrapConfig The Config object to be registered as the
154 * 'BootstrapConfig' service. This has to contain at least the information
155 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
156 * config of the old instance of MediaWikiServices will be re-used. If there
157 * was no previous instance, a new GlobalVarConfig object will be used to
158 * bootstrap the services.
160 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
161 * See SalvageableService for details.
163 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
164 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
165 * is defined).
167 public static function resetGlobalInstance( Config $bootstrapConfig = null, $quick = '' ) {
168 if ( self::$instance === null ) {
169 // no global instance yet, nothing to reset
170 return;
173 self::failIfResetNotAllowed( __METHOD__ );
175 if ( $bootstrapConfig === null ) {
176 $bootstrapConfig = self::$instance->getBootstrapConfig();
179 $oldInstance = self::$instance;
181 self::$instance = self::newInstance( $bootstrapConfig );
182 self::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
184 if ( $quick === 'quick' ) {
185 self::$instance->salvage( $oldInstance );
186 } else {
187 $oldInstance->destroy();
193 * Salvages the state of any salvageable service instances in $other.
195 * @note $other will have been destroyed when salvage() returns.
197 * @param MediaWikiServices $other
199 private function salvage( self $other ) {
200 foreach ( $this->getServiceNames() as $name ) {
201 $oldService = $other->peekService( $name );
203 if ( $oldService instanceof SalvageableService ) {
204 /** @var SalvageableService $newService */
205 $newService = $this->getService( $name );
206 $newService->salvage( $oldService );
210 $other->destroy();
214 * Creates a new MediaWikiServices instance and initializes it according to the
215 * given $bootstrapConfig. In particular, all wiring files defined in the
216 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
218 * @param Config|null $bootstrapConfig The Config object to be registered as the
219 * 'BootstrapConfig' service.
221 * @param string $loadWiring set this to 'load' to load the wiring files specified
222 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
224 * @return MediaWikiServices
225 * @throws MWException
226 * @throws \FatalError
228 private static function newInstance( Config $bootstrapConfig, $loadWiring = '' ) {
229 $instance = new self( $bootstrapConfig );
231 // Load the default wiring from the specified files.
232 if ( $loadWiring === 'load' ) {
233 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
234 $instance->loadWiringFiles( $wiringFiles );
237 // Provide a traditional hook point to allow extensions to configure services.
238 Hooks::run( 'MediaWikiServices', [ $instance ] );
240 return $instance;
244 * Disables all storage layer services. After calling this, any attempt to access the
245 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
246 * operation.
248 * @since 1.28
250 * @warning This is intended for extreme situations only and should never be used
251 * while serving normal web requests. Legitimate use cases for this method include
252 * the installation process. Test fixtures may also use this, if the fixture relies
253 * on globalState.
255 * @see resetGlobalInstance()
256 * @see resetChildProcessServices()
258 public static function disableStorageBackend() {
259 // TODO: also disable some Caches, JobQueues, etc
260 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
261 $services = self::getInstance();
263 foreach ( $destroy as $name ) {
264 $services->disableService( $name );
267 ObjectCache::clear();
271 * Resets any services that may have become stale after a child process
272 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
273 * to call this method from the parent process.
275 * @since 1.28
277 * @note This is intended for use in the context of process forking only!
279 * @see resetGlobalInstance()
280 * @see disableStorageBackend()
282 public static function resetChildProcessServices() {
283 // NOTE: for now, just reset everything. Since we don't know the interdependencies
284 // between services, we can't do this more selectively at this time.
285 self::resetGlobalInstance();
287 // Child, reseed because there is no bug in PHP:
288 // http://bugs.php.net/bug.php?id=42465
289 mt_srand( getmypid() );
293 * Resets the given service for testing purposes.
295 * @since 1.28
297 * @warning This is generally unsafe! Other services may still retain references
298 * to the stale service instance, leading to failures and inconsistencies. Subclasses
299 * may use this method to reset specific services under specific instances, but
300 * it should not be exposed to application logic.
302 * @note With proper dependency injection used throughout the codebase, this method
303 * should not be needed. It is provided to allow tests that pollute global service
304 * instances to clean up.
306 * @param string $name
307 * @param bool $destroy Whether the service instance should be destroyed if it exists.
308 * When set to false, any existing service instance will effectively be detached
309 * from the container.
311 * @throws MWException if called outside of PHPUnit tests.
313 public function resetServiceForTesting( $name, $destroy = true ) {
314 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
315 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
318 $this->resetService( $name, $destroy );
322 * Convenience method that throws an exception unless it is called during a phase in which
323 * resetting of global services is allowed. In general, services should not be reset
324 * individually, since that may introduce inconsistencies.
326 * @since 1.28
328 * This method will throw an exception if:
330 * - self::$resetInProgress is false (to allow all services to be reset together
331 * via resetGlobalInstance)
332 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
333 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
335 * This method is intended to be used to safeguard against accidentally resetting
336 * global service instances that are not yet managed by MediaWikiServices. It is
337 * defined here in the MediaWikiServices services class to have a central place
338 * for managing service bootstrapping and resetting.
340 * @param string $method the name of the caller method, as given by __METHOD__.
342 * @throws MWException if called outside bootstrap mode.
344 * @see resetGlobalInstance()
345 * @see forceGlobalInstance()
346 * @see disableStorageBackend()
348 public static function failIfResetNotAllowed( $method ) {
349 if ( !defined( 'MW_PHPUNIT_TEST' )
350 && !defined( 'MW_PARSER_TEST' )
351 && !defined( 'MEDIAWIKI_INSTALL' )
352 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
353 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
355 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
360 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
361 * This has to contain at least the information needed to set up the 'ConfigFactory'
362 * service.
364 public function __construct( Config $config ) {
365 parent::__construct();
367 // Register the given Config object as the bootstrap config service.
368 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
369 return $config;
370 } );
373 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
376 * Returns the Config object containing the bootstrap configuration.
377 * Bootstrap configuration would typically include database credentials
378 * and other information that may be needed before the ConfigFactory
379 * service can be instantiated.
381 * @note This should only be used during bootstrapping, in particular
382 * when creating the MainConfig service. Application logic should
383 * use getMainConfig() to get a Config instances.
385 * @since 1.27
386 * @return Config
388 public function getBootstrapConfig() {
389 return $this->getService( 'BootstrapConfig' );
393 * @since 1.27
394 * @return ConfigFactory
396 public function getConfigFactory() {
397 return $this->getService( 'ConfigFactory' );
401 * Returns the Config object that provides configuration for MediaWiki core.
402 * This may or may not be the same object that is returned by getBootstrapConfig().
404 * @since 1.27
405 * @return Config
407 public function getMainConfig() {
408 return $this->getService( 'MainConfig' );
412 * @since 1.27
413 * @return SiteLookup
415 public function getSiteLookup() {
416 return $this->getService( 'SiteLookup' );
420 * @since 1.27
421 * @return SiteStore
423 public function getSiteStore() {
424 return $this->getService( 'SiteStore' );
428 * @since 1.28
429 * @return InterwikiLookup
431 public function getInterwikiLookup() {
432 return $this->getService( 'InterwikiLookup' );
436 * @since 1.27
437 * @return StatsdDataFactory
439 public function getStatsdDataFactory() {
440 return $this->getService( 'StatsdDataFactory' );
444 * @since 1.27
445 * @return EventRelayerGroup
447 public function getEventRelayerGroup() {
448 return $this->getService( 'EventRelayerGroup' );
452 * @since 1.27
453 * @return SearchEngine
455 public function newSearchEngine() {
456 // New engine object every time, since they keep state
457 return $this->getService( 'SearchEngineFactory' )->create();
461 * @since 1.27
462 * @return SearchEngineFactory
464 public function getSearchEngineFactory() {
465 return $this->getService( 'SearchEngineFactory' );
469 * @since 1.27
470 * @return SearchEngineConfig
472 public function getSearchEngineConfig() {
473 return $this->getService( 'SearchEngineConfig' );
477 * @since 1.27
478 * @return SkinFactory
480 public function getSkinFactory() {
481 return $this->getService( 'SkinFactory' );
485 * @since 1.28
486 * @return LBFactory
488 public function getDBLoadBalancerFactory() {
489 return $this->getService( 'DBLoadBalancerFactory' );
493 * @since 1.28
494 * @return LoadBalancer The main DB load balancer for the local wiki.
496 public function getDBLoadBalancer() {
497 return $this->getService( 'DBLoadBalancer' );
501 * @since 1.28
502 * @return WatchedItemStore
504 public function getWatchedItemStore() {
505 return $this->getService( 'WatchedItemStore' );
509 * @since 1.28
510 * @return WatchedItemQueryService
512 public function getWatchedItemQueryService() {
513 return $this->getService( 'WatchedItemQueryService' );
517 * @since 1.28
518 * @return MediaHandlerFactory
520 public function getMediaHandlerFactory() {
521 return $this->getService( 'MediaHandlerFactory' );
525 * @since 1.28
526 * @return GenderCache
528 public function getGenderCache() {
529 return $this->getService( 'GenderCache' );
533 * @since 1.28
534 * @return LinkCache
536 public function getLinkCache() {
537 return $this->getService( 'LinkCache' );
541 * @since 1.28
542 * @return LinkRendererFactory
544 public function getLinkRendererFactory() {
545 return $this->getService( 'LinkRendererFactory' );
549 * LinkRenderer instance that can be used
550 * if no custom options are needed
552 * @since 1.28
553 * @return LinkRenderer
555 public function getLinkRenderer() {
556 return $this->getService( 'LinkRenderer' );
560 * @since 1.28
561 * @return TitleFormatter
563 public function getTitleFormatter() {
564 return $this->getService( 'TitleFormatter' );
568 * @since 1.28
569 * @return TitleParser
571 public function getTitleParser() {
572 return $this->getService( 'TitleParser' );
576 * @since 1.28
577 * @return VirtualRESTServiceClient
579 public function getVirtualRESTServiceClient() {
580 return $this->getService( 'VirtualRESTServiceClient' );
583 ///////////////////////////////////////////////////////////////////////////
584 // NOTE: When adding a service getter here, don't forget to add a test
585 // case for it in MediaWikiServicesTest::provideGetters() and in
586 // MediaWikiServicesTest::provideGetService()!
587 ///////////////////////////////////////////////////////////////////////////