3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @author Roan Kattouw
20 * @author Trevor Parscal
24 * Dynamic JavaScript and CSS resource loading system
26 class ResourceLoader
{
28 /* Protected Static Members */
30 // @var array list of module name/ResourceLoaderModule object pairs
31 protected static $modules = array();
32 protected static $initialized = false;
34 /* Protected Static Methods */
37 * Registers core modules and runs registration hooks
39 protected static function initialize() {
42 // Safety check - this should never be called more than once
43 if ( !self
::$initialized ) {
44 wfProfileIn( __METHOD__
);
45 // This needs to be first, because hooks might call ResourceLoader
46 // public interfaces which will call this
47 self
::$initialized = true;
48 self
::register( include( "$IP/resources/Resources.php" ) );
49 wfRunHooks( 'ResourceLoaderRegisterModules' );
50 wfProfileOut( __METHOD__
);
55 * Runs text through a filter, caching the filtered result for future calls
57 * @param $filter String: name of filter to run
58 * @param $data String: text to filter, such as JavaScript or CSS text
59 * @param $file String: path to file being filtered, (optional: only required
60 * for CSS to resolve paths)
61 * @return String: filtered data
63 protected static function filter( $filter, $data ) {
65 wfProfileIn( __METHOD__
);
67 // For empty or whitespace-only things, don't do any processing
68 if ( trim( $data ) === '' ) {
69 wfProfileOut( __METHOD__
);
74 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
75 $cached = $wgMemc->get( $key );
77 if ( $cached !== false && $cached !== null ) {
78 wfProfileOut( __METHOD__
);
86 $result = JSMin
::minify( $data );
89 $result = CSSMin
::minify( $data );
92 $result = CSSJanus
::transform( $data, true, false );
95 // Don't cache anything, just pass right through
96 wfProfileOut( __METHOD__
);
99 } catch ( Exception
$exception ) {
100 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
104 $wgMemc->set( $key, $result );
106 wfProfileOut( __METHOD__
);
113 * Registers a module with the ResourceLoader system.
115 * Note that registering the same object under multiple names is not supported
116 * and may silently fail in all kinds of interesting ways.
118 * @param $name Mixed: string of name of module or array of name/object pairs
119 * @param $object ResourceLoaderModule: module object (optional when using
120 * multiple-registration calling style)
121 * @return Boolean: false if there were any errors, in which case one or more
122 * modules were not registered
124 * @todo We need much more clever error reporting, not just in detailing what
125 * happened, but in bringing errors to the client in a way that they can
126 * easily see them if they want to, such as by using FireBug
128 public static function register( $name, ResourceLoaderModule
$object = null ) {
129 wfProfileIn( __METHOD__
);
132 // Allow multiple modules to be registered in one call
133 if ( is_array( $name ) && !isset( $object ) ) {
134 foreach ( $name as $key => $value ) {
135 self
::register( $key, $value );
138 wfProfileOut( __METHOD__
);
142 // Disallow duplicate registrations
143 if ( isset( self
::$modules[$name] ) ) {
144 // A module has already been registered by this name
145 throw new MWException( 'Another module has already been registered as ' . $name );
148 self
::$modules[$name] = $object;
149 $object->setName( $name );
150 wfProfileOut( __METHOD__
);
154 * Gets a map of all modules and their options
156 * @return Array: array( modulename => ResourceLoaderModule )
158 public static function getModules() {
162 return self
::$modules;
166 * Get the ResourceLoaderModule object for a given module name
168 * @param $name String: module name
169 * @return mixed ResourceLoaderModule or null if not registered
171 public static function getModule( $name ) {
175 return isset( self
::$modules[$name] ) ? self
::$modules[$name] : null;
179 * Gets registration code for all modules
181 * @param $context ResourceLoaderContext object
182 * @return String: JavaScript code for registering all modules with the client loader
184 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
185 wfProfileIn( __METHOD__
);
189 $registrations = array();
191 foreach ( self
::$modules as $name => $module ) {
192 // Support module loader scripts
193 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
194 $deps = FormatJson
::encode( $module->getDependencies() );
195 $group = FormatJson
::encode( $module->getGroup() );
196 $version = wfTimestamp( TS_ISO_8601
, round( $module->getModifiedTime( $context ), -2 ) );
197 $scripts .= "( function( name, version, dependencies ) { $loader } )\n" .
198 "( '$name', '$version', $deps, $group );\n";
200 // Automatically register module
202 // Modules without dependencies or a group pass two arguments (name, timestamp) to
203 // mediaWiki.loader.register()
204 if ( !count( $module->getDependencies() && $module->getGroup() === null ) ) {
205 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
207 // Modules with dependencies but no group pass three arguments (name, timestamp, dependencies)
208 // to mediaWiki.loader.register()
209 else if ( $module->getGroup() === null ) {
210 $registrations[] = array(
211 $name, $module->getModifiedTime( $context ), $module->getDependencies() );
213 // Modules with dependencies pass four arguments (name, timestamp, dependencies, group)
214 // to mediaWiki.loader.register()
216 $registrations[] = array(
217 $name, $module->getModifiedTime( $context ), $module->getDependencies(), $module->getGroup() );
221 $out = $scripts . "mediaWiki.loader.register( " . FormatJson
::encode( $registrations ) . " );\n";
222 wfProfileOut( __METHOD__
);
227 * Get the highest modification time of all modules, based on a given
228 * combination of language code, skin name and debug mode flag.
230 * @param $context ResourceLoaderContext object
231 * @return Integer: UNIX timestamp
233 public static function getHighestModifiedTime( ResourceLoaderContext
$context ) {
237 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
239 foreach ( self
::$modules as $module ) {
240 $time = max( $time, $module->getModifiedTime( $context ) );
247 * Outputs a response to a resource load-request, including a content-type header
249 * @param $context ResourceLoaderContext object
251 public static function respond( ResourceLoaderContext
$context ) {
252 global $wgResourceLoaderMaxage;
254 wfProfileIn( __METHOD__
);
257 // Split requested modules into two groups, modules and missing
261 foreach ( $context->getModules() as $name ) {
262 if ( isset( self
::$modules[$name] ) ) {
269 // If a version wasn't specified we need a shorter expiry time for updates to
270 // propagate to clients quickly
271 if ( is_null( $context->getVersion() ) ) {
272 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
273 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
275 // If a version was specified we can use a longer expiry time since changing
276 // version numbers causes cache misses
278 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
279 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
282 // To send Last-Modified and support If-Modified-Since, we need to detect
283 // the last modified time
284 wfProfileIn( __METHOD__
.'-getModifiedTime' );
286 foreach ( $modules as $name ) {
287 $mtime = max( $mtime, self
::$modules[$name]->getModifiedTime( $context ) );
289 wfProfileOut( __METHOD__
.'-getModifiedTime' );
291 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ?
'text/css' : 'text/javascript' ) );
292 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
293 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
294 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
296 // If there's an If-Modified-Since header, respond with a 304 appropriately
297 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
298 if ( $ims !== false && $mtime >= wfTimestamp( TS_UNIX
, $ims ) ) {
299 header( 'HTTP/1.0 304 Not Modified' );
300 header( 'Status: 304 Not Modified' );
301 wfProfileOut( __METHOD__
);
305 // Use output buffering
309 $blobs = $context->shouldIncludeMessages() ?
310 MessageBlobStore
::get( $modules, $context->getLanguage() ) : array();
313 foreach ( $modules as $name ) {
314 wfProfileIn( __METHOD__
. '-' . $name );
318 if ( $context->shouldIncludeScripts() ) {
319 $scripts .= self
::$modules[$name]->getScript( $context ) . "\n";
326 $context->shouldIncludeStyles()
327 && ( count( $styles = self
::$modules[$name]->getStyles( $context ) ) )
329 foreach ( $styles as $media => $style ) {
330 if ( self
::$modules[$name]->getFlip( $context ) ) {
331 $styles[$media] = self
::filter( 'flip-css', $style );
333 if ( !$context->getDebug() ) {
334 $styles[$media] = self
::filter( 'minify-css', $style );
340 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
343 if ( $context->getOnly() === 'styles' ) {
344 if ( $context->getDebug() ) {
345 echo "/* $name */\n";
346 foreach ( $styles as $media => $style ) {
347 echo "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
350 foreach ( $styles as $media => $style ) {
351 if ( strlen( $style ) ) {
352 echo "@media $media{" . $style . "}";
356 } else if ( $context->getOnly() === 'scripts' ) {
358 } else if ( $context->getOnly() === 'messages' ) {
359 echo "mediaWiki.msg.set( $messages );\n";
361 if ( count( $styles ) ) {
362 $styles = FormatJson
::encode( $styles );
366 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
368 wfProfileOut( __METHOD__
. '-' . $name );
371 // Update the status of script-only modules
372 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
375 foreach ( $modules as $name ) {
376 $statuses[$name] = 'ready';
379 $statuses = FormatJson
::encode( $statuses );
380 echo "mediaWiki.loader.state( $statuses );\n";
383 // Register missing modules
384 if ( $context->shouldIncludeScripts() ) {
385 foreach ( $missing as $name ) {
386 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
390 // Output the appropriate header
391 if ( $context->getOnly() !== 'styles' ) {
392 if ( $context->getDebug() ) {
395 echo self
::filter( 'minify-js', ob_get_clean() );
398 wfProfileOut( __METHOD__
);