Merge "Make JobRunner flush DeferredUpdates after each job"
[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 // Cache for getConfigSettings() as it's called by multiple methods
28 protected $configVars = array();
29 protected $targets = array( 'desktop', 'mobile' );
30
31 /**
32 * @param ResourceLoaderContext $context
33 * @return array
34 */
35 protected function getConfigSettings( $context ) {
36
37 $hash = $context->getHash();
38 if ( isset( $this->configVars[$hash] ) ) {
39 return $this->configVars[$hash];
40 }
41
42 global $wgContLang;
43
44 $mainPage = Title::newMainPage();
45
46 /**
47 * Namespace related preparation
48 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
49 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
50 */
51 $namespaceIds = $wgContLang->getNamespaceIds();
52 $caseSensitiveNamespaces = array();
53 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
54 $namespaceIds[$wgContLang->lc( $name )] = $index;
55 if ( !MWNamespace::isCapitalized( $index ) ) {
56 $caseSensitiveNamespaces[] = $index;
57 }
58 }
59
60 $conf = $this->getConfig();
61 // Build list of variables
62 $vars = array(
63 'wgLoadScript' => wfScript( 'load' ),
64 'debug' => $context->getDebug(),
65 'skin' => $context->getSkin(),
66 'stylepath' => $conf->get( 'StylePath' ),
67 'wgUrlProtocols' => wfUrlProtocols(),
68 'wgArticlePath' => $conf->get( 'ArticlePath' ),
69 'wgScriptPath' => $conf->get( 'ScriptPath' ),
70 'wgScriptExtension' => $conf->get( 'ScriptExtension' ),
71 'wgScript' => wfScript(),
72 'wgSearchType' => $conf->get( 'SearchType' ),
73 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
74 // Force object to avoid "empty" associative array from
75 // becoming [] instead of {} in JS (bug 34604)
76 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
77 'wgServer' => $conf->get( 'Server' ),
78 'wgServerName' => $conf->get( 'ServerName' ),
79 'wgUserLanguage' => $context->getLanguage(),
80 'wgContentLanguage' => $wgContLang->getCode(),
81 'wgVersion' => $conf->get( 'Version' ),
82 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
83 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
84 'wgMainPageTitle' => $mainPage->getPrefixedText(),
85 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
86 'wgNamespaceIds' => $namespaceIds,
87 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
88 'wgSiteName' => $conf->get( 'Sitename' ),
89 'wgDBname' => $conf->get( 'DBname' ),
90 'wgAvailableSkins' => Skin::getSkinNames(),
91 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
92 // MediaWiki sets cookies to have this prefix by default
93 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
94 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
95 'wgCookiePath' => $conf->get( 'CookiePath' ),
96 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
97 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
98 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
99 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
100 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
101 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
102 );
103
104 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
105
106 $this->configVars[$hash] = $vars;
107 return $this->configVars[$hash];
108 }
109
110 /**
111 * Recursively get all explicit and implicit dependencies for to the given module.
112 *
113 * @param array $registryData
114 * @param string $moduleName
115 * @return array
116 */
117 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
118 static $dependencyCache = array();
119
120 // The list of implicit dependencies won't be altered, so we can
121 // cache them without having to worry.
122 if ( !isset( $dependencyCache[$moduleName] ) ) {
123
124 if ( !isset( $registryData[$moduleName] ) ) {
125 // Dependencies may not exist
126 $dependencyCache[$moduleName] = array();
127 } else {
128 $data = $registryData[$moduleName];
129 $dependencyCache[$moduleName] = $data['dependencies'];
130
131 foreach ( $data['dependencies'] as $dependency ) {
132 // Recursively get the dependencies of the dependencies
133 $dependencyCache[$moduleName] = array_merge(
134 $dependencyCache[$moduleName],
135 self::getImplicitDependencies( $registryData, $dependency )
136 );
137 }
138 }
139 }
140
141 return $dependencyCache[$moduleName];
142 }
143
144 /**
145 * Optimize the dependency tree in $this->modules.
146 *
147 * The optimization basically works like this:
148 * Given we have module A with the dependencies B and C
149 * and module B with the dependency C.
150 * Now we don't have to tell the client to explicitly fetch module
151 * C as that's already included in module B.
152 *
153 * This way we can reasonably reduce the amount of module registration
154 * data send to the client.
155 *
156 * @param array &$registryData Modules keyed by name with properties:
157 * - string 'version'
158 * - array 'dependencies'
159 * - string|null 'group'
160 * - string 'source'
161 * - string|false 'loader'
162 */
163 public static function compileUnresolvedDependencies( array &$registryData ) {
164 foreach ( $registryData as $name => &$data ) {
165 if ( $data['loader'] !== false ) {
166 continue;
167 }
168 $dependencies = $data['dependencies'];
169 foreach ( $data['dependencies'] as $dependency ) {
170 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
171 $dependencies = array_diff( $dependencies, $implicitDependencies );
172 }
173 // Rebuild keys
174 $data['dependencies'] = array_values( $dependencies );
175 }
176 }
177
178
179 /**
180 * Get registration code for all modules.
181 *
182 * @param ResourceLoaderContext $context
183 * @return string JavaScript code for registering all modules with the client loader
184 */
185 public function getModuleRegistrations( ResourceLoaderContext $context ) {
186
187 $resourceLoader = $context->getResourceLoader();
188 $target = $context->getRequest()->getVal( 'target', 'desktop' );
189
190 $out = '';
191 $registryData = array();
192
193 // Get registry data
194 foreach ( $resourceLoader->getModuleNames() as $name ) {
195 $module = $resourceLoader->getModule( $name );
196 $moduleTargets = $module->getTargets();
197 if ( !in_array( $target, $moduleTargets ) ) {
198 continue;
199 }
200
201 if ( $module->isRaw() ) {
202 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
203 // depending on them is illegal anyway and would only lead to them being reloaded
204 // causing any state to be lost (like jQuery plugins, mw.config etc.)
205 continue;
206 }
207
208 $versionHash = $module->getVersionHash( $context );
209 if ( strlen( $versionHash ) !== 8 ) {
210 // Module implementation either broken or deviated from ResourceLoader::makeHash
211 // Asserted by tests/phpunit/structure/ResourcesTest.
212 $versionHash = ResourceLoader::makeHash( $versionHash );
213 }
214
215 $skipFunction = $module->getSkipFunction();
216 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
217 $skipFunction = $resourceLoader->filter( 'minify-js',
218 $skipFunction,
219 // There will potentially be lots of these little string in the registrations
220 // manifest, we don't want to blow up the startup module with
221 // "/* cache key: ... */" all over it in non-debug mode.
222 /* cacheReport = */ false
223 );
224 }
225
226 $registryData[$name] = array(
227 'version' => $versionHash,
228 'dependencies' => $module->getDependencies(),
229 'group' => $module->getGroup(),
230 'source' => $module->getSource(),
231 'loader' => $module->getLoaderScript(),
232 'skip' => $skipFunction,
233 );
234 }
235
236 self::compileUnresolvedDependencies( $registryData );
237
238 // Register sources
239 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
240
241 // Concatenate module loader scripts and figure out the different call
242 // signatures for mw.loader.register
243 $registrations = array();
244 foreach ( $registryData as $name => $data ) {
245 if ( $data['loader'] !== false ) {
246 $out .= ResourceLoader::makeCustomLoaderScript(
247 $name,
248 $data['version'],
249 $data['dependencies'],
250 $data['group'],
251 $data['source'],
252 $data['loader']
253 );
254 continue;
255 }
256
257 // Call mw.loader.register(name, version, dependencies, group, source, skip)
258 $registrations[] = array(
259 $name,
260 $data['version'],
261 $data['dependencies'],
262 $data['group'],
263 // Swap default (local) for null
264 $data['source'] === 'local' ? null : $data['source'],
265 $data['skip']
266 );
267 }
268
269 // Register modules
270 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
271
272 return $out;
273 }
274
275 /**
276 * @return bool
277 */
278 public function isRaw() {
279 return true;
280 }
281
282 /**
283 * Base modules required for the base environment of ResourceLoader
284 *
285 * @return array
286 */
287 public static function getStartupModules() {
288 return array( 'jquery', 'mediawiki' );
289 }
290
291 /**
292 * Get the load URL of the startup modules.
293 *
294 * This is a helper for getScript(), but can also be called standalone, such
295 * as when generating an AppCache manifest.
296 *
297 * @param ResourceLoaderContext $context
298 * @return string
299 */
300 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
301 $rl = $context->getResourceLoader();
302 $moduleNames = self::getStartupModules();
303
304 $query = array(
305 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
306 'only' => 'scripts',
307 'lang' => $context->getLanguage(),
308 'skin' => $context->getSkin(),
309 'debug' => $context->getDebug() ? 'true' : 'false',
310 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
311 );
312 // Ensure uniform query order
313 ksort( $query );
314 return wfAppendQuery( wfScript( 'load' ), $query );
315 }
316
317 /**
318 * @param ResourceLoaderContext $context
319 * @return string
320 */
321 public function getScript( ResourceLoaderContext $context ) {
322 global $IP;
323
324 $out = file_get_contents( "$IP/resources/src/startup.js" );
325 if ( $context->getOnly() === 'scripts' ) {
326
327 // Startup function
328 $configuration = $this->getConfigSettings( $context );
329 $registrations = $this->getModuleRegistrations( $context );
330 // Fix indentation
331 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
332 $mwMapJsCall = Xml::encodeJsCall(
333 'mw.Map',
334 array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) )
335 );
336 $mwConfigSetJsCall = Xml::encodeJsCall(
337 'mw.config.set',
338 array( $configuration ),
339 ResourceLoader::inDebugMode()
340 );
341
342 $out .= "var startUp = function () {\n" .
343 "\tmw.config = new " .
344 $mwMapJsCall . "\n" .
345 "\t$registrations\n" .
346 "\t" . $mwConfigSetJsCall .
347 "};\n";
348
349 // Conditional script injection
350 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
351 $out .= "if ( isCompatible() ) {\n" .
352 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
353 "\n}";
354 }
355
356 return $out;
357 }
358
359 /**
360 * @return bool
361 */
362 public function supportsURLLoading() {
363 return false;
364 }
365
366 /**
367 * Get the definition summary for this module.
368 *
369 * @param ResourceLoaderContext $context
370 * @return array
371 */
372 public function getDefinitionSummary( ResourceLoaderContext $context ) {
373 global $IP;
374 $summary = parent::getDefinitionSummary( $context );
375 $summary[] = array(
376 // Detect changes to variables exposed in mw.config (T30899).
377 'vars' => $this->getConfigSettings( $context ),
378 // Changes how getScript() creates mw.Map for mw.config
379 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
380 // Detect changes to the module registrations
381 'moduleHashes' => $this->getAllModuleHashes( $context ),
382
383 'fileMtimes' => array(
384 filemtime( "$IP/resources/src/startup.js" ),
385 ),
386 );
387 return $summary;
388 }
389
390 /**
391 * Helper method for getDefinitionSummary().
392 *
393 * @param ResourceLoaderContext $context
394 * @return string SHA-1
395 */
396 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
397 $rl = $context->getResourceLoader();
398 // Preload for getCombinedVersion()
399 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
400
401 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
402 // Think carefully before making changes to this code!
403 // Pre-populate versionHash with something because the loop over all modules below includes
404 // the startup module (this module).
405 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
406 $this->versionHash[ $context->getHash() ] = null;
407
408 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
409 }
410
411 /**
412 * @return string
413 */
414 public function getGroup() {
415 return 'startup';
416 }
417 }