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