Merge "Convert article delete to use OOUI"
[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 = [];
29 protected $targets = [ 'desktop', 'mobile' ];
30
31 /**
32 * @param ResourceLoaderContext $context
33 * @return array
34 */
35 protected function getConfigSettings( $context ) {
36 $hash = $context->getHash();
37 if ( isset( $this->configVars[$hash] ) ) {
38 return $this->configVars[$hash];
39 }
40
41 global $wgContLang;
42 $conf = $this->getConfig();
43
44 // We can't use Title::newMainPage() if 'mainpage' is in
45 // $wgForceUIMsgAsContentMsg because that will try to use the session
46 // user's language and we have no session user. This does the
47 // equivalent but falling back to our ResourceLoaderContext language
48 // instead.
49 $mainPage = Title::newFromText( $context->msg( 'mainpage' )->inContentLanguage()->text() );
50 if ( !$mainPage ) {
51 $mainPage = Title::newFromText( 'Main Page' );
52 }
53
54 /**
55 * Namespace related preparation
56 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
57 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
58 */
59 $namespaceIds = $wgContLang->getNamespaceIds();
60 $caseSensitiveNamespaces = [];
61 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
62 $namespaceIds[$wgContLang->lc( $name )] = $index;
63 if ( !MWNamespace::isCapitalized( $index ) ) {
64 $caseSensitiveNamespaces[] = $index;
65 }
66 }
67
68 $illegalFileChars = $conf->get( 'IllegalFileChars' );
69
70 // Build list of variables
71 $vars = [
72 'wgLoadScript' => wfScript( 'load' ),
73 'debug' => $context->getDebug(),
74 'skin' => $context->getSkin(),
75 'stylepath' => $conf->get( 'StylePath' ),
76 'wgUrlProtocols' => wfUrlProtocols(),
77 'wgArticlePath' => $conf->get( 'ArticlePath' ),
78 'wgScriptPath' => $conf->get( 'ScriptPath' ),
79 'wgScriptExtension' => '.php',
80 'wgScript' => wfScript(),
81 'wgSearchType' => $conf->get( 'SearchType' ),
82 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
83 // Force object to avoid "empty" associative array from
84 // becoming [] instead of {} in JS (T36604)
85 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
86 'wgServer' => $conf->get( 'Server' ),
87 'wgServerName' => $conf->get( 'ServerName' ),
88 'wgUserLanguage' => $context->getLanguage(),
89 'wgContentLanguage' => $wgContLang->getCode(),
90 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
91 'wgVersion' => $conf->get( 'Version' ),
92 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
93 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
94 'wgMainPageTitle' => $mainPage->getPrefixedText(),
95 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
96 'wgNamespaceIds' => $namespaceIds,
97 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
98 'wgSiteName' => $conf->get( 'Sitename' ),
99 'wgDBname' => $conf->get( 'DBname' ),
100 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
101 'wgAvailableSkins' => Skin::getSkinNames(),
102 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
103 // MediaWiki sets cookies to have this prefix by default
104 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
105 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
106 'wgCookiePath' => $conf->get( 'CookiePath' ),
107 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
108 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
109 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
110 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
111 'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
112 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
113 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
114 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
115 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
116 ];
117
118 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
119
120 $this->configVars[$hash] = $vars;
121 return $this->configVars[$hash];
122 }
123
124 /**
125 * Recursively get all explicit and implicit dependencies for to the given module.
126 *
127 * @param array $registryData
128 * @param string $moduleName
129 * @return array
130 */
131 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
132 static $dependencyCache = [];
133
134 // The list of implicit dependencies won't be altered, so we can
135 // cache them without having to worry.
136 if ( !isset( $dependencyCache[$moduleName] ) ) {
137 if ( !isset( $registryData[$moduleName] ) ) {
138 // Dependencies may not exist
139 $dependencyCache[$moduleName] = [];
140 } else {
141 $data = $registryData[$moduleName];
142 $dependencyCache[$moduleName] = $data['dependencies'];
143
144 foreach ( $data['dependencies'] as $dependency ) {
145 // Recursively get the dependencies of the dependencies
146 $dependencyCache[$moduleName] = array_merge(
147 $dependencyCache[$moduleName],
148 self::getImplicitDependencies( $registryData, $dependency )
149 );
150 }
151 }
152 }
153
154 return $dependencyCache[$moduleName];
155 }
156
157 /**
158 * Optimize the dependency tree in $this->modules.
159 *
160 * The optimization basically works like this:
161 * Given we have module A with the dependencies B and C
162 * and module B with the dependency C.
163 * Now we don't have to tell the client to explicitly fetch module
164 * C as that's already included in module B.
165 *
166 * This way we can reasonably reduce the amount of module registration
167 * data send to the client.
168 *
169 * @param array &$registryData Modules keyed by name with properties:
170 * - string 'version'
171 * - array 'dependencies'
172 * - string|null 'group'
173 * - string 'source'
174 */
175 public static function compileUnresolvedDependencies( array &$registryData ) {
176 foreach ( $registryData as $name => &$data ) {
177 $dependencies = $data['dependencies'];
178 foreach ( $data['dependencies'] as $dependency ) {
179 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
180 $dependencies = array_diff( $dependencies, $implicitDependencies );
181 }
182 // Rebuild keys
183 $data['dependencies'] = array_values( $dependencies );
184 }
185 }
186
187 /**
188 * Get registration code for all modules.
189 *
190 * @param ResourceLoaderContext $context
191 * @return string JavaScript code for registering all modules with the client loader
192 */
193 public function getModuleRegistrations( ResourceLoaderContext $context ) {
194 $resourceLoader = $context->getResourceLoader();
195 $target = $context->getRequest()->getVal( 'target', 'desktop' );
196 // Bypass target filter if this request is Special:JavaScriptTest.
197 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
198 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
199
200 $out = '';
201 $states = [];
202 $registryData = [];
203
204 // Get registry data
205 foreach ( $resourceLoader->getModuleNames() as $name ) {
206 $module = $resourceLoader->getModule( $name );
207 $moduleTargets = $module->getTargets();
208 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
209 continue;
210 }
211
212 if ( $module->isRaw() ) {
213 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
214 // depending on them is illegal anyway and would only lead to them being reloaded
215 // causing any state to be lost (like jQuery plugins, mw.config etc.)
216 continue;
217 }
218
219 try {
220 $versionHash = $module->getVersionHash( $context );
221 } catch ( Exception $e ) {
222 // See also T152266 and ResourceLoader::getCombinedVersion()
223 MWExceptionHandler::logException( $e );
224 $context->getLogger()->warning(
225 'Calculating version for "{module}" failed: {exception}',
226 [
227 'module' => $name,
228 'exception' => $e,
229 ]
230 );
231 $versionHash = '';
232 $states[$name] = 'error';
233 }
234
235 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
236 $context->getLogger()->warning(
237 "Module '{module}' produced an invalid version hash: '{version}'.",
238 [
239 'module' => $name,
240 'version' => $versionHash,
241 ]
242 );
243 // Module implementation either broken or deviated from ResourceLoader::makeHash
244 // Asserted by tests/phpunit/structure/ResourcesTest.
245 $versionHash = ResourceLoader::makeHash( $versionHash );
246 }
247
248 $skipFunction = $module->getSkipFunction();
249 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
250 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
251 }
252
253 $registryData[$name] = [
254 'version' => $versionHash,
255 'dependencies' => $module->getDependencies( $context ),
256 'group' => $module->getGroup(),
257 'source' => $module->getSource(),
258 'skip' => $skipFunction,
259 ];
260 }
261
262 self::compileUnresolvedDependencies( $registryData );
263
264 // Register sources
265 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
266
267 // Figure out the different call signatures for mw.loader.register
268 $registrations = [];
269 foreach ( $registryData as $name => $data ) {
270 // Call mw.loader.register(name, version, dependencies, group, source, skip)
271 $registrations[] = [
272 $name,
273 $data['version'],
274 $data['dependencies'],
275 $data['group'],
276 // Swap default (local) for null
277 $data['source'] === 'local' ? null : $data['source'],
278 $data['skip']
279 ];
280 }
281
282 // Register modules
283 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
284
285 if ( $states ) {
286 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
287 }
288
289 return $out;
290 }
291
292 /**
293 * @return bool
294 */
295 public function isRaw() {
296 return true;
297 }
298
299 /**
300 * Base modules required for the base environment of ResourceLoader
301 *
302 * @return array
303 */
304 public static function getStartupModules() {
305 return [ 'jquery', 'mediawiki' ];
306 }
307
308 public static function getLegacyModules() {
309 global $wgIncludeLegacyJavaScript;
310
311 $legacyModules = [];
312 if ( $wgIncludeLegacyJavaScript ) {
313 $legacyModules[] = 'mediawiki.legacy.wikibits';
314 }
315
316 return $legacyModules;
317 }
318
319 /**
320 * Get the load URL of the startup modules.
321 *
322 * This is a helper for getScript(), but can also be called standalone, such
323 * as when generating an AppCache manifest.
324 *
325 * @param ResourceLoaderContext $context
326 * @return string
327 */
328 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
329 $rl = $context->getResourceLoader();
330 $derivative = new DerivativeResourceLoaderContext( $context );
331 $derivative->setModules( array_merge(
332 self::getStartupModules(),
333 self::getLegacyModules()
334 ) );
335 $derivative->setOnly( 'scripts' );
336 // Must setModules() before makeVersionQuery()
337 $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
338
339 return $rl->createLoaderURL( 'local', $derivative );
340 }
341
342 /**
343 * @param ResourceLoaderContext $context
344 * @return string JavaScript code
345 */
346 public function getScript( ResourceLoaderContext $context ) {
347 global $IP;
348 if ( $context->getOnly() !== 'scripts' ) {
349 return '/* Requires only=script */';
350 }
351
352 $out = file_get_contents( "$IP/resources/src/startup.js" );
353
354 $pairs = array_map( function ( $value ) {
355 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
356 // Fix indentation
357 $value = str_replace( "\n", "\n\t", $value );
358 return $value;
359 }, [
360 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
361 '$VARS.configuration' => $this->getConfigSettings( $context ),
362 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
363 ] );
364 $pairs['$CODE.registrations()'] = str_replace(
365 "\n",
366 "\n\t",
367 trim( $this->getModuleRegistrations( $context ) )
368 );
369
370 return strtr( $out, $pairs );
371 }
372
373 /**
374 * @return bool
375 */
376 public function supportsURLLoading() {
377 return false;
378 }
379
380 /**
381 * Get the definition summary for this module.
382 *
383 * @param ResourceLoaderContext $context
384 * @return array
385 */
386 public function getDefinitionSummary( ResourceLoaderContext $context ) {
387 global $IP;
388 $summary = parent::getDefinitionSummary( $context );
389 $summary[] = [
390 // Detect changes to variables exposed in mw.config (T30899).
391 'vars' => $this->getConfigSettings( $context ),
392 // Changes how getScript() creates mw.Map for mw.config
393 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
394 // Detect changes to the module registrations
395 'moduleHashes' => $this->getAllModuleHashes( $context ),
396
397 'fileMtimes' => [
398 filemtime( "$IP/resources/src/startup.js" ),
399 ],
400 ];
401 return $summary;
402 }
403
404 /**
405 * Helper method for getDefinitionSummary().
406 *
407 * @param ResourceLoaderContext $context
408 * @return string SHA-1
409 */
410 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
411 $rl = $context->getResourceLoader();
412 // Preload for getCombinedVersion()
413 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
414
415 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
416 // Think carefully before making changes to this code!
417 // Pre-populate versionHash with something because the loop over all modules below includes
418 // the startup module (this module).
419 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
420 $this->versionHash[$context->getHash()] = null;
421
422 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
423 }
424
425 /**
426 * @return string
427 */
428 public function getGroup() {
429 return 'startup';
430 }
431 }