10 use EventRelayerGroup
;
14 use IBufferingStatsdDataFactory
;
15 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface
;
16 use MediaWiki\Http\HttpRequestFactory
;
17 use MediaWiki\Permissions\PermissionManager
;
18 use MediaWiki\Preferences\PreferencesFactory
;
19 use MediaWiki\Shell\CommandFactory
;
20 use MediaWiki\Revision\RevisionRenderer
;
21 use MediaWiki\Revision\SlotRoleRegistry
;
22 use MediaWiki\Special\SpecialPageFactory
;
23 use MediaWiki\Storage\BlobStore
;
24 use MediaWiki\Storage\BlobStoreFactory
;
25 use MediaWiki\Storage\NameTableStore
;
26 use MediaWiki\Storage\NameTableStoreFactory
;
27 use MediaWiki\Revision\RevisionFactory
;
28 use MediaWiki\Revision\RevisionLookup
;
29 use MediaWiki\Revision\RevisionStore
;
30 use OldRevisionImporter
;
31 use MediaWiki\Revision\RevisionStoreFactory
;
32 use UploadRevisionImporter
;
33 use Wikimedia\Rdbms\LBFactory
;
35 use Wikimedia\Rdbms\LoadBalancer
;
36 use MediaHandlerFactory
;
37 use MediaWiki\Config\ConfigRepository
;
38 use MediaWiki\Linker\LinkRenderer
;
39 use MediaWiki\Linker\LinkRendererFactory
;
51 use SearchEngineConfig
;
52 use SearchEngineFactory
;
55 use WatchedItemStoreInterface
;
56 use WatchedItemQueryService
;
60 use VirtualRESTServiceClient
;
61 use Wikimedia\Services\SalvageableService
;
62 use Wikimedia\Services\ServiceContainer
;
63 use Wikimedia\Services\NoSuchServiceException
;
64 use MediaWiki\Interwiki\InterwikiLookup
;
68 * Service locator for MediaWiki core services.
70 * This program is free software; you can redistribute it and/or modify
71 * it under the terms of the GNU General Public License as published by
72 * the Free Software Foundation; either version 2 of the License, or
73 * (at your option) any later version.
75 * This program is distributed in the hope that it will be useful,
76 * but WITHOUT ANY WARRANTY; without even the implied warranty of
77 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
78 * GNU General Public License for more details.
80 * You should have received a copy of the GNU General Public License along
81 * with this program; if not, write to the Free Software Foundation, Inc.,
82 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
83 * http://www.gnu.org/copyleft/gpl.html
91 * MediaWikiServices is the service locator for the application scope of MediaWiki.
92 * Its implemented as a simple configurable DI container.
93 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
94 * the network of service objects that defines MediaWiki's application logic.
95 * It acts as an entry point to MediaWiki's dependency injection mechanism.
97 * Services are defined in the "wiring" array passed to the constructor,
98 * or by calling defineService().
100 * @see docs/injection.txt for an overview of using dependency injection in the
101 * MediaWiki code base.
103 class MediaWikiServices
extends ServiceContainer
{
106 * @var MediaWikiServices|null
108 private static $instance = null;
111 * Returns the global default instance of the top level service locator.
115 * The default instance is initialized using the service instantiator functions
116 * defined in ServiceWiring.php.
118 * @note This should only be called by static functions! The instance returned here
119 * should not be passed around! Objects that need access to a service should have
120 * that service injected into the constructor, never a service locator!
122 * @return MediaWikiServices
124 public static function getInstance() {
125 if ( self
::$instance === null ) {
126 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
127 // but some information from the global scope has to be injected here,
128 // even if it's just a file name or database credentials to load
129 // configuration from.
130 $bootstrapConfig = new GlobalVarConfig();
131 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
134 return self
::$instance;
138 * Replaces the global MediaWikiServices instance.
142 * @note This is for use in PHPUnit tests only!
144 * @throws MWException if called outside of PHPUnit tests.
146 * @param MediaWikiServices $services The new MediaWikiServices object.
148 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
150 public static function forceGlobalInstance( MediaWikiServices
$services ) {
151 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
152 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
155 $old = self
::getInstance();
156 self
::$instance = $services;
162 * Creates a new instance of MediaWikiServices and sets it as the global default
163 * instance. getInstance() will return a different MediaWikiServices object
164 * after every call to resetGlobalInstance().
168 * @warning This should not be used during normal operation. It is intended for use
169 * when the configuration has changed significantly since bootstrap time, e.g.
170 * during the installation process or during testing.
172 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
173 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
174 * any of the services managed by MediaWikiServices exist. If any service objects
175 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
176 * with the operation of the services managed by the new MediaWikiServices.
177 * Operating with a mix of services created by the old and the new
178 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
179 * Any class implementing LAZY LOADING is especially prone to this problem,
180 * since instances would typically retain a reference to a storage layer service.
182 * @see forceGlobalInstance()
183 * @see resetGlobalInstance()
184 * @see resetBetweenTest()
186 * @param Config|null $bootstrapConfig The Config object to be registered as the
187 * 'BootstrapConfig' service. This has to contain at least the information
188 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
189 * config of the old instance of MediaWikiServices will be re-used. If there
190 * was no previous instance, a new GlobalVarConfig object will be used to
191 * bootstrap the services.
193 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
194 * See SalvageableService for details.
196 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
197 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
200 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
201 if ( self
::$instance === null ) {
202 // no global instance yet, nothing to reset
206 self
::failIfResetNotAllowed( __METHOD__
);
208 if ( $bootstrapConfig === null ) {
209 $bootstrapConfig = self
::$instance->getBootstrapConfig();
212 $oldInstance = self
::$instance;
214 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
215 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
217 if ( $quick === 'quick' ) {
218 self
::$instance->salvage( $oldInstance );
220 $oldInstance->destroy();
225 * Salvages the state of any salvageable service instances in $other.
227 * @note $other will have been destroyed when salvage() returns.
229 * @param MediaWikiServices $other
231 private function salvage( self
$other ) {
232 foreach ( $this->getServiceNames() as $name ) {
233 // The service could be new in the new instance and not registered in the
234 // other instance (e.g. an extension that was loaded after the instantiation of
235 // the other instance. Skip this service in this case. See T143974
237 $oldService = $other->peekService( $name );
238 } catch ( NoSuchServiceException
$e ) {
242 if ( $oldService instanceof SalvageableService
) {
243 /** @var SalvageableService $newService */
244 $newService = $this->getService( $name );
245 $newService->salvage( $oldService );
253 * Creates a new MediaWikiServices instance and initializes it according to the
254 * given $bootstrapConfig. In particular, all wiring files defined in the
255 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
257 * @param Config|null $bootstrapConfig The Config object to be registered as the
258 * 'BootstrapConfig' service.
260 * @param string $loadWiring set this to 'load' to load the wiring files specified
261 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
263 * @return MediaWikiServices
264 * @throws MWException
265 * @throws \FatalError
267 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
268 $instance = new self( $bootstrapConfig );
270 // Load the default wiring from the specified files.
271 if ( $loadWiring === 'load' ) {
272 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
273 $instance->loadWiringFiles( $wiringFiles );
276 // Provide a traditional hook point to allow extensions to configure services.
277 Hooks
::run( 'MediaWikiServices', [ $instance ] );
283 * Disables all storage layer services. After calling this, any attempt to access the
284 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
289 * @warning This is intended for extreme situations only and should never be used
290 * while serving normal web requests. Legitimate use cases for this method include
291 * the installation process. Test fixtures may also use this, if the fixture relies
294 * @see resetGlobalInstance()
295 * @see resetChildProcessServices()
297 public static function disableStorageBackend() {
298 // TODO: also disable some Caches, JobQueues, etc
299 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
300 $services = self
::getInstance();
302 foreach ( $destroy as $name ) {
303 $services->disableService( $name );
306 ObjectCache
::clear();
310 * Resets any services that may have become stale after a child process
311 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
312 * to call this method from the parent process.
316 * @note This is intended for use in the context of process forking only!
318 * @see resetGlobalInstance()
319 * @see disableStorageBackend()
321 public static function resetChildProcessServices() {
322 // NOTE: for now, just reset everything. Since we don't know the interdependencies
323 // between services, we can't do this more selectively at this time.
324 self
::resetGlobalInstance();
326 // Child, reseed because there is no bug in PHP:
327 // https://bugs.php.net/bug.php?id=42465
328 mt_srand( getmypid() );
332 * Resets the given service for testing purposes.
336 * @warning This is generally unsafe! Other services may still retain references
337 * to the stale service instance, leading to failures and inconsistencies. Subclasses
338 * may use this method to reset specific services under specific instances, but
339 * it should not be exposed to application logic.
341 * @note With proper dependency injection used throughout the codebase, this method
342 * should not be needed. It is provided to allow tests that pollute global service
343 * instances to clean up.
345 * @param string $name
346 * @param bool $destroy Whether the service instance should be destroyed if it exists.
347 * When set to false, any existing service instance will effectively be detached
348 * from the container.
350 * @throws MWException if called outside of PHPUnit tests.
352 public function resetServiceForTesting( $name, $destroy = true ) {
353 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
354 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
357 $this->resetService( $name, $destroy );
361 * Convenience method that throws an exception unless it is called during a phase in which
362 * resetting of global services is allowed. In general, services should not be reset
363 * individually, since that may introduce inconsistencies.
367 * This method will throw an exception if:
369 * - self::$resetInProgress is false (to allow all services to be reset together
370 * via resetGlobalInstance)
371 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
372 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
374 * This method is intended to be used to safeguard against accidentally resetting
375 * global service instances that are not yet managed by MediaWikiServices. It is
376 * defined here in the MediaWikiServices services class to have a central place
377 * for managing service bootstrapping and resetting.
379 * @param string $method the name of the caller method, as given by __METHOD__.
381 * @throws MWException if called outside bootstrap mode.
383 * @see resetGlobalInstance()
384 * @see forceGlobalInstance()
385 * @see disableStorageBackend()
387 public static function failIfResetNotAllowed( $method ) {
388 if ( !defined( 'MW_PHPUNIT_TEST' )
389 && !defined( 'MW_PARSER_TEST' )
390 && !defined( 'MEDIAWIKI_INSTALL' )
391 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
392 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
394 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
399 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
400 * This has to contain at least the information needed to set up the 'ConfigFactory'
403 public function __construct( Config
$config ) {
404 parent
::__construct();
406 // Register the given Config object as the bootstrap config service.
407 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
412 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
416 * @return ActorMigration
418 public function getActorMigration() {
419 return $this->getService( 'ActorMigration' );
426 public function getBlobStore() {
427 return $this->getService( '_SqlBlobStore' );
432 * @return BlobStoreFactory
434 public function getBlobStoreFactory() {
435 return $this->getService( 'BlobStoreFactory' );
439 * Returns the Config object containing the bootstrap configuration.
440 * Bootstrap configuration would typically include database credentials
441 * and other information that may be needed before the ConfigFactory
442 * service can be instantiated.
444 * @note This should only be used during bootstrapping, in particular
445 * when creating the MainConfig service. Application logic should
446 * use getMainConfig() to get a Config instances.
451 public function getBootstrapConfig() {
452 return $this->getService( 'BootstrapConfig' );
457 * @return NameTableStore
459 public function getChangeTagDefStore() {
460 return $this->getService( 'NameTableStoreFactory' )->getChangeTagDef();
465 * @return CommentStore
467 public function getCommentStore() {
468 return $this->getService( 'CommentStore' );
473 * @return ConfigFactory
475 public function getConfigFactory() {
476 return $this->getService( 'ConfigFactory' );
481 * @return ConfigRepository
483 public function getConfigRepository() {
484 return $this->getService( 'ConfigRepository' );
489 * @return \ConfiguredReadOnlyMode
491 public function getConfiguredReadOnlyMode() {
492 return $this->getService( 'ConfiguredReadOnlyMode' );
499 public function getContentLanguage() {
500 return $this->getService( 'ContentLanguage' );
505 * @return NameTableStore
507 public function getContentModelStore() {
508 return $this->getService( 'NameTableStoreFactory' )->getContentModels();
515 public function getCryptHKDF() {
516 return $this->getService( 'CryptHKDF' );
521 * @deprecated since 1.32, use random_bytes()/random_int()
524 public function getCryptRand() {
525 wfDeprecated( __METHOD__
, '1.32' );
526 return $this->getService( 'CryptRand' );
531 * @return LoadBalancer The main DB load balancer for the local wiki.
533 public function getDBLoadBalancer() {
534 return $this->getService( 'DBLoadBalancer' );
541 public function getDBLoadBalancerFactory() {
542 return $this->getService( 'DBLoadBalancerFactory' );
547 * @return EventRelayerGroup
549 public function getEventRelayerGroup() {
550 return $this->getService( 'EventRelayerGroup' );
555 * @return \ExternalStoreFactory
557 public function getExternalStoreFactory() {
558 return $this->getService( 'ExternalStoreFactory' );
563 * @return GenderCache
565 public function getGenderCache() {
566 return $this->getService( 'GenderCache' );
571 * @return HttpRequestFactory
573 public function getHttpRequestFactory() {
574 return $this->getService( 'HttpRequestFactory' );
579 * @return InterwikiLookup
581 public function getInterwikiLookup() {
582 return $this->getService( 'InterwikiLookup' );
589 public function getLinkCache() {
590 return $this->getService( 'LinkCache' );
594 * LinkRenderer instance that can be used
595 * if no custom options are needed
598 * @return LinkRenderer
600 public function getLinkRenderer() {
601 return $this->getService( 'LinkRenderer' );
606 * @return LinkRendererFactory
608 public function getLinkRendererFactory() {
609 return $this->getService( 'LinkRendererFactory' );
616 public function getLocalServerObjectCache() {
617 return $this->getService( 'LocalServerObjectCache' );
622 * @return MagicWordFactory
624 public function getMagicWordFactory() {
625 return $this->getService( 'MagicWordFactory' );
629 * Returns the Config object that provides configuration for MediaWiki core.
630 * This may or may not be the same object that is returned by getBootstrapConfig().
635 public function getMainConfig() {
636 return $this->getService( 'MainConfig' );
643 public function getMainObjectStash() {
644 return $this->getService( 'MainObjectStash' );
649 * @return \WANObjectCache
651 public function getMainWANObjectCache() {
652 return $this->getService( 'MainWANObjectCache' );
657 * @return MediaHandlerFactory
659 public function getMediaHandlerFactory() {
660 return $this->getService( 'MediaHandlerFactory' );
665 * @return MimeAnalyzer
667 public function getMimeAnalyzer() {
668 return $this->getService( 'MimeAnalyzer' );
673 * @return NamespaceInfo
675 public function getNamespaceInfo() : NamespaceInfo
{
676 return $this->getService( 'NamespaceInfo' );
681 * @return NameTableStoreFactory
683 public function getNameTableStoreFactory() {
684 return $this->getService( 'NameTableStoreFactory' );
689 * @return OldRevisionImporter
691 public function getOldRevisionImporter() {
692 return $this->getService( 'OldRevisionImporter' );
699 public function getParser() {
700 return $this->getService( 'Parser' );
705 * @return ParserCache
707 public function getParserCache() {
708 return $this->getService( 'ParserCache' );
713 * @return ParserFactory
715 public function getParserFactory() {
716 return $this->getService( 'ParserFactory' );
721 * @return PasswordFactory
723 public function getPasswordFactory() {
724 return $this->getService( 'PasswordFactory' );
729 * @return StatsdDataFactoryInterface
731 public function getPerDbNameStatsdDataFactory() {
732 return $this->getService( 'PerDbNameStatsdDataFactory' );
737 * @return PermissionManager
739 public function getPermissionManager() {
740 return $this->getService( 'PermissionManager' );
745 * @return PreferencesFactory
747 public function getPreferencesFactory() {
748 return $this->getService( 'PreferencesFactory' );
753 * @return ProxyLookup
755 public function getProxyLookup() {
756 return $this->getService( 'ProxyLookup' );
761 * @return \ReadOnlyMode
763 public function getReadOnlyMode() {
764 return $this->getService( 'ReadOnlyMode' );
769 * @return ResourceLoader
771 public function getResourceLoader() {
772 return $this->getService( 'ResourceLoader' );
777 * @return RevisionFactory
779 public function getRevisionFactory() {
780 return $this->getService( 'RevisionFactory' );
785 * @return RevisionLookup
787 public function getRevisionLookup() {
788 return $this->getService( 'RevisionLookup' );
793 * @return RevisionRenderer
795 public function getRevisionRenderer() {
796 return $this->getService( 'RevisionRenderer' );
801 * @return RevisionStore
803 public function getRevisionStore() {
804 return $this->getService( 'RevisionStore' );
809 * @return RevisionStoreFactory
811 public function getRevisionStoreFactory() {
812 return $this->getService( 'RevisionStoreFactory' );
817 * @return SearchEngine
819 public function newSearchEngine() {
820 // New engine object every time, since they keep state
821 return $this->getService( 'SearchEngineFactory' )->create();
826 * @return SearchEngineConfig
828 public function getSearchEngineConfig() {
829 return $this->getService( 'SearchEngineConfig' );
834 * @return SearchEngineFactory
836 public function getSearchEngineFactory() {
837 return $this->getService( 'SearchEngineFactory' );
842 * @return CommandFactory
844 public function getShellCommandFactory() {
845 return $this->getService( 'ShellCommandFactory' );
852 public function getSiteLookup() {
853 return $this->getService( 'SiteLookup' );
860 public function getSiteStore() {
861 return $this->getService( 'SiteStore' );
866 * @return SkinFactory
868 public function getSkinFactory() {
869 return $this->getService( 'SkinFactory' );
874 * @return SlotRoleRegistry
876 public function getSlotRoleRegistry() {
877 return $this->getService( 'SlotRoleRegistry' );
882 * @return NameTableStore
884 public function getSlotRoleStore() {
885 return $this->getService( 'NameTableStoreFactory' )->getSlotRoles();
890 * @return SpecialPageFactory
892 public function getSpecialPageFactory() : SpecialPageFactory
{
893 return $this->getService( 'SpecialPageFactory' );
898 * @return IBufferingStatsdDataFactory
900 public function getStatsdDataFactory() {
901 return $this->getService( 'StatsdDataFactory' );
906 * @return TitleFormatter
908 public function getTitleFormatter() {
909 return $this->getService( 'TitleFormatter' );
914 * @return TitleParser
916 public function getTitleParser() {
917 return $this->getService( 'TitleParser' );
922 * @return UploadRevisionImporter
924 public function getUploadRevisionImporter() {
925 return $this->getService( 'UploadRevisionImporter' );
930 * @return VirtualRESTServiceClient
932 public function getVirtualRESTServiceClient() {
933 return $this->getService( 'VirtualRESTServiceClient' );
938 * @return WatchedItemQueryService
940 public function getWatchedItemQueryService() {
941 return $this->getService( 'WatchedItemQueryService' );
946 * @return WatchedItemStoreInterface
948 public function getWatchedItemStore() {
949 return $this->getService( 'WatchedItemStore' );
954 * @return \OldRevisionImporter
956 public function getWikiRevisionOldRevisionImporter() {
957 return $this->getService( 'OldRevisionImporter' );
962 * @return \OldRevisionImporter
964 public function getWikiRevisionOldRevisionImporterNoUpdates() {
965 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
970 * @return \UploadRevisionImporter
972 public function getWikiRevisionUploadImporter() {
973 return $this->getService( 'UploadRevisionImporter' );