Deprecate ORMTable::getFieldPrefix
[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 getConfigSettings( $context ) {
40
41 $hash = $context->getHash();
42 if ( isset( $this->configVars[$hash] ) ) {
43 return $this->configVars[$hash];
44 }
45
46 global $wgContLang;
47
48 $mainPage = Title::newMainPage();
49
50 /**
51 * Namespace related preparation
52 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
53 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
54 */
55 $namespaceIds = $wgContLang->getNamespaceIds();
56 $caseSensitiveNamespaces = array();
57 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
58 $namespaceIds[$wgContLang->lc( $name )] = $index;
59 if ( !MWNamespace::isCapitalized( $index ) ) {
60 $caseSensitiveNamespaces[] = $index;
61 }
62 }
63
64 $conf = $this->getConfig();
65 // Build list of variables
66 $vars = array(
67 'wgLoadScript' => wfScript( 'load' ),
68 'debug' => $context->getDebug(),
69 'skin' => $context->getSkin(),
70 'stylepath' => $conf->get( 'StylePath' ),
71 'wgUrlProtocols' => wfUrlProtocols(),
72 'wgArticlePath' => $conf->get( 'ArticlePath' ),
73 'wgScriptPath' => $conf->get( 'ScriptPath' ),
74 'wgScriptExtension' => $conf->get( 'ScriptExtension' ),
75 'wgScript' => wfScript(),
76 'wgSearchType' => $conf->get( 'SearchType' ),
77 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
78 // Force object to avoid "empty" associative array from
79 // becoming [] instead of {} in JS (bug 34604)
80 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
81 'wgServer' => $conf->get( 'Server' ),
82 'wgServerName' => $conf->get( 'ServerName' ),
83 'wgUserLanguage' => $context->getLanguage(),
84 'wgContentLanguage' => $wgContLang->getCode(),
85 'wgVersion' => $conf->get( 'Version' ),
86 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
87 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
88 'wgMainPageTitle' => $mainPage->getPrefixedText(),
89 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
90 'wgNamespaceIds' => $namespaceIds,
91 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
92 'wgSiteName' => $conf->get( 'Sitename' ),
93 'wgFileExtensions' => array_values( array_unique( $conf->get( 'FileExtensions' ) ) ),
94 'wgDBname' => $conf->get( 'DBname' ),
95 // This sucks, it is only needed on Special:Upload, but I could
96 // not find a way to add vars only for a certain module
97 'wgFileCanRotate' => BitmapHandler::canRotate(),
98 'wgAvailableSkins' => Skin::getSkinNames(),
99 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
100 // MediaWiki sets cookies to have this prefix by default
101 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
102 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
103 'wgCookiePath' => $conf->get( 'CookiePath' ),
104 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
105 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
106 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
107 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
108 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
109 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
110 );
111
112 wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$vars ) );
113
114 $this->configVars[$hash] = $vars;
115 return $this->configVars[$hash];
116 }
117
118 /**
119 * Recursively get all explicit and implicit dependencies for to the given module.
120 *
121 * @param array $registryData
122 * @param string $moduleName
123 * @return array
124 */
125 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
126 static $dependencyCache = array();
127
128 // The list of implicit dependencies won't be altered, so we can
129 // cache them without having to worry.
130 if ( !isset( $dependencyCache[$moduleName] ) ) {
131
132 if ( !isset( $registryData[$moduleName] ) ) {
133 // Dependencies may not exist
134 $dependencyCache[$moduleName] = array();
135 } else {
136 $data = $registryData[$moduleName];
137 $dependencyCache[$moduleName] = $data['dependencies'];
138
139 foreach ( $data['dependencies'] as $dependency ) {
140 // Recursively get the dependencies of the dependencies
141 $dependencyCache[$moduleName] = array_merge(
142 $dependencyCache[$moduleName],
143 self::getImplicitDependencies( $registryData, $dependency )
144 );
145 }
146 }
147 }
148
149 return $dependencyCache[$moduleName];
150 }
151
152 /**
153 * Optimize the dependency tree in $this->modules and return it.
154 *
155 * The optimization basically works like this:
156 * Given we have module A with the dependencies B and C
157 * and module B with the dependency C.
158 * Now we don't have to tell the client to explicitly fetch module
159 * C as that's already included in module B.
160 *
161 * This way we can reasonably reduce the amout of module registration
162 * data send to the client.
163 *
164 * @param array &$registryData Modules keyed by name with properties:
165 * - string 'version'
166 * - array 'dependencies'
167 * - string|null 'group'
168 * - string 'source'
169 * - string|false 'loader'
170 */
171 public static function compileUnresolvedDependencies( array &$registryData ) {
172 foreach ( $registryData as $name => &$data ) {
173 if ( $data['loader'] !== false ) {
174 continue;
175 }
176 $dependencies = $data['dependencies'];
177 foreach ( $data['dependencies'] as $dependency ) {
178 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
179 $dependencies = array_diff( $dependencies, $implicitDependencies );
180 }
181 // Rebuild keys
182 $data['dependencies'] = array_values( $dependencies );
183 }
184 }
185
186
187 /**
188 * Get registration code for all modules.
189 *
190 * @param ResourceLoaderContext $context
191 * @return string JavaScript code for registering all modules with the client loader
192 */
193 public function getModuleRegistrations( ResourceLoaderContext $context ) {
194 wfProfileIn( __METHOD__ );
195
196 $resourceLoader = $context->getResourceLoader();
197 $target = $context->getRequest()->getVal( 'target', 'desktop' );
198
199 $out = '';
200 $registryData = array();
201
202 // Get registry data
203 foreach ( $resourceLoader->getModuleNames() as $name ) {
204 $module = $resourceLoader->getModule( $name );
205 $moduleTargets = $module->getTargets();
206 if ( !in_array( $target, $moduleTargets ) ) {
207 continue;
208 }
209
210 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
211 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
212 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
213 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) ) );
214
215 // FIXME: Convert to numbers, wfTimestamp always gives us stings, even for TS_UNIX
216
217 $skipFunction = $module->getSkipFunction();
218 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
219 $skipFunction = $resourceLoader->filter( 'minify-js',
220 $skipFunction,
221 // There will potentially be lots of these little string in the registrations
222 // manifest, we don't want to blow up the startup module with
223 // "/* cache key: ... */" all over it in non-debug mode.
224 /* cacheReport = */ false
225 );
226 }
227
228 $registryData[$name] = array(
229 'version' => $mtime,
230 'dependencies' => $module->getDependencies(),
231 'group' => $module->getGroup(),
232 'source' => $module->getSource(),
233 'loader' => $module->getLoaderScript(),
234 'skip' => $skipFunction,
235 );
236 }
237
238 self::compileUnresolvedDependencies( $registryData );
239
240 // Register sources
241 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
242
243 // Concatenate module loader scripts and figure out the different call
244 // signatures for mw.loader.register
245 $registrations = array();
246 foreach ( $registryData as $name => $data ) {
247 if ( $data['loader'] !== false ) {
248 $out .= ResourceLoader::makeCustomLoaderScript(
249 $name,
250 wfTimestamp( TS_ISO_8601_BASIC, $data['version'] ),
251 $data['dependencies'],
252 $data['group'],
253 $data['source'],
254 $data['loader']
255 );
256 continue;
257 }
258
259 if (
260 !count( $data['dependencies'] ) &&
261 $data['group'] === null &&
262 $data['source'] === 'local' &&
263 $data['skip'] === null
264 ) {
265 // Modules with no dependencies, group, foreign source or skip function;
266 // call mw.loader.register(name, timestamp)
267 $registrations[] = array( $name, $data['version'] );
268 } elseif (
269 $data['group'] === null &&
270 $data['source'] === 'local' &&
271 $data['skip'] === null
272 ) {
273 // Modules with dependencies but no group, foreign source or skip function;
274 // call mw.loader.register(name, timestamp, dependencies)
275 $registrations[] = array( $name, $data['version'], $data['dependencies'] );
276 } elseif (
277 $data['source'] === 'local' &&
278 $data['skip'] === null
279 ) {
280 // Modules with a group but no foreign source or skip function;
281 // call mw.loader.register(name, timestamp, dependencies, group)
282 $registrations[] = array(
283 $name,
284 $data['version'],
285 $data['dependencies'],
286 $data['group']
287 );
288 } elseif ( $data['skip'] === null ) {
289 // Modules with a foreign source but no skip function;
290 // call mw.loader.register(name, timestamp, dependencies, group, source)
291 $registrations[] = array(
292 $name,
293 $data['version'],
294 $data['dependencies'],
295 $data['group'],
296 $data['source']
297 );
298 } else {
299 // Modules with a skip function;
300 // call mw.loader.register(name, timestamp, dependencies, group, source, skip)
301 $registrations[] = array(
302 $name,
303 $data['version'],
304 $data['dependencies'],
305 $data['group'],
306 $data['source'],
307 $data['skip']
308 );
309 }
310 }
311
312 // Register modules
313 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
314
315 wfProfileOut( __METHOD__ );
316 return $out;
317 }
318
319 /* Methods */
320
321 /**
322 * @return bool
323 */
324 public function isRaw() {
325 return true;
326 }
327
328 /**
329 * Base modules required for the the base environment of ResourceLoader
330 *
331 * @return array
332 */
333 public static function getStartupModules() {
334 return array( 'jquery', 'mediawiki' );
335 }
336
337 /**
338 * Get the load URL of the startup modules.
339 *
340 * This is a helper for getScript(), but can also be called standalone, such
341 * as when generating an AppCache manifest.
342 *
343 * @param ResourceLoaderContext $context
344 * @return string
345 */
346 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
347 $moduleNames = self::getStartupModules();
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;
377
378 $out = file_get_contents( "$IP/resources/src/startup.js" );
379 if ( $context->getOnly() === 'scripts' ) {
380
381 // Startup function
382 $configuration = $this->getConfigSettings( $context );
383 $registrations = $this->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( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) ) ) . "\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;
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, $this->getConfig()->get( 'CacheEpoch' ) ),
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 $data = array(
459 'vars' => $this->getConfigSettings( $context ),
460 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
461 );
462
463 return md5( serialize( $data ) );
464 }
465
466 /**
467 * @return string
468 */
469 public function getGroup() {
470 return 'startup';
471 }
472 }