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