Revert "Convert Special:WhatLinksHere from XML form to OOUI form"
[lhc/web/wiklou.git] / includes / MediaWikiServices.php
1 <?php
2 namespace MediaWiki;
3
4 use Config;
5 use ConfigFactory;
6 use EventRelayerGroup;
7 use GlobalVarConfig;
8 use Hooks;
9 use LBFactory;
10 use Liuggio\StatsdClient\Factory\StatsdDataFactory;
11 use LoadBalancer;
12 use MediaWiki\Services\ServiceContainer;
13 use MWException;
14 use ResourceLoader;
15 use SearchEngine;
16 use SearchEngineConfig;
17 use SearchEngineFactory;
18 use SiteLookup;
19 use SiteStore;
20 use WatchedItemStore;
21 use SkinFactory;
22
23 /**
24 * Service locator for MediaWiki core services.
25 *
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 2 of the License, or
29 * (at your option) any later version.
30 *
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
35 *
36 * You should have received a copy of the GNU General Public License along
37 * with this program; if not, write to the Free Software Foundation, Inc.,
38 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
39 * http://www.gnu.org/copyleft/gpl.html
40 *
41 * @file
42 *
43 * @since 1.27
44 */
45
46 /**
47 * MediaWikiServices is the service locator for the application scope of MediaWiki.
48 * Its implemented as a simple configurable DI container.
49 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
50 * the network of service objects that defines MediaWiki's application logic.
51 * It acts as an entry point to MediaWiki's dependency injection mechanism.
52 *
53 * Services are defined in the "wiring" array passed to the constructor,
54 * or by calling defineService().
55 *
56 * @see docs/injection.txt for an overview of using dependency injection in the
57 * MediaWiki code base.
58 */
59 class MediaWikiServices extends ServiceContainer {
60
61 /**
62 * @var MediaWikiServices|null
63 */
64 private static $instance = null;
65
66 /**
67 * Returns the global default instance of the top level service locator.
68 *
69 * @since 1.27
70 *
71 * The default instance is initialized using the service instantiator functions
72 * defined in ServiceWiring.php.
73 *
74 * @note This should only be called by static functions! The instance returned here
75 * should not be passed around! Objects that need access to a service should have
76 * that service injected into the constructor, never a service locator!
77 *
78 * @return MediaWikiServices
79 */
80 public static function getInstance() {
81 if ( self::$instance === null ) {
82 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
83 // but some information from the global scope has to be injected here,
84 // even if it's just a file name or database credentials to load
85 // configuration from.
86 $bootstrapConfig = new GlobalVarConfig();
87 self::$instance = self::newInstance( $bootstrapConfig );
88 }
89
90 return self::$instance;
91 }
92
93 /**
94 * Replaces the global MediaWikiServices instance.
95 *
96 * @since 1.28
97 *
98 * @note This is for use in PHPUnit tests only!
99 *
100 * @throws MWException if called outside of PHPUnit tests.
101 *
102 * @param MediaWikiServices $services The new MediaWikiServices object.
103 *
104 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
105 */
106 public static function forceGlobalInstance( MediaWikiServices $services ) {
107 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
108 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
109 }
110
111 $old = self::getInstance();
112 self::$instance = $services;
113
114 return $old;
115 }
116
117 /**
118 * Creates a new instance of MediaWikiServices and sets it as the global default
119 * instance. getInstance() will return a different MediaWikiServices object
120 * after every call to resetGlobalServiceLocator().
121 *
122 * @since 1.28
123 *
124 * @warning This should not be used during normal operation. It is intended for use
125 * when the configuration has changed significantly since bootstrap time, e.g.
126 * during the installation process or during testing.
127 *
128 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
129 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
130 * any of the services managed by MediaWikiServices exist. If any service objects
131 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
132 * with the operation of the services managed by the new MediaWikiServices.
133 * Operating with a mix of services created by the old and the new
134 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
135 * Any class implementing LAZY LOADING is especially prone to this problem,
136 * since instances would typically retain a reference to a storage layer service.
137 *
138 * @see forceGlobalInstance()
139 * @see resetGlobalInstance()
140 * @see resetBetweenTest()
141 *
142 * @param Config|null $bootstrapConfig The Config object to be registered as the
143 * 'BootstrapConfig' service. This has to contain at least the information
144 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
145 * config of the old instance of MediaWikiServices will be re-used. If there
146 * was no previous instance, a new GlobalVarConfig object will be used to
147 * bootstrap the services.
148 *
149 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
150 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
151 * is defined).
152 */
153 public static function resetGlobalInstance( Config $bootstrapConfig = null ) {
154 if ( self::$instance === null ) {
155 // no global instance yet, nothing to reset
156 return;
157 }
158
159 self::failIfResetNotAllowed( __METHOD__ );
160
161 if ( $bootstrapConfig === null ) {
162 $bootstrapConfig = self::$instance->getBootstrapConfig();
163 }
164
165 self::$instance->destroy();
166
167 self::$instance = self::newInstance( $bootstrapConfig );
168 }
169
170 /**
171 * Creates a new MediaWikiServices instance and initializes it according to the
172 * given $bootstrapConfig. In particular, all wiring files defined in the
173 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
174 *
175 * @param Config|null $bootstrapConfig The Config object to be registered as the
176 * 'BootstrapConfig' service. This has to contain at least the information
177 * needed to set up the 'ConfigFactory' service. If not provided, any call
178 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
179 * A MediaWikiServices instance without access to configuration is called
180 * "primordial".
181 *
182 * @return MediaWikiServices
183 * @throws MWException
184 */
185 private static function newInstance( Config $bootstrapConfig ) {
186 $instance = new self( $bootstrapConfig );
187
188 // Load the default wiring from the specified files.
189 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
190 $instance->loadWiringFiles( $wiringFiles );
191
192 // Provide a traditional hook point to allow extensions to configure services.
193 Hooks::run( 'MediaWikiServices', [ $instance ] );
194
195 return $instance;
196 }
197
198 /**
199 * Disables all storage layer services. After calling this, any attempt to access the
200 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
201 * operation.
202 *
203 * @since 1.28
204 *
205 * @warning This is intended for extreme situations only and should never be used
206 * while serving normal web requests. Legitimate use cases for this method include
207 * the installation process. Test fixtures may also use this, if the fixture relies
208 * on globalState.
209 *
210 * @see resetGlobalInstance()
211 * @see resetChildProcessServices()
212 */
213 public static function disableStorageBackend() {
214 // TODO: also disable some Caches, JobQueues, etc
215 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
216 $services = self::getInstance();
217
218 foreach ( $destroy as $name ) {
219 $services->disableService( $name );
220 }
221 }
222
223 /**
224 * Resets any services that may have become stale after a child process
225 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
226 * to call this method from the parent process.
227 *
228 * @since 1.28
229 *
230 * @note This is intended for use in the context of process forking only!
231 *
232 * @see resetGlobalInstance()
233 * @see disableStorageBackend()
234 */
235 public static function resetChildProcessServices() {
236 // NOTE: for now, just reset everything. Since we don't know the interdependencies
237 // between services, we can't do this more selectively at this time.
238 self::resetGlobalInstance();
239
240 // Child, reseed because there is no bug in PHP:
241 // http://bugs.php.net/bug.php?id=42465
242 mt_srand( getmypid() );
243 }
244
245 /**
246 * Resets the given service for testing purposes.
247 *
248 * @since 1.28
249 *
250 * @warning This is generally unsafe! Other services may still retain references
251 * to the stale service instance, leading to failures and inconsistencies. Subclasses
252 * may use this method to reset specific services under specific instances, but
253 * it should not be exposed to application logic.
254 *
255 * @note With proper dependency injection used throughout the codebase, this method
256 * should not be needed. It is provided to allow tests that pollute global service
257 * instances to clean up.
258 *
259 * @param string $name
260 * @param string $destroy Whether the service instance should be destroyed if it exists.
261 * When set to false, any existing service instance will effectively be detached
262 * from the container.
263 *
264 * @throws MWException if called outside of PHPUnit tests.
265 */
266 public function resetServiceForTesting( $name, $destroy = true ) {
267 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
268 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
269 }
270
271 $this->resetService( $name, $destroy );
272 }
273
274 /**
275 * Convenience method that throws an exception unless it is called during a phase in which
276 * resetting of global services is allowed. In general, services should not be reset
277 * individually, since that may introduce inconsistencies.
278 *
279 * @since 1.28
280 *
281 * This method will throw an exception if:
282 *
283 * - self::$resetInProgress is false (to allow all services to be reset together
284 * via resetGlobalInstance)
285 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
286 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
287 *
288 * This method is intended to be used to safeguard against accidentally resetting
289 * global service instances that are not yet managed by MediaWikiServices. It is
290 * defined here in the MediaWikiServices services class to have a central place
291 * for managing service bootstrapping and resetting.
292 *
293 * @param string $method the name of the caller method, as given by __METHOD__.
294 *
295 * @throws MWException if called outside bootstrap mode.
296 *
297 * @see resetGlobalInstance()
298 * @see forceGlobalInstance()
299 * @see disableStorageBackend()
300 */
301 public static function failIfResetNotAllowed( $method ) {
302 if ( !defined( 'MW_PHPUNIT_TEST' )
303 && !defined( 'MW_PARSER_TEST' )
304 && !defined( 'MEDIAWIKI_INSTALL' )
305 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
306 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
307 ) {
308 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
309 }
310 }
311
312 /**
313 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
314 * This has to contain at least the information needed to set up the 'ConfigFactory'
315 * service.
316 */
317 public function __construct( Config $config ) {
318 parent::__construct();
319
320 // Register the given Config object as the bootstrap config service.
321 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
322 return $config;
323 } );
324 }
325
326 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
327
328 /**
329 * Returns the Config object containing the bootstrap configuration.
330 * Bootstrap configuration would typically include database credentials
331 * and other information that may be needed before the ConfigFactory
332 * service can be instantiated.
333 *
334 * @note This should only be used during bootstrapping, in particular
335 * when creating the MainConfig service. Application logic should
336 * use getMainConfig() to get a Config instances.
337 *
338 * @since 1.27
339 * @return Config
340 */
341 public function getBootstrapConfig() {
342 return $this->getService( 'BootstrapConfig' );
343 }
344
345 /**
346 * @since 1.27
347 * @return ConfigFactory
348 */
349 public function getConfigFactory() {
350 return $this->getService( 'ConfigFactory' );
351 }
352
353 /**
354 * Returns the Config object that provides configuration for MediaWiki core.
355 * This may or may not be the same object that is returned by getBootstrapConfig().
356 *
357 * @since 1.27
358 * @return Config
359 */
360 public function getMainConfig() {
361 return $this->getService( 'MainConfig' );
362 }
363
364 /**
365 * @since 1.27
366 * @return SiteLookup
367 */
368 public function getSiteLookup() {
369 return $this->getService( 'SiteLookup' );
370 }
371
372 /**
373 * @since 1.27
374 * @return SiteStore
375 */
376 public function getSiteStore() {
377 return $this->getService( 'SiteStore' );
378 }
379
380 /**
381 * @since 1.27
382 * @return StatsdDataFactory
383 */
384 public function getStatsdDataFactory() {
385 return $this->getService( 'StatsdDataFactory' );
386 }
387
388 /**
389 * @since 1.27
390 * @return EventRelayerGroup
391 */
392 public function getEventRelayerGroup() {
393 return $this->getService( 'EventRelayerGroup' );
394 }
395
396 /**
397 * @since 1.27
398 * @return SearchEngine
399 */
400 public function newSearchEngine() {
401 // New engine object every time, since they keep state
402 return $this->getService( 'SearchEngineFactory' )->create();
403 }
404
405 /**
406 * @since 1.27
407 * @return SearchEngineFactory
408 */
409 public function getSearchEngineFactory() {
410 return $this->getService( 'SearchEngineFactory' );
411 }
412
413 /**
414 * @since 1.27
415 * @return SearchEngineConfig
416 */
417 public function getSearchEngineConfig() {
418 return $this->getService( 'SearchEngineConfig' );
419 }
420
421 /**
422 * @since 1.27
423 * @return SkinFactory
424 */
425 public function getSkinFactory() {
426 return $this->getService( 'SkinFactory' );
427 }
428
429 /**
430 * @since 1.28
431 * @return LBFactory
432 */
433 public function getDBLoadBalancerFactory() {
434 return $this->getService( 'DBLoadBalancerFactory' );
435 }
436
437 /**
438 * @since 1.28
439 * @return LoadBalancer The main DB load balancer for the local wiki.
440 */
441 public function getDBLoadBalancer() {
442 return $this->getService( 'DBLoadBalancer' );
443 }
444
445 /**
446 * @since 1.28
447 * @return WatchedItemStore
448 */
449 public function getWatchedItemStore() {
450 return $this->getService( 'WatchedItemStore' );
451 }
452
453 ///////////////////////////////////////////////////////////////////////////
454 // NOTE: When adding a service getter here, don't forget to add a test
455 // case for it in MediaWikiServicesTest::provideGetters() and in
456 // MediaWikiServicesTest::provideGetService()!
457 ///////////////////////////////////////////////////////////////////////////
458
459 }