EditPage::newSectionSummary should return a value in all code paths
[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 $skipFunction = $module->getSkipFunction();
226 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
227 $skipFunction = $resourceLoader->filter( 'minify-js',
228 $skipFunction,
229 // There will potentially be lots of these little string in the registrations
230 // manifest, we don't want to blow up the startup module with
231 // "/* cache key: ... */" all over it in non-debug mode.
232 /* cacheReport = */ false
233 );
234 }
235
236 $registryData[$name] = array(
237 'version' => $mtime,
238 'dependencies' => $module->getDependencies(),
239 'group' => $module->getGroup(),
240 'source' => $module->getSource(),
241 'loader' => $module->getLoaderScript(),
242 'skip' => $skipFunction,
243 );
244 }
245
246 self::compileUnresolvedDependencies( $registryData );
247
248 // Register sources
249 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
250
251 // Concatenate module loader scripts and figure out the different call
252 // signatures for mw.loader.register
253 $registrations = array();
254 foreach ( $registryData as $name => $data ) {
255 if ( $data['loader'] !== false ) {
256 $out .= ResourceLoader::makeCustomLoaderScript(
257 $name,
258 wfTimestamp( TS_ISO_8601_BASIC, $data['version'] ),
259 $data['dependencies'],
260 $data['group'],
261 $data['source'],
262 $data['loader']
263 );
264 continue;
265 }
266
267 if (
268 !count( $data['dependencies'] ) &&
269 $data['group'] === null &&
270 $data['source'] === 'local' &&
271 $data['skip'] === null
272 ) {
273 // Modules with no dependencies, group, foreign source or skip function;
274 // call mw.loader.register(name, timestamp)
275 $registrations[] = array( $name, $data['version'] );
276 } elseif (
277 $data['group'] === null &&
278 $data['source'] === 'local' &&
279 $data['skip'] === null
280 ) {
281 // Modules with dependencies but no group, foreign source or skip function;
282 // call mw.loader.register(name, timestamp, dependencies)
283 $registrations[] = array( $name, $data['version'], $data['dependencies'] );
284 } elseif (
285 $data['source'] === 'local' &&
286 $data['skip'] === null
287 ) {
288 // Modules with a group but no foreign source or skip function;
289 // call mw.loader.register(name, timestamp, dependencies, group)
290 $registrations[] = array(
291 $name,
292 $data['version'],
293 $data['dependencies'],
294 $data['group']
295 );
296 } elseif ( $data['skip'] === null ) {
297 // Modules with a foreign source but no skip function;
298 // call mw.loader.register(name, timestamp, dependencies, group, source)
299 $registrations[] = array(
300 $name,
301 $data['version'],
302 $data['dependencies'],
303 $data['group'],
304 $data['source']
305 );
306 } else {
307 // Modules with a skip function;
308 // call mw.loader.register(name, timestamp, dependencies, group, source, skip)
309 $registrations[] = array(
310 $name,
311 $data['version'],
312 $data['dependencies'],
313 $data['group'],
314 $data['source'],
315 $data['skip']
316 );
317 }
318 }
319
320 // Register modules
321 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
322
323 wfProfileOut( __METHOD__ );
324 return $out;
325 }
326
327 /* Methods */
328
329 /**
330 * @return bool
331 */
332 public function isRaw() {
333 return true;
334 }
335
336 /**
337 * Get the load URL of the startup modules.
338 *
339 * This is a helper for getScript(), but can also be called standalone, such
340 * as when generating an AppCache manifest.
341 *
342 * @param ResourceLoaderContext $context
343 * @return string
344 */
345 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
346 // The core modules:
347 $moduleNames = array( 'jquery', 'mediawiki' );
348
349 // Get the latest version
350 $loader = $context->getResourceLoader();
351 $version = 0;
352 foreach ( $moduleNames as $moduleName ) {
353 $version = max( $version,
354 $loader->getModule( $moduleName )->getModifiedTime( $context )
355 );
356 }
357
358 $query = array(
359 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
360 'only' => 'scripts',
361 'lang' => $context->getLanguage(),
362 'skin' => $context->getSkin(),
363 'debug' => $context->getDebug() ? 'true' : 'false',
364 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
365 );
366 // Ensure uniform query order
367 ksort( $query );
368 return wfAppendQuery( wfScript( 'load' ), $query );
369 }
370
371 /**
372 * @param ResourceLoaderContext $context
373 * @return string
374 */
375 public function getScript( ResourceLoaderContext $context ) {
376 global $IP, $wgLegacyJavaScriptGlobals;
377
378 $out = file_get_contents( "$IP/resources/src/startup.js" );
379 if ( $context->getOnly() === 'scripts' ) {
380
381 // Startup function
382 $configuration = $this->getConfig( $context );
383 $registrations = self::getModuleRegistrations( $context );
384 // Fix indentation
385 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
386 $out .= "var startUp = function () {\n" .
387 "\tmw.config = new " .
388 Xml::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
389 "\t$registrations\n" .
390 "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
391 "};\n";
392
393 // Conditional script injection
394 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
395 $out .= "if ( isCompatible() ) {\n" .
396 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
397 "}";
398 }
399
400 return $out;
401 }
402
403 /**
404 * @return bool
405 */
406 public function supportsURLLoading() {
407 return false;
408 }
409
410 /**
411 * @param ResourceLoaderContext $context
412 * @return array|mixed
413 */
414 public function getModifiedTime( ResourceLoaderContext $context ) {
415 global $IP, $wgCacheEpoch;
416
417 $hash = $context->getHash();
418 if ( isset( $this->modifiedTime[$hash] ) ) {
419 return $this->modifiedTime[$hash];
420 }
421
422 // Call preloadModuleInfo() on ALL modules as we're about
423 // to call getModifiedTime() on all of them
424 $loader = $context->getResourceLoader();
425 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
426
427 $time = max(
428 wfTimestamp( TS_UNIX, $wgCacheEpoch ),
429 filemtime( "$IP/resources/src/startup.js" ),
430 $this->getHashMtime( $context )
431 );
432
433 // ATTENTION!: Because of the line below, this is not going to cause
434 // infinite recursion - think carefully before making changes to this
435 // code!
436 // Pre-populate modifiedTime with something because the the loop over
437 // all modules below includes the the startup module (this module).
438 $this->modifiedTime[$hash] = 1;
439
440 foreach ( $loader->getModuleNames() as $name ) {
441 $module = $loader->getModule( $name );
442 $time = max( $time, $module->getModifiedTime( $context ) );
443 }
444
445 $this->modifiedTime[$hash] = $time;
446 return $this->modifiedTime[$hash];
447 }
448
449 /**
450 * Hash of all dynamic data embedded in getScript().
451 *
452 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
453 *
454 * @param ResourceLoaderContext $context
455 * @return string Hash
456 */
457 public function getModifiedHash( ResourceLoaderContext $context ) {
458 global $wgLegacyJavaScriptGlobals;
459
460 $data = array(
461 'vars' => $this->getConfig( $context ),
462 'wgLegacyJavaScriptGlobals' => $wgLegacyJavaScriptGlobals,
463 );
464
465 return md5( serialize( $data ) );
466 }
467
468 /**
469 * @return string
470 */
471 public function getGroup() {
472 return 'startup';
473 }
474 }