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