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();
33 /* Protected Static Methods */
36 * Runs text through a filter, caching the filtered result for future calls
38 * @param $filter String: name of filter to run
39 * @param $data String: text to filter, such as JavaScript or CSS text
40 * @param $file String: path to file being filtered, (optional: only required for CSS to resolve paths)
41 * @return String: filtered data
43 protected static function filter( $filter, $data ) {
46 // For empty or whitespace-only things, don't do any processing
47 if ( trim( $data ) === '' ) {
52 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
53 $cached = $wgMemc->get( $key );
55 if ( $cached !== false && $cached !== null ) {
63 $result = JSMin
::minify( $data );
66 $result = CSSMin
::minify( $data );
69 $result = CSSJanus
::transform( $data, true, false );
72 // Don't cache anything, just pass right through
75 } catch ( Exception
$exception ) {
76 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
80 $wgMemc->set( $key, $result );
88 * Registers a module with the ResourceLoader system.
90 * Note that registering the same object under multiple names is not supported and may silently fail in all
91 * kinds of interesting ways.
93 * @param $name Mixed: string of name of module or array of name/object pairs
94 * @param $object ResourceLoaderModule: module object (optional when using multiple-registration calling style)
95 * @return Boolean: false if there were any errors, in which case one or more modules were not registered
97 * @todo We need much more clever error reporting, not just in detailing what happened, but in bringing errors to
98 * the client in a way that they can easily see them if they want to, such as by using FireBug
100 public static function register( $name, ResourceLoaderModule
$object = null ) {
101 // Allow multiple modules to be registered in one call
102 if ( is_array( $name ) && !isset( $object ) ) {
103 foreach ( $name as $key => $value ) {
104 self
::register( $key, $value );
110 // Disallow duplicate registrations
111 if ( isset( self
::$modules[$name] ) ) {
112 // A module has already been registered by this name
113 throw new MWException( 'Another module has already been registered as ' . $name );
116 self
::$modules[$name] = $object;
117 $object->setName( $name );
121 * Gets a map of all modules and their options
123 * @return Array: array( modulename => ResourceLoaderModule )
125 public static function getModules() {
126 return self
::$modules;
130 * Get the ResourceLoaderModule object for a given module name
132 * @param $name String: module name
133 * @return mixed ResourceLoaderModule or null if not registered
135 public static function getModule( $name ) {
136 return isset( self
::$modules[$name] ) ? self
::$modules[$name] : null;
140 * Gets registration code for all modules, except pre-registered ones listed in self::$preRegisteredModules
142 * @param $context ResourceLoaderContext object
143 * @return String: JavaScript code for registering all modules with the client loader
145 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
147 $registrations = array();
149 foreach ( self
::$modules as $name => $module ) {
150 // Support module loader scripts
151 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
152 $deps = FormatJson
::encode( $module->getDependencies() );
153 $version = wfTimestamp( TS_ISO_8601
, round( $module->getModifiedTime( $context ), -2 ) );
154 $scripts .= "( function( name, version, dependencies ) { $loader } )( '$name', '$version', $deps );";
156 // Automatically register module
158 // Modules without dependencies pass two arguments (name, timestamp) to mediaWiki.loader.register()
159 if ( !count( $module->getDependencies() ) ) {
160 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
162 // Modules with dependencies pass three arguments (name, timestamp, dependencies) to mediaWiki.loader.register()
164 $registrations[] = array( $name, $module->getModifiedTime( $context ), $module->getDependencies() );
168 return $scripts . "mediaWiki.loader.register( " . FormatJson
::encode( $registrations ) . " );";
172 * Get the highest modification time of all modules, based on a given combination of language code,
173 * skin name and debug mode flag.
175 * @param $context ResourceLoaderContext object
176 * @return Integer: UNIX timestamp
178 public static function getHighestModifiedTime( ResourceLoaderContext
$context ) {
179 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
181 foreach ( self
::$modules as $module ) {
182 $time = max( $time, $module->getModifiedTime( $context ) );
189 * Outputs a response to a resource load-request, including a content-type header
191 * @param $context ResourceLoaderContext object
193 public static function respond( ResourceLoaderContext
$context ) {
194 global $wgResourceLoaderVersionedClientMaxage, $wgResourceLoaderVersionedServerMaxage;
195 global $wgResourceLoaderUnversionedServerMaxage, $wgResourceLoaderUnversionedClientMaxage;
197 // Split requested modules into two groups, modules and missing
201 foreach ( $context->getModules() as $name ) {
202 if ( isset( self
::$modules[$name] ) ) {
209 // If a version wasn't specified we need a shorter expiry time for updates to propagate to clients quickly
210 if ( is_null( $context->getVersion() ) ) {
211 $maxage = $wgResourceLoaderUnversionedClientMaxage;
212 $smaxage = $wgResourceLoaderUnversionedServerMaxage;
214 // If a version was specified we can use a longer expiry time since changing version numbers causes cache misses
216 $maxage = $wgResourceLoaderVersionedClientMaxage;
217 $smaxage = $wgResourceLoaderVersionedServerMaxage;
220 // To send Last-Modified and support If-Modified-Since, we need to detect the last modified time
222 foreach ( $modules as $name ) {
223 $mtime = max( $mtime, self
::$modules[$name]->getModifiedTime( $context ) );
226 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ?
'text/css' : 'text/javascript' ) );
227 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
228 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
229 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
231 // If there's an If-Modified-Since header, respond with a 304 appropriately
232 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
233 if ( $ims !== false && $mtime >= wfTimestamp( TS_UNIX
, $ims ) ) {
234 header( 'HTTP/1.0 304 Not Modified' );
235 header( 'Status: 304 Not Modified' );
239 // Use output buffering
243 $blobs = $context->shouldIncludeMessages() ?
244 MessageBlobStore
::get( $modules, $context->getLanguage() ) : array();
247 foreach ( $modules as $name ) {
251 if ( $context->shouldIncludeScripts() ) {
252 $scripts .= self
::$modules[$name]->getScript( $context );
259 $context->shouldIncludeStyles() && ( count( $styles = self
::$modules[$name]->getStyles( $context ) ) )
261 foreach ( $styles as $media => $style ) {
262 if ( self
::$modules[$name]->getFlip( $context ) ) {
263 $styles[$media] = self
::filter( 'flip-css', $style );
265 if ( !$context->getDebug() ) {
266 $styles[$media] = self
::filter( 'minify-css', $style );
272 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
275 if ( $context->getOnly() === 'styles' ) {
276 if ( $context->getDebug() ) {
277 echo "/* $name */\n";
278 foreach ( $styles as $media => $style ) {
279 echo "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
282 foreach ( $styles as $media => $style ) {
283 if ( strlen( $style ) ) {
284 echo "@media $media{" . $style . "}";
288 } else if ( $context->getOnly() === 'scripts' ) {
290 } else if ( $context->getOnly() === 'messages' ) {
291 echo "mediaWiki.msg.set( $messages );\n";
293 $styles = FormatJson
::encode( $styles );
294 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
298 // Update the status of script-only modules
299 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
302 foreach ( $modules as $name ) {
303 $statuses[$name] = 'ready';
306 $statuses = FormatJson
::encode( $statuses );
307 echo "mediaWiki.loader.state( $statuses );\n";
310 // Register missing modules
311 if ( $context->shouldIncludeScripts() ) {
312 foreach ( $missing as $name ) {
313 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
317 // Output the appropriate header
318 if ( $context->getOnly() !== 'styles' ) {
319 if ( $context->getDebug() ) {
322 echo self
::filter( 'minify-js', ob_get_clean() );
328 ResourceLoader
::register( include( "$IP/resources/Resources.php" ) );
329 wfRunHook( 'ResourceLoaderRegisterModules' );