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