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