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