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