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