Set mw.config wgFileCanRotate only on Special:Upload instead of
[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 /* Protected Members */
28
29 protected $modifiedTime = array();
30 protected $configVars = array();
31 protected $targets = array( 'desktop', 'mobile' );
32
33 /* Protected Methods */
34
35 /**
36 * @param ResourceLoaderContext $context
37 * @return array
38 */
39 protected function getConfigSettings( $context ) {
40
41 $hash = $context->getHash();
42 if ( isset( $this->configVars[$hash] ) ) {
43 return $this->configVars[$hash];
44 }
45
46 global $wgContLang;
47
48 $mainPage = Title::newMainPage();
49
50 /**
51 * Namespace related preparation
52 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
53 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
54 */
55 $namespaceIds = $wgContLang->getNamespaceIds();
56 $caseSensitiveNamespaces = array();
57 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
58 $namespaceIds[$wgContLang->lc( $name )] = $index;
59 if ( !MWNamespace::isCapitalized( $index ) ) {
60 $caseSensitiveNamespaces[] = $index;
61 }
62 }
63
64 $conf = $this->getConfig();
65 // Build list of variables
66 $vars = array(
67 'wgLoadScript' => wfScript( 'load' ),
68 'debug' => $context->getDebug(),
69 'skin' => $context->getSkin(),
70 'stylepath' => $conf->get( 'StylePath' ),
71 'wgUrlProtocols' => wfUrlProtocols(),
72 'wgArticlePath' => $conf->get( 'ArticlePath' ),
73 'wgScriptPath' => $conf->get( 'ScriptPath' ),
74 'wgScriptExtension' => $conf->get( 'ScriptExtension' ),
75 'wgScript' => wfScript(),
76 'wgSearchType' => $conf->get( 'SearchType' ),
77 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
78 // Force object to avoid "empty" associative array from
79 // becoming [] instead of {} in JS (bug 34604)
80 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
81 'wgServer' => $conf->get( 'Server' ),
82 'wgServerName' => $conf->get( 'ServerName' ),
83 'wgUserLanguage' => $context->getLanguage(),
84 'wgContentLanguage' => $wgContLang->getCode(),
85 'wgVersion' => $conf->get( 'Version' ),
86 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
87 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
88 'wgMainPageTitle' => $mainPage->getPrefixedText(),
89 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
90 'wgNamespaceIds' => $namespaceIds,
91 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
92 'wgSiteName' => $conf->get( 'Sitename' ),
93 'wgFileExtensions' => array_values( array_unique( $conf->get( 'FileExtensions' ) ) ),
94 'wgDBname' => $conf->get( 'DBname' ),
95 'wgAvailableSkins' => Skin::getSkinNames(),
96 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
97 // MediaWiki sets cookies to have this prefix by default
98 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
99 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
100 'wgCookiePath' => $conf->get( 'CookiePath' ),
101 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
102 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
103 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
104 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
105 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
106 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
107 );
108
109 wfRunHooks( '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 and return it.
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 amout 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 * - string|false 'loader'
167 */
168 public static function compileUnresolvedDependencies( array &$registryData ) {
169 foreach ( $registryData as $name => &$data ) {
170 if ( $data['loader'] !== false ) {
171 continue;
172 }
173 $dependencies = $data['dependencies'];
174 foreach ( $data['dependencies'] as $dependency ) {
175 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
176 $dependencies = array_diff( $dependencies, $implicitDependencies );
177 }
178 // Rebuild keys
179 $data['dependencies'] = array_values( $dependencies );
180 }
181 }
182
183
184 /**
185 * Get registration code for all modules.
186 *
187 * @param ResourceLoaderContext $context
188 * @return string JavaScript code for registering all modules with the client loader
189 */
190 public function getModuleRegistrations( ResourceLoaderContext $context ) {
191 wfProfileIn( __METHOD__ );
192
193 $resourceLoader = $context->getResourceLoader();
194 $target = $context->getRequest()->getVal( 'target', 'desktop' );
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 ( !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 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
215 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
216 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
217 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) ) );
218
219 // FIXME: Convert to numbers, wfTimestamp always gives us stings, even for TS_UNIX
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 string in the registrations
226 // manifest, we don't want to blow up the startup module with
227 // "/* cache key: ... */" all over it in non-debug mode.
228 /* cacheReport = */ false
229 );
230 }
231
232 $registryData[$name] = array(
233 'version' => $mtime,
234 'dependencies' => $module->getDependencies(),
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 wfTimestamp( TS_ISO_8601_BASIC, $data['version'] ),
255 $data['dependencies'],
256 $data['group'],
257 $data['source'],
258 $data['loader']
259 );
260 continue;
261 }
262
263 if (
264 !count( $data['dependencies'] ) &&
265 $data['group'] === null &&
266 $data['source'] === 'local' &&
267 $data['skip'] === null
268 ) {
269 // Modules with no dependencies, group, foreign source or skip function;
270 // call mw.loader.register(name, timestamp)
271 $registrations[] = array( $name, $data['version'] );
272 } elseif (
273 $data['group'] === null &&
274 $data['source'] === 'local' &&
275 $data['skip'] === null
276 ) {
277 // Modules with dependencies but no group, foreign source or skip function;
278 // call mw.loader.register(name, timestamp, dependencies)
279 $registrations[] = array( $name, $data['version'], $data['dependencies'] );
280 } elseif (
281 $data['source'] === 'local' &&
282 $data['skip'] === null
283 ) {
284 // Modules with a group but no foreign source or skip function;
285 // call mw.loader.register(name, timestamp, dependencies, group)
286 $registrations[] = array(
287 $name,
288 $data['version'],
289 $data['dependencies'],
290 $data['group']
291 );
292 } elseif ( $data['skip'] === null ) {
293 // Modules with a foreign source but no skip function;
294 // call mw.loader.register(name, timestamp, dependencies, group, source)
295 $registrations[] = array(
296 $name,
297 $data['version'],
298 $data['dependencies'],
299 $data['group'],
300 $data['source']
301 );
302 } else {
303 // Modules with a skip function;
304 // call mw.loader.register(name, timestamp, dependencies, group, source, skip)
305 $registrations[] = array(
306 $name,
307 $data['version'],
308 $data['dependencies'],
309 $data['group'],
310 $data['source'],
311 $data['skip']
312 );
313 }
314 }
315
316 // Register modules
317 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
318
319 wfProfileOut( __METHOD__ );
320 return $out;
321 }
322
323 /* Methods */
324
325 /**
326 * @return bool
327 */
328 public function isRaw() {
329 return true;
330 }
331
332 /**
333 * Base modules required for the the base environment of ResourceLoader
334 *
335 * @return array
336 */
337 public static function getStartupModules() {
338 return array( 'jquery', 'mediawiki' );
339 }
340
341 /**
342 * Get the load URL of the startup modules.
343 *
344 * This is a helper for getScript(), but can also be called standalone, such
345 * as when generating an AppCache manifest.
346 *
347 * @param ResourceLoaderContext $context
348 * @return string
349 */
350 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
351 $moduleNames = self::getStartupModules();
352
353 // Get the latest version
354 $loader = $context->getResourceLoader();
355 $version = 0;
356 foreach ( $moduleNames as $moduleName ) {
357 $version = max( $version,
358 $loader->getModule( $moduleName )->getModifiedTime( $context )
359 );
360 }
361
362 $query = array(
363 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
364 'only' => 'scripts',
365 'lang' => $context->getLanguage(),
366 'skin' => $context->getSkin(),
367 'debug' => $context->getDebug() ? 'true' : 'false',
368 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
369 );
370 // Ensure uniform query order
371 ksort( $query );
372 return wfAppendQuery( wfScript( 'load' ), $query );
373 }
374
375 /**
376 * @param ResourceLoaderContext $context
377 * @return string
378 */
379 public function getScript( ResourceLoaderContext $context ) {
380 global $IP;
381
382 $out = file_get_contents( "$IP/resources/src/startup.js" );
383 if ( $context->getOnly() === 'scripts' ) {
384
385 // Startup function
386 $configuration = $this->getConfigSettings( $context );
387 $registrations = $this->getModuleRegistrations( $context );
388 // Fix indentation
389 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
390 $out .= "var startUp = function () {\n" .
391 "\tmw.config = new " .
392 Xml::encodeJsCall( 'mw.Map', array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) ) ) . "\n" .
393 "\t$registrations\n" .
394 "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
395 "};\n";
396
397 // Conditional script injection
398 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
399 $out .= "if ( isCompatible() ) {\n" .
400 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
401 "}";
402 }
403
404 return $out;
405 }
406
407 /**
408 * @return bool
409 */
410 public function supportsURLLoading() {
411 return false;
412 }
413
414 /**
415 * @param ResourceLoaderContext $context
416 * @return array|mixed
417 */
418 public function getModifiedTime( ResourceLoaderContext $context ) {
419 global $IP;
420
421 $hash = $context->getHash();
422 if ( isset( $this->modifiedTime[$hash] ) ) {
423 return $this->modifiedTime[$hash];
424 }
425
426 // Call preloadModuleInfo() on ALL modules as we're about
427 // to call getModifiedTime() on all of them
428 $loader = $context->getResourceLoader();
429 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
430
431 $time = max(
432 wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) ),
433 filemtime( "$IP/resources/src/startup.js" ),
434 $this->getHashMtime( $context )
435 );
436
437 // ATTENTION!: Because of the line below, this is not going to cause
438 // infinite recursion - think carefully before making changes to this
439 // code!
440 // Pre-populate modifiedTime with something because the the loop over
441 // all modules below includes the the startup module (this module).
442 $this->modifiedTime[$hash] = 1;
443
444 foreach ( $loader->getModuleNames() as $name ) {
445 $module = $loader->getModule( $name );
446 $time = max( $time, $module->getModifiedTime( $context ) );
447 }
448
449 $this->modifiedTime[$hash] = $time;
450 return $this->modifiedTime[$hash];
451 }
452
453 /**
454 * Hash of all dynamic data embedded in getScript().
455 *
456 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
457 *
458 * @param ResourceLoaderContext $context
459 * @return string Hash
460 */
461 public function getModifiedHash( ResourceLoaderContext $context ) {
462 $data = array(
463 'vars' => $this->getConfigSettings( $context ),
464 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
465 );
466
467 return md5( serialize( $data ) );
468 }
469
470 /**
471 * @return string
472 */
473 public function getGroup() {
474 return 'startup';
475 }
476 }