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