Remove duplicate ServiceWiring definitions
[lhc/web/wiklou.git] / includes / ServiceWiring.php
1 <?php
2 /**
3 * Default wiring for MediaWiki services.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 *
22 * This file is loaded by MediaWiki\MediaWikiServices::getInstance() during the
23 * bootstrapping of the dependency injection framework.
24 *
25 * This file returns an array that associates service name with instantiator functions
26 * that create the default instances for the services used by MediaWiki core.
27 * For every service that MediaWiki core requires, an instantiator must be defined in
28 * this file.
29 *
30 * @note As of version 1.27, MediaWiki is only beginning to use dependency injection.
31 * The services defined here do not yet fully represent all services used by core,
32 * much of the code still relies on global state for this accessing services.
33 *
34 * @since 1.27
35 *
36 * @see docs/injection.txt for an overview of using dependency injection in the
37 * MediaWiki code base.
38 */
39
40 use MediaWiki\Interwiki\ClassicInterwikiLookup;
41 use MediaWiki\Linker\LinkRendererFactory;
42 use MediaWiki\Logger\LoggerFactory;
43 use MediaWiki\MediaWikiServices;
44 use MediaWiki\Shell\CommandFactory;
45 use MediaWiki\Storage\RevisionStore;
46 use MediaWiki\Storage\SqlBlobStore;
47
48 return [
49 'DBLoadBalancerFactory' => function ( MediaWikiServices $services ) {
50 $mainConfig = $services->getMainConfig();
51
52 $lbConf = MWLBFactory::applyDefaultConfig(
53 $mainConfig->get( 'LBFactoryConf' ),
54 $mainConfig,
55 $services->getConfiguredReadOnlyMode()
56 );
57 $class = MWLBFactory::getLBFactoryClass( $lbConf );
58
59 return new $class( $lbConf );
60 },
61
62 'DBLoadBalancer' => function ( MediaWikiServices $services ) {
63 // just return the default LB from the DBLoadBalancerFactory service
64 return $services->getDBLoadBalancerFactory()->getMainLB();
65 },
66
67 'SiteStore' => function ( MediaWikiServices $services ) {
68 $rawSiteStore = new DBSiteStore( $services->getDBLoadBalancer() );
69
70 // TODO: replace wfGetCache with a CacheFactory service.
71 // TODO: replace wfIsHHVM with a capabilities service.
72 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL : CACHE_ANYTHING );
73
74 return new CachingSiteStore( $rawSiteStore, $cache );
75 },
76
77 'SiteLookup' => function ( MediaWikiServices $services ) {
78 $cacheFile = $services->getMainConfig()->get( 'SitesCacheFile' );
79
80 if ( $cacheFile !== false ) {
81 return new FileBasedSiteLookup( $cacheFile );
82 } else {
83 // Use the default SiteStore as the SiteLookup implementation for now
84 return $services->getSiteStore();
85 }
86 },
87
88 'ConfigFactory' => function ( MediaWikiServices $services ) {
89 // Use the bootstrap config to initialize the ConfigFactory.
90 $registry = $services->getBootstrapConfig()->get( 'ConfigRegistry' );
91 $factory = new ConfigFactory();
92
93 foreach ( $registry as $name => $callback ) {
94 $factory->register( $name, $callback );
95 }
96 return $factory;
97 },
98
99 'MainConfig' => function ( MediaWikiServices $services ) {
100 // Use the 'main' config from the ConfigFactory service.
101 return $services->getConfigFactory()->makeConfig( 'main' );
102 },
103
104 'InterwikiLookup' => function ( MediaWikiServices $services ) {
105 global $wgContLang; // TODO: manage $wgContLang as a service
106 $config = $services->getMainConfig();
107 return new ClassicInterwikiLookup(
108 $wgContLang,
109 $services->getMainWANObjectCache(),
110 $config->get( 'InterwikiExpiry' ),
111 $config->get( 'InterwikiCache' ),
112 $config->get( 'InterwikiScopes' ),
113 $config->get( 'InterwikiFallbackSite' )
114 );
115 },
116
117 'StatsdDataFactory' => function ( MediaWikiServices $services ) {
118 return new BufferingStatsdDataFactory(
119 rtrim( $services->getMainConfig()->get( 'StatsdMetricPrefix' ), '.' )
120 );
121 },
122
123 'EventRelayerGroup' => function ( MediaWikiServices $services ) {
124 return new EventRelayerGroup( $services->getMainConfig()->get( 'EventRelayerConfig' ) );
125 },
126
127 'SearchEngineFactory' => function ( MediaWikiServices $services ) {
128 return new SearchEngineFactory( $services->getSearchEngineConfig() );
129 },
130
131 'SearchEngineConfig' => function ( MediaWikiServices $services ) {
132 global $wgContLang;
133 return new SearchEngineConfig( $services->getMainConfig(), $wgContLang );
134 },
135
136 'SkinFactory' => function ( MediaWikiServices $services ) {
137 $factory = new SkinFactory();
138
139 $names = $services->getMainConfig()->get( 'ValidSkinNames' );
140
141 foreach ( $names as $name => $skin ) {
142 $factory->register( $name, $skin, function () use ( $name, $skin ) {
143 $class = "Skin$skin";
144 return new $class( $name );
145 } );
146 }
147 // Register a hidden "fallback" skin
148 $factory->register( 'fallback', 'Fallback', function () {
149 return new SkinFallback;
150 } );
151 // Register a hidden skin for api output
152 $factory->register( 'apioutput', 'ApiOutput', function () {
153 return new SkinApi;
154 } );
155
156 return $factory;
157 },
158
159 'WatchedItemStore' => function ( MediaWikiServices $services ) {
160 $store = new WatchedItemStore(
161 $services->getDBLoadBalancer(),
162 new HashBagOStuff( [ 'maxKeys' => 100 ] ),
163 $services->getReadOnlyMode()
164 );
165 $store->setStatsdDataFactory( $services->getStatsdDataFactory() );
166 return $store;
167 },
168
169 'WatchedItemQueryService' => function ( MediaWikiServices $services ) {
170 return new WatchedItemQueryService( $services->getDBLoadBalancer() );
171 },
172
173 'CryptRand' => function ( MediaWikiServices $services ) {
174 $secretKey = $services->getMainConfig()->get( 'SecretKey' );
175 return new CryptRand(
176 [
177 // To try vary the system information of the state a bit more
178 // by including the system's hostname into the state
179 'wfHostname',
180 // It's mostly worthless but throw the wiki's id into the data
181 // for a little more variance
182 'wfWikiID',
183 // If we have a secret key set then throw it into the state as well
184 function () use ( $secretKey ) {
185 return $secretKey ?: '';
186 }
187 ],
188 // The config file is likely the most often edited file we know should
189 // be around so include its stat info into the state.
190 // The constant with its location will almost always be defined, as
191 // WebStart.php defines MW_CONFIG_FILE to $IP/LocalSettings.php unless
192 // being configured with MW_CONFIG_CALLBACK (e.g. the installer).
193 defined( 'MW_CONFIG_FILE' ) ? [ MW_CONFIG_FILE ] : [],
194 LoggerFactory::getInstance( 'CryptRand' )
195 );
196 },
197
198 'CryptHKDF' => function ( MediaWikiServices $services ) {
199 $config = $services->getMainConfig();
200
201 $secret = $config->get( 'HKDFSecret' ) ?: $config->get( 'SecretKey' );
202 if ( !$secret ) {
203 throw new RuntimeException( "Cannot use MWCryptHKDF without a secret." );
204 }
205
206 // In HKDF, the context can be known to the attacker, but this will
207 // keep simultaneous runs from producing the same output.
208 $context = [ microtime(), getmypid(), gethostname() ];
209
210 // Setup salt cache. Use APC, or fallback to the main cache if it isn't setup
211 $cache = $services->getLocalServerObjectCache();
212 if ( $cache instanceof EmptyBagOStuff ) {
213 $cache = ObjectCache::getLocalClusterInstance();
214 }
215
216 return new CryptHKDF( $secret, $config->get( 'HKDFAlgorithm' ),
217 $cache, $context, $services->getCryptRand()
218 );
219 },
220
221 'MediaHandlerFactory' => function ( MediaWikiServices $services ) {
222 return new MediaHandlerFactory(
223 $services->getMainConfig()->get( 'MediaHandlers' )
224 );
225 },
226
227 'MimeAnalyzer' => function ( MediaWikiServices $services ) {
228 $logger = LoggerFactory::getInstance( 'Mime' );
229 $mainConfig = $services->getMainConfig();
230 $params = [
231 'typeFile' => $mainConfig->get( 'MimeTypeFile' ),
232 'infoFile' => $mainConfig->get( 'MimeInfoFile' ),
233 'xmlTypes' => $mainConfig->get( 'XMLMimeTypes' ),
234 'guessCallback' =>
235 function ( $mimeAnalyzer, &$head, &$tail, $file, &$mime ) use ( $logger ) {
236 // Also test DjVu
237 $deja = new DjVuImage( $file );
238 if ( $deja->isValid() ) {
239 $logger->info( __METHOD__ . ": detected $file as image/vnd.djvu\n" );
240 $mime = 'image/vnd.djvu';
241
242 return;
243 }
244 // Some strings by reference for performance - assuming well-behaved hooks
245 Hooks::run(
246 'MimeMagicGuessFromContent',
247 [ $mimeAnalyzer, &$head, &$tail, $file, &$mime ]
248 );
249 },
250 'extCallback' => function ( $mimeAnalyzer, $ext, &$mime ) {
251 // Media handling extensions can improve the MIME detected
252 Hooks::run( 'MimeMagicImproveFromExtension', [ $mimeAnalyzer, $ext, &$mime ] );
253 },
254 'initCallback' => function ( $mimeAnalyzer ) {
255 // Allow media handling extensions adding MIME-types and MIME-info
256 Hooks::run( 'MimeMagicInit', [ $mimeAnalyzer ] );
257 },
258 'logger' => $logger
259 ];
260
261 if ( $params['infoFile'] === 'includes/mime.info' ) {
262 $params['infoFile'] = __DIR__ . "/libs/mime/mime.info";
263 }
264
265 if ( $params['typeFile'] === 'includes/mime.types' ) {
266 $params['typeFile'] = __DIR__ . "/libs/mime/mime.types";
267 }
268
269 $detectorCmd = $mainConfig->get( 'MimeDetectorCommand' );
270 if ( $detectorCmd ) {
271 $params['detectCallback'] = function ( $file ) use ( $detectorCmd ) {
272 return wfShellExec( "$detectorCmd " . wfEscapeShellArg( $file ) );
273 };
274 }
275
276 // XXX: MimeMagic::singleton currently requires this service to return an instance of MimeMagic
277 return new MimeMagic( $params );
278 },
279
280 'ProxyLookup' => function ( MediaWikiServices $services ) {
281 $mainConfig = $services->getMainConfig();
282 return new ProxyLookup(
283 $mainConfig->get( 'SquidServers' ),
284 $mainConfig->get( 'SquidServersNoPurge' )
285 );
286 },
287
288 'Parser' => function ( MediaWikiServices $services ) {
289 $conf = $services->getMainConfig()->get( 'ParserConf' );
290 return ObjectFactory::constructClassInstance( $conf['class'], [ $conf ] );
291 },
292
293 'ParserCache' => function ( MediaWikiServices $services ) {
294 $config = $services->getMainConfig();
295 $cache = ObjectCache::getInstance( $config->get( 'ParserCacheType' ) );
296 wfDebugLog( 'caches', 'parser: ' . get_class( $cache ) );
297
298 return new ParserCache(
299 $cache,
300 $config->get( 'CacheEpoch' )
301 );
302 },
303
304 'LinkCache' => function ( MediaWikiServices $services ) {
305 return new LinkCache(
306 $services->getTitleFormatter(),
307 $services->getMainWANObjectCache()
308 );
309 },
310
311 'LinkRendererFactory' => function ( MediaWikiServices $services ) {
312 return new LinkRendererFactory(
313 $services->getTitleFormatter(),
314 $services->getLinkCache()
315 );
316 },
317
318 'LinkRenderer' => function ( MediaWikiServices $services ) {
319 global $wgUser;
320
321 if ( defined( 'MW_NO_SESSION' ) ) {
322 return $services->getLinkRendererFactory()->create();
323 } else {
324 return $services->getLinkRendererFactory()->createForUser( $wgUser );
325 }
326 },
327
328 'GenderCache' => function ( MediaWikiServices $services ) {
329 return new GenderCache();
330 },
331
332 '_MediaWikiTitleCodec' => function ( MediaWikiServices $services ) {
333 global $wgContLang;
334
335 return new MediaWikiTitleCodec(
336 $wgContLang,
337 $services->getGenderCache(),
338 $services->getMainConfig()->get( 'LocalInterwikis' )
339 );
340 },
341
342 'TitleFormatter' => function ( MediaWikiServices $services ) {
343 return $services->getService( '_MediaWikiTitleCodec' );
344 },
345
346 'TitleParser' => function ( MediaWikiServices $services ) {
347 return $services->getService( '_MediaWikiTitleCodec' );
348 },
349
350 'MainObjectStash' => function ( MediaWikiServices $services ) {
351 $mainConfig = $services->getMainConfig();
352
353 $id = $mainConfig->get( 'MainStash' );
354 if ( !isset( $mainConfig->get( 'ObjectCaches' )[$id] ) ) {
355 throw new UnexpectedValueException(
356 "Cache type \"$id\" is not present in \$wgObjectCaches." );
357 }
358
359 return \ObjectCache::newFromParams( $mainConfig->get( 'ObjectCaches' )[$id] );
360 },
361
362 'MainWANObjectCache' => function ( MediaWikiServices $services ) {
363 $mainConfig = $services->getMainConfig();
364
365 $id = $mainConfig->get( 'MainWANCache' );
366 if ( !isset( $mainConfig->get( 'WANObjectCaches' )[$id] ) ) {
367 throw new UnexpectedValueException(
368 "WAN cache type \"$id\" is not present in \$wgWANObjectCaches." );
369 }
370
371 $params = $mainConfig->get( 'WANObjectCaches' )[$id];
372 $objectCacheId = $params['cacheId'];
373 if ( !isset( $mainConfig->get( 'ObjectCaches' )[$objectCacheId] ) ) {
374 throw new UnexpectedValueException(
375 "Cache type \"$objectCacheId\" is not present in \$wgObjectCaches." );
376 }
377 $params['store'] = $mainConfig->get( 'ObjectCaches' )[$objectCacheId];
378
379 return \ObjectCache::newWANCacheFromParams( $params );
380 },
381
382 'LocalServerObjectCache' => function ( MediaWikiServices $services ) {
383 $mainConfig = $services->getMainConfig();
384
385 if ( function_exists( 'apc_fetch' ) ) {
386 $id = 'apc';
387 } elseif ( function_exists( 'apcu_fetch' ) ) {
388 $id = 'apcu';
389 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
390 $id = 'xcache';
391 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
392 $id = 'wincache';
393 } else {
394 $id = CACHE_NONE;
395 }
396
397 if ( !isset( $mainConfig->get( 'ObjectCaches' )[$id] ) ) {
398 throw new UnexpectedValueException(
399 "Cache type \"$id\" is not present in \$wgObjectCaches." );
400 }
401
402 return \ObjectCache::newFromParams( $mainConfig->get( 'ObjectCaches' )[$id] );
403 },
404
405 'VirtualRESTServiceClient' => function ( MediaWikiServices $services ) {
406 $config = $services->getMainConfig()->get( 'VirtualRestConfig' );
407
408 $vrsClient = new VirtualRESTServiceClient( new MultiHttpClient( [] ) );
409 foreach ( $config['paths'] as $prefix => $serviceConfig ) {
410 $class = $serviceConfig['class'];
411 // Merge in the global defaults
412 $constructArg = isset( $serviceConfig['options'] )
413 ? $serviceConfig['options']
414 : [];
415 $constructArg += $config['global'];
416 // Make the VRS service available at the mount point
417 $vrsClient->mount( $prefix, [ 'class' => $class, 'config' => $constructArg ] );
418 }
419
420 return $vrsClient;
421 },
422
423 'ConfiguredReadOnlyMode' => function ( MediaWikiServices $services ) {
424 return new ConfiguredReadOnlyMode( $services->getMainConfig() );
425 },
426
427 'ReadOnlyMode' => function ( MediaWikiServices $services ) {
428 return new ReadOnlyMode(
429 $services->getConfiguredReadOnlyMode(),
430 $services->getDBLoadBalancer()
431 );
432 },
433
434 'ShellCommandFactory' => function ( MediaWikiServices $services ) {
435 $config = $services->getMainConfig();
436
437 $limits = [
438 'time' => $config->get( 'MaxShellTime' ),
439 'walltime' => $config->get( 'MaxShellWallClockTime' ),
440 'memory' => $config->get( 'MaxShellMemory' ),
441 'filesize' => $config->get( 'MaxShellFileSize' ),
442 ];
443 $cgroup = $config->get( 'ShellCgroup' );
444 $restrictionMethod = $config->get( 'ShellRestrictionMethod' );
445
446 $factory = new CommandFactory( $limits, $cgroup, $restrictionMethod );
447 $factory->setLogger( LoggerFactory::getInstance( 'exec' ) );
448 $factory->logStderr();
449
450 return $factory;
451 },
452
453 'ExternalStoreFactory' => function ( MediaWikiServices $services ) {
454 $config = $services->getMainConfig();
455
456 return new ExternalStoreFactory(
457 $config->get( 'ExternalStores' )
458 );
459 },
460
461 'RevisionStore' => function ( MediaWikiServices $services ) {
462 /** @var SqlBlobStore $blobStore */
463 $blobStore = $services->getService( '_SqlBlobStore' );
464
465 $store = new RevisionStore(
466 $services->getDBLoadBalancer(),
467 $blobStore,
468 $services->getMainWANObjectCache()
469 );
470
471 $config = $services->getMainConfig();
472 $store->setContentHandlerUseDB( $config->get( 'ContentHandlerUseDB' ) );
473
474 return $store;
475 },
476
477 'BlobStore' => function ( MediaWikiServices $services ) {
478 return $services->getService( '_SqlBlobStore' );
479 },
480
481 '_SqlBlobStore' => function ( MediaWikiServices $services ) {
482 global $wgContLang; // TODO: manage $wgContLang as a service
483
484 $store = new SqlBlobStore(
485 $services->getDBLoadBalancer(),
486 $services->getMainWANObjectCache()
487 );
488
489 $config = $services->getMainConfig();
490 $store->setCompressBlobs( $config->get( 'CompressRevisions' ) );
491 $store->setCacheExpiry( $config->get( 'RevisionCacheExpiry' ) );
492 $store->setUseExternalStore( $config->get( 'DefaultExternalStore' ) !== false );
493
494 if ( $config->get( 'LegacyEncoding' ) ) {
495 $store->setLegacyEncoding( $config->get( 'LegacyEncoding' ), $wgContLang );
496 }
497
498 return $store;
499 },
500
501 ///////////////////////////////////////////////////////////////////////////
502 // NOTE: When adding a service here, don't forget to add a getter function
503 // in the MediaWikiServices class. The convenience getter should just call
504 // $this->getService( 'FooBarService' ).
505 ///////////////////////////////////////////////////////////////////////////
506
507 ];