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