Merge "resourceloader: Document 'target' query param in StartupModule"
[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 $target = $context->getRequest()->getVal( 'target', 'desktop' );
210 // Bypass target filter if this request is Special:JavaScriptTest.
211 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
212 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
213
214 $out = '';
215 $states = [];
216 $registryData = [];
217
218 // Get registry data
219 foreach ( $resourceLoader->getModuleNames() as $name ) {
220 $module = $resourceLoader->getModule( $name );
221 $moduleTargets = $module->getTargets();
222 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
223 continue;
224 }
225
226 if ( $module->isRaw() ) {
227 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
228 // depending on them is illegal anyway and would only lead to them being reloaded
229 // causing any state to be lost (like jQuery plugins, mw.config etc.)
230 continue;
231 }
232
233 try {
234 $versionHash = $module->getVersionHash( $context );
235 } catch ( Exception $e ) {
236 // See also T152266 and ResourceLoader::getCombinedVersion()
237 MWExceptionHandler::logException( $e );
238 $context->getLogger()->warning(
239 'Calculating version for "{module}" failed: {exception}',
240 [
241 'module' => $name,
242 'exception' => $e,
243 ]
244 );
245 $versionHash = '';
246 $states[$name] = 'error';
247 }
248
249 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
250 $context->getLogger()->warning(
251 "Module '{module}' produced an invalid version hash: '{version}'.",
252 [
253 'module' => $name,
254 'version' => $versionHash,
255 ]
256 );
257 // Module implementation either broken or deviated from ResourceLoader::makeHash
258 // Asserted by tests/phpunit/structure/ResourcesTest.
259 $versionHash = ResourceLoader::makeHash( $versionHash );
260 }
261
262 $skipFunction = $module->getSkipFunction();
263 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
264 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
265 }
266
267 $registryData[$name] = [
268 'version' => $versionHash,
269 'dependencies' => $module->getDependencies( $context ),
270 'group' => $module->getGroup(),
271 'source' => $module->getSource(),
272 'skip' => $skipFunction,
273 ];
274 }
275
276 self::compileUnresolvedDependencies( $registryData );
277
278 // Register sources
279 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
280
281 // Figure out the different call signatures for mw.loader.register
282 $registrations = [];
283 foreach ( $registryData as $name => $data ) {
284 // Call mw.loader.register(name, version, dependencies, group, source, skip)
285 $registrations[] = [
286 $name,
287 $data['version'],
288 $data['dependencies'],
289 $data['group'],
290 // Swap default (local) for null
291 $data['source'] === 'local' ? null : $data['source'],
292 $data['skip']
293 ];
294 }
295
296 // Register modules
297 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
298
299 if ( $states ) {
300 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
301 }
302
303 return $out;
304 }
305
306 /**
307 * @return bool
308 */
309 public function isRaw() {
310 return true;
311 }
312
313 /**
314 * @param ResourceLoaderContext $context
315 * @return array
316 */
317 public function getPreloadLinks( ResourceLoaderContext $context ) {
318 $url = self::getStartupModulesUrl( $context );
319 return [
320 $url => [ 'as' => 'script' ]
321 ];
322 }
323
324 /**
325 * Base modules required for the base environment of ResourceLoader
326 *
327 * @return array
328 */
329 public static function getStartupModules() {
330 return [ 'jquery', 'mediawiki' ];
331 }
332
333 public static function getLegacyModules() {
334 global $wgIncludeLegacyJavaScript;
335
336 $legacyModules = [];
337 if ( $wgIncludeLegacyJavaScript ) {
338 $legacyModules[] = 'mediawiki.legacy.wikibits';
339 }
340
341 return $legacyModules;
342 }
343
344 /**
345 * Get the load URL of the startup modules.
346 *
347 * This is a helper for getScript(), but can also be called standalone, such
348 * as when generating an AppCache manifest.
349 *
350 * @param ResourceLoaderContext $context
351 * @return string
352 */
353 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
354 $rl = $context->getResourceLoader();
355 $derivative = new DerivativeResourceLoaderContext( $context );
356 $derivative->setModules( array_merge(
357 self::getStartupModules(),
358 self::getLegacyModules()
359 ) );
360 $derivative->setOnly( 'scripts' );
361 // Must setModules() before makeVersionQuery()
362 $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
363
364 return $rl->createLoaderURL( 'local', $derivative );
365 }
366
367 /**
368 * @param ResourceLoaderContext $context
369 * @return string JavaScript code
370 */
371 public function getScript( ResourceLoaderContext $context ) {
372 global $IP;
373 if ( $context->getOnly() !== 'scripts' ) {
374 return '/* Requires only=script */';
375 }
376
377 $out = file_get_contents( "$IP/resources/src/startup.js" );
378
379 $pairs = array_map( function ( $value ) {
380 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
381 // Fix indentation
382 $value = str_replace( "\n", "\n\t", $value );
383 return $value;
384 }, [
385 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
386 '$VARS.configuration' => $this->getConfigSettings( $context ),
387 // This url may be preloaded. See getPreloadLinks().
388 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
389 ] );
390 $pairs['$CODE.registrations()'] = str_replace(
391 "\n",
392 "\n\t",
393 trim( $this->getModuleRegistrations( $context ) )
394 );
395
396 return strtr( $out, $pairs );
397 }
398
399 /**
400 * @return bool
401 */
402 public function supportsURLLoading() {
403 return false;
404 }
405
406 /**
407 * Get the definition summary for this module.
408 *
409 * @param ResourceLoaderContext $context
410 * @return array
411 */
412 public function getDefinitionSummary( ResourceLoaderContext $context ) {
413 global $IP;
414 $summary = parent::getDefinitionSummary( $context );
415 $summary[] = [
416 // Detect changes to variables exposed in mw.config (T30899).
417 'vars' => $this->getConfigSettings( $context ),
418 // Changes how getScript() creates mw.Map for mw.config
419 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
420 // Detect changes to the module registrations
421 'moduleHashes' => $this->getAllModuleHashes( $context ),
422
423 'fileMtimes' => [
424 filemtime( "$IP/resources/src/startup.js" ),
425 ],
426 ];
427 return $summary;
428 }
429
430 /**
431 * Helper method for getDefinitionSummary().
432 *
433 * @param ResourceLoaderContext $context
434 * @return string SHA-1
435 */
436 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
437 $rl = $context->getResourceLoader();
438 // Preload for getCombinedVersion()
439 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
440
441 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
442 // Think carefully before making changes to this code!
443 // Pre-populate versionHash with something because the loop over all modules below includes
444 // the startup module (this module).
445 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
446 $this->versionHash[$context->getHash()] = null;
447
448 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
449 }
450
451 /**
452 * @return string
453 */
454 public function getGroup() {
455 return 'startup';
456 }
457 }