Merge "Normalize `input[type="search"]`"
[lhc/web/wiklou.git] / includes / MediaWikiServices.php
1 <?php
2 namespace MediaWiki;
3
4 use ApiQueryInfo;
5 use CentralIdLookup;
6 use Config;
7 use ConfigFactory;
8 use DeferredUpdates;
9 use FileBackendGroup;
10 use GlobalVarConfig;
11 use Hooks;
12 use IP;
13 use JobQueueAggregator;
14 use Language;
15 use LBFactory;
16 use LinkCache;
17 use LoadBalancer;
18 use LockManagerGroup;
19 use MagicWord;
20 use MediaHandler;
21 use MediaWiki\Services\ServiceContainer;
22 use MediaWiki\Session\SessionManager;
23 use MessageCache;
24 use MWException;
25 use MWNamespace;
26 use MWTidy;
27 use ObjectCache;
28 use RedisConnectionPool;
29 use RepoGroup;
30 use RequestContext;
31 use ResourceLoader;
32 use SiteLookup;
33 use SiteStore;
34 use SpecialPageFactory;
35 use Title;
36 use User;
37 use WatchedItemStore;
38 use Wikimedia\Assert\Assert;
39
40 /**
41 * Service locator for MediaWiki core services.
42 *
43 * This program is free software; you can redistribute it and/or modify
44 * it under the terms of the GNU General Public License as published by
45 * the Free Software Foundation; either version 2 of the License, or
46 * (at your option) any later version.
47 *
48 * This program is distributed in the hope that it will be useful,
49 * but WITHOUT ANY WARRANTY; without even the implied warranty of
50 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
51 * GNU General Public License for more details.
52 *
53 * You should have received a copy of the GNU General Public License along
54 * with this program; if not, write to the Free Software Foundation, Inc.,
55 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
56 * http://www.gnu.org/copyleft/gpl.html
57 *
58 * @file
59 *
60 * @since 1.27
61 */
62
63 /**
64 * MediaWikiServices is the service locator for the application scope of MediaWiki.
65 * Its implemented as a simple configurable DI container.
66 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
67 * the network of service objects that defines MediaWiki's application logic.
68 * It acts as an entry point to MediaWiki's dependency injection mechanism.
69 *
70 * Services are defined in the "wiring" array passed to the constructor,
71 * or by calling defineService().
72 *
73 * @see docs/injection.txt for an overview of using dependency injection in the
74 * MediaWiki code base.
75 */
76 class MediaWikiServices extends ServiceContainer {
77
78 /**
79 * @var MediaWikiServices|null
80 */
81 private static $instance = null;
82
83 /**
84 * Returns the global default instance of the top level service locator.
85 *
86 * The default instance is initialized using the service instantiator functions
87 * defined in ServiceWiring.php.
88 *
89 * @note This should only be called by static functions! The instance returned here
90 * should not be passed around! Objects that need access to a service should have
91 * that service injected into the constructor, never a service locator!
92 *
93 * @return MediaWikiServices
94 */
95 public static function getInstance() {
96 if ( self::$instance === null ) {
97 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
98 // but some information from the global scope has to be injected here,
99 // even if it's just a file name or database credentials to load
100 // configuration from.
101 $bootstrapConfig = new GlobalVarConfig();
102 self::$instance = self::newInstance( $bootstrapConfig );
103 }
104
105 return self::$instance;
106 }
107
108 /**
109 * Replaces the global MediaWikiServices instance.
110 *
111 * @note This is for use in PHPUnit tests only!
112 *
113 * @throws MWException if called outside of PHPUnit tests.
114 *
115 * @param MediaWikiServices $services The new MediaWikiServices object.
116 *
117 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
118 */
119 public static function forceGlobalInstance( MediaWikiServices $services ) {
120 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
121 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
122 }
123
124 $old = self::getInstance();
125 self::$instance = $services;
126
127 self::resetLegacyServices();
128
129 return $old;
130 }
131
132 /**
133 * Creates a new instance of MediaWikiServices and sets it as the global default
134 * instance. getInstance() will return a different MediaWikiServices object
135 * after every call to resetGlobalServiceLocator().
136 *
137 * @warning This should not be used during normal operation. It is intended for use
138 * when the configuration has changed significantly since bootstrap time, e.g.
139 * during the installation process or during testing.
140 *
141 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
142 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
143 * any of the services managed by MediaWikiServices exist. If any service objects
144 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
145 * with the operation of the services managed by the new MediaWikiServices.
146 * Operating with a mix of services created by the old and the new
147 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
148 * Any class implementing LAZY LOADING is especially prone to this problem,
149 * since instances would typically retain a reference to a storage layer service.
150 *
151 * @see forceGlobalInstance()
152 * @see resetGlobalInstance()
153 * @see resetBetweenTest()
154 *
155 * @param Config|null $bootstrapConfig The Config object to be registered as the
156 * 'BootstrapConfig' service. This has to contain at least the information
157 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
158 * config of the old instance of MediaWikiServices will be re-used. If there
159 * was no previous instance, a new GlobalVarConfig object will be used to
160 * bootstrap the services.
161 *
162 * @throws MWException
163 */
164 public static function resetGlobalInstance( Config $bootstrapConfig = null ) {
165 if ( self::$instance === null ) {
166 // no global instance yet, nothing to reset
167 return;
168 }
169
170 if ( $bootstrapConfig === null ) {
171 $bootstrapConfig = self::$instance->getBootstrapConfig();
172 }
173
174 self::$instance->destroy();
175
176 self::$instance = self::newInstance( $bootstrapConfig );
177
178 self::resetLegacyServices();
179 }
180
181 /**
182 * Creates a new MediaWikiServices instance and initializes it according to the
183 * given $bootstrapConfig. In particular, all wiring files defined in the
184 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
185 *
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 provided, any call
189 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
190 * A MediaWikiServices instance without access to configuration is called
191 * "primordial".
192 *
193 * @return MediaWikiServices
194 * @throws MWException
195 */
196 private static function newInstance( Config $bootstrapConfig ) {
197 $instance = new self( $bootstrapConfig );
198
199 // Load the default wiring from the specified files.
200 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
201 $instance->loadWiringFiles( $wiringFiles );
202
203 // Provide a traditional hook point to allow extensions to configure services.
204 Hooks::run( 'MediaWikiServices', [ $instance ] );
205
206 return $instance;
207 }
208
209 /**
210 * Resets global instances of services that have not yet been ported to using
211 * MediaWikiServices to manage their default instance.
212 *
213 * @note eventually, all global service instances are to be managed by MediaWikiServices.
214 * To emulate the effect of resetting the global service locator, we reset the individual
215 * static singletons for now.
216 *
217 * @note As long as we don't know the interdependencies between the services, the only way
218 * to reset services consistently is to reset all services at once. This should be ok since
219 * there should rarely be a need to reset all processes.
220 */
221 private static function resetLegacyServices() {
222 global $wgContLang, $wgUser, $wgMemc, $wgRequest;
223
224 $services = self::getInstance();
225 $config = $services->getMainConfig();
226
227 // NOTE: all the services instance that get reset below should be migrated
228 // to be managed by MediaWikiServices. Eventually, this method can then be
229 // removed.
230
231 User::resetIdByNameCache();
232 LinkCache::singleton()->clear();
233 Title::clearCaches();
234
235 MWTidy::destroySingleton();
236 MagicWord::clearCache();
237 SpecialPageFactory::resetList();
238 JobQueueAggregator::destroySingleton();
239 DeferredUpdates::clearPendingUpdates();
240 CentralIdLookup::resetCache();
241 MediaHandler::resetCache();
242 IP::clearCaches();
243 ResourceLoader::clearCache();
244
245 ApiQueryInfo::resetTokenCache();
246
247 RepoGroup::destroySingleton();
248
249 MessageCache::destroyInstance();
250
251 MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
252 Language::$mLangObjCache = [];
253 Language::getLocalisationCache()->unloadAll();
254
255 ObjectCache::clear();
256 RedisConnectionPool::destroySingletons();
257 FileBackendGroup::destroySingleton();
258 LockManagerGroup::destroySingletons();
259
260 RequestContext::resetMain();
261 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
262
263 $wgContLang = Language::factory( $config->get( 'LanguageCode' ) );
264 $wgContLang->resetNamespaces(); # reset namespace cache
265
266 $wgMemc = ObjectCache::getLocalClusterInstance();
267 $wgUser = RequestContext::getMain()->getUser();
268
269 SessionManager::resetCache();
270
271 // Provide a hook point for extensions that need to reset global service instances.
272 Hooks::run( 'MediaWikiServices::resetLegacyServices', [ $services ] );
273 }
274
275 /**
276 * Disables all storage layer services. After calling this, any attempt to access the
277 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
278 * operation.
279 *
280 * @warning This is intended for extreme situations only and should never be used
281 * while serving normal web requests. Legitimate use cases for this method include
282 * the installation process. Test fixtures may also use this, if the fixture relies
283 * on globalState.
284 *
285 * @see resetGlobalInstance()
286 * @see resetChildProcessServices()
287 */
288 public static function disableStorageBackend() {
289 // TODO: also disable some Caches, JobQueues, etc
290 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
291 $services = self::getInstance();
292
293 foreach ( $destroy as $name ) {
294 $services->disableService( $name );
295 }
296 }
297
298 /**
299 * Resets any services that may have become stale after a child process
300 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
301 * to call this method from the parent process.
302 *
303 * @note This is intended for use in the context of process forking only!
304 *
305 * @see resetGlobalInstance()
306 * @see disableStorageBackend()
307 */
308 public static function resetChildProcessServices() {
309 // NOTE: for now, just reset everything. Since we don't know the interdependencies
310 // between services, we can't do this more selectively at this time.
311 self::resetGlobalInstance();
312
313 // Child, reseed because there is no bug in PHP:
314 // http://bugs.php.net/bug.php?id=42465
315 mt_srand( getmypid() );
316 }
317
318 /**
319 * Resets the given service for testing purposes.
320 *
321 * @warning This is generally unsafe! Other services may still retain references
322 * to the stale service instance, leading to failures and inconsistencies. Subclasses
323 * may use this method to reset specific services under specific instances, but
324 * it should not be exposed to application logic.
325 *
326 * @note With proper dependency injection used throughout the codebase, this method
327 * should not be needed. It is provided to allow tests that pollute global service
328 * instances to clean up.
329 *
330 * @param string $name
331 * @param string $destroy Whether the service instance should be destroyed if it exists.
332 * When set to false, any existing service instance will effectively be detached
333 * from the container.
334 *
335 * @throws MWException if called outside of PHPUnit tests.
336 */
337 public function resetServiceForTesting( $name, $destroy = true ) {
338 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
339 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
340 }
341
342 $this->resetService( $name, $destroy );
343 }
344
345 /**
346 * Convenience method that throws an exception if called outside the service bootstrapping
347 * phase as indicated by the MW_SERVICE_BOOTSTRAP_COMPLETE constant - that is, after
348 * Setup.php has called resetGlobalInstance(). Additionally, no exception is thrown if
349 * this method is called during unit testing (as indicated by MW_PHPUNIT_TEST) or
350 * during installation (as indicated by MEDIAWIKI_INSTALL).
351 *
352 * This method is intended to be used to safeguard against accidentally resetting
353 * global service instances that are not yet managed by MediaWikiServices. It is
354 * defined here in the MediaWikiServices services class to keep the knowledge about
355 * how the bootstrapping phase is managed central.
356 *
357 * @param string $method the name of the caller method, as given by __METHOD__.
358 *
359 * @throws MWException if called outside bootstrap mode.
360 *
361 * @see resetGlobalInstance()
362 * @see forceGlobalInstance()
363 * @see disableStorageBackend()
364 */
365 public static function failUnlessBootstrapping( $method ) {
366 if ( !defined( 'MW_PHPUNIT_TEST' )
367 && !defined( 'MEDIAWIKI_INSTALL' )
368 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
369 ) {
370 throw new MWException( $method . ' may only be called during bootstrapping unit tests!' );
371 }
372
373 ObjectCache::clear();
374 }
375
376 /**
377 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
378 * This has to contain at least the information needed to set up the 'ConfigFactory'
379 * service.
380 */
381 public function __construct( Config $config ) {
382 parent::__construct();
383
384 // Register the given Config object as the bootstrap config service.
385 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
386 return $config;
387 } );
388 }
389
390 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
391
392 /**
393 * Returns the Config object containing the bootstrap configuration.
394 * Bootstrap configuration would typically include database credentials
395 * and other information that may be needed before the ConfigFactory
396 * service can be instantiated.
397 *
398 * @note This should only be used during bootstrapping, in particular
399 * when creating the MainConfig service. Application logic should
400 * use getMainConfig() to get a Config instances.
401 *
402 * @return Config
403 */
404 public function getBootstrapConfig() {
405 return $this->getService( 'BootstrapConfig' );
406 }
407
408 /**
409 * @return ConfigFactory
410 */
411 public function getConfigFactory() {
412 return $this->getService( 'ConfigFactory' );
413 }
414
415 /**
416 * Returns the Config object that provides configuration for MediaWiki core.
417 * This may or may not be the same object that is returned by getBootstrapConfig().
418 *
419 * @return Config
420 */
421 public function getMainConfig() {
422 return $this->getService( 'MainConfig' );
423 }
424
425 /**
426 * @return SiteLookup
427 */
428 public function getSiteLookup() {
429 return $this->getService( 'SiteLookup' );
430 }
431
432 /**
433 * @return SiteStore
434 */
435 public function getSiteStore() {
436 return $this->getService( 'SiteStore' );
437 }
438
439 /**
440 * @return LBFactory
441 */
442 public function getDBLoadBalancerFactory() {
443 return $this->getService( 'DBLoadBalancerFactory' );
444 }
445
446 /**
447 * @return LoadBalancer The main DB load balancer for the local wiki.
448 */
449 public function getDBLoadBalancer() {
450 return $this->getService( 'DBLoadBalancer' );
451 }
452
453 /**
454 * @return WatchedItemStore
455 */
456 public function getWatchedItemStore() {
457 return $this->getService( 'WatchedItemStore' );
458 }
459
460 ///////////////////////////////////////////////////////////////////////////
461 // NOTE: When adding a service getter here, don't forget to add a test
462 // case for it in MediaWikiServicesTest::provideGetters() and in
463 // MediaWikiServicesTest::provideGetService()!
464 ///////////////////////////////////////////////////////////////////////////
465
466 }