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