Merge "ResourceLoaderStartUpModule: Use hashMtime to detect config changes"
[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 $context ResourceLoaderContext
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 * Gets registration code for all modules
122 *
123 * @param $context ResourceLoaderContext 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 $out = '';
131 $registrations = array();
132 $resourceLoader = $context->getResourceLoader();
133 $target = $context->getRequest()->getVal( 'target', 'desktop' );
134
135 // Register sources
136 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
137
138 // Register modules
139 foreach ( $resourceLoader->getModuleNames() as $name ) {
140 $module = $resourceLoader->getModule( $name );
141 $moduleTargets = $module->getTargets();
142 if ( !in_array( $target, $moduleTargets ) ) {
143 continue;
144 }
145 $deps = $module->getDependencies();
146 $group = $module->getGroup();
147 $source = $module->getSource();
148 // Support module loader scripts
149 $loader = $module->getLoaderScript();
150 if ( $loader !== false ) {
151 $version = wfTimestamp( TS_ISO_8601_BASIC,
152 $module->getModifiedTime( $context ) );
153 $out .= ResourceLoader::makeCustomLoaderScript( $name, $version, $deps, $group, $source, $loader );
154 continue;
155 }
156
157 // Automatically register module
158 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
159 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
160 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
161 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $wgCacheEpoch ) );
162
163 if ( !count( $deps ) && $group === null && $source === 'local' ) {
164 // Modules without dependencies, a group or a foreign source pass two arguments (name, timestamp) to
165 // mw.loader.register()
166 $registrations[] = array( $name, $mtime );
167 } elseif ( $group === null && $source === 'local' ) {
168 // Modules with dependencies but no group or foreign source pass three arguments
169 // (name, timestamp, dependencies) to mw.loader.register()
170 $registrations[] = array( $name, $mtime, $deps );
171 } elseif ( $source === 'local' ) {
172 // Modules with a group but no foreign source pass four arguments (name, timestamp, dependencies, group)
173 // to mw.loader.register()
174 $registrations[] = array( $name, $mtime, $deps, $group );
175 } else {
176 // Modules with a foreign source pass five arguments (name, timestamp, dependencies, group, source)
177 // to mw.loader.register()
178 $registrations[] = array( $name, $mtime, $deps, $group, $source );
179 }
180 }
181 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
182
183 wfProfileOut( __METHOD__ );
184 return $out;
185 }
186
187 /* Methods */
188
189 /**
190 * @return bool
191 */
192 public function isRaw() {
193 return true;
194 }
195
196 /**
197 * Get the load URL of the startup modules.
198 *
199 * This is a helper for getScript(), but can also be called standalone, such
200 * as when generating an AppCache manifest.
201 *
202 * @param $context ResourceLoaderContext
203 * @return string
204 */
205 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
206 // The core modules:
207 $moduleNames = array( 'jquery', 'mediawiki' );
208 wfRunHooks( 'ResourceLoaderGetStartupModules', array( &$moduleNames ) );
209
210 // Get the latest version
211 $loader = $context->getResourceLoader();
212 $version = 0;
213 foreach ( $moduleNames as $moduleName ) {
214 $version = max( $version,
215 $loader->getModule( $moduleName )->getModifiedTime( $context )
216 );
217 }
218
219 $query = array(
220 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
221 'only' => 'scripts',
222 'lang' => $context->getLanguage(),
223 'skin' => $context->getSkin(),
224 'debug' => $context->getDebug() ? 'true' : 'false',
225 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
226 );
227 // Ensure uniform query order
228 ksort( $query );
229 return wfAppendQuery( wfScript( 'load' ), $query );
230 }
231
232 /**
233 * @param $context ResourceLoaderContext
234 * @return string
235 */
236 public function getScript( ResourceLoaderContext $context ) {
237 global $IP, $wgLegacyJavaScriptGlobals;
238
239 $out = file_get_contents( "$IP/resources/startup.js" );
240 if ( $context->getOnly() === 'scripts' ) {
241
242 // Startup function
243 $configuration = $this->getConfig( $context );
244 $registrations = self::getModuleRegistrations( $context );
245 // Fix indentation
246 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
247 $out .= "var startUp = function () {\n" .
248 "\tmw.config = new " . Xml::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
249 "\t$registrations\n" .
250 "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
251 "};\n";
252
253 // Conditional script injection
254 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
255 $out .= "if ( isCompatible() ) {\n" .
256 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
257 "}";
258 }
259
260 return $out;
261 }
262
263 /**
264 * @return bool
265 */
266 public function supportsURLLoading() {
267 return false;
268 }
269
270 /**
271 * @param $context ResourceLoaderContext
272 * @return array|mixed
273 */
274 public function getModifiedTime( ResourceLoaderContext $context ) {
275 global $IP, $wgCacheEpoch;
276
277 $hash = $context->getHash();
278 if ( isset( $this->modifiedTime[$hash] ) ) {
279 return $this->modifiedTime[$hash];
280 }
281
282 // Call preloadModuleInfo() on ALL modules as we're about
283 // to call getModifiedTime() on all of them
284 $loader = $context->getResourceLoader();
285 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
286
287 $time = max(
288 wfTimestamp( TS_UNIX, $wgCacheEpoch ),
289 filemtime( "$IP/resources/startup.js" ),
290 $this->getHashMtime( $context )
291 );
292
293 // ATTENTION!: Because of the line below, this is not going to cause
294 // infinite recursion - think carefully before making changes to this
295 // code!
296 // Pre-populate modifiedTime with something because the the loop over
297 // all modules below includes the the startup module (this module).
298 $this->modifiedTime[$hash] = 1;
299
300 foreach ( $loader->getModuleNames() as $name ) {
301 $module = $loader->getModule( $name );
302 $time = max( $time, $module->getModifiedTime( $context ) );
303 }
304
305 $this->modifiedTime[$hash] = $time;
306 return $this->modifiedTime[$hash];
307 }
308
309 /**
310 * Hash of all dynamic data embedded in getScript().
311 *
312 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
313 *
314 * @param $context ResourceLoaderContext
315 * @return string: Hash
316 */
317 public function getModifiedHash( ResourceLoaderContext $context ) {
318 global $wgLegacyJavaScriptGlobals;
319
320 $data = array(
321 'vars' => $this->getConfig( $context ),
322 'wgLegacyJavaScriptGlobals' => $wgLegacyJavaScriptGlobals,
323 );
324
325 return md5( serialize( $data ) );
326 }
327
328 /**
329 * @return string
330 */
331 public function getGroup() {
332 return 'startup';
333 }
334 }