Merge "resourceloader: Log warning if module produces an invalid version hash"
[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 = 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' => '.php',
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 'wgResourceLoaderLegacyModules' => self::getLegacyModules(),
105 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
106 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
107 );
108
109 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
110
111 $this->configVars[$hash] = $vars;
112 return $this->configVars[$hash];
113 }
114
115 /**
116 * Recursively get all explicit and implicit dependencies for to the given module.
117 *
118 * @param array $registryData
119 * @param string $moduleName
120 * @return array
121 */
122 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
123 static $dependencyCache = array();
124
125 // The list of implicit dependencies won't be altered, so we can
126 // cache them without having to worry.
127 if ( !isset( $dependencyCache[$moduleName] ) ) {
128
129 if ( !isset( $registryData[$moduleName] ) ) {
130 // Dependencies may not exist
131 $dependencyCache[$moduleName] = array();
132 } else {
133 $data = $registryData[$moduleName];
134 $dependencyCache[$moduleName] = $data['dependencies'];
135
136 foreach ( $data['dependencies'] as $dependency ) {
137 // Recursively get the dependencies of the dependencies
138 $dependencyCache[$moduleName] = array_merge(
139 $dependencyCache[$moduleName],
140 self::getImplicitDependencies( $registryData, $dependency )
141 );
142 }
143 }
144 }
145
146 return $dependencyCache[$moduleName];
147 }
148
149 /**
150 * Optimize the dependency tree in $this->modules.
151 *
152 * The optimization basically works like this:
153 * Given we have module A with the dependencies B and C
154 * and module B with the dependency C.
155 * Now we don't have to tell the client to explicitly fetch module
156 * C as that's already included in module B.
157 *
158 * This way we can reasonably reduce the amount of module registration
159 * data send to the client.
160 *
161 * @param array &$registryData Modules keyed by name with properties:
162 * - string 'version'
163 * - array 'dependencies'
164 * - string|null 'group'
165 * - string 'source'
166 */
167 public static function compileUnresolvedDependencies( array &$registryData ) {
168 foreach ( $registryData as $name => &$data ) {
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 Special:JavaScriptTest.
191 // To prevent misuse in 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 $context->getLogger()->warning(
215 "Module '{module}' produced an invalid version hash: '{version}'.",
216 array(
217 'module' => $name,
218 'version' => $versionHash,
219 )
220 );
221 // Module implementation either broken or deviated from ResourceLoader::makeHash
222 // Asserted by tests/phpunit/structure/ResourcesTest.
223 $versionHash = ResourceLoader::makeHash( $versionHash );
224 }
225
226 $skipFunction = $module->getSkipFunction();
227 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
228 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
229 }
230
231 $registryData[$name] = array(
232 'version' => $versionHash,
233 'dependencies' => $module->getDependencies( $context ),
234 'group' => $module->getGroup(),
235 'source' => $module->getSource(),
236 'skip' => $skipFunction,
237 );
238 }
239
240 self::compileUnresolvedDependencies( $registryData );
241
242 // Register sources
243 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
244
245 // Figure out the different call signatures for mw.loader.register
246 $registrations = array();
247 foreach ( $registryData as $name => $data ) {
248 // Call mw.loader.register(name, version, dependencies, group, source, skip)
249 $registrations[] = array(
250 $name,
251 $data['version'],
252 $data['dependencies'],
253 $data['group'],
254 // Swap default (local) for null
255 $data['source'] === 'local' ? null : $data['source'],
256 $data['skip']
257 );
258 }
259
260 // Register modules
261 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
262
263 return $out;
264 }
265
266 /**
267 * @return bool
268 */
269 public function isRaw() {
270 return true;
271 }
272
273 /**
274 * Base modules required for the base environment of ResourceLoader
275 *
276 * @return array
277 */
278 public static function getStartupModules() {
279 return array( 'jquery', 'mediawiki' );
280 }
281
282 public static function getLegacyModules() {
283 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil;
284
285 $legacyModules = array();
286 if ( $wgIncludeLegacyJavaScript ) {
287 $legacyModules[] = 'mediawiki.legacy.wikibits';
288 }
289 if ( $wgPreloadJavaScriptMwUtil ) {
290 $legacyModules[] = 'mediawiki.util';
291 }
292
293 return $legacyModules;
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(
345 "\n",
346 "\n\t",
347 trim( $this->getModuleRegistrations( $context ) )
348 );
349
350 return strtr( $out, $pairs );
351 }
352
353 /**
354 * @return bool
355 */
356 public function supportsURLLoading() {
357 return false;
358 }
359
360 /**
361 * Get the definition summary for this module.
362 *
363 * @param ResourceLoaderContext $context
364 * @return array
365 */
366 public function getDefinitionSummary( ResourceLoaderContext $context ) {
367 global $IP;
368 $summary = parent::getDefinitionSummary( $context );
369 $summary[] = array(
370 // Detect changes to variables exposed in mw.config (T30899).
371 'vars' => $this->getConfigSettings( $context ),
372 // Changes how getScript() creates mw.Map for mw.config
373 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
374 // Detect changes to the module registrations
375 'moduleHashes' => $this->getAllModuleHashes( $context ),
376
377 'fileMtimes' => array(
378 filemtime( "$IP/resources/src/startup.js" ),
379 ),
380 );
381 return $summary;
382 }
383
384 /**
385 * Helper method for getDefinitionSummary().
386 *
387 * @param ResourceLoaderContext $context
388 * @return string SHA-1
389 */
390 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
391 $rl = $context->getResourceLoader();
392 // Preload for getCombinedVersion()
393 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
394
395 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
396 // Think carefully before making changes to this code!
397 // Pre-populate versionHash with something because the loop over all modules below includes
398 // the startup module (this module).
399 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
400 $this->versionHash[$context->getHash()] = null;
401
402 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
403 }
404
405 /**
406 * @return string
407 */
408 public function getGroup() {
409 return 'startup';
410 }
411 }