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