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