resourceloader: Add method to get the startup modules load url
[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 $targets = array( 'desktop', 'mobile' );
31
32 /* Protected Methods */
33
34 /**
35 * @param $context ResourceLoaderContext
36 * @return array
37 */
38 protected function getConfig( $context ) {
39 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension,
40 $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang,
41 $wgVariantArticlePath, $wgActionPaths, $wgVersion,
42 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname,
43 $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath,
44 $wgCookiePrefix, $wgResourceLoaderMaxQueryLength,
45 $wgResourceLoaderStorageEnabled, $wgResourceLoaderStorageVersion;
46
47 $mainPage = Title::newMainPage();
48
49 /**
50 * Namespace related preparation
51 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
52 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
53 */
54 $namespaceIds = $wgContLang->getNamespaceIds();
55 $caseSensitiveNamespaces = array();
56 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
57 $namespaceIds[$wgContLang->lc( $name )] = $index;
58 if ( !MWNamespace::isCapitalized( $index ) ) {
59 $caseSensitiveNamespaces[] = $index;
60 }
61 }
62
63 // Build list of variables
64 $vars = array(
65 'wgLoadScript' => $wgLoadScript,
66 'debug' => $context->getDebug(),
67 'skin' => $context->getSkin(),
68 'stylepath' => $wgStylePath,
69 'wgUrlProtocols' => wfUrlProtocols(),
70 'wgArticlePath' => $wgArticlePath,
71 'wgScriptPath' => $wgScriptPath,
72 'wgScriptExtension' => $wgScriptExtension,
73 'wgScript' => $wgScript,
74 'wgVariantArticlePath' => $wgVariantArticlePath,
75 // Force object to avoid "empty" associative array from
76 // becoming [] instead of {} in JS (bug 34604)
77 'wgActionPaths' => (object)$wgActionPaths,
78 'wgServer' => $wgServer,
79 'wgUserLanguage' => $context->getLanguage(),
80 'wgContentLanguage' => $wgContLang->getCode(),
81 'wgVersion' => $wgVersion,
82 'wgEnableAPI' => $wgEnableAPI,
83 'wgEnableWriteAPI' => $wgEnableWriteAPI,
84 'wgMainPageTitle' => $mainPage->getPrefixedText(),
85 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
86 'wgNamespaceIds' => $namespaceIds,
87 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
88 'wgSiteName' => $wgSitename,
89 'wgFileExtensions' => array_values( array_unique( $wgFileExtensions ) ),
90 'wgDBname' => $wgDBname,
91 // This sucks, it is only needed on Special:Upload, but I could
92 // not find a way to add vars only for a certain module
93 'wgFileCanRotate' => BitmapHandler::canRotate(),
94 'wgAvailableSkins' => Skin::getSkinNames(),
95 'wgExtensionAssetsPath' => $wgExtensionAssetsPath,
96 // MediaWiki sets cookies to have this prefix by default
97 'wgCookiePrefix' => $wgCookiePrefix,
98 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength,
99 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
100 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
101 'wgResourceLoaderStorageVersion' => $wgResourceLoaderStorageVersion,
102 'wgResourceLoaderStorageEnabled' => $wgResourceLoaderStorageEnabled,
103 );
104
105 wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$vars ) );
106
107 return $vars;
108 }
109
110 /**
111 * Gets registration code for all modules
112 *
113 * @param $context ResourceLoaderContext object
114 * @return String: JavaScript code for registering all modules with the client loader
115 */
116 public static function getModuleRegistrations( ResourceLoaderContext $context ) {
117 global $wgCacheEpoch;
118 wfProfileIn( __METHOD__ );
119
120 $out = '';
121 $registrations = array();
122 $resourceLoader = $context->getResourceLoader();
123 $target = $context->getRequest()->getVal( 'target', 'desktop' );
124
125 // Register sources
126 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
127
128 // Register modules
129 foreach ( $resourceLoader->getModuleNames() as $name ) {
130 $module = $resourceLoader->getModule( $name );
131 $moduleTargets = $module->getTargets();
132 if ( !in_array( $target, $moduleTargets ) ) {
133 continue;
134 }
135 $deps = $module->getDependencies();
136 $group = $module->getGroup();
137 $source = $module->getSource();
138 // Support module loader scripts
139 $loader = $module->getLoaderScript();
140 if ( $loader !== false ) {
141 $version = wfTimestamp( TS_ISO_8601_BASIC,
142 $module->getModifiedTime( $context ) );
143 $out .= ResourceLoader::makeCustomLoaderScript( $name, $version, $deps, $group, $source, $loader );
144 continue;
145 }
146
147 // Automatically register module
148 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
149 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
150 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
151 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $wgCacheEpoch ) );
152 // Modules without dependencies, a group or a foreign source pass two arguments (name, timestamp) to
153 // mw.loader.register()
154 if ( !count( $deps ) && $group === null && $source === 'local' ) {
155 $registrations[] = array( $name, $mtime );
156 }
157 // Modules with dependencies but no group or foreign source pass three arguments
158 // (name, timestamp, dependencies) to mw.loader.register()
159 elseif ( $group === null && $source === 'local' ) {
160 $registrations[] = array( $name, $mtime, $deps );
161 }
162 // Modules with a group but no foreign source pass four arguments (name, timestamp, dependencies, group)
163 // to mw.loader.register()
164 elseif ( $source === 'local' ) {
165 $registrations[] = array( $name, $mtime, $deps, $group );
166 }
167 // Modules with a foreign source pass five arguments (name, timestamp, dependencies, group, source)
168 // to mw.loader.register()
169 else {
170 $registrations[] = array( $name, $mtime, $deps, $group, $source );
171 }
172 }
173 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
174
175 wfProfileOut( __METHOD__ );
176 return $out;
177 }
178
179 /* Methods */
180
181 /**
182 * @return bool
183 */
184 public function isRaw() {
185 return true;
186 }
187
188 /**
189 * Get the load URL of the startup modules.
190 *
191 * This is a helper for getScript(), but can also be called standalone, such
192 * as when generating an AppCache manifest.
193 *
194 * @param $context ResourceLoaderContext
195 * @return string
196 */
197 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
198 // The core modules:
199 $moduleNames = array( 'jquery', 'mediawiki' );
200 wfRunHooks( 'ResourceLoaderGetStartupModules', array( &$moduleNames ) );
201
202 // Get the latest version
203 $loader = $context->getResourceLoader();
204 $version = 0;
205 foreach ( $moduleNames as $moduleName ) {
206 $version = max( $version,
207 $loader->getModule( $moduleName )->getModifiedTime( $context )
208 );
209 }
210
211 $query = array(
212 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
213 'only' => 'scripts',
214 'lang' => $context->getLanguage(),
215 'skin' => $context->getSkin(),
216 'debug' => $context->getDebug() ? 'true' : 'false',
217 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
218 );
219 // Ensure uniform query order
220 ksort( $query );
221 return wfAppendQuery( wfScript( 'load' ), $query );
222 }
223
224
225 /**
226 * @param $context ResourceLoaderContext
227 * @return string
228 */
229 public function getScript( ResourceLoaderContext $context ) {
230 global $IP, $wgLegacyJavaScriptGlobals;
231
232 $out = file_get_contents( "$IP/resources/startup.js" );
233 if ( $context->getOnly() === 'scripts' ) {
234
235 // Startup function
236 $configuration = $this->getConfig( $context );
237 $registrations = self::getModuleRegistrations( $context );
238 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) ); // fix indentation
239 $out .= "var startUp = function() {\n" .
240 "\tmw.config = new " . Xml::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
241 "\t$registrations\n" .
242 "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
243 "};\n";
244
245 // Conditional script injection
246 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
247 $out .= "if ( isCompatible() ) {\n" .
248 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
249 "}\n" .
250 "delete isCompatible;";
251 }
252
253 return $out;
254 }
255
256 /**
257 * @return bool
258 */
259 public function supportsURLLoading() {
260 return false;
261 }
262
263 /**
264 * @param $context ResourceLoaderContext
265 * @return array|mixed
266 */
267 public function getModifiedTime( ResourceLoaderContext $context ) {
268 global $IP, $wgCacheEpoch;
269
270 $hash = $context->getHash();
271 if ( isset( $this->modifiedTime[$hash] ) ) {
272 return $this->modifiedTime[$hash];
273 }
274
275 // Call preloadModuleInfo() on ALL modules as we're about
276 // to call getModifiedTime() on all of them
277 $loader = $context->getResourceLoader();
278 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
279
280 $this->modifiedTime[$hash] = filemtime( "$IP/resources/startup.js" );
281 // ATTENTION!: Because of the line above, this is not going to cause
282 // infinite recursion - think carefully before making changes to this
283 // code!
284 $time = wfTimestamp( TS_UNIX, $wgCacheEpoch );
285 foreach ( $loader->getModuleNames() as $name ) {
286 $module = $loader->getModule( $name );
287 $time = max( $time, $module->getModifiedTime( $context ) );
288 }
289 $this->modifiedTime[$hash] = $time;
290 return $this->modifiedTime[$hash];
291 }
292
293 /* Methods */
294
295 /**
296 * @return string
297 */
298 public function getGroup() {
299 return 'startup';
300 }
301 }