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