Merge "Fix and make some types in PHPDoc and JSDoc tags more specific"
[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
45 return [
46 'DBLoadBalancerFactory' => function ( MediaWikiServices $services ) {
47 $mainConfig = $services->getMainConfig();
48
49 $lbConf = MWLBFactory::applyDefaultConfig(
50 $mainConfig->get( 'LBFactoryConf' ),
51 $mainConfig,
52 $services->getConfiguredReadOnlyMode()
53 );
54 $class = MWLBFactory::getLBFactoryClass( $lbConf );
55
56 return new $class( $lbConf );
57 },
58
59 'DBLoadBalancer' => function ( MediaWikiServices $services ) {
60 // just return the default LB from the DBLoadBalancerFactory service
61 return $services->getDBLoadBalancerFactory()->getMainLB();
62 },
63
64 'SiteStore' => function ( MediaWikiServices $services ) {
65 $rawSiteStore = new DBSiteStore( $services->getDBLoadBalancer() );
66
67 // TODO: replace wfGetCache with a CacheFactory service.
68 // TODO: replace wfIsHHVM with a capabilities service.
69 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL : CACHE_ANYTHING );
70
71 return new CachingSiteStore( $rawSiteStore, $cache );
72 },
73
74 'SiteLookup' => function ( MediaWikiServices $services ) {
75 $cacheFile = $services->getMainConfig()->get( 'SitesCacheFile' );
76
77 if ( $cacheFile !== false ) {
78 return new FileBasedSiteLookup( $cacheFile );
79 } else {
80 // Use the default SiteStore as the SiteLookup implementation for now
81 return $services->getSiteStore();
82 }
83 },
84
85 'ConfigFactory' => function ( MediaWikiServices $services ) {
86 // Use the bootstrap config to initialize the ConfigFactory.
87 $registry = $services->getBootstrapConfig()->get( 'ConfigRegistry' );
88 $factory = new ConfigFactory();
89
90 foreach ( $registry as $name => $callback ) {
91 $factory->register( $name, $callback );
92 }
93 return $factory;
94 },
95
96 'MainConfig' => function ( MediaWikiServices $services ) {
97 // Use the 'main' config from the ConfigFactory service.
98 return $services->getConfigFactory()->makeConfig( 'main' );
99 },
100
101 'InterwikiLookup' => function ( MediaWikiServices $services ) {
102 global $wgContLang; // TODO: manage $wgContLang as a service
103 $config = $services->getMainConfig();
104 return new ClassicInterwikiLookup(
105 $wgContLang,
106 $services->getMainWANObjectCache(),
107 $config->get( 'InterwikiExpiry' ),
108 $config->get( 'InterwikiCache' ),
109 $config->get( 'InterwikiScopes' ),
110 $config->get( 'InterwikiFallbackSite' )
111 );
112 },
113
114 'StatsdDataFactory' => function ( MediaWikiServices $services ) {
115 return new BufferingStatsdDataFactory(
116 rtrim( $services->getMainConfig()->get( 'StatsdMetricPrefix' ), '.' )
117 );
118 },
119
120 'EventRelayerGroup' => function ( MediaWikiServices $services ) {
121 return new EventRelayerGroup( $services->getMainConfig()->get( 'EventRelayerConfig' ) );
122 },
123
124 'SearchEngineFactory' => function ( MediaWikiServices $services ) {
125 return new SearchEngineFactory( $services->getSearchEngineConfig() );
126 },
127
128 'SearchEngineConfig' => function ( MediaWikiServices $services ) {
129 global $wgContLang;
130 return new SearchEngineConfig( $services->getMainConfig(), $wgContLang );
131 },
132
133 'SkinFactory' => function ( MediaWikiServices $services ) {
134 $factory = new SkinFactory();
135
136 $names = $services->getMainConfig()->get( 'ValidSkinNames' );
137
138 foreach ( $names as $name => $skin ) {
139 $factory->register( $name, $skin, function () use ( $name, $skin ) {
140 $class = "Skin$skin";
141 return new $class( $name );
142 } );
143 }
144 // Register a hidden "fallback" skin
145 $factory->register( 'fallback', 'Fallback', function () {
146 return new SkinFallback;
147 } );
148 // Register a hidden skin for api output
149 $factory->register( 'apioutput', 'ApiOutput', function () {
150 return new SkinApi;
151 } );
152
153 return $factory;
154 },
155
156 'WatchedItemStore' => function ( MediaWikiServices $services ) {
157 $store = new WatchedItemStore(
158 $services->getDBLoadBalancer(),
159 new HashBagOStuff( [ 'maxKeys' => 100 ] ),
160 $services->getReadOnlyMode()
161 );
162 $store->setStatsdDataFactory( $services->getStatsdDataFactory() );
163 return $store;
164 },
165
166 'WatchedItemQueryService' => function ( MediaWikiServices $services ) {
167 return new WatchedItemQueryService( $services->getDBLoadBalancer() );
168 },
169
170 'CryptRand' => function ( MediaWikiServices $services ) {
171 $secretKey = $services->getMainConfig()->get( 'SecretKey' );
172 return new CryptRand(
173 [
174 // To try vary the system information of the state a bit more
175 // by including the system's hostname into the state
176 'wfHostname',
177 // It's mostly worthless but throw the wiki's id into the data
178 // for a little more variance
179 'wfWikiID',
180 // If we have a secret key set then throw it into the state as well
181 function () use ( $secretKey ) {
182 return $secretKey ?: '';
183 }
184 ],
185 // The config file is likely the most often edited file we know should
186 // be around so include its stat info into the state.
187 // The constant with its location will almost always be defined, as
188 // WebStart.php defines MW_CONFIG_FILE to $IP/LocalSettings.php unless
189 // being configured with MW_CONFIG_CALLBACK (e.g. the installer).
190 defined( 'MW_CONFIG_FILE' ) ? [ MW_CONFIG_FILE ] : [],
191 LoggerFactory::getInstance( 'CryptRand' )
192 );
193 },
194
195 'CryptHKDF' => function ( MediaWikiServices $services ) {
196 $config = $services->getMainConfig();
197
198 $secret = $config->get( 'HKDFSecret' ) ?: $config->get( 'SecretKey' );
199 if ( !$secret ) {
200 throw new RuntimeException( "Cannot use MWCryptHKDF without a secret." );
201 }
202
203 // In HKDF, the context can be known to the attacker, but this will
204 // keep simultaneous runs from producing the same output.
205 $context = [ microtime(), getmypid(), gethostname() ];
206
207 // Setup salt cache. Use APC, or fallback to the main cache if it isn't setup
208 $cache = $services->getLocalServerObjectCache();
209 if ( $cache instanceof EmptyBagOStuff ) {
210 $cache = ObjectCache::getLocalClusterInstance();
211 }
212
213 return new CryptHKDF( $secret, $config->get( 'HKDFAlgorithm' ),
214 $cache, $context, $services->getCryptRand()
215 );
216 },
217
218 'MediaHandlerFactory' => function ( MediaWikiServices $services ) {
219 return new MediaHandlerFactory(
220 $services->getMainConfig()->get( 'MediaHandlers' )
221 );
222 },
223
224 'MimeAnalyzer' => function ( MediaWikiServices $services ) {
225 $logger = LoggerFactory::getInstance( 'Mime' );
226 $mainConfig = $services->getMainConfig();
227 $params = [
228 'typeFile' => $mainConfig->get( 'MimeTypeFile' ),
229 'infoFile' => $mainConfig->get( 'MimeInfoFile' ),
230 'xmlTypes' => $mainConfig->get( 'XMLMimeTypes' ),
231 'guessCallback' =>
232 function ( $mimeAnalyzer, &$head, &$tail, $file, &$mime ) use ( $logger ) {
233 // Also test DjVu
234 $deja = new DjVuImage( $file );
235 if ( $deja->isValid() ) {
236 $logger->info( __METHOD__ . ": detected $file as image/vnd.djvu\n" );
237 $mime = 'image/vnd.djvu';
238
239 return;
240 }
241 // Some strings by reference for performance - assuming well-behaved hooks
242 Hooks::run(
243 'MimeMagicGuessFromContent',
244 [ $mimeAnalyzer, &$head, &$tail, $file, &$mime ]
245 );
246 },
247 'extCallback' => function ( $mimeAnalyzer, $ext, &$mime ) {
248 // Media handling extensions can improve the MIME detected
249 Hooks::run( 'MimeMagicImproveFromExtension', [ $mimeAnalyzer, $ext, &$mime ] );
250 },
251 'initCallback' => function ( $mimeAnalyzer ) {
252 // Allow media handling extensions adding MIME-types and MIME-info
253 Hooks::run( 'MimeMagicInit', [ $mimeAnalyzer ] );
254 },
255 'logger' => $logger
256 ];
257
258 if ( $params['infoFile'] === 'includes/mime.info' ) {
259 $params['infoFile'] = __DIR__ . "/libs/mime/mime.info";
260 }
261
262 if ( $params['typeFile'] === 'includes/mime.types' ) {
263 $params['typeFile'] = __DIR__ . "/libs/mime/mime.types";
264 }
265
266 $detectorCmd = $mainConfig->get( 'MimeDetectorCommand' );
267 if ( $detectorCmd ) {
268 $params['detectCallback'] = function ( $file ) use ( $detectorCmd ) {
269 return wfShellExec( "$detectorCmd " . wfEscapeShellArg( $file ) );
270 };
271 }
272
273 // XXX: MimeMagic::singleton currently requires this service to return an instance of MimeMagic
274 return new MimeMagic( $params );
275 },
276
277 'ProxyLookup' => function ( MediaWikiServices $services ) {
278 $mainConfig = $services->getMainConfig();
279 return new ProxyLookup(
280 $mainConfig->get( 'SquidServers' ),
281 $mainConfig->get( 'SquidServersNoPurge' )
282 );
283 },
284
285 'Parser' => function ( MediaWikiServices $services ) {
286 $conf = $services->getMainConfig()->get( 'ParserConf' );
287 return ObjectFactory::constructClassInstance( $conf['class'], [ $conf ] );
288 },
289
290 'ParserCache' => function ( MediaWikiServices $services ) {
291 $config = $services->getMainConfig();
292 $cache = ObjectCache::getInstance( $config->get( 'ParserCacheType' ) );
293 wfDebugLog( 'caches', 'parser: ' . get_class( $cache ) );
294
295 return new ParserCache(
296 $cache,
297 $config->get( 'CacheEpoch' )
298 );
299 },
300
301 'LinkCache' => function ( MediaWikiServices $services ) {
302 return new LinkCache(
303 $services->getTitleFormatter(),
304 $services->getMainWANObjectCache()
305 );
306 },
307
308 'LinkRendererFactory' => function ( MediaWikiServices $services ) {
309 return new LinkRendererFactory(
310 $services->getTitleFormatter(),
311 $services->getLinkCache()
312 );
313 },
314
315 'LinkRenderer' => function ( MediaWikiServices $services ) {
316 global $wgUser;
317
318 if ( defined( 'MW_NO_SESSION' ) ) {
319 return $services->getLinkRendererFactory()->create();
320 } else {
321 return $services->getLinkRendererFactory()->createForUser( $wgUser );
322 }
323 },
324
325 'GenderCache' => function ( MediaWikiServices $services ) {
326 return new GenderCache();
327 },
328
329 '_MediaWikiTitleCodec' => function ( MediaWikiServices $services ) {
330 global $wgContLang;
331
332 return new MediaWikiTitleCodec(
333 $wgContLang,
334 $services->getGenderCache(),
335 $services->getMainConfig()->get( 'LocalInterwikis' )
336 );
337 },
338
339 'TitleFormatter' => function ( MediaWikiServices $services ) {
340 return $services->getService( '_MediaWikiTitleCodec' );
341 },
342
343 'TitleParser' => function ( MediaWikiServices $services ) {
344 return $services->getService( '_MediaWikiTitleCodec' );
345 },
346
347 'MainObjectStash' => function ( MediaWikiServices $services ) {
348 $mainConfig = $services->getMainConfig();
349
350 $id = $mainConfig->get( 'MainStash' );
351 if ( !isset( $mainConfig->get( 'ObjectCaches' )[$id] ) ) {
352 throw new UnexpectedValueException(
353 "Cache type \"$id\" is not present in \$wgObjectCaches." );
354 }
355
356 return \ObjectCache::newFromParams( $mainConfig->get( 'ObjectCaches' )[$id] );
357 },
358
359 'MainWANObjectCache' => function ( MediaWikiServices $services ) {
360 $mainConfig = $services->getMainConfig();
361
362 $id = $mainConfig->get( 'MainWANCache' );
363 if ( !isset( $mainConfig->get( 'WANObjectCaches' )[$id] ) ) {
364 throw new UnexpectedValueException(
365 "WAN cache type \"$id\" is not present in \$wgWANObjectCaches." );
366 }
367
368 $params = $mainConfig->get( 'WANObjectCaches' )[$id];
369 $objectCacheId = $params['cacheId'];
370 if ( !isset( $mainConfig->get( 'ObjectCaches' )[$objectCacheId] ) ) {
371 throw new UnexpectedValueException(
372 "Cache type \"$objectCacheId\" is not present in \$wgObjectCaches." );
373 }
374 $params['store'] = $mainConfig->get( 'ObjectCaches' )[$objectCacheId];
375
376 return \ObjectCache::newWANCacheFromParams( $params );
377 },
378
379 'LocalServerObjectCache' => function ( MediaWikiServices $services ) {
380 $mainConfig = $services->getMainConfig();
381
382 if ( function_exists( 'apc_fetch' ) ) {
383 $id = 'apc';
384 } elseif ( function_exists( 'apcu_fetch' ) ) {
385 $id = 'apcu';
386 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
387 $id = 'xcache';
388 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
389 $id = 'wincache';
390 } else {
391 $id = CACHE_NONE;
392 }
393
394 if ( !isset( $mainConfig->get( 'ObjectCaches' )[$id] ) ) {
395 throw new UnexpectedValueException(
396 "Cache type \"$id\" is not present in \$wgObjectCaches." );
397 }
398
399 return \ObjectCache::newFromParams( $mainConfig->get( 'ObjectCaches' )[$id] );
400 },
401
402 'VirtualRESTServiceClient' => function ( MediaWikiServices $services ) {
403 $config = $services->getMainConfig()->get( 'VirtualRestConfig' );
404
405 $vrsClient = new VirtualRESTServiceClient( new MultiHttpClient( [] ) );
406 foreach ( $config['paths'] as $prefix => $serviceConfig ) {
407 $class = $serviceConfig['class'];
408 // Merge in the global defaults
409 $constructArg = isset( $serviceConfig['options'] )
410 ? $serviceConfig['options']
411 : [];
412 $constructArg += $config['global'];
413 // Make the VRS service available at the mount point
414 $vrsClient->mount( $prefix, [ 'class' => $class, 'config' => $constructArg ] );
415 }
416
417 return $vrsClient;
418 },
419
420 'ConfiguredReadOnlyMode' => function ( MediaWikiServices $services ) {
421 return new ConfiguredReadOnlyMode( $services->getMainConfig() );
422 },
423
424 'ReadOnlyMode' => function ( MediaWikiServices $services ) {
425 return new ReadOnlyMode(
426 $services->getConfiguredReadOnlyMode(),
427 $services->getDBLoadBalancer()
428 );
429 },
430
431 ///////////////////////////////////////////////////////////////////////////
432 // NOTE: When adding a service here, don't forget to add a getter function
433 // in the MediaWikiServices class. The convenience getter should just call
434 // $this->getService( 'FooBarService' ).
435 ///////////////////////////////////////////////////////////////////////////
436
437 ];