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