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