Merge "mediawiki.mixins: Move .box-sizing mixin from mediawiki.ui utilities"
[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, $wgContLang,
48 $wgVariantArticlePath, $wgActionPaths, $wgVersion,
49 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname,
50 $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath,
51 $wgCookiePrefix, $wgResourceLoaderMaxQueryLength,
52 $wgResourceLoaderStorageEnabled, $wgResourceLoaderStorageVersion,
53 $wgSearchType;
54
55 $mainPage = Title::newMainPage();
56
57 /**
58 * Namespace related preparation
59 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
60 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
61 */
62 $namespaceIds = $wgContLang->getNamespaceIds();
63 $caseSensitiveNamespaces = array();
64 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
65 $namespaceIds[$wgContLang->lc( $name )] = $index;
66 if ( !MWNamespace::isCapitalized( $index ) ) {
67 $caseSensitiveNamespaces[] = $index;
68 }
69 }
70
71 // Build list of variables
72 $vars = array(
73 'wgLoadScript' => $wgLoadScript,
74 'debug' => $context->getDebug(),
75 'skin' => $context->getSkin(),
76 'stylepath' => $wgStylePath,
77 'wgUrlProtocols' => wfUrlProtocols(),
78 'wgArticlePath' => $wgArticlePath,
79 'wgScriptPath' => $wgScriptPath,
80 'wgScriptExtension' => $wgScriptExtension,
81 'wgScript' => $wgScript,
82 'wgSearchType' => $wgSearchType,
83 'wgVariantArticlePath' => $wgVariantArticlePath,
84 // Force object to avoid "empty" associative array from
85 // becoming [] instead of {} in JS (bug 34604)
86 'wgActionPaths' => (object)$wgActionPaths,
87 'wgServer' => $wgServer,
88 'wgUserLanguage' => $context->getLanguage(),
89 'wgContentLanguage' => $wgContLang->getCode(),
90 'wgVersion' => $wgVersion,
91 'wgEnableAPI' => $wgEnableAPI,
92 'wgEnableWriteAPI' => $wgEnableWriteAPI,
93 'wgMainPageTitle' => $mainPage->getPrefixedText(),
94 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
95 'wgNamespaceIds' => $namespaceIds,
96 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
97 'wgSiteName' => $wgSitename,
98 'wgFileExtensions' => array_values( array_unique( $wgFileExtensions ) ),
99 'wgDBname' => $wgDBname,
100 // This sucks, it is only needed on Special:Upload, but I could
101 // not find a way to add vars only for a certain module
102 'wgFileCanRotate' => BitmapHandler::canRotate(),
103 'wgAvailableSkins' => Skin::getSkinNames(),
104 'wgExtensionAssetsPath' => $wgExtensionAssetsPath,
105 // MediaWiki sets cookies to have this prefix by default
106 'wgCookiePrefix' => $wgCookiePrefix,
107 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength,
108 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
109 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
110 'wgResourceLoaderStorageVersion' => $wgResourceLoaderStorageVersion,
111 'wgResourceLoaderStorageEnabled' => $wgResourceLoaderStorageEnabled,
112 );
113
114 wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$vars ) );
115
116 $this->configVars[$hash] = $vars;
117 return $this->configVars[$hash];
118 }
119
120 /**
121 * Recursively get all explicit and implicit dependencies for to the given module.
122 *
123 * @param array $registryData
124 * @param string $moduleName
125 * @return array
126 */
127 protected static function getImplicitDependencies( Array $registryData, $moduleName ) {
128 static $dependencyCache = array();
129
130 // The list of implicit dependencies won't be altered, so we can
131 // cache them without having to worry.
132 if ( !isset( $dependencyCache[$moduleName] ) ) {
133
134 if ( !isset( $registryData[$moduleName] ) ) {
135 // Dependencies may not exist
136 $dependencyCache[$moduleName] = array();
137 } else {
138 $data = $registryData[$moduleName];
139 $dependencyCache[$moduleName] = $data['dependencies'];
140
141 foreach ( $data['dependencies'] as $dependency ) {
142 // Recursively get the dependencies of the dependencies
143 $dependencyCache[$moduleName] = array_merge(
144 $dependencyCache[$moduleName],
145 self::getImplicitDependencies( $registryData, $dependency )
146 );
147 }
148 }
149 }
150
151 return $dependencyCache[$moduleName];
152 }
153
154 /**
155 * Optimize the dependency tree in $this->modules and return it.
156 *
157 * The optimization basically works like this:
158 * Given we have module A with the dependencies B and C
159 * and module B with the dependency C.
160 * Now we don't have to tell the client to explicitly fetch module
161 * C as that's already included in module B.
162 *
163 * This way we can reasonably reduce the amout of module registration
164 * data send to the client.
165 *
166 * @param Array &$registryData Modules keyed by name with properties:
167 * - string 'version'
168 * - array 'dependencies'
169 * - string|null 'group'
170 * - string 'source'
171 * - string|false 'loader'
172 */
173 public static function compileUnresolvedDependencies( Array &$registryData ) {
174 foreach ( $registryData as $name => &$data ) {
175 if ( $data['loader'] !== false ) {
176 continue;
177 }
178 $dependencies = $data['dependencies'];
179 foreach ( $data['dependencies'] as $dependency ) {
180 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
181 $dependencies = array_diff( $dependencies, $implicitDependencies );
182 }
183 // Rebuild keys
184 $data['dependencies'] = array_values( $dependencies );
185 }
186 }
187
188
189 /**
190 * Get registration code for all modules.
191 *
192 * @param ResourceLoaderContext $context
193 * @return string JavaScript code for registering all modules with the client loader
194 */
195 public static function getModuleRegistrations( ResourceLoaderContext $context ) {
196 global $wgCacheEpoch;
197 wfProfileIn( __METHOD__ );
198
199 $resourceLoader = $context->getResourceLoader();
200 $target = $context->getRequest()->getVal( 'target', 'desktop' );
201
202 $out = '';
203 $registryData = array();
204
205 // Get registry data
206 foreach ( $resourceLoader->getModuleNames() as $name ) {
207 $module = $resourceLoader->getModule( $name );
208 $moduleTargets = $module->getTargets();
209 if ( !in_array( $target, $moduleTargets ) ) {
210 continue;
211 }
212
213 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
214 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
215 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
216 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $wgCacheEpoch ) );
217
218 // FIXME: Convert to numbers, wfTimestamp always gives us stings, even for TS_UNIX
219
220 $registryData[ $name ] = array(
221 'version' => $mtime,
222 'dependencies' => $module->getDependencies(),
223 'group' => $module->getGroup(),
224 'source' => $module->getSource(),
225 'loader' => $module->getLoaderScript(),
226 );
227 }
228
229 self::compileUnresolvedDependencies( $registryData );
230
231 // Register sources
232 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
233
234 // Concatenate module loader scripts and figure out the different call
235 // signatures for mw.loader.register
236 $registrations = array();
237 foreach ( $registryData as $name => $data ) {
238 if ( $data['loader'] !== false ) {
239 $out .= ResourceLoader::makeCustomLoaderScript(
240 $name,
241 wfTimestamp( TS_ISO_8601_BASIC, $data['version'] ),
242 $data['dependencies'],
243 $data['group'],
244 $data['source'],
245 $data['loader']
246 );
247 continue;
248 }
249
250 if (
251 !count( $data['dependencies'] ) &&
252 $data['group'] === null &&
253 $data['source'] === 'local'
254 ) {
255 // Modules without dependencies, a group or a foreign source;
256 // call mw.loader.register(name, timestamp)
257 $registrations[] = array( $name, $data['version'] );
258 } elseif ( $data['group'] === null && $data['source'] === 'local' ) {
259 // Modules with dependencies but no group or foreign source;
260 // call mw.loader.register(name, timestamp, dependencies)
261 $registrations[] = array( $name, $data['version'], $data['dependencies'] );
262 } elseif ( $data['source'] === 'local' ) {
263 // Modules with a group but no foreign source;
264 // call mw.loader.register(name, timestamp, dependencies, group)
265 $registrations[] = array(
266 $name,
267 $data['version'],
268 $data['dependencies'],
269 $data['group']
270 );
271 } else {
272 // Modules with a foreign source;
273 // call mw.loader.register(name, timestamp, dependencies, group, source)
274 $registrations[] = array(
275 $name,
276 $data['version'],
277 $data['dependencies'],
278 $data['group'],
279 $data['source']
280 );
281 }
282 }
283
284 // Register modules
285 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
286
287 wfProfileOut( __METHOD__ );
288 return $out;
289 }
290
291 /* Methods */
292
293 /**
294 * @return bool
295 */
296 public function isRaw() {
297 return true;
298 }
299
300 /**
301 * Get the load URL of the startup modules.
302 *
303 * This is a helper for getScript(), but can also be called standalone, such
304 * as when generating an AppCache manifest.
305 *
306 * @param ResourceLoaderContext $context
307 * @return string
308 */
309 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
310 // The core modules:
311 $moduleNames = array( 'jquery', 'mediawiki' );
312 wfRunHooks( 'ResourceLoaderGetStartupModules', array( &$moduleNames ), '1.23' );
313
314 // Get the latest version
315 $loader = $context->getResourceLoader();
316 $version = 0;
317 foreach ( $moduleNames as $moduleName ) {
318 $version = max( $version,
319 $loader->getModule( $moduleName )->getModifiedTime( $context )
320 );
321 }
322
323 $query = array(
324 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
325 'only' => 'scripts',
326 'lang' => $context->getLanguage(),
327 'skin' => $context->getSkin(),
328 'debug' => $context->getDebug() ? 'true' : 'false',
329 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
330 );
331 // Ensure uniform query order
332 ksort( $query );
333 return wfAppendQuery( wfScript( 'load' ), $query );
334 }
335
336 /**
337 * @param ResourceLoaderContext $context
338 * @return string
339 */
340 public function getScript( ResourceLoaderContext $context ) {
341 global $IP, $wgLegacyJavaScriptGlobals;
342
343 $out = file_get_contents( "$IP/resources/src/startup.js" );
344 if ( $context->getOnly() === 'scripts' ) {
345
346 // Startup function
347 $configuration = $this->getConfig( $context );
348 $registrations = self::getModuleRegistrations( $context );
349 // Fix indentation
350 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
351 $out .= "var startUp = function () {\n" .
352 "\tmw.config = new " .
353 Xml::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
354 "\t$registrations\n" .
355 "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
356 "};\n";
357
358 // Conditional script injection
359 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
360 $out .= "if ( isCompatible() ) {\n" .
361 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
362 "}";
363 }
364
365 return $out;
366 }
367
368 /**
369 * @return bool
370 */
371 public function supportsURLLoading() {
372 return false;
373 }
374
375 /**
376 * @param ResourceLoaderContext $context
377 * @return array|mixed
378 */
379 public function getModifiedTime( ResourceLoaderContext $context ) {
380 global $IP, $wgCacheEpoch;
381
382 $hash = $context->getHash();
383 if ( isset( $this->modifiedTime[$hash] ) ) {
384 return $this->modifiedTime[$hash];
385 }
386
387 // Call preloadModuleInfo() on ALL modules as we're about
388 // to call getModifiedTime() on all of them
389 $loader = $context->getResourceLoader();
390 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
391
392 $time = max(
393 wfTimestamp( TS_UNIX, $wgCacheEpoch ),
394 filemtime( "$IP/resources/src/startup.js" ),
395 $this->getHashMtime( $context )
396 );
397
398 // ATTENTION!: Because of the line below, this is not going to cause
399 // infinite recursion - think carefully before making changes to this
400 // code!
401 // Pre-populate modifiedTime with something because the the loop over
402 // all modules below includes the the startup module (this module).
403 $this->modifiedTime[$hash] = 1;
404
405 foreach ( $loader->getModuleNames() as $name ) {
406 $module = $loader->getModule( $name );
407 $time = max( $time, $module->getModifiedTime( $context ) );
408 }
409
410 $this->modifiedTime[$hash] = $time;
411 return $this->modifiedTime[$hash];
412 }
413
414 /**
415 * Hash of all dynamic data embedded in getScript().
416 *
417 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
418 *
419 * @param ResourceLoaderContext $context
420 * @return string Hash
421 */
422 public function getModifiedHash( ResourceLoaderContext $context ) {
423 global $wgLegacyJavaScriptGlobals;
424
425 $data = array(
426 'vars' => $this->getConfig( $context ),
427 'wgLegacyJavaScriptGlobals' => $wgLegacyJavaScriptGlobals,
428 );
429
430 return md5( serialize( $data ) );
431 }
432
433 /**
434 * @return string
435 */
436 public function getGroup() {
437 return 'startup';
438 }
439 }