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