Merge "mediawiki.toc: Simplify ternary operator"
[lhc/web/wiklou.git] / includes / MediaWikiServices.php
1 <?php
2 namespace MediaWiki;
3
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;
33
34 /**
35 * Service locator for MediaWiki core services.
36 *
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.
41 *
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.
46 *
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
51 *
52 * @file
53 *
54 * @since 1.27
55 */
56
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.
63 *
64 * Services are defined in the "wiring" array passed to the constructor,
65 * or by calling defineService().
66 *
67 * @see docs/injection.txt for an overview of using dependency injection in the
68 * MediaWiki code base.
69 */
70 class MediaWikiServices extends ServiceContainer {
71
72 /**
73 * @var MediaWikiServices|null
74 */
75 private static $instance = null;
76
77 /**
78 * Returns the global default instance of the top level service locator.
79 *
80 * @since 1.27
81 *
82 * The default instance is initialized using the service instantiator functions
83 * defined in ServiceWiring.php.
84 *
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!
88 *
89 * @return MediaWikiServices
90 */
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' );
99 }
100
101 return self::$instance;
102 }
103
104 /**
105 * Replaces the global MediaWikiServices instance.
106 *
107 * @since 1.28
108 *
109 * @note This is for use in PHPUnit tests only!
110 *
111 * @throws MWException if called outside of PHPUnit tests.
112 *
113 * @param MediaWikiServices $services The new MediaWikiServices object.
114 *
115 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
116 */
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.' );
120 }
121
122 $old = self::getInstance();
123 self::$instance = $services;
124
125 return $old;
126 }
127
128 /**
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().
132 *
133 * @since 1.28
134 *
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.
138 *
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.
148 *
149 * @see forceGlobalInstance()
150 * @see resetGlobalInstance()
151 * @see resetBetweenTest()
152 *
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.
159 *
160 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
161 * See SalvageableService for details.
162 *
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).
166 */
167 public static function resetGlobalInstance( Config $bootstrapConfig = null, $quick = '' ) {
168 if ( self::$instance === null ) {
169 // no global instance yet, nothing to reset
170 return;
171 }
172
173 self::failIfResetNotAllowed( __METHOD__ );
174
175 if ( $bootstrapConfig === null ) {
176 $bootstrapConfig = self::$instance->getBootstrapConfig();
177 }
178
179 $oldInstance = self::$instance;
180
181 self::$instance = self::newInstance( $bootstrapConfig );
182 self::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
183
184 if ( $quick === 'quick' ) {
185 self::$instance->salvage( $oldInstance );
186 } else {
187 $oldInstance->destroy();
188 }
189
190 }
191
192 /**
193 * Salvages the state of any salvageable service instances in $other.
194 *
195 * @note $other will have been destroyed when salvage() returns.
196 *
197 * @param MediaWikiServices $other
198 */
199 private function salvage( self $other ) {
200 foreach ( $this->getServiceNames() as $name ) {
201 // The service could be new in the new instance and not registered in the
202 // other instance (e.g. an extension that was loaded after the instantiation of
203 // the other instance. Skip this service in this case. See T143974
204 try {
205 $oldService = $other->peekService( $name );
206 } catch ( NoSuchServiceException $e ) {
207 continue;
208 }
209
210 if ( $oldService instanceof SalvageableService ) {
211 /** @var SalvageableService $newService */
212 $newService = $this->getService( $name );
213 $newService->salvage( $oldService );
214 }
215 }
216
217 $other->destroy();
218 }
219
220 /**
221 * Creates a new MediaWikiServices instance and initializes it according to the
222 * given $bootstrapConfig. In particular, all wiring files defined in the
223 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
224 *
225 * @param Config|null $bootstrapConfig The Config object to be registered as the
226 * 'BootstrapConfig' service.
227 *
228 * @param string $loadWiring set this to 'load' to load the wiring files specified
229 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
230 *
231 * @return MediaWikiServices
232 * @throws MWException
233 * @throws \FatalError
234 */
235 private static function newInstance( Config $bootstrapConfig, $loadWiring = '' ) {
236 $instance = new self( $bootstrapConfig );
237
238 // Load the default wiring from the specified files.
239 if ( $loadWiring === 'load' ) {
240 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
241 $instance->loadWiringFiles( $wiringFiles );
242 }
243
244 // Provide a traditional hook point to allow extensions to configure services.
245 Hooks::run( 'MediaWikiServices', [ $instance ] );
246
247 return $instance;
248 }
249
250 /**
251 * Disables all storage layer services. After calling this, any attempt to access the
252 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
253 * operation.
254 *
255 * @since 1.28
256 *
257 * @warning This is intended for extreme situations only and should never be used
258 * while serving normal web requests. Legitimate use cases for this method include
259 * the installation process. Test fixtures may also use this, if the fixture relies
260 * on globalState.
261 *
262 * @see resetGlobalInstance()
263 * @see resetChildProcessServices()
264 */
265 public static function disableStorageBackend() {
266 // TODO: also disable some Caches, JobQueues, etc
267 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
268 $services = self::getInstance();
269
270 foreach ( $destroy as $name ) {
271 $services->disableService( $name );
272 }
273
274 ObjectCache::clear();
275 }
276
277 /**
278 * Resets any services that may have become stale after a child process
279 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
280 * to call this method from the parent process.
281 *
282 * @since 1.28
283 *
284 * @note This is intended for use in the context of process forking only!
285 *
286 * @see resetGlobalInstance()
287 * @see disableStorageBackend()
288 */
289 public static function resetChildProcessServices() {
290 // NOTE: for now, just reset everything. Since we don't know the interdependencies
291 // between services, we can't do this more selectively at this time.
292 self::resetGlobalInstance();
293
294 // Child, reseed because there is no bug in PHP:
295 // http://bugs.php.net/bug.php?id=42465
296 mt_srand( getmypid() );
297 }
298
299 /**
300 * Resets the given service for testing purposes.
301 *
302 * @since 1.28
303 *
304 * @warning This is generally unsafe! Other services may still retain references
305 * to the stale service instance, leading to failures and inconsistencies. Subclasses
306 * may use this method to reset specific services under specific instances, but
307 * it should not be exposed to application logic.
308 *
309 * @note With proper dependency injection used throughout the codebase, this method
310 * should not be needed. It is provided to allow tests that pollute global service
311 * instances to clean up.
312 *
313 * @param string $name
314 * @param bool $destroy Whether the service instance should be destroyed if it exists.
315 * When set to false, any existing service instance will effectively be detached
316 * from the container.
317 *
318 * @throws MWException if called outside of PHPUnit tests.
319 */
320 public function resetServiceForTesting( $name, $destroy = true ) {
321 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
322 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
323 }
324
325 $this->resetService( $name, $destroy );
326 }
327
328 /**
329 * Convenience method that throws an exception unless it is called during a phase in which
330 * resetting of global services is allowed. In general, services should not be reset
331 * individually, since that may introduce inconsistencies.
332 *
333 * @since 1.28
334 *
335 * This method will throw an exception if:
336 *
337 * - self::$resetInProgress is false (to allow all services to be reset together
338 * via resetGlobalInstance)
339 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
340 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
341 *
342 * This method is intended to be used to safeguard against accidentally resetting
343 * global service instances that are not yet managed by MediaWikiServices. It is
344 * defined here in the MediaWikiServices services class to have a central place
345 * for managing service bootstrapping and resetting.
346 *
347 * @param string $method the name of the caller method, as given by __METHOD__.
348 *
349 * @throws MWException if called outside bootstrap mode.
350 *
351 * @see resetGlobalInstance()
352 * @see forceGlobalInstance()
353 * @see disableStorageBackend()
354 */
355 public static function failIfResetNotAllowed( $method ) {
356 if ( !defined( 'MW_PHPUNIT_TEST' )
357 && !defined( 'MW_PARSER_TEST' )
358 && !defined( 'MEDIAWIKI_INSTALL' )
359 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
360 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
361 ) {
362 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
363 }
364 }
365
366 /**
367 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
368 * This has to contain at least the information needed to set up the 'ConfigFactory'
369 * service.
370 */
371 public function __construct( Config $config ) {
372 parent::__construct();
373
374 // Register the given Config object as the bootstrap config service.
375 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
376 return $config;
377 } );
378 }
379
380 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
381
382 /**
383 * Returns the Config object containing the bootstrap configuration.
384 * Bootstrap configuration would typically include database credentials
385 * and other information that may be needed before the ConfigFactory
386 * service can be instantiated.
387 *
388 * @note This should only be used during bootstrapping, in particular
389 * when creating the MainConfig service. Application logic should
390 * use getMainConfig() to get a Config instances.
391 *
392 * @since 1.27
393 * @return Config
394 */
395 public function getBootstrapConfig() {
396 return $this->getService( 'BootstrapConfig' );
397 }
398
399 /**
400 * @since 1.27
401 * @return ConfigFactory
402 */
403 public function getConfigFactory() {
404 return $this->getService( 'ConfigFactory' );
405 }
406
407 /**
408 * Returns the Config object that provides configuration for MediaWiki core.
409 * This may or may not be the same object that is returned by getBootstrapConfig().
410 *
411 * @since 1.27
412 * @return Config
413 */
414 public function getMainConfig() {
415 return $this->getService( 'MainConfig' );
416 }
417
418 /**
419 * @since 1.27
420 * @return SiteLookup
421 */
422 public function getSiteLookup() {
423 return $this->getService( 'SiteLookup' );
424 }
425
426 /**
427 * @since 1.27
428 * @return SiteStore
429 */
430 public function getSiteStore() {
431 return $this->getService( 'SiteStore' );
432 }
433
434 /**
435 * @since 1.28
436 * @return InterwikiLookup
437 */
438 public function getInterwikiLookup() {
439 return $this->getService( 'InterwikiLookup' );
440 }
441
442 /**
443 * @since 1.27
444 * @return StatsdDataFactory
445 */
446 public function getStatsdDataFactory() {
447 return $this->getService( 'StatsdDataFactory' );
448 }
449
450 /**
451 * @since 1.27
452 * @return EventRelayerGroup
453 */
454 public function getEventRelayerGroup() {
455 return $this->getService( 'EventRelayerGroup' );
456 }
457
458 /**
459 * @since 1.27
460 * @return SearchEngine
461 */
462 public function newSearchEngine() {
463 // New engine object every time, since they keep state
464 return $this->getService( 'SearchEngineFactory' )->create();
465 }
466
467 /**
468 * @since 1.27
469 * @return SearchEngineFactory
470 */
471 public function getSearchEngineFactory() {
472 return $this->getService( 'SearchEngineFactory' );
473 }
474
475 /**
476 * @since 1.27
477 * @return SearchEngineConfig
478 */
479 public function getSearchEngineConfig() {
480 return $this->getService( 'SearchEngineConfig' );
481 }
482
483 /**
484 * @since 1.27
485 * @return SkinFactory
486 */
487 public function getSkinFactory() {
488 return $this->getService( 'SkinFactory' );
489 }
490
491 /**
492 * @since 1.28
493 * @return LBFactory
494 */
495 public function getDBLoadBalancerFactory() {
496 return $this->getService( 'DBLoadBalancerFactory' );
497 }
498
499 /**
500 * @since 1.28
501 * @return LoadBalancer The main DB load balancer for the local wiki.
502 */
503 public function getDBLoadBalancer() {
504 return $this->getService( 'DBLoadBalancer' );
505 }
506
507 /**
508 * @since 1.28
509 * @return WatchedItemStore
510 */
511 public function getWatchedItemStore() {
512 return $this->getService( 'WatchedItemStore' );
513 }
514
515 /**
516 * @since 1.28
517 * @return WatchedItemQueryService
518 */
519 public function getWatchedItemQueryService() {
520 return $this->getService( 'WatchedItemQueryService' );
521 }
522
523 /**
524 * @since 1.28
525 * @return MediaHandlerFactory
526 */
527 public function getMediaHandlerFactory() {
528 return $this->getService( 'MediaHandlerFactory' );
529 }
530
531 /**
532 * @since 1.28
533 * @return GenderCache
534 */
535 public function getGenderCache() {
536 return $this->getService( 'GenderCache' );
537 }
538
539 /**
540 * @since 1.28
541 * @return LinkCache
542 */
543 public function getLinkCache() {
544 return $this->getService( 'LinkCache' );
545 }
546
547 /**
548 * @since 1.28
549 * @return LinkRendererFactory
550 */
551 public function getLinkRendererFactory() {
552 return $this->getService( 'LinkRendererFactory' );
553 }
554
555 /**
556 * LinkRenderer instance that can be used
557 * if no custom options are needed
558 *
559 * @since 1.28
560 * @return LinkRenderer
561 */
562 public function getLinkRenderer() {
563 return $this->getService( 'LinkRenderer' );
564 }
565
566 /**
567 * @since 1.28
568 * @return TitleFormatter
569 */
570 public function getTitleFormatter() {
571 return $this->getService( 'TitleFormatter' );
572 }
573
574 /**
575 * @since 1.28
576 * @return TitleParser
577 */
578 public function getTitleParser() {
579 return $this->getService( 'TitleParser' );
580 }
581
582 /**
583 * @since 1.28
584 * @return VirtualRESTServiceClient
585 */
586 public function getVirtualRESTServiceClient() {
587 return $this->getService( 'VirtualRESTServiceClient' );
588 }
589
590 ///////////////////////////////////////////////////////////////////////////
591 // NOTE: When adding a service getter here, don't forget to add a test
592 // case for it in MediaWikiServicesTest::provideGetters() and in
593 // MediaWikiServicesTest::provideGetService()!
594 ///////////////////////////////////////////////////////////////////////////
595
596 }