Merge "Forward port of https://www.mediawiki.org/wiki/Special:Code/MediaWiki/105964"
[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
31 /* Protected Methods */
32
33 /**
34 * @param $context ResourceLoaderContext
35 * @return array
36 */
37 protected function getConfig( $context ) {
38 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension,
39 $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang,
40 $wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgVersion,
41 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest,
42 $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath,
43 $wgCookiePrefix, $wgResourceLoaderMaxQueryLength;
44
45 $mainPage = Title::newMainPage();
46
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.
51 */
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;
58 }
59 }
60
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 'wgDefaultDateFormat' => $wgContLang->getDefaultDateFormat(),
83 'wgMonthNames' => $wgContLang->getMonthNamesArray(),
84 'wgMonthNamesShort' => $wgContLang->getMonthAbbreviationsArray(),
85 'wgMainPageTitle' => $mainPage->getPrefixedText(),
86 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
87 'wgNamespaceIds' => $namespaceIds,
88 'wgSiteName' => $wgSitename,
89 'wgFileExtensions' => array_values( $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 );
101 if ( $wgUseAjax && $wgEnableMWSuggest ) {
102 $vars['wgMWSuggestTemplate'] = SearchEngine::getMWSuggestTemplate();
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
124 // Register sources
125 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
126
127 // Register modules
128 foreach ( $resourceLoader->getModuleNames() as $name ) {
129 $module = $resourceLoader->getModule( $name );
130 $deps = $module->getDependencies();
131 $group = $module->getGroup();
132 $source = $module->getSource();
133 // Support module loader scripts
134 $loader = $module->getLoaderScript();
135 if ( $loader !== false ) {
136 $version = wfTimestamp( TS_ISO_8601_BASIC,
137 $module->getModifiedTime( $context ) );
138 $out .= ResourceLoader::makeCustomLoaderScript( $name, $version, $deps, $group, $source, $loader );
139 }
140 // Automatically register module
141 else {
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 );
150 }
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 );
155 }
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 );
160 }
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 );
165 }
166 }
167 }
168 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
169
170 wfProfileOut( __METHOD__ );
171 return $out;
172 }
173
174 /* Methods */
175
176 /**
177 * @param $context ResourceLoaderContext
178 * @return string
179 */
180 public function getScript( ResourceLoaderContext $context ) {
181 global $IP, $wgLoadScript, $wgLegacyJavaScriptGlobals;
182
183 $out = file_get_contents( "$IP/resources/startup.js" );
184 if ( $context->getOnly() === 'scripts' ) {
185
186 // The core modules:
187 $moduleNames = array( 'jquery', 'mediawiki' );
188 wfRunHooks( 'ResourceLoaderGetStartupModules', array( &$moduleNames ) );
189
190 // Get the latest version
191 $loader = $context->getResourceLoader();
192 $version = 0;
193 foreach ( $moduleNames as $moduleName ) {
194 $version = max( $version,
195 $loader->getModule( $moduleName )->getModifiedTime( $context )
196 );
197 }
198 // Build load query for StartupModules
199 $query = array(
200 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
201 'only' => 'scripts',
202 'lang' => $context->getLanguage(),
203 'skin' => $context->getSkin(),
204 'debug' => $context->getDebug() ? 'true' : 'false',
205 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
206 );
207 // Ensure uniform query order
208 ksort( $query );
209
210 // Startup function
211 $configuration = $this->getConfig( $context );
212 $registrations = self::getModuleRegistrations( $context );
213 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) ); // fix indentation
214 $out .= "var startUp = function() {\n" .
215 "\tmw.config = new " . Xml::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
216 "\t$registrations\n" .
217 "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
218 "};\n";
219
220 // Conditional script injection
221 $scriptTag = Html::linkedScript( $wgLoadScript . '?' . wfArrayToCGI( $query ) );
222 $out .= "if ( isCompatible() ) {\n" .
223 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
224 "}\n" .
225 "delete isCompatible;";
226 }
227
228 return $out;
229 }
230
231 /**
232 * @return bool
233 */
234 public function supportsURLLoading() {
235 return false;
236 }
237
238 /**
239 * @param $context ResourceLoaderContext
240 * @return array|mixed
241 */
242 public function getModifiedTime( ResourceLoaderContext $context ) {
243 global $IP, $wgCacheEpoch;
244
245 $hash = $context->getHash();
246 if ( isset( $this->modifiedTime[$hash] ) ) {
247 return $this->modifiedTime[$hash];
248 }
249
250 // Call preloadModuleInfo() on ALL modules as we're about
251 // to call getModifiedTime() on all of them
252 $loader = $context->getResourceLoader();
253 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
254
255 $this->modifiedTime[$hash] = filemtime( "$IP/resources/startup.js" );
256 // ATTENTION!: Because of the line above, this is not going to cause
257 // infinite recursion - think carefully before making changes to this
258 // code!
259 $time = wfTimestamp( TS_UNIX, $wgCacheEpoch );
260 foreach ( $loader->getModuleNames() as $name ) {
261 $module = $loader->getModule( $name );
262 $time = max( $time, $module->getModifiedTime( $context ) );
263 }
264 return $this->modifiedTime[$hash] = $time;
265 }
266
267 /* Methods */
268
269 /**
270 * @return string
271 */
272 public function getGroup() {
273 return 'startup';
274 }
275 }