AuthManager: Commit transaction after auto-creating a user
[mediawiki.git] / includes / MediaWikiServices.php
blobff292cfb617532ad35113e17ad24ff34987336d0
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 MediaWiki\Linker\LinkRenderer;
15 use MediaWiki\Linker\LinkRendererFactory;
16 use MediaWiki\Services\SalvageableService;
17 use MediaWiki\Services\ServiceContainer;
18 use MWException;
19 use ObjectCache;
20 use SearchEngine;
21 use SearchEngineConfig;
22 use SearchEngineFactory;
23 use SiteLookup;
24 use SiteStore;
25 use WatchedItemStore;
26 use WatchedItemQueryService;
27 use SkinFactory;
28 use TitleFormatter;
29 use TitleParser;
30 use MediaWiki\Interwiki\InterwikiLookup;
32 /**
33 * Service locator for MediaWiki core services.
35 * This program is free software; you can redistribute it and/or modify
36 * it under the terms of the GNU General Public License as published by
37 * the Free Software Foundation; either version 2 of the License, or
38 * (at your option) any later version.
40 * This program is distributed in the hope that it will be useful,
41 * but WITHOUT ANY WARRANTY; without even the implied warranty of
42 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 * GNU General Public License for more details.
45 * You should have received a copy of the GNU General Public License along
46 * with this program; if not, write to the Free Software Foundation, Inc.,
47 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
48 * http://www.gnu.org/copyleft/gpl.html
50 * @file
52 * @since 1.27
55 /**
56 * MediaWikiServices is the service locator for the application scope of MediaWiki.
57 * Its implemented as a simple configurable DI container.
58 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
59 * the network of service objects that defines MediaWiki's application logic.
60 * It acts as an entry point to MediaWiki's dependency injection mechanism.
62 * Services are defined in the "wiring" array passed to the constructor,
63 * or by calling defineService().
65 * @see docs/injection.txt for an overview of using dependency injection in the
66 * MediaWiki code base.
68 class MediaWikiServices extends ServiceContainer {
70 /**
71 * @var MediaWikiServices|null
73 private static $instance = null;
75 /**
76 * Returns the global default instance of the top level service locator.
78 * @since 1.27
80 * The default instance is initialized using the service instantiator functions
81 * defined in ServiceWiring.php.
83 * @note This should only be called by static functions! The instance returned here
84 * should not be passed around! Objects that need access to a service should have
85 * that service injected into the constructor, never a service locator!
87 * @return MediaWikiServices
89 public static function getInstance() {
90 if ( self::$instance === null ) {
91 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
92 // but some information from the global scope has to be injected here,
93 // even if it's just a file name or database credentials to load
94 // configuration from.
95 $bootstrapConfig = new GlobalVarConfig();
96 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
99 return self::$instance;
103 * Replaces the global MediaWikiServices instance.
105 * @since 1.28
107 * @note This is for use in PHPUnit tests only!
109 * @throws MWException if called outside of PHPUnit tests.
111 * @param MediaWikiServices $services The new MediaWikiServices object.
113 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
115 public static function forceGlobalInstance( MediaWikiServices $services ) {
116 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
117 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
120 $old = self::getInstance();
121 self::$instance = $services;
123 return $old;
127 * Creates a new instance of MediaWikiServices and sets it as the global default
128 * instance. getInstance() will return a different MediaWikiServices object
129 * after every call to resetGlobalInstance().
131 * @since 1.28
133 * @warning This should not be used during normal operation. It is intended for use
134 * when the configuration has changed significantly since bootstrap time, e.g.
135 * during the installation process or during testing.
137 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
138 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
139 * any of the services managed by MediaWikiServices exist. If any service objects
140 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
141 * with the operation of the services managed by the new MediaWikiServices.
142 * Operating with a mix of services created by the old and the new
143 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
144 * Any class implementing LAZY LOADING is especially prone to this problem,
145 * since instances would typically retain a reference to a storage layer service.
147 * @see forceGlobalInstance()
148 * @see resetGlobalInstance()
149 * @see resetBetweenTest()
151 * @param Config|null $bootstrapConfig The Config object to be registered as the
152 * 'BootstrapConfig' service. This has to contain at least the information
153 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
154 * config of the old instance of MediaWikiServices will be re-used. If there
155 * was no previous instance, a new GlobalVarConfig object will be used to
156 * bootstrap the services.
158 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
159 * See SalvageableService for details.
161 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
162 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
163 * is defined).
165 public static function resetGlobalInstance( Config $bootstrapConfig = null, $quick = '' ) {
166 if ( self::$instance === null ) {
167 // no global instance yet, nothing to reset
168 return;
171 self::failIfResetNotAllowed( __METHOD__ );
173 if ( $bootstrapConfig === null ) {
174 $bootstrapConfig = self::$instance->getBootstrapConfig();
177 $oldInstance = self::$instance;
179 self::$instance = self::newInstance( $bootstrapConfig );
180 self::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
182 if ( $quick === 'quick' ) {
183 self::$instance->salvage( $oldInstance );
184 } else {
185 $oldInstance->destroy();
191 * Salvages the state of any salvageable service instances in $other.
193 * @note $other will have been destroyed when salvage() returns.
195 * @param MediaWikiServices $other
197 private function salvage( self $other ) {
198 foreach ( $this->getServiceNames() as $name ) {
199 $oldService = $other->peekService( $name );
201 if ( $oldService instanceof SalvageableService ) {
202 /** @var SalvageableService $newService */
203 $newService = $this->getService( $name );
204 $newService->salvage( $oldService );
208 $other->destroy();
212 * Creates a new MediaWikiServices instance and initializes it according to the
213 * given $bootstrapConfig. In particular, all wiring files defined in the
214 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
216 * @param Config|null $bootstrapConfig The Config object to be registered as the
217 * 'BootstrapConfig' service.
219 * @param string $loadWiring set this to 'load' to load the wiring files specified
220 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
222 * @return MediaWikiServices
223 * @throws MWException
224 * @throws \FatalError
226 private static function newInstance( Config $bootstrapConfig, $loadWiring = '' ) {
227 $instance = new self( $bootstrapConfig );
229 // Load the default wiring from the specified files.
230 if ( $loadWiring === 'load' ) {
231 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
232 $instance->loadWiringFiles( $wiringFiles );
235 // Provide a traditional hook point to allow extensions to configure services.
236 Hooks::run( 'MediaWikiServices', [ $instance ] );
238 return $instance;
242 * Disables all storage layer services. After calling this, any attempt to access the
243 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
244 * operation.
246 * @since 1.28
248 * @warning This is intended for extreme situations only and should never be used
249 * while serving normal web requests. Legitimate use cases for this method include
250 * the installation process. Test fixtures may also use this, if the fixture relies
251 * on globalState.
253 * @see resetGlobalInstance()
254 * @see resetChildProcessServices()
256 public static function disableStorageBackend() {
257 // TODO: also disable some Caches, JobQueues, etc
258 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
259 $services = self::getInstance();
261 foreach ( $destroy as $name ) {
262 $services->disableService( $name );
265 ObjectCache::clear();
269 * Resets any services that may have become stale after a child process
270 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
271 * to call this method from the parent process.
273 * @since 1.28
275 * @note This is intended for use in the context of process forking only!
277 * @see resetGlobalInstance()
278 * @see disableStorageBackend()
280 public static function resetChildProcessServices() {
281 // NOTE: for now, just reset everything. Since we don't know the interdependencies
282 // between services, we can't do this more selectively at this time.
283 self::resetGlobalInstance();
285 // Child, reseed because there is no bug in PHP:
286 // http://bugs.php.net/bug.php?id=42465
287 mt_srand( getmypid() );
291 * Resets the given service for testing purposes.
293 * @since 1.28
295 * @warning This is generally unsafe! Other services may still retain references
296 * to the stale service instance, leading to failures and inconsistencies. Subclasses
297 * may use this method to reset specific services under specific instances, but
298 * it should not be exposed to application logic.
300 * @note With proper dependency injection used throughout the codebase, this method
301 * should not be needed. It is provided to allow tests that pollute global service
302 * instances to clean up.
304 * @param string $name
305 * @param bool $destroy Whether the service instance should be destroyed if it exists.
306 * When set to false, any existing service instance will effectively be detached
307 * from the container.
309 * @throws MWException if called outside of PHPUnit tests.
311 public function resetServiceForTesting( $name, $destroy = true ) {
312 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
313 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
316 $this->resetService( $name, $destroy );
320 * Convenience method that throws an exception unless it is called during a phase in which
321 * resetting of global services is allowed. In general, services should not be reset
322 * individually, since that may introduce inconsistencies.
324 * @since 1.28
326 * This method will throw an exception if:
328 * - self::$resetInProgress is false (to allow all services to be reset together
329 * via resetGlobalInstance)
330 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
331 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
333 * This method is intended to be used to safeguard against accidentally resetting
334 * global service instances that are not yet managed by MediaWikiServices. It is
335 * defined here in the MediaWikiServices services class to have a central place
336 * for managing service bootstrapping and resetting.
338 * @param string $method the name of the caller method, as given by __METHOD__.
340 * @throws MWException if called outside bootstrap mode.
342 * @see resetGlobalInstance()
343 * @see forceGlobalInstance()
344 * @see disableStorageBackend()
346 public static function failIfResetNotAllowed( $method ) {
347 if ( !defined( 'MW_PHPUNIT_TEST' )
348 && !defined( 'MW_PARSER_TEST' )
349 && !defined( 'MEDIAWIKI_INSTALL' )
350 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
351 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
353 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
358 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
359 * This has to contain at least the information needed to set up the 'ConfigFactory'
360 * service.
362 public function __construct( Config $config ) {
363 parent::__construct();
365 // Register the given Config object as the bootstrap config service.
366 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
367 return $config;
368 } );
371 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
374 * Returns the Config object containing the bootstrap configuration.
375 * Bootstrap configuration would typically include database credentials
376 * and other information that may be needed before the ConfigFactory
377 * service can be instantiated.
379 * @note This should only be used during bootstrapping, in particular
380 * when creating the MainConfig service. Application logic should
381 * use getMainConfig() to get a Config instances.
383 * @since 1.27
384 * @return Config
386 public function getBootstrapConfig() {
387 return $this->getService( 'BootstrapConfig' );
391 * @since 1.27
392 * @return ConfigFactory
394 public function getConfigFactory() {
395 return $this->getService( 'ConfigFactory' );
399 * Returns the Config object that provides configuration for MediaWiki core.
400 * This may or may not be the same object that is returned by getBootstrapConfig().
402 * @since 1.27
403 * @return Config
405 public function getMainConfig() {
406 return $this->getService( 'MainConfig' );
410 * @since 1.27
411 * @return SiteLookup
413 public function getSiteLookup() {
414 return $this->getService( 'SiteLookup' );
418 * @since 1.27
419 * @return SiteStore
421 public function getSiteStore() {
422 return $this->getService( 'SiteStore' );
426 * @since 1.28
427 * @return InterwikiLookup
429 public function getInterwikiLookup() {
430 return $this->getService( 'InterwikiLookup' );
434 * @since 1.27
435 * @return StatsdDataFactory
437 public function getStatsdDataFactory() {
438 return $this->getService( 'StatsdDataFactory' );
442 * @since 1.27
443 * @return EventRelayerGroup
445 public function getEventRelayerGroup() {
446 return $this->getService( 'EventRelayerGroup' );
450 * @since 1.27
451 * @return SearchEngine
453 public function newSearchEngine() {
454 // New engine object every time, since they keep state
455 return $this->getService( 'SearchEngineFactory' )->create();
459 * @since 1.27
460 * @return SearchEngineFactory
462 public function getSearchEngineFactory() {
463 return $this->getService( 'SearchEngineFactory' );
467 * @since 1.27
468 * @return SearchEngineConfig
470 public function getSearchEngineConfig() {
471 return $this->getService( 'SearchEngineConfig' );
475 * @since 1.27
476 * @return SkinFactory
478 public function getSkinFactory() {
479 return $this->getService( 'SkinFactory' );
483 * @since 1.28
484 * @return LBFactory
486 public function getDBLoadBalancerFactory() {
487 return $this->getService( 'DBLoadBalancerFactory' );
491 * @since 1.28
492 * @return LoadBalancer The main DB load balancer for the local wiki.
494 public function getDBLoadBalancer() {
495 return $this->getService( 'DBLoadBalancer' );
499 * @since 1.28
500 * @return WatchedItemStore
502 public function getWatchedItemStore() {
503 return $this->getService( 'WatchedItemStore' );
507 * @since 1.28
508 * @return WatchedItemQueryService
510 public function getWatchedItemQueryService() {
511 return $this->getService( 'WatchedItemQueryService' );
515 * @since 1.28
516 * @return GenderCache
518 public function getGenderCache() {
519 return $this->getService( 'GenderCache' );
523 * @since 1.28
524 * @return LinkCache
526 public function getLinkCache() {
527 return $this->getService( 'LinkCache' );
531 * @since 1.28
532 * @return LinkRendererFactory
534 public function getLinkRendererFactory() {
535 return $this->getService( 'LinkRendererFactory' );
539 * LinkRenderer instance that can be used
540 * if no custom options are needed
542 * @since 1.28
543 * @return LinkRenderer
545 public function getLinkRenderer() {
546 return $this->getService( 'LinkRenderer' );
550 * @since 1.28
551 * @return TitleFormatter
553 public function getTitleFormatter() {
554 return $this->getService( 'TitleFormatter' );
558 * @since 1.28
559 * @return TitleParser
561 public function getTitleParser() {
562 return $this->getService( 'TitleParser' );
565 ///////////////////////////////////////////////////////////////////////////
566 // NOTE: When adding a service getter here, don't forget to add a test
567 // case for it in MediaWikiServicesTest::provideGetters() and in
568 // MediaWikiServicesTest::provideGetService()!
569 ///////////////////////////////////////////////////////////////////////////