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 // This needs to be first, because hooks might call ResourceLoader public interfaces which will call this
45 self
::$initialized = true;
46 self
::register( include( "$IP/resources/Resources.php" ) );
47 wfRunHooks( 'ResourceLoaderRegisterModules' );
52 * Runs text through a filter, caching the filtered result for future calls
54 * @param $filter String: name of filter to run
55 * @param $data String: text to filter, such as JavaScript or CSS text
56 * @param $file String: path to file being filtered, (optional: only required for CSS to resolve paths)
57 * @return String: filtered data
59 protected static function filter( $filter, $data ) {
62 // For empty or whitespace-only things, don't do any processing
63 if ( trim( $data ) === '' ) {
68 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
69 $cached = $wgMemc->get( $key );
71 if ( $cached !== false && $cached !== null ) {
79 $result = JSMin
::minify( $data );
82 $result = CSSMin
::minify( $data );
85 $result = CSSJanus
::transform( $data, true, false );
88 // Don't cache anything, just pass right through
91 } catch ( Exception
$exception ) {
92 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
96 $wgMemc->set( $key, $result );
104 * Registers a module with the ResourceLoader system.
106 * Note that registering the same object under multiple names is not supported and may silently fail in all
107 * kinds of interesting ways.
109 * @param $name Mixed: string of name of module or array of name/object pairs
110 * @param $object ResourceLoaderModule: module object (optional when using multiple-registration calling style)
111 * @return Boolean: false if there were any errors, in which case one or more modules were not registered
113 * @todo We need much more clever error reporting, not just in detailing what happened, but in bringing errors to
114 * the client in a way that they can easily see them if they want to, such as by using FireBug
116 public static function register( $name, ResourceLoaderModule
$object = null ) {
120 // Allow multiple modules to be registered in one call
121 if ( is_array( $name ) && !isset( $object ) ) {
122 foreach ( $name as $key => $value ) {
123 self
::register( $key, $value );
129 // Disallow duplicate registrations
130 if ( isset( self
::$modules[$name] ) ) {
131 // A module has already been registered by this name
132 throw new MWException( 'Another module has already been registered as ' . $name );
135 self
::$modules[$name] = $object;
136 $object->setName( $name );
140 * Gets a map of all modules and their options
142 * @return Array: array( modulename => ResourceLoaderModule )
144 public static function getModules() {
148 return self
::$modules;
152 * Get the ResourceLoaderModule object for a given module name
154 * @param $name String: module name
155 * @return mixed ResourceLoaderModule or null if not registered
157 public static function getModule( $name ) {
161 return isset( self
::$modules[$name] ) ? self
::$modules[$name] : null;
165 * Gets registration code for all modules, except pre-registered ones listed in self::$preRegisteredModules
167 * @param $context ResourceLoaderContext object
168 * @return String: JavaScript code for registering all modules with the client loader
170 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
175 $registrations = array();
177 foreach ( self
::$modules as $name => $module ) {
178 // Support module loader scripts
179 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
180 $deps = FormatJson
::encode( $module->getDependencies() );
181 $version = wfTimestamp( TS_ISO_8601
, round( $module->getModifiedTime( $context ), -2 ) );
182 $scripts .= "( function( name, version, dependencies ) { $loader } )( '$name', '$version', $deps );";
184 // Automatically register module
186 // Modules without dependencies pass two arguments (name, timestamp) to mediaWiki.loader.register()
187 if ( !count( $module->getDependencies() ) ) {
188 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
190 // Modules with dependencies pass three arguments (name, timestamp, dependencies) to mediaWiki.loader.register()
192 $registrations[] = array( $name, $module->getModifiedTime( $context ), $module->getDependencies() );
196 return $scripts . "mediaWiki.loader.register( " . FormatJson
::encode( $registrations ) . " );";
200 * Get the highest modification time of all modules, based on a given combination of language code,
201 * skin name and debug mode flag.
203 * @param $context ResourceLoaderContext object
204 * @return Integer: UNIX timestamp
206 public static function getHighestModifiedTime( ResourceLoaderContext
$context ) {
210 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
212 foreach ( self
::$modules as $module ) {
213 $time = max( $time, $module->getModifiedTime( $context ) );
220 * Outputs a response to a resource load-request, including a content-type header
222 * @param $context ResourceLoaderContext object
224 public static function respond( ResourceLoaderContext
$context ) {
225 global $wgResourceLoaderVersionedClientMaxage, $wgResourceLoaderVersionedServerMaxage;
226 global $wgResourceLoaderUnversionedServerMaxage, $wgResourceLoaderUnversionedClientMaxage;
230 // Split requested modules into two groups, modules and missing
234 foreach ( $context->getModules() as $name ) {
235 if ( isset( self
::$modules[$name] ) ) {
242 // If a version wasn't specified we need a shorter expiry time for updates to propagate to clients quickly
243 if ( is_null( $context->getVersion() ) ) {
244 $maxage = $wgResourceLoaderUnversionedClientMaxage;
245 $smaxage = $wgResourceLoaderUnversionedServerMaxage;
247 // If a version was specified we can use a longer expiry time since changing version numbers causes cache misses
249 $maxage = $wgResourceLoaderVersionedClientMaxage;
250 $smaxage = $wgResourceLoaderVersionedServerMaxage;
253 // To send Last-Modified and support If-Modified-Since, we need to detect the last modified time
255 foreach ( $modules as $name ) {
256 $mtime = max( $mtime, self
::$modules[$name]->getModifiedTime( $context ) );
259 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ?
'text/css' : 'text/javascript' ) );
260 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
261 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
262 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
264 // If there's an If-Modified-Since header, respond with a 304 appropriately
265 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
266 if ( $ims !== false && $mtime >= wfTimestamp( TS_UNIX
, $ims ) ) {
267 header( 'HTTP/1.0 304 Not Modified' );
268 header( 'Status: 304 Not Modified' );
272 // Use output buffering
276 $blobs = $context->shouldIncludeMessages() ?
277 MessageBlobStore
::get( $modules, $context->getLanguage() ) : array();
280 foreach ( $modules as $name ) {
284 if ( $context->shouldIncludeScripts() ) {
285 $scripts .= self
::$modules[$name]->getScript( $context );
292 $context->shouldIncludeStyles() && ( count( $styles = self
::$modules[$name]->getStyles( $context ) ) )
294 foreach ( $styles as $media => $style ) {
295 if ( self
::$modules[$name]->getFlip( $context ) ) {
296 $styles[$media] = self
::filter( 'flip-css', $style );
298 if ( !$context->getDebug() ) {
299 $styles[$media] = self
::filter( 'minify-css', $style );
305 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
308 if ( $context->getOnly() === 'styles' ) {
309 if ( $context->getDebug() ) {
310 echo "/* $name */\n";
311 foreach ( $styles as $media => $style ) {
312 echo "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
315 foreach ( $styles as $media => $style ) {
316 if ( strlen( $style ) ) {
317 echo "@media $media{" . $style . "}";
321 } else if ( $context->getOnly() === 'scripts' ) {
323 } else if ( $context->getOnly() === 'messages' ) {
324 echo "mediaWiki.msg.set( $messages );\n";
326 if ( count( $styles ) ) {
327 $styles = FormatJson
::encode( $styles );
331 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
335 // Update the status of script-only modules
336 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
339 foreach ( $modules as $name ) {
340 $statuses[$name] = 'ready';
343 $statuses = FormatJson
::encode( $statuses );
344 echo "mediaWiki.loader.state( $statuses );\n";
347 // Register missing modules
348 if ( $context->shouldIncludeScripts() ) {
349 foreach ( $missing as $name ) {
350 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
354 // Output the appropriate header
355 if ( $context->getOnly() !== 'styles' ) {
356 if ( $context->getDebug() ) {
359 echo self
::filter( 'minify-js', ob_get_clean() );