Merge "mw.htmlform: Don't refer to OO.ui if it might not be loaded"
[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 $oldService = $other->peekService( $name );
202
203 if ( $oldService instanceof SalvageableService ) {
204 /** @var SalvageableService $newService */
205 $newService = $this->getService( $name );
206 $newService->salvage( $oldService );
207 }
208 }
209
210 $other->destroy();
211 }
212
213 /**
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.
217 *
218 * @param Config|null $bootstrapConfig The Config object to be registered as the
219 * 'BootstrapConfig' service.
220 *
221 * @param string $loadWiring set this to 'load' to load the wiring files specified
222 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
223 *
224 * @return MediaWikiServices
225 * @throws MWException
226 * @throws \FatalError
227 */
228 private static function newInstance( Config $bootstrapConfig, $loadWiring = '' ) {
229 $instance = new self( $bootstrapConfig );
230
231 // Load the default wiring from the specified files.
232 if ( $loadWiring === 'load' ) {
233 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
234 $instance->loadWiringFiles( $wiringFiles );
235 }
236
237 // Provide a traditional hook point to allow extensions to configure services.
238 Hooks::run( 'MediaWikiServices', [ $instance ] );
239
240 return $instance;
241 }
242
243 /**
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.
247 *
248 * @since 1.28
249 *
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.
254 *
255 * @see resetGlobalInstance()
256 * @see resetChildProcessServices()
257 */
258 public static function disableStorageBackend() {
259 // TODO: also disable some Caches, JobQueues, etc
260 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
261 $services = self::getInstance();
262
263 foreach ( $destroy as $name ) {
264 $services->disableService( $name );
265 }
266
267 ObjectCache::clear();
268 }
269
270 /**
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.
274 *
275 * @since 1.28
276 *
277 * @note This is intended for use in the context of process forking only!
278 *
279 * @see resetGlobalInstance()
280 * @see disableStorageBackend()
281 */
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();
286
287 // Child, reseed because there is no bug in PHP:
288 // http://bugs.php.net/bug.php?id=42465
289 mt_srand( getmypid() );
290 }
291
292 /**
293 * Resets the given service for testing purposes.
294 *
295 * @since 1.28
296 *
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.
301 *
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.
305 *
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.
310 *
311 * @throws MWException if called outside of PHPUnit tests.
312 */
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.' );
316 }
317
318 $this->resetService( $name, $destroy );
319 }
320
321 /**
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.
325 *
326 * @since 1.28
327 *
328 * This method will throw an exception if:
329 *
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)
334 *
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.
339 *
340 * @param string $method the name of the caller method, as given by __METHOD__.
341 *
342 * @throws MWException if called outside bootstrap mode.
343 *
344 * @see resetGlobalInstance()
345 * @see forceGlobalInstance()
346 * @see disableStorageBackend()
347 */
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' )
354 ) {
355 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
356 }
357 }
358
359 /**
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.
363 */
364 public function __construct( Config $config ) {
365 parent::__construct();
366
367 // Register the given Config object as the bootstrap config service.
368 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
369 return $config;
370 } );
371 }
372
373 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
374
375 /**
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.
380 *
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.
384 *
385 * @since 1.27
386 * @return Config
387 */
388 public function getBootstrapConfig() {
389 return $this->getService( 'BootstrapConfig' );
390 }
391
392 /**
393 * @since 1.27
394 * @return ConfigFactory
395 */
396 public function getConfigFactory() {
397 return $this->getService( 'ConfigFactory' );
398 }
399
400 /**
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().
403 *
404 * @since 1.27
405 * @return Config
406 */
407 public function getMainConfig() {
408 return $this->getService( 'MainConfig' );
409 }
410
411 /**
412 * @since 1.27
413 * @return SiteLookup
414 */
415 public function getSiteLookup() {
416 return $this->getService( 'SiteLookup' );
417 }
418
419 /**
420 * @since 1.27
421 * @return SiteStore
422 */
423 public function getSiteStore() {
424 return $this->getService( 'SiteStore' );
425 }
426
427 /**
428 * @since 1.28
429 * @return InterwikiLookup
430 */
431 public function getInterwikiLookup() {
432 return $this->getService( 'InterwikiLookup' );
433 }
434
435 /**
436 * @since 1.27
437 * @return StatsdDataFactory
438 */
439 public function getStatsdDataFactory() {
440 return $this->getService( 'StatsdDataFactory' );
441 }
442
443 /**
444 * @since 1.27
445 * @return EventRelayerGroup
446 */
447 public function getEventRelayerGroup() {
448 return $this->getService( 'EventRelayerGroup' );
449 }
450
451 /**
452 * @since 1.27
453 * @return SearchEngine
454 */
455 public function newSearchEngine() {
456 // New engine object every time, since they keep state
457 return $this->getService( 'SearchEngineFactory' )->create();
458 }
459
460 /**
461 * @since 1.27
462 * @return SearchEngineFactory
463 */
464 public function getSearchEngineFactory() {
465 return $this->getService( 'SearchEngineFactory' );
466 }
467
468 /**
469 * @since 1.27
470 * @return SearchEngineConfig
471 */
472 public function getSearchEngineConfig() {
473 return $this->getService( 'SearchEngineConfig' );
474 }
475
476 /**
477 * @since 1.27
478 * @return SkinFactory
479 */
480 public function getSkinFactory() {
481 return $this->getService( 'SkinFactory' );
482 }
483
484 /**
485 * @since 1.28
486 * @return LBFactory
487 */
488 public function getDBLoadBalancerFactory() {
489 return $this->getService( 'DBLoadBalancerFactory' );
490 }
491
492 /**
493 * @since 1.28
494 * @return LoadBalancer The main DB load balancer for the local wiki.
495 */
496 public function getDBLoadBalancer() {
497 return $this->getService( 'DBLoadBalancer' );
498 }
499
500 /**
501 * @since 1.28
502 * @return WatchedItemStore
503 */
504 public function getWatchedItemStore() {
505 return $this->getService( 'WatchedItemStore' );
506 }
507
508 /**
509 * @since 1.28
510 * @return WatchedItemQueryService
511 */
512 public function getWatchedItemQueryService() {
513 return $this->getService( 'WatchedItemQueryService' );
514 }
515
516 /**
517 * @since 1.28
518 * @return MediaHandlerFactory
519 */
520 public function getMediaHandlerFactory() {
521 return $this->getService( 'MediaHandlerFactory' );
522 }
523
524 /**
525 * @since 1.28
526 * @return GenderCache
527 */
528 public function getGenderCache() {
529 return $this->getService( 'GenderCache' );
530 }
531
532 /**
533 * @since 1.28
534 * @return LinkCache
535 */
536 public function getLinkCache() {
537 return $this->getService( 'LinkCache' );
538 }
539
540 /**
541 * @since 1.28
542 * @return LinkRendererFactory
543 */
544 public function getLinkRendererFactory() {
545 return $this->getService( 'LinkRendererFactory' );
546 }
547
548 /**
549 * LinkRenderer instance that can be used
550 * if no custom options are needed
551 *
552 * @since 1.28
553 * @return LinkRenderer
554 */
555 public function getLinkRenderer() {
556 return $this->getService( 'LinkRenderer' );
557 }
558
559 /**
560 * @since 1.28
561 * @return TitleFormatter
562 */
563 public function getTitleFormatter() {
564 return $this->getService( 'TitleFormatter' );
565 }
566
567 /**
568 * @since 1.28
569 * @return TitleParser
570 */
571 public function getTitleParser() {
572 return $this->getService( 'TitleParser' );
573 }
574
575 /**
576 * @since 1.28
577 * @return VirtualRESTServiceClient
578 */
579 public function getVirtualRESTServiceClient() {
580 return $this->getService( 'VirtualRESTServiceClient' );
581 }
582
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 ///////////////////////////////////////////////////////////////////////////
588
589 }