Hide edit toolbar Signature button in non-discussion namespaces
[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 );
105
106 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
107
108 $this->configVars[$hash] = $vars;
109 return $this->configVars[$hash];
110 }
111
112 /**
113 * Recursively get all explicit and implicit dependencies for to the given module.
114 *
115 * @param array $registryData
116 * @param string $moduleName
117 * @return array
118 */
119 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
120 static $dependencyCache = array();
121
122 // The list of implicit dependencies won't be altered, so we can
123 // cache them without having to worry.
124 if ( !isset( $dependencyCache[$moduleName] ) ) {
125
126 if ( !isset( $registryData[$moduleName] ) ) {
127 // Dependencies may not exist
128 $dependencyCache[$moduleName] = array();
129 } else {
130 $data = $registryData[$moduleName];
131 $dependencyCache[$moduleName] = $data['dependencies'];
132
133 foreach ( $data['dependencies'] as $dependency ) {
134 // Recursively get the dependencies of the dependencies
135 $dependencyCache[$moduleName] = array_merge(
136 $dependencyCache[$moduleName],
137 self::getImplicitDependencies( $registryData, $dependency )
138 );
139 }
140 }
141 }
142
143 return $dependencyCache[$moduleName];
144 }
145
146 /**
147 * Optimize the dependency tree in $this->modules.
148 *
149 * The optimization basically works like this:
150 * Given we have module A with the dependencies B and C
151 * and module B with the dependency C.
152 * Now we don't have to tell the client to explicitly fetch module
153 * C as that's already included in module B.
154 *
155 * This way we can reasonably reduce the amount of module registration
156 * data send to the client.
157 *
158 * @param array &$registryData Modules keyed by name with properties:
159 * - string 'version'
160 * - array 'dependencies'
161 * - string|null 'group'
162 * - string 'source'
163 * - string|false 'loader'
164 */
165 public static function compileUnresolvedDependencies( array &$registryData ) {
166 foreach ( $registryData as $name => &$data ) {
167 if ( $data['loader'] !== false ) {
168 continue;
169 }
170 $dependencies = $data['dependencies'];
171 foreach ( $data['dependencies'] as $dependency ) {
172 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
173 $dependencies = array_diff( $dependencies, $implicitDependencies );
174 }
175 // Rebuild keys
176 $data['dependencies'] = array_values( $dependencies );
177 }
178 }
179
180
181 /**
182 * Get registration code for all modules.
183 *
184 * @param ResourceLoaderContext $context
185 * @return string JavaScript code for registering all modules with the client loader
186 */
187 public function getModuleRegistrations( ResourceLoaderContext $context ) {
188
189 $resourceLoader = $context->getResourceLoader();
190 $target = $context->getRequest()->getVal( 'target', 'desktop' );
191
192 $out = '';
193 $registryData = array();
194
195 // Get registry data
196 foreach ( $resourceLoader->getModuleNames() as $name ) {
197 $module = $resourceLoader->getModule( $name );
198 $moduleTargets = $module->getTargets();
199 if ( !in_array( $target, $moduleTargets ) ) {
200 continue;
201 }
202
203 if ( $module->isRaw() ) {
204 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
205 // depending on them is illegal anyway and would only lead to them being reloaded
206 // causing any state to be lost (like jQuery plugins, mw.config etc.)
207 continue;
208 }
209
210 $versionHash = $module->getVersionHash( $context );
211 if ( strlen( $versionHash ) !== 8 ) {
212 // Module implementation either broken or deviated from ResourceLoader::makeHash
213 // Asserted by tests/phpunit/structure/ResourcesTest.
214 $versionHash = ResourceLoader::makeHash( $versionHash );
215 }
216
217 $skipFunction = $module->getSkipFunction();
218 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
219 $skipFunction = $resourceLoader->filter( 'minify-js',
220 $skipFunction,
221 // There will potentially be lots of these little strings in the registrations
222 // manifest, we don't want to blow up the startup module with
223 // "/* cache key: ... */" all over it.
224 /* cacheReport = */ false
225 );
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 /**
294 * Get the load URL of the startup modules.
295 *
296 * This is a helper for getScript(), but can also be called standalone, such
297 * as when generating an AppCache manifest.
298 *
299 * @param ResourceLoaderContext $context
300 * @return string
301 */
302 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
303 $rl = $context->getResourceLoader();
304 $moduleNames = self::getStartupModules();
305
306 $query = array(
307 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
308 'only' => 'scripts',
309 'lang' => $context->getLanguage(),
310 'skin' => $context->getSkin(),
311 'debug' => $context->getDebug() ? 'true' : 'false',
312 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
313 );
314 // Ensure uniform query order
315 ksort( $query );
316 return wfAppendQuery( wfScript( 'load' ), $query );
317 }
318
319 /**
320 * @param ResourceLoaderContext $context
321 * @return string
322 */
323 public function getScript( ResourceLoaderContext $context ) {
324 global $IP;
325 if ( $context->getOnly() !== 'scripts' ) {
326 return '/* Requires only=script */';
327 }
328
329 $out = file_get_contents( "$IP/resources/src/startup.js" );
330
331 $pairs = array_map( function ( $value ) {
332 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
333 // Fix indentation
334 $value = str_replace( "\n", "\n\t", $value );
335 return $value;
336 }, array(
337 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
338 '$VARS.configuration' => $this->getConfigSettings( $context ),
339 '$VARS.baseModulesScript' => Html::linkedScript( self::getStartupModulesUrl( $context ) ),
340 ) );
341 $pairs['$CODE.registrations()'] = str_replace( "\n", "\n\t", trim( $this->getModuleRegistrations( $context ) ) );
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 }