c79554a618e2bf23a49b7477f3095fe33538cb16
[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 Hooks::run( '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.
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 amount of module registration
159 * data send to the client.
160 *
161 * @param array &$registryData Modules keyed by name with properties:
162 * - number '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 $data['version'],
259 $data['dependencies'],
260 $data['group'],
261 $data['source'],
262 $data['loader']
263 );
264 continue;
265 }
266
267 // Call mw.loader.register(name, timestamp, dependencies, group, source, skip)
268 $registrations[] = array(
269 $name,
270 $data['version'],
271 $data['dependencies'],
272 $data['group'],
273 // Swap default (local) for null
274 $data['source'] === 'local' ? null : $data['source'],
275 $data['skip']
276 );
277 }
278
279 // Register modules
280 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
281
282 wfProfileOut( __METHOD__ );
283 return $out;
284 }
285
286 /* Methods */
287
288 /**
289 * @return bool
290 */
291 public function isRaw() {
292 return true;
293 }
294
295 /**
296 * Base modules required for the base environment of ResourceLoader
297 *
298 * @return array
299 */
300 public static function getStartupModules() {
301 return array( 'jquery', 'mediawiki' );
302 }
303
304 /**
305 * Get the load URL of the startup modules.
306 *
307 * This is a helper for getScript(), but can also be called standalone, such
308 * as when generating an AppCache manifest.
309 *
310 * @param ResourceLoaderContext $context
311 * @return string
312 */
313 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
314 $moduleNames = self::getStartupModules();
315
316 // Get the latest version
317 $loader = $context->getResourceLoader();
318 $version = 1;
319 foreach ( $moduleNames as $moduleName ) {
320 $version = max( $version,
321 $loader->getModule( $moduleName )->getModifiedTime( $context )
322 );
323 }
324
325 $query = array(
326 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
327 'only' => 'scripts',
328 'lang' => $context->getLanguage(),
329 'skin' => $context->getSkin(),
330 'debug' => $context->getDebug() ? 'true' : 'false',
331 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
332 );
333 // Ensure uniform query order
334 ksort( $query );
335 return wfAppendQuery( wfScript( 'load' ), $query );
336 }
337
338 /**
339 * @param ResourceLoaderContext $context
340 * @return string
341 */
342 public function getScript( ResourceLoaderContext $context ) {
343 global $IP;
344
345 $out = file_get_contents( "$IP/resources/src/startup.js" );
346 if ( $context->getOnly() === 'scripts' ) {
347
348 // Startup function
349 $configuration = $this->getConfigSettings( $context );
350 $registrations = $this->getModuleRegistrations( $context );
351 // Fix indentation
352 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
353 $mwMapJsCall = Xml::encodeJsCall(
354 'mw.Map',
355 array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) )
356 );
357 $mwConfigSetJsCall = Xml::encodeJsCall(
358 'mw.config.set',
359 array( $configuration )
360 );
361
362 $out .= "var startUp = function () {\n" .
363 "\tmw.config = new " .
364 $mwMapJsCall . "\n" .
365 "\t$registrations\n" .
366 "\t" . $mwConfigSetJsCall .
367 "};\n";
368
369 // Conditional script injection
370 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
371 $out .= "if ( isCompatible() ) {\n" .
372 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
373 "}";
374 }
375
376 return $out;
377 }
378
379 /**
380 * @return bool
381 */
382 public function supportsURLLoading() {
383 return false;
384 }
385
386 /**
387 * @param ResourceLoaderContext $context
388 * @return array|mixed
389 */
390 public function getModifiedTime( ResourceLoaderContext $context ) {
391 global $IP;
392
393 $hash = $context->getHash();
394 if ( isset( $this->modifiedTime[$hash] ) ) {
395 return $this->modifiedTime[$hash];
396 }
397
398 // Call preloadModuleInfo() on ALL modules as we're about
399 // to call getModifiedTime() on all of them
400 $loader = $context->getResourceLoader();
401 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
402
403 $time = max(
404 wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) ),
405 filemtime( "$IP/resources/src/startup.js" ),
406 $this->getHashMtime( $context )
407 );
408
409 // ATTENTION!: Because of the line below, this is not going to cause
410 // infinite recursion - think carefully before making changes to this
411 // code!
412 // Pre-populate modifiedTime with something because the loop over
413 // all modules below includes the startup module (this module).
414 $this->modifiedTime[$hash] = 1;
415
416 foreach ( $loader->getModuleNames() as $name ) {
417 $module = $loader->getModule( $name );
418 $time = max( $time, $module->getModifiedTime( $context ) );
419 }
420
421 $this->modifiedTime[$hash] = $time;
422 return $this->modifiedTime[$hash];
423 }
424
425 /**
426 * Hash of all dynamic data embedded in getScript().
427 *
428 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
429 *
430 * @param ResourceLoaderContext $context
431 * @return string Hash
432 */
433 public function getModifiedHash( ResourceLoaderContext $context ) {
434 $data = array(
435 'vars' => $this->getConfigSettings( $context ),
436 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
437 );
438
439 return md5( serialize( $data ) );
440 }
441
442 /**
443 * @return string
444 */
445 public function getGroup() {
446 return 'startup';
447 }
448 }