Merge "Title: Refactor JS/CSS page handling to be more sane"
[lhc/web/wiklou.git] / includes / MediaWikiServices.php
1 <?php
2 namespace MediaWiki;
3
4 use CommentStore;
5 use Config;
6 use ConfigFactory;
7 use CryptHKDF;
8 use CryptRand;
9 use EventRelayerGroup;
10 use GenderCache;
11 use GlobalVarConfig;
12 use Hooks;
13 use IBufferingStatsdDataFactory;
14 use MediaWiki\Http\HttpRequestFactory;
15 use MediaWiki\Preferences\PreferencesFactory;
16 use MediaWiki\Shell\CommandFactory;
17 use MediaWiki\Storage\BlobStore;
18 use MediaWiki\Storage\BlobStoreFactory;
19 use MediaWiki\Storage\RevisionFactory;
20 use MediaWiki\Storage\RevisionLookup;
21 use MediaWiki\Storage\RevisionStore;
22 use Wikimedia\Rdbms\LBFactory;
23 use LinkCache;
24 use Wikimedia\Rdbms\LoadBalancer;
25 use MediaHandlerFactory;
26 use MediaWiki\Linker\LinkRenderer;
27 use MediaWiki\Linker\LinkRendererFactory;
28 use MediaWiki\Services\SalvageableService;
29 use MediaWiki\Services\ServiceContainer;
30 use MediaWiki\Services\NoSuchServiceException;
31 use MWException;
32 use MimeAnalyzer;
33 use ObjectCache;
34 use Parser;
35 use ParserCache;
36 use ProxyLookup;
37 use SearchEngine;
38 use SearchEngineConfig;
39 use SearchEngineFactory;
40 use SiteLookup;
41 use SiteStore;
42 use WatchedItemStoreInterface;
43 use WatchedItemQueryService;
44 use SkinFactory;
45 use TitleFormatter;
46 use TitleParser;
47 use VirtualRESTServiceClient;
48 use MediaWiki\Interwiki\InterwikiLookup;
49
50 /**
51 * Service locator for MediaWiki core services.
52 *
53 * This program is free software; you can redistribute it and/or modify
54 * it under the terms of the GNU General Public License as published by
55 * the Free Software Foundation; either version 2 of the License, or
56 * (at your option) any later version.
57 *
58 * This program is distributed in the hope that it will be useful,
59 * but WITHOUT ANY WARRANTY; without even the implied warranty of
60 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
61 * GNU General Public License for more details.
62 *
63 * You should have received a copy of the GNU General Public License along
64 * with this program; if not, write to the Free Software Foundation, Inc.,
65 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
66 * http://www.gnu.org/copyleft/gpl.html
67 *
68 * @file
69 *
70 * @since 1.27
71 */
72
73 /**
74 * MediaWikiServices is the service locator for the application scope of MediaWiki.
75 * Its implemented as a simple configurable DI container.
76 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
77 * the network of service objects that defines MediaWiki's application logic.
78 * It acts as an entry point to MediaWiki's dependency injection mechanism.
79 *
80 * Services are defined in the "wiring" array passed to the constructor,
81 * or by calling defineService().
82 *
83 * @see docs/injection.txt for an overview of using dependency injection in the
84 * MediaWiki code base.
85 */
86 class MediaWikiServices extends ServiceContainer {
87
88 /**
89 * @var MediaWikiServices|null
90 */
91 private static $instance = null;
92
93 /**
94 * Returns the global default instance of the top level service locator.
95 *
96 * @since 1.27
97 *
98 * The default instance is initialized using the service instantiator functions
99 * defined in ServiceWiring.php.
100 *
101 * @note This should only be called by static functions! The instance returned here
102 * should not be passed around! Objects that need access to a service should have
103 * that service injected into the constructor, never a service locator!
104 *
105 * @return MediaWikiServices
106 */
107 public static function getInstance() {
108 if ( self::$instance === null ) {
109 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
110 // but some information from the global scope has to be injected here,
111 // even if it's just a file name or database credentials to load
112 // configuration from.
113 $bootstrapConfig = new GlobalVarConfig();
114 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
115 }
116
117 return self::$instance;
118 }
119
120 /**
121 * Replaces the global MediaWikiServices instance.
122 *
123 * @since 1.28
124 *
125 * @note This is for use in PHPUnit tests only!
126 *
127 * @throws MWException if called outside of PHPUnit tests.
128 *
129 * @param MediaWikiServices $services The new MediaWikiServices object.
130 *
131 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
132 */
133 public static function forceGlobalInstance( MediaWikiServices $services ) {
134 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
135 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
136 }
137
138 $old = self::getInstance();
139 self::$instance = $services;
140
141 return $old;
142 }
143
144 /**
145 * Creates a new instance of MediaWikiServices and sets it as the global default
146 * instance. getInstance() will return a different MediaWikiServices object
147 * after every call to resetGlobalInstance().
148 *
149 * @since 1.28
150 *
151 * @warning This should not be used during normal operation. It is intended for use
152 * when the configuration has changed significantly since bootstrap time, e.g.
153 * during the installation process or during testing.
154 *
155 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
156 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
157 * any of the services managed by MediaWikiServices exist. If any service objects
158 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
159 * with the operation of the services managed by the new MediaWikiServices.
160 * Operating with a mix of services created by the old and the new
161 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
162 * Any class implementing LAZY LOADING is especially prone to this problem,
163 * since instances would typically retain a reference to a storage layer service.
164 *
165 * @see forceGlobalInstance()
166 * @see resetGlobalInstance()
167 * @see resetBetweenTest()
168 *
169 * @param Config|null $bootstrapConfig The Config object to be registered as the
170 * 'BootstrapConfig' service. This has to contain at least the information
171 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
172 * config of the old instance of MediaWikiServices will be re-used. If there
173 * was no previous instance, a new GlobalVarConfig object will be used to
174 * bootstrap the services.
175 *
176 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
177 * See SalvageableService for details.
178 *
179 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
180 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
181 * is defined).
182 */
183 public static function resetGlobalInstance( Config $bootstrapConfig = null, $quick = '' ) {
184 if ( self::$instance === null ) {
185 // no global instance yet, nothing to reset
186 return;
187 }
188
189 self::failIfResetNotAllowed( __METHOD__ );
190
191 if ( $bootstrapConfig === null ) {
192 $bootstrapConfig = self::$instance->getBootstrapConfig();
193 }
194
195 $oldInstance = self::$instance;
196
197 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
198 self::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
199
200 if ( $quick === 'quick' ) {
201 self::$instance->salvage( $oldInstance );
202 } else {
203 $oldInstance->destroy();
204 }
205 }
206
207 /**
208 * Salvages the state of any salvageable service instances in $other.
209 *
210 * @note $other will have been destroyed when salvage() returns.
211 *
212 * @param MediaWikiServices $other
213 */
214 private function salvage( self $other ) {
215 foreach ( $this->getServiceNames() as $name ) {
216 // The service could be new in the new instance and not registered in the
217 // other instance (e.g. an extension that was loaded after the instantiation of
218 // the other instance. Skip this service in this case. See T143974
219 try {
220 $oldService = $other->peekService( $name );
221 } catch ( NoSuchServiceException $e ) {
222 continue;
223 }
224
225 if ( $oldService instanceof SalvageableService ) {
226 /** @var SalvageableService $newService */
227 $newService = $this->getService( $name );
228 $newService->salvage( $oldService );
229 }
230 }
231
232 $other->destroy();
233 }
234
235 /**
236 * Creates a new MediaWikiServices instance and initializes it according to the
237 * given $bootstrapConfig. In particular, all wiring files defined in the
238 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
239 *
240 * @param Config|null $bootstrapConfig The Config object to be registered as the
241 * 'BootstrapConfig' service.
242 *
243 * @param string $loadWiring set this to 'load' to load the wiring files specified
244 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
245 *
246 * @return MediaWikiServices
247 * @throws MWException
248 * @throws \FatalError
249 */
250 private static function newInstance( Config $bootstrapConfig, $loadWiring = '' ) {
251 $instance = new self( $bootstrapConfig );
252
253 // Load the default wiring from the specified files.
254 if ( $loadWiring === 'load' ) {
255 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
256 $instance->loadWiringFiles( $wiringFiles );
257 }
258
259 // Provide a traditional hook point to allow extensions to configure services.
260 Hooks::run( 'MediaWikiServices', [ $instance ] );
261
262 return $instance;
263 }
264
265 /**
266 * Disables all storage layer services. After calling this, any attempt to access the
267 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
268 * operation.
269 *
270 * @since 1.28
271 *
272 * @warning This is intended for extreme situations only and should never be used
273 * while serving normal web requests. Legitimate use cases for this method include
274 * the installation process. Test fixtures may also use this, if the fixture relies
275 * on globalState.
276 *
277 * @see resetGlobalInstance()
278 * @see resetChildProcessServices()
279 */
280 public static function disableStorageBackend() {
281 // TODO: also disable some Caches, JobQueues, etc
282 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
283 $services = self::getInstance();
284
285 foreach ( $destroy as $name ) {
286 $services->disableService( $name );
287 }
288
289 ObjectCache::clear();
290 }
291
292 /**
293 * Resets any services that may have become stale after a child process
294 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
295 * to call this method from the parent process.
296 *
297 * @since 1.28
298 *
299 * @note This is intended for use in the context of process forking only!
300 *
301 * @see resetGlobalInstance()
302 * @see disableStorageBackend()
303 */
304 public static function resetChildProcessServices() {
305 // NOTE: for now, just reset everything. Since we don't know the interdependencies
306 // between services, we can't do this more selectively at this time.
307 self::resetGlobalInstance();
308
309 // Child, reseed because there is no bug in PHP:
310 // https://bugs.php.net/bug.php?id=42465
311 mt_srand( getmypid() );
312 }
313
314 /**
315 * Resets the given service for testing purposes.
316 *
317 * @since 1.28
318 *
319 * @warning This is generally unsafe! Other services may still retain references
320 * to the stale service instance, leading to failures and inconsistencies. Subclasses
321 * may use this method to reset specific services under specific instances, but
322 * it should not be exposed to application logic.
323 *
324 * @note With proper dependency injection used throughout the codebase, this method
325 * should not be needed. It is provided to allow tests that pollute global service
326 * instances to clean up.
327 *
328 * @param string $name
329 * @param bool $destroy Whether the service instance should be destroyed if it exists.
330 * When set to false, any existing service instance will effectively be detached
331 * from the container.
332 *
333 * @throws MWException if called outside of PHPUnit tests.
334 */
335 public function resetServiceForTesting( $name, $destroy = true ) {
336 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
337 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
338 }
339
340 $this->resetService( $name, $destroy );
341 }
342
343 /**
344 * Convenience method that throws an exception unless it is called during a phase in which
345 * resetting of global services is allowed. In general, services should not be reset
346 * individually, since that may introduce inconsistencies.
347 *
348 * @since 1.28
349 *
350 * This method will throw an exception if:
351 *
352 * - self::$resetInProgress is false (to allow all services to be reset together
353 * via resetGlobalInstance)
354 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
355 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
356 *
357 * This method is intended to be used to safeguard against accidentally resetting
358 * global service instances that are not yet managed by MediaWikiServices. It is
359 * defined here in the MediaWikiServices services class to have a central place
360 * for managing service bootstrapping and resetting.
361 *
362 * @param string $method the name of the caller method, as given by __METHOD__.
363 *
364 * @throws MWException if called outside bootstrap mode.
365 *
366 * @see resetGlobalInstance()
367 * @see forceGlobalInstance()
368 * @see disableStorageBackend()
369 */
370 public static function failIfResetNotAllowed( $method ) {
371 if ( !defined( 'MW_PHPUNIT_TEST' )
372 && !defined( 'MW_PARSER_TEST' )
373 && !defined( 'MEDIAWIKI_INSTALL' )
374 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
375 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
376 ) {
377 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
378 }
379 }
380
381 /**
382 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
383 * This has to contain at least the information needed to set up the 'ConfigFactory'
384 * service.
385 */
386 public function __construct( Config $config ) {
387 parent::__construct();
388
389 // Register the given Config object as the bootstrap config service.
390 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
391 return $config;
392 } );
393 }
394
395 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
396
397 /**
398 * Returns the Config object containing the bootstrap configuration.
399 * Bootstrap configuration would typically include database credentials
400 * and other information that may be needed before the ConfigFactory
401 * service can be instantiated.
402 *
403 * @note This should only be used during bootstrapping, in particular
404 * when creating the MainConfig service. Application logic should
405 * use getMainConfig() to get a Config instances.
406 *
407 * @since 1.27
408 * @return Config
409 */
410 public function getBootstrapConfig() {
411 return $this->getService( 'BootstrapConfig' );
412 }
413
414 /**
415 * @since 1.27
416 * @return ConfigFactory
417 */
418 public function getConfigFactory() {
419 return $this->getService( 'ConfigFactory' );
420 }
421
422 /**
423 * Returns the Config object that provides configuration for MediaWiki core.
424 * This may or may not be the same object that is returned by getBootstrapConfig().
425 *
426 * @since 1.27
427 * @return Config
428 */
429 public function getMainConfig() {
430 return $this->getService( 'MainConfig' );
431 }
432
433 /**
434 * @since 1.27
435 * @return SiteLookup
436 */
437 public function getSiteLookup() {
438 return $this->getService( 'SiteLookup' );
439 }
440
441 /**
442 * @since 1.27
443 * @return SiteStore
444 */
445 public function getSiteStore() {
446 return $this->getService( 'SiteStore' );
447 }
448
449 /**
450 * @since 1.28
451 * @return InterwikiLookup
452 */
453 public function getInterwikiLookup() {
454 return $this->getService( 'InterwikiLookup' );
455 }
456
457 /**
458 * @since 1.27
459 * @return IBufferingStatsdDataFactory
460 */
461 public function getStatsdDataFactory() {
462 return $this->getService( 'StatsdDataFactory' );
463 }
464
465 /**
466 * @since 1.27
467 * @return EventRelayerGroup
468 */
469 public function getEventRelayerGroup() {
470 return $this->getService( 'EventRelayerGroup' );
471 }
472
473 /**
474 * @since 1.27
475 * @return SearchEngine
476 */
477 public function newSearchEngine() {
478 // New engine object every time, since they keep state
479 return $this->getService( 'SearchEngineFactory' )->create();
480 }
481
482 /**
483 * @since 1.27
484 * @return SearchEngineFactory
485 */
486 public function getSearchEngineFactory() {
487 return $this->getService( 'SearchEngineFactory' );
488 }
489
490 /**
491 * @since 1.27
492 * @return SearchEngineConfig
493 */
494 public function getSearchEngineConfig() {
495 return $this->getService( 'SearchEngineConfig' );
496 }
497
498 /**
499 * @since 1.27
500 * @return SkinFactory
501 */
502 public function getSkinFactory() {
503 return $this->getService( 'SkinFactory' );
504 }
505
506 /**
507 * @since 1.28
508 * @return LBFactory
509 */
510 public function getDBLoadBalancerFactory() {
511 return $this->getService( 'DBLoadBalancerFactory' );
512 }
513
514 /**
515 * @since 1.28
516 * @return LoadBalancer The main DB load balancer for the local wiki.
517 */
518 public function getDBLoadBalancer() {
519 return $this->getService( 'DBLoadBalancer' );
520 }
521
522 /**
523 * @since 1.28
524 * @return WatchedItemStoreInterface
525 */
526 public function getWatchedItemStore() {
527 return $this->getService( 'WatchedItemStore' );
528 }
529
530 /**
531 * @since 1.28
532 * @return WatchedItemQueryService
533 */
534 public function getWatchedItemQueryService() {
535 return $this->getService( 'WatchedItemQueryService' );
536 }
537
538 /**
539 * @since 1.28
540 * @return CryptRand
541 */
542 public function getCryptRand() {
543 return $this->getService( 'CryptRand' );
544 }
545
546 /**
547 * @since 1.28
548 * @return CryptHKDF
549 */
550 public function getCryptHKDF() {
551 return $this->getService( 'CryptHKDF' );
552 }
553
554 /**
555 * @since 1.28
556 * @return MediaHandlerFactory
557 */
558 public function getMediaHandlerFactory() {
559 return $this->getService( 'MediaHandlerFactory' );
560 }
561
562 /**
563 * @since 1.28
564 * @return MimeAnalyzer
565 */
566 public function getMimeAnalyzer() {
567 return $this->getService( 'MimeAnalyzer' );
568 }
569
570 /**
571 * @since 1.28
572 * @return ProxyLookup
573 */
574 public function getProxyLookup() {
575 return $this->getService( 'ProxyLookup' );
576 }
577
578 /**
579 * @since 1.29
580 * @return Parser
581 */
582 public function getParser() {
583 return $this->getService( 'Parser' );
584 }
585
586 /**
587 * @since 1.30
588 * @return ParserCache
589 */
590 public function getParserCache() {
591 return $this->getService( 'ParserCache' );
592 }
593
594 /**
595 * @since 1.28
596 * @return GenderCache
597 */
598 public function getGenderCache() {
599 return $this->getService( 'GenderCache' );
600 }
601
602 /**
603 * @since 1.28
604 * @return LinkCache
605 */
606 public function getLinkCache() {
607 return $this->getService( 'LinkCache' );
608 }
609
610 /**
611 * @since 1.28
612 * @return LinkRendererFactory
613 */
614 public function getLinkRendererFactory() {
615 return $this->getService( 'LinkRendererFactory' );
616 }
617
618 /**
619 * LinkRenderer instance that can be used
620 * if no custom options are needed
621 *
622 * @since 1.28
623 * @return LinkRenderer
624 */
625 public function getLinkRenderer() {
626 return $this->getService( 'LinkRenderer' );
627 }
628
629 /**
630 * @since 1.28
631 * @return TitleFormatter
632 */
633 public function getTitleFormatter() {
634 return $this->getService( 'TitleFormatter' );
635 }
636
637 /**
638 * @since 1.28
639 * @return TitleParser
640 */
641 public function getTitleParser() {
642 return $this->getService( 'TitleParser' );
643 }
644
645 /**
646 * @since 1.28
647 * @return \BagOStuff
648 */
649 public function getMainObjectStash() {
650 return $this->getService( 'MainObjectStash' );
651 }
652
653 /**
654 * @since 1.28
655 * @return \WANObjectCache
656 */
657 public function getMainWANObjectCache() {
658 return $this->getService( 'MainWANObjectCache' );
659 }
660
661 /**
662 * @since 1.28
663 * @return \BagOStuff
664 */
665 public function getLocalServerObjectCache() {
666 return $this->getService( 'LocalServerObjectCache' );
667 }
668
669 /**
670 * @since 1.28
671 * @return VirtualRESTServiceClient
672 */
673 public function getVirtualRESTServiceClient() {
674 return $this->getService( 'VirtualRESTServiceClient' );
675 }
676
677 /**
678 * @since 1.29
679 * @return \ConfiguredReadOnlyMode
680 */
681 public function getConfiguredReadOnlyMode() {
682 return $this->getService( 'ConfiguredReadOnlyMode' );
683 }
684
685 /**
686 * @since 1.29
687 * @return \ReadOnlyMode
688 */
689 public function getReadOnlyMode() {
690 return $this->getService( 'ReadOnlyMode' );
691 }
692
693 /**
694 * @since 1.31
695 * @return \UploadRevisionImporter
696 */
697 public function getWikiRevisionUploadImporter() {
698 return $this->getService( 'UploadRevisionImporter' );
699 }
700
701 /**
702 * @since 1.31
703 * @return \OldRevisionImporter
704 */
705 public function getWikiRevisionOldRevisionImporter() {
706 return $this->getService( 'OldRevisionImporter' );
707 }
708
709 /**
710 * @since 1.31
711 * @return \OldRevisionImporter
712 */
713 public function getWikiRevisionOldRevisionImporterNoUpdates() {
714 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
715 }
716
717 /**
718 * @since 1.30
719 * @return CommandFactory
720 */
721 public function getShellCommandFactory() {
722 return $this->getService( 'ShellCommandFactory' );
723 }
724
725 /**
726 * @since 1.31
727 * @return \ExternalStoreFactory
728 */
729 public function getExternalStoreFactory() {
730 return $this->getService( 'ExternalStoreFactory' );
731 }
732
733 /**
734 * @since 1.31
735 * @return BlobStoreFactory
736 */
737 public function getBlobStoreFactory() {
738 return $this->getService( 'BlobStoreFactory' );
739 }
740
741 /**
742 * @since 1.31
743 * @return BlobStore
744 */
745 public function getBlobStore() {
746 return $this->getService( '_SqlBlobStore' );
747 }
748
749 /**
750 * @since 1.31
751 * @return RevisionStore
752 */
753 public function getRevisionStore() {
754 return $this->getService( 'RevisionStore' );
755 }
756
757 /**
758 * @since 1.31
759 * @return RevisionLookup
760 */
761 public function getRevisionLookup() {
762 return $this->getService( 'RevisionLookup' );
763 }
764
765 /**
766 * @since 1.31
767 * @return RevisionFactory
768 */
769 public function getRevisionFactory() {
770 return $this->getService( 'RevisionFactory' );
771 }
772
773 /**
774 * @since 1.31
775 * @return PreferencesFactory
776 */
777 public function getPreferencesFactory() {
778 return $this->getService( 'PreferencesFactory' );
779 }
780
781 /**
782 * @since 1.31
783 * @return HttpRequestFactory
784 */
785 public function getHttpRequestFactory() {
786 return $this->getService( 'HttpRequestFactory' );
787 }
788
789 /**
790 * @since 1.31
791 * @return CommentStore
792 */
793 public function getCommentStore() {
794 return $this->getService( 'CommentStore' );
795 }
796
797 ///////////////////////////////////////////////////////////////////////////
798 // NOTE: When adding a service getter here, don't forget to add a test
799 // case for it in MediaWikiServicesTest::provideGetters() and in
800 // MediaWikiServicesTest::provideGetService()!
801 ///////////////////////////////////////////////////////////////////////////
802
803 }