Merge "Allow overriding the resultSetType reported via event logging of suggestions"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
1 <?php
2 /**
3 * Module for ResourceLoader initialization.
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 * @author Trevor Parscal
22 * @author Roan Kattouw
23 */
24
25 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
26
27 // Cache for getConfigSettings() as it's called by multiple methods
28 protected $configVars = array();
29 protected $targets = array( 'desktop', 'mobile' );
30
31 /**
32 * @param ResourceLoaderContext $context
33 * @return array
34 */
35 protected function getConfigSettings( $context ) {
36
37 $hash = $context->getHash();
38 if ( isset( $this->configVars[$hash] ) ) {
39 return $this->configVars[$hash];
40 }
41
42 global $wgContLang;
43
44 $mainPage = Title::newMainPage();
45
46 /**
47 * Namespace related preparation
48 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
49 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
50 */
51 $namespaceIds = $wgContLang->getNamespaceIds();
52 $caseSensitiveNamespaces = array();
53 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
54 $namespaceIds[$wgContLang->lc( $name )] = $index;
55 if ( !MWNamespace::isCapitalized( $index ) ) {
56 $caseSensitiveNamespaces[] = $index;
57 }
58 }
59
60 $conf = $this->getConfig();
61 // Build list of variables
62 $vars = array(
63 'wgLoadScript' => wfScript( 'load' ),
64 'debug' => $context->getDebug(),
65 'skin' => $context->getSkin(),
66 'stylepath' => $conf->get( 'StylePath' ),
67 'wgUrlProtocols' => wfUrlProtocols(),
68 'wgArticlePath' => $conf->get( 'ArticlePath' ),
69 'wgScriptPath' => $conf->get( 'ScriptPath' ),
70 'wgScriptExtension' => '.php',
71 'wgScript' => wfScript(),
72 'wgSearchType' => $conf->get( 'SearchType' ),
73 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
74 // Force object to avoid "empty" associative array from
75 // becoming [] instead of {} in JS (bug 34604)
76 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
77 'wgServer' => $conf->get( 'Server' ),
78 'wgServerName' => $conf->get( 'ServerName' ),
79 'wgUserLanguage' => $context->getLanguage(),
80 'wgContentLanguage' => $wgContLang->getCode(),
81 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
82 'wgVersion' => $conf->get( 'Version' ),
83 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
84 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
85 'wgMainPageTitle' => $mainPage->getPrefixedText(),
86 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
87 'wgNamespaceIds' => $namespaceIds,
88 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
89 'wgSiteName' => $conf->get( 'Sitename' ),
90 'wgDBname' => $conf->get( 'DBname' ),
91 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
92 'wgAvailableSkins' => Skin::getSkinNames(),
93 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
94 // MediaWiki sets cookies to have this prefix by default
95 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
96 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
97 'wgCookiePath' => $conf->get( 'CookiePath' ),
98 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
99 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
100 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
101 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
102 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
103 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
104 'wgResourceLoaderLegacyModules' => self::getLegacyModules(),
105 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
106 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
107 'wgForeignUploadTestEnabled' => $conf->get( 'ForeignUploadTestEnabled' ),
108 'wgForeignUploadTestDefault' => $conf->get( 'ForeignUploadTestDefault' ),
109 );
110
111 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
112
113 $this->configVars[$hash] = $vars;
114 return $this->configVars[$hash];
115 }
116
117 /**
118 * Recursively get all explicit and implicit dependencies for to the given module.
119 *
120 * @param array $registryData
121 * @param string $moduleName
122 * @return array
123 */
124 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
125 static $dependencyCache = array();
126
127 // The list of implicit dependencies won't be altered, so we can
128 // cache them without having to worry.
129 if ( !isset( $dependencyCache[$moduleName] ) ) {
130
131 if ( !isset( $registryData[$moduleName] ) ) {
132 // Dependencies may not exist
133 $dependencyCache[$moduleName] = array();
134 } else {
135 $data = $registryData[$moduleName];
136 $dependencyCache[$moduleName] = $data['dependencies'];
137
138 foreach ( $data['dependencies'] as $dependency ) {
139 // Recursively get the dependencies of the dependencies
140 $dependencyCache[$moduleName] = array_merge(
141 $dependencyCache[$moduleName],
142 self::getImplicitDependencies( $registryData, $dependency )
143 );
144 }
145 }
146 }
147
148 return $dependencyCache[$moduleName];
149 }
150
151 /**
152 * Optimize the dependency tree in $this->modules.
153 *
154 * The optimization basically works like this:
155 * Given we have module A with the dependencies B and C
156 * and module B with the dependency C.
157 * Now we don't have to tell the client to explicitly fetch module
158 * C as that's already included in module B.
159 *
160 * This way we can reasonably reduce the amount of module registration
161 * data send to the client.
162 *
163 * @param array &$registryData Modules keyed by name with properties:
164 * - string 'version'
165 * - array 'dependencies'
166 * - string|null 'group'
167 * - string 'source'
168 */
169 public static function compileUnresolvedDependencies( array &$registryData ) {
170 foreach ( $registryData as $name => &$data ) {
171 $dependencies = $data['dependencies'];
172 foreach ( $data['dependencies'] as $dependency ) {
173 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
174 $dependencies = array_diff( $dependencies, $implicitDependencies );
175 }
176 // Rebuild keys
177 $data['dependencies'] = array_values( $dependencies );
178 }
179 }
180
181
182 /**
183 * Get registration code for all modules.
184 *
185 * @param ResourceLoaderContext $context
186 * @return string JavaScript code for registering all modules with the client loader
187 */
188 public function getModuleRegistrations( ResourceLoaderContext $context ) {
189
190 $resourceLoader = $context->getResourceLoader();
191 $target = $context->getRequest()->getVal( 'target', 'desktop' );
192 // Bypass target filter if this request is Special:JavaScriptTest.
193 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
194 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
195
196 $out = '';
197 $registryData = array();
198
199 // Get registry data
200 foreach ( $resourceLoader->getModuleNames() as $name ) {
201 $module = $resourceLoader->getModule( $name );
202 $moduleTargets = $module->getTargets();
203 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
204 continue;
205 }
206
207 if ( $module->isRaw() ) {
208 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
209 // depending on them is illegal anyway and would only lead to them being reloaded
210 // causing any state to be lost (like jQuery plugins, mw.config etc.)
211 continue;
212 }
213
214 $versionHash = $module->getVersionHash( $context );
215 if ( strlen( $versionHash ) !== 8 ) {
216 $context->getLogger()->warning(
217 "Module '{module}' produced an invalid version hash: '{version}'.",
218 array(
219 'module' => $name,
220 'version' => $versionHash,
221 )
222 );
223 // Module implementation either broken or deviated from ResourceLoader::makeHash
224 // Asserted by tests/phpunit/structure/ResourcesTest.
225 $versionHash = ResourceLoader::makeHash( $versionHash );
226 }
227
228 $skipFunction = $module->getSkipFunction();
229 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
230 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
231 }
232
233 $registryData[$name] = array(
234 'version' => $versionHash,
235 'dependencies' => $module->getDependencies( $context ),
236 'group' => $module->getGroup(),
237 'source' => $module->getSource(),
238 'skip' => $skipFunction,
239 );
240 }
241
242 self::compileUnresolvedDependencies( $registryData );
243
244 // Register sources
245 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
246
247 // Figure out the different call signatures for mw.loader.register
248 $registrations = array();
249 foreach ( $registryData as $name => $data ) {
250 // Call mw.loader.register(name, version, dependencies, group, source, skip)
251 $registrations[] = array(
252 $name,
253 $data['version'],
254 $data['dependencies'],
255 $data['group'],
256 // Swap default (local) for null
257 $data['source'] === 'local' ? null : $data['source'],
258 $data['skip']
259 );
260 }
261
262 // Register modules
263 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
264
265 return $out;
266 }
267
268 /**
269 * @return bool
270 */
271 public function isRaw() {
272 return true;
273 }
274
275 /**
276 * Base modules required for the base environment of ResourceLoader
277 *
278 * @return array
279 */
280 public static function getStartupModules() {
281 return array( 'jquery', 'mediawiki' );
282 }
283
284 public static function getLegacyModules() {
285 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil;
286
287 $legacyModules = array();
288 if ( $wgIncludeLegacyJavaScript ) {
289 $legacyModules[] = 'mediawiki.legacy.wikibits';
290 }
291 if ( $wgPreloadJavaScriptMwUtil ) {
292 $legacyModules[] = 'mediawiki.util';
293 }
294
295 return $legacyModules;
296 }
297
298 /**
299 * Get the load URL of the startup modules.
300 *
301 * This is a helper for getScript(), but can also be called standalone, such
302 * as when generating an AppCache manifest.
303 *
304 * @param ResourceLoaderContext $context
305 * @return string
306 */
307 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
308 $rl = $context->getResourceLoader();
309 $moduleNames = self::getStartupModules();
310
311 $query = array(
312 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
313 'only' => 'scripts',
314 'lang' => $context->getLanguage(),
315 'skin' => $context->getSkin(),
316 'debug' => $context->getDebug() ? 'true' : 'false',
317 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
318 );
319 // Ensure uniform query order
320 ksort( $query );
321 return wfAppendQuery( wfScript( 'load' ), $query );
322 }
323
324 /**
325 * @param ResourceLoaderContext $context
326 * @return string
327 */
328 public function getScript( ResourceLoaderContext $context ) {
329 global $IP;
330 if ( $context->getOnly() !== 'scripts' ) {
331 return '/* Requires only=script */';
332 }
333
334 $out = file_get_contents( "$IP/resources/src/startup.js" );
335
336 $pairs = array_map( function ( $value ) {
337 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
338 // Fix indentation
339 $value = str_replace( "\n", "\n\t", $value );
340 return $value;
341 }, array(
342 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
343 '$VARS.configuration' => $this->getConfigSettings( $context ),
344 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
345 ) );
346 $pairs['$CODE.registrations()'] = str_replace(
347 "\n",
348 "\n\t",
349 trim( $this->getModuleRegistrations( $context ) )
350 );
351
352 return strtr( $out, $pairs );
353 }
354
355 /**
356 * @return bool
357 */
358 public function supportsURLLoading() {
359 return false;
360 }
361
362 /**
363 * Get the definition summary for this module.
364 *
365 * @param ResourceLoaderContext $context
366 * @return array
367 */
368 public function getDefinitionSummary( ResourceLoaderContext $context ) {
369 global $IP;
370 $summary = parent::getDefinitionSummary( $context );
371 $summary[] = array(
372 // Detect changes to variables exposed in mw.config (T30899).
373 'vars' => $this->getConfigSettings( $context ),
374 // Changes how getScript() creates mw.Map for mw.config
375 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
376 // Detect changes to the module registrations
377 'moduleHashes' => $this->getAllModuleHashes( $context ),
378
379 'fileMtimes' => array(
380 filemtime( "$IP/resources/src/startup.js" ),
381 ),
382 );
383 return $summary;
384 }
385
386 /**
387 * Helper method for getDefinitionSummary().
388 *
389 * @param ResourceLoaderContext $context
390 * @return string SHA-1
391 */
392 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
393 $rl = $context->getResourceLoader();
394 // Preload for getCombinedVersion()
395 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
396
397 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
398 // Think carefully before making changes to this code!
399 // Pre-populate versionHash with something because the loop over all modules below includes
400 // the startup module (this module).
401 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
402 $this->versionHash[$context->getHash()] = null;
403
404 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
405 }
406
407 /**
408 * @return string
409 */
410 public function getGroup() {
411 return 'startup';
412 }
413 }