Merge "Split SiteLookup interface from SiteStore"
[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 'wgDBname' => $conf->get( 'DBname' ),
94 'wgAvailableSkins' => Skin::getSkinNames(),
95 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
96 // MediaWiki sets cookies to have this prefix by default
97 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
98 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
99 'wgCookiePath' => $conf->get( 'CookiePath' ),
100 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
101 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
102 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
103 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
104 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
105 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
106 );
107
108 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
109
110 $this->configVars[$hash] = $vars;
111 return $this->configVars[$hash];
112 }
113
114 /**
115 * Recursively get all explicit and implicit dependencies for to the given module.
116 *
117 * @param array $registryData
118 * @param string $moduleName
119 * @return array
120 */
121 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
122 static $dependencyCache = array();
123
124 // The list of implicit dependencies won't be altered, so we can
125 // cache them without having to worry.
126 if ( !isset( $dependencyCache[$moduleName] ) ) {
127
128 if ( !isset( $registryData[$moduleName] ) ) {
129 // Dependencies may not exist
130 $dependencyCache[$moduleName] = array();
131 } else {
132 $data = $registryData[$moduleName];
133 $dependencyCache[$moduleName] = $data['dependencies'];
134
135 foreach ( $data['dependencies'] as $dependency ) {
136 // Recursively get the dependencies of the dependencies
137 $dependencyCache[$moduleName] = array_merge(
138 $dependencyCache[$moduleName],
139 self::getImplicitDependencies( $registryData, $dependency )
140 );
141 }
142 }
143 }
144
145 return $dependencyCache[$moduleName];
146 }
147
148 /**
149 * Optimize the dependency tree in $this->modules.
150 *
151 * The optimization basically works like this:
152 * Given we have module A with the dependencies B and C
153 * and module B with the dependency C.
154 * Now we don't have to tell the client to explicitly fetch module
155 * C as that's already included in module B.
156 *
157 * This way we can reasonably reduce the amount of module registration
158 * data send to the client.
159 *
160 * @param array &$registryData Modules keyed by name with properties:
161 * - number 'version'
162 * - array 'dependencies'
163 * - string|null 'group'
164 * - string 'source'
165 * - string|false 'loader'
166 */
167 public static function compileUnresolvedDependencies( array &$registryData ) {
168 foreach ( $registryData as $name => &$data ) {
169 if ( $data['loader'] !== false ) {
170 continue;
171 }
172 $dependencies = $data['dependencies'];
173 foreach ( $data['dependencies'] as $dependency ) {
174 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
175 $dependencies = array_diff( $dependencies, $implicitDependencies );
176 }
177 // Rebuild keys
178 $data['dependencies'] = array_values( $dependencies );
179 }
180 }
181
182
183 /**
184 * Get registration code for all modules.
185 *
186 * @param ResourceLoaderContext $context
187 * @return string JavaScript code for registering all modules with the client loader
188 */
189 public function getModuleRegistrations( ResourceLoaderContext $context ) {
190
191 $resourceLoader = $context->getResourceLoader();
192 $target = $context->getRequest()->getVal( 'target', 'desktop' );
193
194 $out = '';
195 $registryData = array();
196
197 // Get registry data
198 foreach ( $resourceLoader->getModuleNames() as $name ) {
199 $module = $resourceLoader->getModule( $name );
200 $moduleTargets = $module->getTargets();
201 if ( !in_array( $target, $moduleTargets ) ) {
202 continue;
203 }
204
205 if ( $module->isRaw() ) {
206 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
207 // depending on them is illegal anyway and would only lead to them being reloaded
208 // causing any state to be lost (like jQuery plugins, mw.config etc.)
209 continue;
210 }
211
212 // Coerce module timestamp to UNIX timestamp.
213 // getModifiedTime() is supposed to return a UNIX timestamp, but custom implementations
214 // might forget. TODO: Maybe emit warning?
215 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
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 $mtime = max(
229 $moduleMtime,
230 wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) )
231 );
232
233 $registryData[$name] = array(
234 // Convert to numbers as wfTimestamp always returns a string, even for TS_UNIX
235 'version' => (int) $mtime,
236 'dependencies' => $module->getDependencies(),
237 'group' => $module->getGroup(),
238 'source' => $module->getSource(),
239 'loader' => $module->getLoaderScript(),
240 'skip' => $skipFunction,
241 );
242 }
243
244 self::compileUnresolvedDependencies( $registryData );
245
246 // Register sources
247 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
248
249 // Concatenate module loader scripts and figure out the different call
250 // signatures for mw.loader.register
251 $registrations = array();
252 foreach ( $registryData as $name => $data ) {
253 if ( $data['loader'] !== false ) {
254 $out .= ResourceLoader::makeCustomLoaderScript(
255 $name,
256 $data['version'],
257 $data['dependencies'],
258 $data['group'],
259 $data['source'],
260 $data['loader']
261 );
262 continue;
263 }
264
265 // Call mw.loader.register(name, timestamp, dependencies, group, source, skip)
266 $registrations[] = array(
267 $name,
268 $data['version'],
269 $data['dependencies'],
270 $data['group'],
271 // Swap default (local) for null
272 $data['source'] === 'local' ? null : $data['source'],
273 $data['skip']
274 );
275 }
276
277 // Register modules
278 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
279
280 return $out;
281 }
282
283 /* Methods */
284
285 /**
286 * @return bool
287 */
288 public function isRaw() {
289 return true;
290 }
291
292 /**
293 * Base modules required for the base environment of ResourceLoader
294 *
295 * @return array
296 */
297 public static function getStartupModules() {
298 return array( 'jquery', 'mediawiki' );
299 }
300
301 /**
302 * Get the load URL of the startup modules.
303 *
304 * This is a helper for getScript(), but can also be called standalone, such
305 * as when generating an AppCache manifest.
306 *
307 * @param ResourceLoaderContext $context
308 * @return string
309 */
310 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
311 $moduleNames = self::getStartupModules();
312
313 // Get the latest version
314 $loader = $context->getResourceLoader();
315 $version = 1;
316 foreach ( $moduleNames as $moduleName ) {
317 $version = max( $version,
318 $loader->getModule( $moduleName )->getModifiedTime( $context )
319 );
320 }
321
322 $query = array(
323 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
324 'only' => 'scripts',
325 'lang' => $context->getLanguage(),
326 'skin' => $context->getSkin(),
327 'debug' => $context->getDebug() ? 'true' : 'false',
328 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
329 );
330 // Ensure uniform query order
331 ksort( $query );
332 return wfAppendQuery( wfScript( 'load' ), $query );
333 }
334
335 /**
336 * @param ResourceLoaderContext $context
337 * @return string
338 */
339 public function getScript( ResourceLoaderContext $context ) {
340 global $IP;
341
342 $out = file_get_contents( "$IP/resources/src/startup.js" );
343 if ( $context->getOnly() === 'scripts' ) {
344
345 // Startup function
346 $configuration = $this->getConfigSettings( $context );
347 $registrations = $this->getModuleRegistrations( $context );
348 // Fix indentation
349 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
350 $mwMapJsCall = Xml::encodeJsCall(
351 'mw.Map',
352 array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) )
353 );
354 $mwConfigSetJsCall = Xml::encodeJsCall(
355 'mw.config.set',
356 array( $configuration ),
357 ResourceLoader::inDebugMode()
358 );
359
360 // Process the deferred inline script queue, and ensure that any
361 // functions enqueued after this point are executed immediately.
362 $mwqJs = (
363 'window._mwq = window._mwq || [];' .
364 'while ( _mwq.length ) _mwq.shift()( mw );' .
365 '_mwq.push = function ( f ) { f( mw ); };'
366 );
367
368 $out .= "var startUp = function () {\n" .
369 "\tmw.config = new " .
370 $mwMapJsCall . "\n" .
371 "\t$registrations\n" .
372 "\t" . $mwConfigSetJsCall . "\n" .
373 "\t" . $mwqJs . "\n" .
374 "};\n";
375
376 // Conditional script injection
377 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
378 $out .= "if ( isCompatible() ) {\n" .
379 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
380 "\n}";
381 }
382
383 return $out;
384 }
385
386 /**
387 * @return bool
388 */
389 public function supportsURLLoading() {
390 return false;
391 }
392
393 /**
394 * @param ResourceLoaderContext $context
395 * @return array|mixed
396 */
397 public function getModifiedTime( ResourceLoaderContext $context ) {
398 global $IP;
399
400 $hash = $context->getHash();
401 if ( isset( $this->modifiedTime[$hash] ) ) {
402 return $this->modifiedTime[$hash];
403 }
404
405 // Call preloadModuleInfo() on ALL modules as we're about
406 // to call getModifiedTime() on all of them
407 $loader = $context->getResourceLoader();
408 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
409
410 $time = max(
411 wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) ),
412 filemtime( "$IP/resources/src/startup.js" ),
413 $this->getHashMtime( $context )
414 );
415
416 // ATTENTION!: Because of the line below, this is not going to cause
417 // infinite recursion - think carefully before making changes to this
418 // code!
419 // Pre-populate modifiedTime with something because the loop over
420 // all modules below includes the startup module (this module).
421 $this->modifiedTime[$hash] = 1;
422
423 foreach ( $loader->getModuleNames() as $name ) {
424 $module = $loader->getModule( $name );
425 $time = max( $time, $module->getModifiedTime( $context ) );
426 }
427
428 $this->modifiedTime[$hash] = $time;
429 return $this->modifiedTime[$hash];
430 }
431
432 /**
433 * Hash of all dynamic data embedded in getScript().
434 *
435 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
436 *
437 * @param ResourceLoaderContext $context
438 * @return string Hash
439 */
440 public function getModifiedHash( ResourceLoaderContext $context ) {
441 $data = array(
442 'vars' => $this->getConfigSettings( $context ),
443 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
444 );
445
446 return md5( serialize( $data ) );
447 }
448
449 /**
450 * @return string
451 */
452 public function getGroup() {
453 return 'startup';
454 }
455 }