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