Merge "Combine JavaScript and JSON encoding logic"
[mediawiki.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
blob32cf6b2673dece833d659bb7e1446734be4943a8
1 <?php
2 /**
3 * Module for resource loader initialization.
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.
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.
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
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
27 /* Protected Members */
29 protected $modifiedTime = array();
31 /* Protected Methods */
33 /**
34 * @param $context ResourceLoaderContext
35 * @return array
37 protected function getConfig( $context ) {
38 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension,
39 $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang,
40 $wgVariantArticlePath, $wgActionPaths, $wgVersion,
41 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname,
42 $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath,
43 $wgCookiePrefix, $wgResourceLoaderMaxQueryLength;
45 $mainPage = Title::newMainPage();
47 /**
48 * Namespace related preparation
49 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
50 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
52 $namespaceIds = $wgContLang->getNamespaceIds();
53 $caseSensitiveNamespaces = array();
54 foreach( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
55 $namespaceIds[$wgContLang->lc( $name )] = $index;
56 if ( !MWNamespace::isCapitalized( $index ) ) {
57 $caseSensitiveNamespaces[] = $index;
61 // Build list of variables
62 $vars = array(
63 'wgLoadScript' => $wgLoadScript,
64 'debug' => $context->getDebug(),
65 'skin' => $context->getSkin(),
66 'stylepath' => $wgStylePath,
67 'wgUrlProtocols' => wfUrlProtocols(),
68 'wgArticlePath' => $wgArticlePath,
69 'wgScriptPath' => $wgScriptPath,
70 'wgScriptExtension' => $wgScriptExtension,
71 'wgScript' => $wgScript,
72 'wgVariantArticlePath' => $wgVariantArticlePath,
73 // Force object to avoid "empty" associative array from
74 // becoming [] instead of {} in JS (bug 34604)
75 'wgActionPaths' => (object)$wgActionPaths,
76 'wgServer' => $wgServer,
77 'wgUserLanguage' => $context->getLanguage(),
78 'wgContentLanguage' => $wgContLang->getCode(),
79 'wgVersion' => $wgVersion,
80 'wgEnableAPI' => $wgEnableAPI,
81 'wgEnableWriteAPI' => $wgEnableWriteAPI,
82 'wgMainPageTitle' => $mainPage->getPrefixedText(),
83 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
84 'wgNamespaceIds' => $namespaceIds,
85 'wgSiteName' => $wgSitename,
86 'wgFileExtensions' => array_values( $wgFileExtensions ),
87 'wgDBname' => $wgDBname,
88 // This sucks, it is only needed on Special:Upload, but I could
89 // not find a way to add vars only for a certain module
90 'wgFileCanRotate' => BitmapHandler::canRotate(),
91 'wgAvailableSkins' => Skin::getSkinNames(),
92 'wgExtensionAssetsPath' => $wgExtensionAssetsPath,
93 // MediaWiki sets cookies to have this prefix by default
94 'wgCookiePrefix' => $wgCookiePrefix,
95 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength,
96 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
99 wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$vars ) );
101 return $vars;
105 * Gets registration code for all modules
107 * @param $context ResourceLoaderContext object
108 * @return String: JavaScript code for registering all modules with the client loader
110 public static function getModuleRegistrations( ResourceLoaderContext $context ) {
111 global $wgCacheEpoch;
112 wfProfileIn( __METHOD__ );
114 $out = '';
115 $registrations = array();
116 $resourceLoader = $context->getResourceLoader();
117 $target = $context->getRequest()->getVal( 'target', 'desktop' );
119 // Register sources
120 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
122 // Register modules
123 foreach ( $resourceLoader->getModuleNames() as $name ) {
124 $module = $resourceLoader->getModule( $name );
125 $moduleTargets = $module->getTargets();
126 if ( !in_array( $target, $moduleTargets ) ) {
127 continue;
129 $deps = $module->getDependencies();
130 $group = $module->getGroup();
131 $source = $module->getSource();
132 // Support module loader scripts
133 $loader = $module->getLoaderScript();
134 if ( $loader !== false ) {
135 $version = wfTimestamp( TS_ISO_8601_BASIC,
136 $module->getModifiedTime( $context ) );
137 $out .= ResourceLoader::makeCustomLoaderScript( $name, $version, $deps, $group, $source, $loader );
138 continue;
141 // Automatically register module
142 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
143 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
144 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
145 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $wgCacheEpoch ) );
146 // Modules without dependencies, a group or a foreign source pass two arguments (name, timestamp) to
147 // mw.loader.register()
148 if ( !count( $deps ) && $group === null && $source === 'local' ) {
149 $registrations[] = array( $name, $mtime );
151 // Modules with dependencies but no group or foreign source pass three arguments
152 // (name, timestamp, dependencies) to mw.loader.register()
153 elseif ( $group === null && $source === 'local' ) {
154 $registrations[] = array( $name, $mtime, $deps );
156 // Modules with a group but no foreign source pass four arguments (name, timestamp, dependencies, group)
157 // to mw.loader.register()
158 elseif ( $source === 'local' ) {
159 $registrations[] = array( $name, $mtime, $deps, $group );
161 // Modules with a foreign source pass five arguments (name, timestamp, dependencies, group, source)
162 // to mw.loader.register()
163 else {
164 $registrations[] = array( $name, $mtime, $deps, $group, $source );
167 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
169 wfProfileOut( __METHOD__ );
170 return $out;
173 /* Methods */
176 * @return bool
178 public function isRaw() {
179 return true;
183 * @param $context ResourceLoaderContext
184 * @return string
186 public function getScript( ResourceLoaderContext $context ) {
187 global $IP, $wgLoadScript, $wgLegacyJavaScriptGlobals;
189 $out = file_get_contents( "$IP/resources/startup.js" );
190 if ( $context->getOnly() === 'scripts' ) {
192 // The core modules:
193 $moduleNames = array( 'jquery', 'mediawiki' );
194 wfRunHooks( 'ResourceLoaderGetStartupModules', array( &$moduleNames ) );
196 // Get the latest version
197 $loader = $context->getResourceLoader();
198 $version = 0;
199 foreach ( $moduleNames as $moduleName ) {
200 $version = max( $version,
201 $loader->getModule( $moduleName )->getModifiedTime( $context )
204 // Build load query for StartupModules
205 $query = array(
206 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
207 'only' => 'scripts',
208 'lang' => $context->getLanguage(),
209 'skin' => $context->getSkin(),
210 'debug' => $context->getDebug() ? 'true' : 'false',
211 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
213 // Ensure uniform query order
214 ksort( $query );
216 // Startup function
217 $configuration = $this->getConfig( $context );
218 $registrations = self::getModuleRegistrations( $context );
219 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) ); // fix indentation
220 $out .= "var startUp = function() {\n" .
221 "\tmw.config = new " . Xml::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
222 "\t$registrations\n" .
223 "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
224 "};\n";
226 // Conditional script injection
227 $scriptTag = Html::linkedScript( $wgLoadScript . '?' . wfArrayToCgi( $query ) );
228 $out .= "if ( isCompatible() ) {\n" .
229 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
230 "}\n" .
231 "delete isCompatible;";
234 return $out;
238 * @return bool
240 public function supportsURLLoading() {
241 return false;
245 * @param $context ResourceLoaderContext
246 * @return array|mixed
248 public function getModifiedTime( ResourceLoaderContext $context ) {
249 global $IP, $wgCacheEpoch;
251 $hash = $context->getHash();
252 if ( isset( $this->modifiedTime[$hash] ) ) {
253 return $this->modifiedTime[$hash];
256 // Call preloadModuleInfo() on ALL modules as we're about
257 // to call getModifiedTime() on all of them
258 $loader = $context->getResourceLoader();
259 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
261 $this->modifiedTime[$hash] = filemtime( "$IP/resources/startup.js" );
262 // ATTENTION!: Because of the line above, this is not going to cause
263 // infinite recursion - think carefully before making changes to this
264 // code!
265 $time = wfTimestamp( TS_UNIX, $wgCacheEpoch );
266 foreach ( $loader->getModuleNames() as $name ) {
267 $module = $loader->getModule( $name );
268 $time = max( $time, $module->getModifiedTime( $context ) );
270 return $this->modifiedTime[$hash] = $time;
273 /* Methods */
276 * @return string
278 public function getGroup() {
279 return 'startup';