e5f3fb8bc2a9cc233bf8ca8fbe18625302e23aab
[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',
225 $skipFunction,
226 // There will potentially be lots of these little strings in the registrations
227 // manifest, we don't want to blow up the startup module with
228 // "/* cache key: ... */" all over it.
229 /* cacheReport = */ false
230 );
231 }
232
233 $registryData[$name] = array(
234 'version' => $versionHash,
235 'dependencies' => $module->getDependencies( $context ),
236 'group' => $module->getGroup(),
237 'source' => $module->getSource(),
238 'loader' => $module->getLoaderScript(),
239 'skip' => $skipFunction,
240 );
241 }
242
243 self::compileUnresolvedDependencies( $registryData );
244
245 // Register sources
246 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
247
248 // Concatenate module loader scripts and figure out the different call
249 // signatures for mw.loader.register
250 $registrations = array();
251 foreach ( $registryData as $name => $data ) {
252 if ( $data['loader'] !== false ) {
253 $out .= ResourceLoader::makeCustomLoaderScript(
254 $name,
255 $data['version'],
256 $data['dependencies'],
257 $data['group'],
258 $data['source'],
259 $data['loader']
260 );
261 continue;
262 }
263
264 // Call mw.loader.register(name, version, dependencies, group, source, skip)
265 $registrations[] = array(
266 $name,
267 $data['version'],
268 $data['dependencies'],
269 $data['group'],
270 // Swap default (local) for null
271 $data['source'] === 'local' ? null : $data['source'],
272 $data['skip']
273 );
274 }
275
276 // Register modules
277 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
278
279 return $out;
280 }
281
282 /**
283 * @return bool
284 */
285 public function isRaw() {
286 return true;
287 }
288
289 /**
290 * Base modules required for the base environment of ResourceLoader
291 *
292 * @return array
293 */
294 public static function getStartupModules() {
295 return array( 'jquery', 'mediawiki' );
296 }
297
298 public static function getLegacyModules() {
299 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil;
300
301 $legacyModules = array();
302 if ( $wgIncludeLegacyJavaScript ) {
303 $legacyModules[] = 'mediawiki.legacy.wikibits';
304 }
305 if ( $wgPreloadJavaScriptMwUtil ) {
306 $legacyModules[] = 'mediawiki.util';
307 }
308
309 return $legacyModules;
310 }
311
312 /**
313 * Get the load URL of the startup modules.
314 *
315 * This is a helper for getScript(), but can also be called standalone, such
316 * as when generating an AppCache manifest.
317 *
318 * @param ResourceLoaderContext $context
319 * @return string
320 */
321 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
322 $rl = $context->getResourceLoader();
323 $moduleNames = self::getStartupModules();
324
325 $query = array(
326 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
327 'only' => 'scripts',
328 'lang' => $context->getLanguage(),
329 'skin' => $context->getSkin(),
330 'debug' => $context->getDebug() ? 'true' : 'false',
331 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
332 );
333 // Ensure uniform query order
334 ksort( $query );
335 return wfAppendQuery( wfScript( 'load' ), $query );
336 }
337
338 /**
339 * @param ResourceLoaderContext $context
340 * @return string
341 */
342 public function getScript( ResourceLoaderContext $context ) {
343 global $IP;
344 if ( $context->getOnly() !== 'scripts' ) {
345 return '/* Requires only=script */';
346 }
347
348 $out = file_get_contents( "$IP/resources/src/startup.js" );
349
350 $pairs = array_map( function ( $value ) {
351 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
352 // Fix indentation
353 $value = str_replace( "\n", "\n\t", $value );
354 return $value;
355 }, array(
356 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
357 '$VARS.configuration' => $this->getConfigSettings( $context ),
358 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
359 ) );
360 $pairs['$CODE.registrations()'] = str_replace(
361 "\n",
362 "\n\t",
363 trim( $this->getModuleRegistrations( $context ) )
364 );
365
366 return strtr( $out, $pairs );
367 }
368
369 /**
370 * @return bool
371 */
372 public function supportsURLLoading() {
373 return false;
374 }
375
376 /**
377 * Get the definition summary for this module.
378 *
379 * @param ResourceLoaderContext $context
380 * @return array
381 */
382 public function getDefinitionSummary( ResourceLoaderContext $context ) {
383 global $IP;
384 $summary = parent::getDefinitionSummary( $context );
385 $summary[] = array(
386 // Detect changes to variables exposed in mw.config (T30899).
387 'vars' => $this->getConfigSettings( $context ),
388 // Changes how getScript() creates mw.Map for mw.config
389 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
390 // Detect changes to the module registrations
391 'moduleHashes' => $this->getAllModuleHashes( $context ),
392
393 'fileMtimes' => array(
394 filemtime( "$IP/resources/src/startup.js" ),
395 ),
396 );
397 return $summary;
398 }
399
400 /**
401 * Helper method for getDefinitionSummary().
402 *
403 * @param ResourceLoaderContext $context
404 * @return string SHA-1
405 */
406 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
407 $rl = $context->getResourceLoader();
408 // Preload for getCombinedVersion()
409 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
410
411 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
412 // Think carefully before making changes to this code!
413 // Pre-populate versionHash with something because the loop over all modules below includes
414 // the startup module (this module).
415 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
416 $this->versionHash[$context->getHash()] = null;
417
418 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
419 }
420
421 /**
422 * @return string
423 */
424 public function getGroup() {
425 return 'startup';
426 }
427 }