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