Merge "Deprecate EditFilterMerged hook, final ContentHandler replaced hook"
[lhc/web/wiklou.git] / includes / MediaWikiServices.php
1 <?php
2 namespace MediaWiki;
3
4 use Config;
5 use ConfigFactory;
6 use CryptRand;
7 use EventRelayerGroup;
8 use GenderCache;
9 use GlobalVarConfig;
10 use Hooks;
11 use LBFactory;
12 use LinkCache;
13 use Liuggio\StatsdClient\Factory\StatsdDataFactory;
14 use LoadBalancer;
15 use MediaHandlerFactory;
16 use MediaWiki\Linker\LinkRenderer;
17 use MediaWiki\Linker\LinkRendererFactory;
18 use MediaWiki\Services\SalvageableService;
19 use MediaWiki\Services\ServiceContainer;
20 use MediaWiki\Services\NoSuchServiceException;
21 use MWException;
22 use MimeAnalyzer;
23 use ObjectCache;
24 use ProxyLookup;
25 use SearchEngine;
26 use SearchEngineConfig;
27 use SearchEngineFactory;
28 use SiteLookup;
29 use SiteStore;
30 use WatchedItemStore;
31 use WatchedItemQueryService;
32 use SkinFactory;
33 use TitleFormatter;
34 use TitleParser;
35 use VirtualRESTServiceClient;
36 use MediaWiki\Interwiki\InterwikiLookup;
37
38 /**
39 * Service locator for MediaWiki core services.
40 *
41 * This program is free software; you can redistribute it and/or modify
42 * it under the terms of the GNU General Public License as published by
43 * the Free Software Foundation; either version 2 of the License, or
44 * (at your option) any later version.
45 *
46 * This program is distributed in the hope that it will be useful,
47 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
49 * GNU General Public License for more details.
50 *
51 * You should have received a copy of the GNU General Public License along
52 * with this program; if not, write to the Free Software Foundation, Inc.,
53 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
54 * http://www.gnu.org/copyleft/gpl.html
55 *
56 * @file
57 *
58 * @since 1.27
59 */
60
61 /**
62 * MediaWikiServices is the service locator for the application scope of MediaWiki.
63 * Its implemented as a simple configurable DI container.
64 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
65 * the network of service objects that defines MediaWiki's application logic.
66 * It acts as an entry point to MediaWiki's dependency injection mechanism.
67 *
68 * Services are defined in the "wiring" array passed to the constructor,
69 * or by calling defineService().
70 *
71 * @see docs/injection.txt for an overview of using dependency injection in the
72 * MediaWiki code base.
73 */
74 class MediaWikiServices extends ServiceContainer {
75
76 /**
77 * @var MediaWikiServices|null
78 */
79 private static $instance = null;
80
81 /**
82 * Returns the global default instance of the top level service locator.
83 *
84 * @since 1.27
85 *
86 * The default instance is initialized using the service instantiator functions
87 * defined in ServiceWiring.php.
88 *
89 * @note This should only be called by static functions! The instance returned here
90 * should not be passed around! Objects that need access to a service should have
91 * that service injected into the constructor, never a service locator!
92 *
93 * @return MediaWikiServices
94 */
95 public static function getInstance() {
96 if ( self::$instance === null ) {
97 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
98 // but some information from the global scope has to be injected here,
99 // even if it's just a file name or database credentials to load
100 // configuration from.
101 $bootstrapConfig = new GlobalVarConfig();
102 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
103 }
104
105 return self::$instance;
106 }
107
108 /**
109 * Replaces the global MediaWikiServices instance.
110 *
111 * @since 1.28
112 *
113 * @note This is for use in PHPUnit tests only!
114 *
115 * @throws MWException if called outside of PHPUnit tests.
116 *
117 * @param MediaWikiServices $services The new MediaWikiServices object.
118 *
119 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
120 */
121 public static function forceGlobalInstance( MediaWikiServices $services ) {
122 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
123 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
124 }
125
126 $old = self::getInstance();
127 self::$instance = $services;
128
129 return $old;
130 }
131
132 /**
133 * Creates a new instance of MediaWikiServices and sets it as the global default
134 * instance. getInstance() will return a different MediaWikiServices object
135 * after every call to resetGlobalInstance().
136 *
137 * @since 1.28
138 *
139 * @warning This should not be used during normal operation. It is intended for use
140 * when the configuration has changed significantly since bootstrap time, e.g.
141 * during the installation process or during testing.
142 *
143 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
144 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
145 * any of the services managed by MediaWikiServices exist. If any service objects
146 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
147 * with the operation of the services managed by the new MediaWikiServices.
148 * Operating with a mix of services created by the old and the new
149 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
150 * Any class implementing LAZY LOADING is especially prone to this problem,
151 * since instances would typically retain a reference to a storage layer service.
152 *
153 * @see forceGlobalInstance()
154 * @see resetGlobalInstance()
155 * @see resetBetweenTest()
156 *
157 * @param Config|null $bootstrapConfig The Config object to be registered as the
158 * 'BootstrapConfig' service. This has to contain at least the information
159 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
160 * config of the old instance of MediaWikiServices will be re-used. If there
161 * was no previous instance, a new GlobalVarConfig object will be used to
162 * bootstrap the services.
163 *
164 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
165 * See SalvageableService for details.
166 *
167 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
168 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
169 * is defined).
170 */
171 public static function resetGlobalInstance( Config $bootstrapConfig = null, $quick = '' ) {
172 if ( self::$instance === null ) {
173 // no global instance yet, nothing to reset
174 return;
175 }
176
177 self::failIfResetNotAllowed( __METHOD__ );
178
179 if ( $bootstrapConfig === null ) {
180 $bootstrapConfig = self::$instance->getBootstrapConfig();
181 }
182
183 $oldInstance = self::$instance;
184
185 self::$instance = self::newInstance( $bootstrapConfig );
186 self::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
187
188 if ( $quick === 'quick' ) {
189 self::$instance->salvage( $oldInstance );
190 } else {
191 $oldInstance->destroy();
192 }
193
194 }
195
196 /**
197 * Salvages the state of any salvageable service instances in $other.
198 *
199 * @note $other will have been destroyed when salvage() returns.
200 *
201 * @param MediaWikiServices $other
202 */
203 private function salvage( self $other ) {
204 foreach ( $this->getServiceNames() as $name ) {
205 // The service could be new in the new instance and not registered in the
206 // other instance (e.g. an extension that was loaded after the instantiation of
207 // the other instance. Skip this service in this case. See T143974
208 try {
209 $oldService = $other->peekService( $name );
210 } catch ( NoSuchServiceException $e ) {
211 continue;
212 }
213
214 if ( $oldService instanceof SalvageableService ) {
215 /** @var SalvageableService $newService */
216 $newService = $this->getService( $name );
217 $newService->salvage( $oldService );
218 }
219 }
220
221 $other->destroy();
222 }
223
224 /**
225 * Creates a new MediaWikiServices instance and initializes it according to the
226 * given $bootstrapConfig. In particular, all wiring files defined in the
227 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
228 *
229 * @param Config|null $bootstrapConfig The Config object to be registered as the
230 * 'BootstrapConfig' service.
231 *
232 * @param string $loadWiring set this to 'load' to load the wiring files specified
233 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
234 *
235 * @return MediaWikiServices
236 * @throws MWException
237 * @throws \FatalError
238 */
239 private static function newInstance( Config $bootstrapConfig, $loadWiring = '' ) {
240 $instance = new self( $bootstrapConfig );
241
242 // Load the default wiring from the specified files.
243 if ( $loadWiring === 'load' ) {
244 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
245 $instance->loadWiringFiles( $wiringFiles );
246 }
247
248 // Provide a traditional hook point to allow extensions to configure services.
249 Hooks::run( 'MediaWikiServices', [ $instance ] );
250
251 return $instance;
252 }
253
254 /**
255 * Disables all storage layer services. After calling this, any attempt to access the
256 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
257 * operation.
258 *
259 * @since 1.28
260 *
261 * @warning This is intended for extreme situations only and should never be used
262 * while serving normal web requests. Legitimate use cases for this method include
263 * the installation process. Test fixtures may also use this, if the fixture relies
264 * on globalState.
265 *
266 * @see resetGlobalInstance()
267 * @see resetChildProcessServices()
268 */
269 public static function disableStorageBackend() {
270 // TODO: also disable some Caches, JobQueues, etc
271 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
272 $services = self::getInstance();
273
274 foreach ( $destroy as $name ) {
275 $services->disableService( $name );
276 }
277
278 ObjectCache::clear();
279 }
280
281 /**
282 * Resets any services that may have become stale after a child process
283 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
284 * to call this method from the parent process.
285 *
286 * @since 1.28
287 *
288 * @note This is intended for use in the context of process forking only!
289 *
290 * @see resetGlobalInstance()
291 * @see disableStorageBackend()
292 */
293 public static function resetChildProcessServices() {
294 // NOTE: for now, just reset everything. Since we don't know the interdependencies
295 // between services, we can't do this more selectively at this time.
296 self::resetGlobalInstance();
297
298 // Child, reseed because there is no bug in PHP:
299 // http://bugs.php.net/bug.php?id=42465
300 mt_srand( getmypid() );
301 }
302
303 /**
304 * Resets the given service for testing purposes.
305 *
306 * @since 1.28
307 *
308 * @warning This is generally unsafe! Other services may still retain references
309 * to the stale service instance, leading to failures and inconsistencies. Subclasses
310 * may use this method to reset specific services under specific instances, but
311 * it should not be exposed to application logic.
312 *
313 * @note With proper dependency injection used throughout the codebase, this method
314 * should not be needed. It is provided to allow tests that pollute global service
315 * instances to clean up.
316 *
317 * @param string $name
318 * @param bool $destroy Whether the service instance should be destroyed if it exists.
319 * When set to false, any existing service instance will effectively be detached
320 * from the container.
321 *
322 * @throws MWException if called outside of PHPUnit tests.
323 */
324 public function resetServiceForTesting( $name, $destroy = true ) {
325 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
326 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
327 }
328
329 $this->resetService( $name, $destroy );
330 }
331
332 /**
333 * Convenience method that throws an exception unless it is called during a phase in which
334 * resetting of global services is allowed. In general, services should not be reset
335 * individually, since that may introduce inconsistencies.
336 *
337 * @since 1.28
338 *
339 * This method will throw an exception if:
340 *
341 * - self::$resetInProgress is false (to allow all services to be reset together
342 * via resetGlobalInstance)
343 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
344 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
345 *
346 * This method is intended to be used to safeguard against accidentally resetting
347 * global service instances that are not yet managed by MediaWikiServices. It is
348 * defined here in the MediaWikiServices services class to have a central place
349 * for managing service bootstrapping and resetting.
350 *
351 * @param string $method the name of the caller method, as given by __METHOD__.
352 *
353 * @throws MWException if called outside bootstrap mode.
354 *
355 * @see resetGlobalInstance()
356 * @see forceGlobalInstance()
357 * @see disableStorageBackend()
358 */
359 public static function failIfResetNotAllowed( $method ) {
360 if ( !defined( 'MW_PHPUNIT_TEST' )
361 && !defined( 'MW_PARSER_TEST' )
362 && !defined( 'MEDIAWIKI_INSTALL' )
363 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
364 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
365 ) {
366 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
367 }
368 }
369
370 /**
371 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
372 * This has to contain at least the information needed to set up the 'ConfigFactory'
373 * service.
374 */
375 public function __construct( Config $config ) {
376 parent::__construct();
377
378 // Register the given Config object as the bootstrap config service.
379 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
380 return $config;
381 } );
382 }
383
384 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
385
386 /**
387 * Returns the Config object containing the bootstrap configuration.
388 * Bootstrap configuration would typically include database credentials
389 * and other information that may be needed before the ConfigFactory
390 * service can be instantiated.
391 *
392 * @note This should only be used during bootstrapping, in particular
393 * when creating the MainConfig service. Application logic should
394 * use getMainConfig() to get a Config instances.
395 *
396 * @since 1.27
397 * @return Config
398 */
399 public function getBootstrapConfig() {
400 return $this->getService( 'BootstrapConfig' );
401 }
402
403 /**
404 * @since 1.27
405 * @return ConfigFactory
406 */
407 public function getConfigFactory() {
408 return $this->getService( 'ConfigFactory' );
409 }
410
411 /**
412 * Returns the Config object that provides configuration for MediaWiki core.
413 * This may or may not be the same object that is returned by getBootstrapConfig().
414 *
415 * @since 1.27
416 * @return Config
417 */
418 public function getMainConfig() {
419 return $this->getService( 'MainConfig' );
420 }
421
422 /**
423 * @since 1.27
424 * @return SiteLookup
425 */
426 public function getSiteLookup() {
427 return $this->getService( 'SiteLookup' );
428 }
429
430 /**
431 * @since 1.27
432 * @return SiteStore
433 */
434 public function getSiteStore() {
435 return $this->getService( 'SiteStore' );
436 }
437
438 /**
439 * @since 1.28
440 * @return InterwikiLookup
441 */
442 public function getInterwikiLookup() {
443 return $this->getService( 'InterwikiLookup' );
444 }
445
446 /**
447 * @since 1.27
448 * @return StatsdDataFactory
449 */
450 public function getStatsdDataFactory() {
451 return $this->getService( 'StatsdDataFactory' );
452 }
453
454 /**
455 * @since 1.27
456 * @return EventRelayerGroup
457 */
458 public function getEventRelayerGroup() {
459 return $this->getService( 'EventRelayerGroup' );
460 }
461
462 /**
463 * @since 1.27
464 * @return SearchEngine
465 */
466 public function newSearchEngine() {
467 // New engine object every time, since they keep state
468 return $this->getService( 'SearchEngineFactory' )->create();
469 }
470
471 /**
472 * @since 1.27
473 * @return SearchEngineFactory
474 */
475 public function getSearchEngineFactory() {
476 return $this->getService( 'SearchEngineFactory' );
477 }
478
479 /**
480 * @since 1.27
481 * @return SearchEngineConfig
482 */
483 public function getSearchEngineConfig() {
484 return $this->getService( 'SearchEngineConfig' );
485 }
486
487 /**
488 * @since 1.27
489 * @return SkinFactory
490 */
491 public function getSkinFactory() {
492 return $this->getService( 'SkinFactory' );
493 }
494
495 /**
496 * @since 1.28
497 * @return LBFactory
498 */
499 public function getDBLoadBalancerFactory() {
500 return $this->getService( 'DBLoadBalancerFactory' );
501 }
502
503 /**
504 * @since 1.28
505 * @return LoadBalancer The main DB load balancer for the local wiki.
506 */
507 public function getDBLoadBalancer() {
508 return $this->getService( 'DBLoadBalancer' );
509 }
510
511 /**
512 * @since 1.28
513 * @return WatchedItemStore
514 */
515 public function getWatchedItemStore() {
516 return $this->getService( 'WatchedItemStore' );
517 }
518
519 /**
520 * @since 1.28
521 * @return WatchedItemQueryService
522 */
523 public function getWatchedItemQueryService() {
524 return $this->getService( 'WatchedItemQueryService' );
525 }
526
527 /**
528 * @since 1.28
529 * @return CryptRand
530 */
531 public function getCryptRand() {
532 return $this->getService( 'CryptRand' );
533 }
534
535 /**
536 * @since 1.28
537 * @return MediaHandlerFactory
538 */
539 public function getMediaHandlerFactory() {
540 return $this->getService( 'MediaHandlerFactory' );
541 }
542
543 /**
544 * @since 1.28
545 * @return MimeAnalyzer
546 */
547 public function getMimeAnalyzer() {
548 return $this->getService( 'MimeAnalyzer' );
549 }
550
551 /**
552 * @since 1.28
553 * @return ProxyLookup
554 */
555 public function getProxyLookup() {
556 return $this->getService( 'ProxyLookup' );
557 }
558
559 /**
560 * @since 1.28
561 * @return GenderCache
562 */
563 public function getGenderCache() {
564 return $this->getService( 'GenderCache' );
565 }
566
567 /**
568 * @since 1.28
569 * @return LinkCache
570 */
571 public function getLinkCache() {
572 return $this->getService( 'LinkCache' );
573 }
574
575 /**
576 * @since 1.28
577 * @return LinkRendererFactory
578 */
579 public function getLinkRendererFactory() {
580 return $this->getService( 'LinkRendererFactory' );
581 }
582
583 /**
584 * LinkRenderer instance that can be used
585 * if no custom options are needed
586 *
587 * @since 1.28
588 * @return LinkRenderer
589 */
590 public function getLinkRenderer() {
591 return $this->getService( 'LinkRenderer' );
592 }
593
594 /**
595 * @since 1.28
596 * @return TitleFormatter
597 */
598 public function getTitleFormatter() {
599 return $this->getService( 'TitleFormatter' );
600 }
601
602 /**
603 * @since 1.28
604 * @return TitleParser
605 */
606 public function getTitleParser() {
607 return $this->getService( 'TitleParser' );
608 }
609
610 /**
611 * @since 1.28
612 * @return \BagOStuff
613 */
614 public function getMainObjectStash() {
615 return $this->getService( 'MainObjectStash' );
616 }
617
618 /**
619 * @since 1.28
620 * @return \WANObjectCache
621 */
622 public function getMainWANObjectCache() {
623 return $this->getService( 'MainWANObjectCache' );
624 }
625
626 /**
627 * @since 1.28
628 * @return \BagOStuff
629 */
630 public function getLocalServerObjectCache() {
631 return $this->getService( 'LocalServerObjectCache' );
632 }
633
634 /**
635 * @since 1.28
636 * @return VirtualRESTServiceClient
637 */
638 public function getVirtualRESTServiceClient() {
639 return $this->getService( 'VirtualRESTServiceClient' );
640 }
641
642 ///////////////////////////////////////////////////////////////////////////
643 // NOTE: When adding a service getter here, don't forget to add a test
644 // case for it in MediaWikiServicesTest::provideGetters() and in
645 // MediaWikiServicesTest::provideGetService()!
646 ///////////////////////////////////////////////////////////////////////////
647
648 }