Note that jquery.json will be removed in 1.25
[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 getConfig( $context ) {
40
41 $hash = $context->getHash();
42 if ( isset( $this->configVars[$hash] ) ) {
43 return $this->configVars[$hash];
44 }
45
46 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension,
47 $wgArticlePath, $wgScriptPath, $wgServer, $wgServerName,
48 $wgContLang, $wgVariantArticlePath, $wgActionPaths, $wgVersion,
49 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname,
50 $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath,
51 $wgCookiePrefix, $wgCookieDomain, $wgCookiePath,
52 $wgCookieExpiration, $wgResourceLoaderMaxQueryLength,
53 $wgResourceLoaderStorageEnabled, $wgResourceLoaderStorageVersion,
54 $wgSearchType;
55
56 $mainPage = Title::newMainPage();
57
58 /**
59 * Namespace related preparation
60 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
61 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
62 */
63 $namespaceIds = $wgContLang->getNamespaceIds();
64 $caseSensitiveNamespaces = array();
65 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
66 $namespaceIds[$wgContLang->lc( $name )] = $index;
67 if ( !MWNamespace::isCapitalized( $index ) ) {
68 $caseSensitiveNamespaces[] = $index;
69 }
70 }
71
72 // Build list of variables
73 $vars = array(
74 'wgLoadScript' => $wgLoadScript,
75 'debug' => $context->getDebug(),
76 'skin' => $context->getSkin(),
77 'stylepath' => $wgStylePath,
78 'wgUrlProtocols' => wfUrlProtocols(),
79 'wgArticlePath' => $wgArticlePath,
80 'wgScriptPath' => $wgScriptPath,
81 'wgScriptExtension' => $wgScriptExtension,
82 'wgScript' => $wgScript,
83 'wgSearchType' => $wgSearchType,
84 'wgVariantArticlePath' => $wgVariantArticlePath,
85 // Force object to avoid "empty" associative array from
86 // becoming [] instead of {} in JS (bug 34604)
87 'wgActionPaths' => (object)$wgActionPaths,
88 'wgServer' => $wgServer,
89 'wgServerName' => $wgServerName,
90 'wgUserLanguage' => $context->getLanguage(),
91 'wgContentLanguage' => $wgContLang->getCode(),
92 'wgVersion' => $wgVersion,
93 'wgEnableAPI' => $wgEnableAPI,
94 'wgEnableWriteAPI' => $wgEnableWriteAPI,
95 'wgMainPageTitle' => $mainPage->getPrefixedText(),
96 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
97 'wgNamespaceIds' => $namespaceIds,
98 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
99 'wgSiteName' => $wgSitename,
100 'wgFileExtensions' => array_values( array_unique( $wgFileExtensions ) ),
101 'wgDBname' => $wgDBname,
102 // This sucks, it is only needed on Special:Upload, but I could
103 // not find a way to add vars only for a certain module
104 'wgFileCanRotate' => BitmapHandler::canRotate(),
105 'wgAvailableSkins' => Skin::getSkinNames(),
106 'wgExtensionAssetsPath' => $wgExtensionAssetsPath,
107 // MediaWiki sets cookies to have this prefix by default
108 'wgCookiePrefix' => $wgCookiePrefix,
109 'wgCookieDomain' => $wgCookieDomain,
110 'wgCookiePath' => $wgCookiePath,
111 'wgCookieExpiration' => $wgCookieExpiration,
112 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength,
113 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
114 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
115 'wgResourceLoaderStorageVersion' => $wgResourceLoaderStorageVersion,
116 'wgResourceLoaderStorageEnabled' => $wgResourceLoaderStorageEnabled,
117 );
118
119 wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$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 = array();
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] = array();
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 and return it.
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 amout 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 * - string|false 'loader'
177 */
178 public static function compileUnresolvedDependencies( Array &$registryData ) {
179 foreach ( $registryData as $name => &$data ) {
180 if ( $data['loader'] !== false ) {
181 continue;
182 }
183 $dependencies = $data['dependencies'];
184 foreach ( $data['dependencies'] as $dependency ) {
185 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
186 $dependencies = array_diff( $dependencies, $implicitDependencies );
187 }
188 // Rebuild keys
189 $data['dependencies'] = array_values( $dependencies );
190 }
191 }
192
193
194 /**
195 * Get registration code for all modules.
196 *
197 * @param ResourceLoaderContext $context
198 * @return string JavaScript code for registering all modules with the client loader
199 */
200 public static function getModuleRegistrations( ResourceLoaderContext $context ) {
201 global $wgCacheEpoch;
202 wfProfileIn( __METHOD__ );
203
204 $resourceLoader = $context->getResourceLoader();
205 $target = $context->getRequest()->getVal( 'target', 'desktop' );
206
207 $out = '';
208 $registryData = array();
209
210 // Get registry data
211 foreach ( $resourceLoader->getModuleNames() as $name ) {
212 $module = $resourceLoader->getModule( $name );
213 $moduleTargets = $module->getTargets();
214 if ( !in_array( $target, $moduleTargets ) ) {
215 continue;
216 }
217
218 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
219 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
220 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
221 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $wgCacheEpoch ) );
222
223 // FIXME: Convert to numbers, wfTimestamp always gives us stings, even for TS_UNIX
224
225 $skipFunction = $module->getSkipFunction();
226 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
227 $skipFunction = $resourceLoader->filter( 'minify-js',
228 $skipFunction,
229 // There will potentially be lots of these little string in the registrations
230 // manifest, we don't want to blow up the startup module with
231 // "/* cache key: ... */" all over it in non-debug mode.
232 /* cacheReport = */ false
233 );
234 }
235
236 $registryData[ $name ] = array(
237 'version' => $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 * Get the load URL of the startup modules.
338 *
339 * This is a helper for getScript(), but can also be called standalone, such
340 * as when generating an AppCache manifest.
341 *
342 * @param ResourceLoaderContext $context
343 * @return string
344 */
345 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
346 // The core modules:
347 $moduleNames = array( 'jquery', 'mediawiki' );
348 wfRunHooks( 'ResourceLoaderGetStartupModules', array( &$moduleNames ), '1.23' );
349
350 // Get the latest version
351 $loader = $context->getResourceLoader();
352 $version = 0;
353 foreach ( $moduleNames as $moduleName ) {
354 $version = max( $version,
355 $loader->getModule( $moduleName )->getModifiedTime( $context )
356 );
357 }
358
359 $query = array(
360 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
361 'only' => 'scripts',
362 'lang' => $context->getLanguage(),
363 'skin' => $context->getSkin(),
364 'debug' => $context->getDebug() ? 'true' : 'false',
365 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
366 );
367 // Ensure uniform query order
368 ksort( $query );
369 return wfAppendQuery( wfScript( 'load' ), $query );
370 }
371
372 /**
373 * @param ResourceLoaderContext $context
374 * @return string
375 */
376 public function getScript( ResourceLoaderContext $context ) {
377 global $IP, $wgLegacyJavaScriptGlobals;
378
379 $out = file_get_contents( "$IP/resources/src/startup.js" );
380 if ( $context->getOnly() === 'scripts' ) {
381
382 // Startup function
383 $configuration = $this->getConfig( $context );
384 $registrations = self::getModuleRegistrations( $context );
385 // Fix indentation
386 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
387 $out .= "var startUp = function () {\n" .
388 "\tmw.config = new " .
389 Xml::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
390 "\t$registrations\n" .
391 "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
392 "};\n";
393
394 // Conditional script injection
395 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
396 $out .= "if ( isCompatible() ) {\n" .
397 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
398 "}";
399 }
400
401 return $out;
402 }
403
404 /**
405 * @return bool
406 */
407 public function supportsURLLoading() {
408 return false;
409 }
410
411 /**
412 * @param ResourceLoaderContext $context
413 * @return array|mixed
414 */
415 public function getModifiedTime( ResourceLoaderContext $context ) {
416 global $IP, $wgCacheEpoch;
417
418 $hash = $context->getHash();
419 if ( isset( $this->modifiedTime[$hash] ) ) {
420 return $this->modifiedTime[$hash];
421 }
422
423 // Call preloadModuleInfo() on ALL modules as we're about
424 // to call getModifiedTime() on all of them
425 $loader = $context->getResourceLoader();
426 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
427
428 $time = max(
429 wfTimestamp( TS_UNIX, $wgCacheEpoch ),
430 filemtime( "$IP/resources/src/startup.js" ),
431 $this->getHashMtime( $context )
432 );
433
434 // ATTENTION!: Because of the line below, this is not going to cause
435 // infinite recursion - think carefully before making changes to this
436 // code!
437 // Pre-populate modifiedTime with something because the the loop over
438 // all modules below includes the the startup module (this module).
439 $this->modifiedTime[$hash] = 1;
440
441 foreach ( $loader->getModuleNames() as $name ) {
442 $module = $loader->getModule( $name );
443 $time = max( $time, $module->getModifiedTime( $context ) );
444 }
445
446 $this->modifiedTime[$hash] = $time;
447 return $this->modifiedTime[$hash];
448 }
449
450 /**
451 * Hash of all dynamic data embedded in getScript().
452 *
453 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
454 *
455 * @param ResourceLoaderContext $context
456 * @return string Hash
457 */
458 public function getModifiedHash( ResourceLoaderContext $context ) {
459 global $wgLegacyJavaScriptGlobals;
460
461 $data = array(
462 'vars' => $this->getConfig( $context ),
463 'wgLegacyJavaScriptGlobals' => $wgLegacyJavaScriptGlobals,
464 );
465
466 return md5( serialize( $data ) );
467 }
468
469 /**
470 * @return string
471 */
472 public function getGroup() {
473 return 'startup';
474 }
475 }