Merge "Add tests for class names in the api main and query module manager"
[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 // Coerce module timestamp to UNIX timestamp.
215 // getModifiedTime() is supposed to return a UNIX timestamp, but custom implementations
216 // might forget. TODO: Maybe emit warning?
217 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
218
219 $skipFunction = $module->getSkipFunction();
220 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
221 $skipFunction = $resourceLoader->filter( 'minify-js',
222 $skipFunction,
223 // There will potentially be lots of these little string in the registrations
224 // manifest, we don't want to blow up the startup module with
225 // "/* cache key: ... */" all over it in non-debug mode.
226 /* cacheReport = */ false
227 );
228 }
229
230 $mtime = max(
231 $moduleMtime,
232 wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) )
233 );
234
235 $registryData[$name] = array(
236 // Convert to numbers as wfTimestamp always returns a string, even for TS_UNIX
237 'version' => (int) $mtime,
238 'dependencies' => $module->getDependencies(),
239 'group' => $module->getGroup(),
240 'source' => $module->getSource(),
241 'loader' => $module->getLoaderScript(),
242 'skip' => $skipFunction,
243 );
244 }
245
246 self::compileUnresolvedDependencies( $registryData );
247
248 // Register sources
249 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
250
251 // Concatenate module loader scripts and figure out the different call
252 // signatures for mw.loader.register
253 $registrations = array();
254 foreach ( $registryData as $name => $data ) {
255 if ( $data['loader'] !== false ) {
256 $out .= ResourceLoader::makeCustomLoaderScript(
257 $name,
258 wfTimestamp( TS_ISO_8601_BASIC, $data['version'] ),
259 $data['dependencies'],
260 $data['group'],
261 $data['source'],
262 $data['loader']
263 );
264 continue;
265 }
266
267 if (
268 !count( $data['dependencies'] ) &&
269 $data['group'] === null &&
270 $data['source'] === 'local' &&
271 $data['skip'] === null
272 ) {
273 // Modules with no dependencies, group, foreign source or skip function;
274 // call mw.loader.register(name, timestamp)
275 $registrations[] = array( $name, $data['version'] );
276 } elseif (
277 $data['group'] === null &&
278 $data['source'] === 'local' &&
279 $data['skip'] === null
280 ) {
281 // Modules with dependencies but no group, foreign source or skip function;
282 // call mw.loader.register(name, timestamp, dependencies)
283 $registrations[] = array( $name, $data['version'], $data['dependencies'] );
284 } elseif (
285 $data['source'] === 'local' &&
286 $data['skip'] === null
287 ) {
288 // Modules with a group but no foreign source or skip function;
289 // call mw.loader.register(name, timestamp, dependencies, group)
290 $registrations[] = array(
291 $name,
292 $data['version'],
293 $data['dependencies'],
294 $data['group']
295 );
296 } elseif ( $data['skip'] === null ) {
297 // Modules with a foreign source but no skip function;
298 // call mw.loader.register(name, timestamp, dependencies, group, source)
299 $registrations[] = array(
300 $name,
301 $data['version'],
302 $data['dependencies'],
303 $data['group'],
304 $data['source']
305 );
306 } else {
307 // Modules with a skip function;
308 // call mw.loader.register(name, timestamp, dependencies, group, source, skip)
309 $registrations[] = array(
310 $name,
311 $data['version'],
312 $data['dependencies'],
313 $data['group'],
314 $data['source'],
315 $data['skip']
316 );
317 }
318 }
319
320 // Register modules
321 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
322
323 wfProfileOut( __METHOD__ );
324 return $out;
325 }
326
327 /* Methods */
328
329 /**
330 * @return bool
331 */
332 public function isRaw() {
333 return true;
334 }
335
336 /**
337 * Base modules required for the the base environment of ResourceLoader
338 *
339 * @return array
340 */
341 public static function getStartupModules() {
342 return array( 'jquery', 'mediawiki' );
343 }
344
345 /**
346 * Get the load URL of the startup modules.
347 *
348 * This is a helper for getScript(), but can also be called standalone, such
349 * as when generating an AppCache manifest.
350 *
351 * @param ResourceLoaderContext $context
352 * @return string
353 */
354 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
355 $moduleNames = self::getStartupModules();
356
357 // Get the latest version
358 $loader = $context->getResourceLoader();
359 $version = 1;
360 foreach ( $moduleNames as $moduleName ) {
361 $version = max( $version,
362 $loader->getModule( $moduleName )->getModifiedTime( $context )
363 );
364 }
365
366 $query = array(
367 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
368 'only' => 'scripts',
369 'lang' => $context->getLanguage(),
370 'skin' => $context->getSkin(),
371 'debug' => $context->getDebug() ? 'true' : 'false',
372 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
373 );
374 // Ensure uniform query order
375 ksort( $query );
376 return wfAppendQuery( wfScript( 'load' ), $query );
377 }
378
379 /**
380 * @param ResourceLoaderContext $context
381 * @return string
382 */
383 public function getScript( ResourceLoaderContext $context ) {
384 global $IP;
385
386 $out = file_get_contents( "$IP/resources/src/startup.js" );
387 if ( $context->getOnly() === 'scripts' ) {
388
389 // Startup function
390 $configuration = $this->getConfigSettings( $context );
391 $registrations = $this->getModuleRegistrations( $context );
392 // Fix indentation
393 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
394 $mwMapJsCall = Xml::encodeJsCall(
395 'mw.Map',
396 array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) )
397 );
398 $mwConfigSetJsCall = Xml::encodeJsCall(
399 'mw.config.set',
400 array( $configuration )
401 );
402
403 $out .= "var startUp = function () {\n" .
404 "\tmw.config = new " .
405 $mwMapJsCall . "\n" .
406 "\t$registrations\n" .
407 "\t" . $mwConfigSetJsCall .
408 "};\n";
409
410 // Conditional script injection
411 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
412 $out .= "if ( isCompatible() ) {\n" .
413 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
414 "}";
415 }
416
417 return $out;
418 }
419
420 /**
421 * @return bool
422 */
423 public function supportsURLLoading() {
424 return false;
425 }
426
427 /**
428 * @param ResourceLoaderContext $context
429 * @return array|mixed
430 */
431 public function getModifiedTime( ResourceLoaderContext $context ) {
432 global $IP;
433
434 $hash = $context->getHash();
435 if ( isset( $this->modifiedTime[$hash] ) ) {
436 return $this->modifiedTime[$hash];
437 }
438
439 // Call preloadModuleInfo() on ALL modules as we're about
440 // to call getModifiedTime() on all of them
441 $loader = $context->getResourceLoader();
442 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
443
444 $time = max(
445 wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) ),
446 filemtime( "$IP/resources/src/startup.js" ),
447 $this->getHashMtime( $context )
448 );
449
450 // ATTENTION!: Because of the line below, this is not going to cause
451 // infinite recursion - think carefully before making changes to this
452 // code!
453 // Pre-populate modifiedTime with something because the the loop over
454 // all modules below includes the the startup module (this module).
455 $this->modifiedTime[$hash] = 1;
456
457 foreach ( $loader->getModuleNames() as $name ) {
458 $module = $loader->getModule( $name );
459 $time = max( $time, $module->getModifiedTime( $context ) );
460 }
461
462 $this->modifiedTime[$hash] = $time;
463 return $this->modifiedTime[$hash];
464 }
465
466 /**
467 * Hash of all dynamic data embedded in getScript().
468 *
469 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
470 *
471 * @param ResourceLoaderContext $context
472 * @return string Hash
473 */
474 public function getModifiedHash( ResourceLoaderContext $context ) {
475 $data = array(
476 'vars' => $this->getConfigSettings( $context ),
477 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
478 );
479
480 return md5( serialize( $data ) );
481 }
482
483 /**
484 * @return string
485 */
486 public function getGroup() {
487 return 'startup';
488 }
489 }