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