Merge "Special:Allpages replace table with unordered list"
[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 // This sucks, it is only needed on Special:Upload, but I could
96 // not find a way to add vars only for a certain module
97 'wgFileCanRotate' => BitmapHandler::canRotate(),
98 'wgAvailableSkins' => Skin::getSkinNames(),
99 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
100 // MediaWiki sets cookies to have this prefix by default
101 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
102 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
103 'wgCookiePath' => $conf->get( 'CookiePath' ),
104 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
105 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
106 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
107 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
108 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
109 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
110 );
111
112 wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$vars ) );
113
114 $this->configVars[$hash] = $vars;
115 return $this->configVars[$hash];
116 }
117
118 /**
119 * Recursively get all explicit and implicit dependencies for to the given module.
120 *
121 * @param array $registryData
122 * @param string $moduleName
123 * @return array
124 */
125 protected static function getImplicitDependencies( Array $registryData, $moduleName ) {
126 static $dependencyCache = array();
127
128 // The list of implicit dependencies won't be altered, so we can
129 // cache them without having to worry.
130 if ( !isset( $dependencyCache[$moduleName] ) ) {
131
132 if ( !isset( $registryData[$moduleName] ) ) {
133 // Dependencies may not exist
134 $dependencyCache[$moduleName] = array();
135 } else {
136 $data = $registryData[$moduleName];
137 $dependencyCache[$moduleName] = $data['dependencies'];
138
139 foreach ( $data['dependencies'] as $dependency ) {
140 // Recursively get the dependencies of the dependencies
141 $dependencyCache[$moduleName] = array_merge(
142 $dependencyCache[$moduleName],
143 self::getImplicitDependencies( $registryData, $dependency )
144 );
145 }
146 }
147 }
148
149 return $dependencyCache[$moduleName];
150 }
151
152 /**
153 * Optimize the dependency tree in $this->modules and return it.
154 *
155 * The optimization basically works like this:
156 * Given we have module A with the dependencies B and C
157 * and module B with the dependency C.
158 * Now we don't have to tell the client to explicitly fetch module
159 * C as that's already included in module B.
160 *
161 * This way we can reasonably reduce the amout of module registration
162 * data send to the client.
163 *
164 * @param array &$registryData Modules keyed by name with properties:
165 * - string 'version'
166 * - array 'dependencies'
167 * - string|null 'group'
168 * - string 'source'
169 * - string|false 'loader'
170 */
171 public static function compileUnresolvedDependencies( Array &$registryData ) {
172 foreach ( $registryData as $name => &$data ) {
173 if ( $data['loader'] !== false ) {
174 continue;
175 }
176 $dependencies = $data['dependencies'];
177 foreach ( $data['dependencies'] as $dependency ) {
178 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
179 $dependencies = array_diff( $dependencies, $implicitDependencies );
180 }
181 // Rebuild keys
182 $data['dependencies'] = array_values( $dependencies );
183 }
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 wfProfileIn( __METHOD__ );
195
196 $resourceLoader = $context->getResourceLoader();
197 $target = $context->getRequest()->getVal( 'target', 'desktop' );
198
199 $out = '';
200 $registryData = array();
201
202 // Get registry data
203 foreach ( $resourceLoader->getModuleNames() as $name ) {
204 $module = $resourceLoader->getModule( $name );
205 $moduleTargets = $module->getTargets();
206 if ( !in_array( $target, $moduleTargets ) ) {
207 continue;
208 }
209
210 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
211 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
212 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
213 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) ) );
214
215 // FIXME: Convert to numbers, wfTimestamp always gives us stings, even for TS_UNIX
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 string in the registrations
222 // manifest, we don't want to blow up the startup module with
223 // "/* cache key: ... */" all over it in non-debug mode.
224 /* cacheReport = */ false
225 );
226 }
227
228 $registryData[$name] = array(
229 'version' => $mtime,
230 'dependencies' => $module->getDependencies(),
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 wfTimestamp( TS_ISO_8601_BASIC, $data['version'] ),
251 $data['dependencies'],
252 $data['group'],
253 $data['source'],
254 $data['loader']
255 );
256 continue;
257 }
258
259 if (
260 !count( $data['dependencies'] ) &&
261 $data['group'] === null &&
262 $data['source'] === 'local' &&
263 $data['skip'] === null
264 ) {
265 // Modules with no dependencies, group, foreign source or skip function;
266 // call mw.loader.register(name, timestamp)
267 $registrations[] = array( $name, $data['version'] );
268 } elseif (
269 $data['group'] === null &&
270 $data['source'] === 'local' &&
271 $data['skip'] === null
272 ) {
273 // Modules with dependencies but no group, foreign source or skip function;
274 // call mw.loader.register(name, timestamp, dependencies)
275 $registrations[] = array( $name, $data['version'], $data['dependencies'] );
276 } elseif (
277 $data['source'] === 'local' &&
278 $data['skip'] === null
279 ) {
280 // Modules with a group but no foreign source or skip function;
281 // call mw.loader.register(name, timestamp, dependencies, group)
282 $registrations[] = array(
283 $name,
284 $data['version'],
285 $data['dependencies'],
286 $data['group']
287 );
288 } elseif ( $data['skip'] === null ) {
289 // Modules with a foreign source but no skip function;
290 // call mw.loader.register(name, timestamp, dependencies, group, source)
291 $registrations[] = array(
292 $name,
293 $data['version'],
294 $data['dependencies'],
295 $data['group'],
296 $data['source']
297 );
298 } else {
299 // Modules with a skip function;
300 // call mw.loader.register(name, timestamp, dependencies, group, source, skip)
301 $registrations[] = array(
302 $name,
303 $data['version'],
304 $data['dependencies'],
305 $data['group'],
306 $data['source'],
307 $data['skip']
308 );
309 }
310 }
311
312 // Register modules
313 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
314
315 wfProfileOut( __METHOD__ );
316 return $out;
317 }
318
319 /* Methods */
320
321 /**
322 * @return bool
323 */
324 public function isRaw() {
325 return true;
326 }
327
328 /**
329 * Get the load URL of the startup modules.
330 *
331 * This is a helper for getScript(), but can also be called standalone, such
332 * as when generating an AppCache manifest.
333 *
334 * @param ResourceLoaderContext $context
335 * @return string
336 */
337 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
338 // The core modules:
339 $moduleNames = array( 'jquery', 'mediawiki' );
340
341 // Get the latest version
342 $loader = $context->getResourceLoader();
343 $version = 0;
344 foreach ( $moduleNames as $moduleName ) {
345 $version = max( $version,
346 $loader->getModule( $moduleName )->getModifiedTime( $context )
347 );
348 }
349
350 $query = array(
351 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
352 'only' => 'scripts',
353 'lang' => $context->getLanguage(),
354 'skin' => $context->getSkin(),
355 'debug' => $context->getDebug() ? 'true' : 'false',
356 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
357 );
358 // Ensure uniform query order
359 ksort( $query );
360 return wfAppendQuery( wfScript( 'load' ), $query );
361 }
362
363 /**
364 * @param ResourceLoaderContext $context
365 * @return string
366 */
367 public function getScript( ResourceLoaderContext $context ) {
368 global $IP;
369
370 $out = file_get_contents( "$IP/resources/src/startup.js" );
371 if ( $context->getOnly() === 'scripts' ) {
372
373 // Startup function
374 $configuration = $this->getConfigSettings( $context );
375 $registrations = $this->getModuleRegistrations( $context );
376 // Fix indentation
377 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
378 $out .= "var startUp = function () {\n" .
379 "\tmw.config = new " .
380 Xml::encodeJsCall( 'mw.Map', array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) ) ) . "\n" .
381 "\t$registrations\n" .
382 "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
383 "};\n";
384
385 // Conditional script injection
386 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
387 $out .= "if ( isCompatible() ) {\n" .
388 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
389 "}";
390 }
391
392 return $out;
393 }
394
395 /**
396 * @return bool
397 */
398 public function supportsURLLoading() {
399 return false;
400 }
401
402 /**
403 * @param ResourceLoaderContext $context
404 * @return array|mixed
405 */
406 public function getModifiedTime( ResourceLoaderContext $context ) {
407 global $IP;
408
409 $hash = $context->getHash();
410 if ( isset( $this->modifiedTime[$hash] ) ) {
411 return $this->modifiedTime[$hash];
412 }
413
414 // Call preloadModuleInfo() on ALL modules as we're about
415 // to call getModifiedTime() on all of them
416 $loader = $context->getResourceLoader();
417 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
418
419 $time = max(
420 wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) ),
421 filemtime( "$IP/resources/src/startup.js" ),
422 $this->getHashMtime( $context )
423 );
424
425 // ATTENTION!: Because of the line below, this is not going to cause
426 // infinite recursion - think carefully before making changes to this
427 // code!
428 // Pre-populate modifiedTime with something because the the loop over
429 // all modules below includes the the startup module (this module).
430 $this->modifiedTime[$hash] = 1;
431
432 foreach ( $loader->getModuleNames() as $name ) {
433 $module = $loader->getModule( $name );
434 $time = max( $time, $module->getModifiedTime( $context ) );
435 }
436
437 $this->modifiedTime[$hash] = $time;
438 return $this->modifiedTime[$hash];
439 }
440
441 /**
442 * Hash of all dynamic data embedded in getScript().
443 *
444 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
445 *
446 * @param ResourceLoaderContext $context
447 * @return string Hash
448 */
449 public function getModifiedHash( ResourceLoaderContext $context ) {
450 $data = array(
451 'vars' => $this->getConfigSettings( $context ),
452 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
453 );
454
455 return md5( serialize( $data ) );
456 }
457
458 /**
459 * @return string
460 */
461 public function getGroup() {
462 return 'startup';
463 }
464 }