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