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