Merge "SpecialJavaScriptTest: Bypass ResourceLoader 'target' scope"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
1 <?php
2 /**
3 * Module for resource loader 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' => $conf->get( 'ScriptExtension' ),
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 );
105
106 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
107
108 $this->configVars[$hash] = $vars;
109 return $this->configVars[$hash];
110 }
111
112 /**
113 * Recursively get all explicit and implicit dependencies for to the given module.
114 *
115 * @param array $registryData
116 * @param string $moduleName
117 * @return array
118 */
119 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
120 static $dependencyCache = array();
121
122 // The list of implicit dependencies won't be altered, so we can
123 // cache them without having to worry.
124 if ( !isset( $dependencyCache[$moduleName] ) ) {
125
126 if ( !isset( $registryData[$moduleName] ) ) {
127 // Dependencies may not exist
128 $dependencyCache[$moduleName] = array();
129 } else {
130 $data = $registryData[$moduleName];
131 $dependencyCache[$moduleName] = $data['dependencies'];
132
133 foreach ( $data['dependencies'] as $dependency ) {
134 // Recursively get the dependencies of the dependencies
135 $dependencyCache[$moduleName] = array_merge(
136 $dependencyCache[$moduleName],
137 self::getImplicitDependencies( $registryData, $dependency )
138 );
139 }
140 }
141 }
142
143 return $dependencyCache[$moduleName];
144 }
145
146 /**
147 * Optimize the dependency tree in $this->modules.
148 *
149 * The optimization basically works like this:
150 * Given we have module A with the dependencies B and C
151 * and module B with the dependency C.
152 * Now we don't have to tell the client to explicitly fetch module
153 * C as that's already included in module B.
154 *
155 * This way we can reasonably reduce the amount of module registration
156 * data send to the client.
157 *
158 * @param array &$registryData Modules keyed by name with properties:
159 * - string 'version'
160 * - array 'dependencies'
161 * - string|null 'group'
162 * - string 'source'
163 * - string|false 'loader'
164 */
165 public static function compileUnresolvedDependencies( array &$registryData ) {
166 foreach ( $registryData as $name => &$data ) {
167 if ( $data['loader'] !== false ) {
168 continue;
169 }
170 $dependencies = $data['dependencies'];
171 foreach ( $data['dependencies'] as $dependency ) {
172 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
173 $dependencies = array_diff( $dependencies, $implicitDependencies );
174 }
175 // Rebuild keys
176 $data['dependencies'] = array_values( $dependencies );
177 }
178 }
179
180
181 /**
182 * Get registration code for all modules.
183 *
184 * @param ResourceLoaderContext $context
185 * @return string JavaScript code for registering all modules with the client loader
186 */
187 public function getModuleRegistrations( ResourceLoaderContext $context ) {
188
189 $resourceLoader = $context->getResourceLoader();
190 $target = $context->getRequest()->getVal( 'target', 'desktop' );
191 // Bypass target filter if this request is from a unit test context. To prevent misuse in
192 // production, this is only allowed if testing is enabled server-side.
193 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
194
195 $out = '';
196 $registryData = array();
197
198 // Get registry data
199 foreach ( $resourceLoader->getModuleNames() as $name ) {
200 $module = $resourceLoader->getModule( $name );
201 $moduleTargets = $module->getTargets();
202 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
203 continue;
204 }
205
206 if ( $module->isRaw() ) {
207 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
208 // depending on them is illegal anyway and would only lead to them being reloaded
209 // causing any state to be lost (like jQuery plugins, mw.config etc.)
210 continue;
211 }
212
213 $versionHash = $module->getVersionHash( $context );
214 if ( strlen( $versionHash ) !== 8 ) {
215 // Module implementation either broken or deviated from ResourceLoader::makeHash
216 // Asserted by tests/phpunit/structure/ResourcesTest.
217 $versionHash = ResourceLoader::makeHash( $versionHash );
218 }
219
220 $skipFunction = $module->getSkipFunction();
221 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
222 $skipFunction = $resourceLoader->filter( 'minify-js',
223 $skipFunction,
224 // There will potentially be lots of these little strings in the registrations
225 // manifest, we don't want to blow up the startup module with
226 // "/* cache key: ... */" all over it.
227 /* cacheReport = */ false
228 );
229 }
230
231 $registryData[$name] = array(
232 'version' => $versionHash,
233 'dependencies' => $module->getDependencies( $context ),
234 'group' => $module->getGroup(),
235 'source' => $module->getSource(),
236 'loader' => $module->getLoaderScript(),
237 'skip' => $skipFunction,
238 );
239 }
240
241 self::compileUnresolvedDependencies( $registryData );
242
243 // Register sources
244 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
245
246 // Concatenate module loader scripts and figure out the different call
247 // signatures for mw.loader.register
248 $registrations = array();
249 foreach ( $registryData as $name => $data ) {
250 if ( $data['loader'] !== false ) {
251 $out .= ResourceLoader::makeCustomLoaderScript(
252 $name,
253 $data['version'],
254 $data['dependencies'],
255 $data['group'],
256 $data['source'],
257 $data['loader']
258 );
259 continue;
260 }
261
262 // Call mw.loader.register(name, version, dependencies, group, source, skip)
263 $registrations[] = array(
264 $name,
265 $data['version'],
266 $data['dependencies'],
267 $data['group'],
268 // Swap default (local) for null
269 $data['source'] === 'local' ? null : $data['source'],
270 $data['skip']
271 );
272 }
273
274 // Register modules
275 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
276
277 return $out;
278 }
279
280 /**
281 * @return bool
282 */
283 public function isRaw() {
284 return true;
285 }
286
287 /**
288 * Base modules required for the base environment of ResourceLoader
289 *
290 * @return array
291 */
292 public static function getStartupModules() {
293 return array( 'jquery', 'mediawiki' );
294 }
295
296 /**
297 * Get the load URL of the startup modules.
298 *
299 * This is a helper for getScript(), but can also be called standalone, such
300 * as when generating an AppCache manifest.
301 *
302 * @param ResourceLoaderContext $context
303 * @return string
304 */
305 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
306 $rl = $context->getResourceLoader();
307 $moduleNames = self::getStartupModules();
308
309 $query = array(
310 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
311 'only' => 'scripts',
312 'lang' => $context->getLanguage(),
313 'skin' => $context->getSkin(),
314 'debug' => $context->getDebug() ? 'true' : 'false',
315 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
316 );
317 // Ensure uniform query order
318 ksort( $query );
319 return wfAppendQuery( wfScript( 'load' ), $query );
320 }
321
322 /**
323 * @param ResourceLoaderContext $context
324 * @return string
325 */
326 public function getScript( ResourceLoaderContext $context ) {
327 global $IP;
328 if ( $context->getOnly() !== 'scripts' ) {
329 return '/* Requires only=script */';
330 }
331
332 $out = file_get_contents( "$IP/resources/src/startup.js" );
333
334 $pairs = array_map( function ( $value ) {
335 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
336 // Fix indentation
337 $value = str_replace( "\n", "\n\t", $value );
338 return $value;
339 }, array(
340 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
341 '$VARS.configuration' => $this->getConfigSettings( $context ),
342 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
343 ) );
344 $pairs['$CODE.registrations()'] = str_replace( "\n", "\n\t", trim( $this->getModuleRegistrations( $context ) ) );
345
346 return strtr( $out, $pairs );
347 }
348
349 /**
350 * @return bool
351 */
352 public function supportsURLLoading() {
353 return false;
354 }
355
356 /**
357 * Get the definition summary for this module.
358 *
359 * @param ResourceLoaderContext $context
360 * @return array
361 */
362 public function getDefinitionSummary( ResourceLoaderContext $context ) {
363 global $IP;
364 $summary = parent::getDefinitionSummary( $context );
365 $summary[] = array(
366 // Detect changes to variables exposed in mw.config (T30899).
367 'vars' => $this->getConfigSettings( $context ),
368 // Changes how getScript() creates mw.Map for mw.config
369 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
370 // Detect changes to the module registrations
371 'moduleHashes' => $this->getAllModuleHashes( $context ),
372
373 'fileMtimes' => array(
374 filemtime( "$IP/resources/src/startup.js" ),
375 ),
376 );
377 return $summary;
378 }
379
380 /**
381 * Helper method for getDefinitionSummary().
382 *
383 * @param ResourceLoaderContext $context
384 * @return string SHA-1
385 */
386 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
387 $rl = $context->getResourceLoader();
388 // Preload for getCombinedVersion()
389 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
390
391 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
392 // Think carefully before making changes to this code!
393 // Pre-populate versionHash with something because the loop over all modules below includes
394 // the startup module (this module).
395 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
396 $this->versionHash[$context->getHash()] = null;
397
398 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
399 }
400
401 /**
402 * @return string
403 */
404 public function getGroup() {
405 return 'startup';
406 }
407 }