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
27 * // Registers a module with the resource loading system
28 * ResourceLoader::register( 'foo', array(
29 * // Script or list of scripts to include when implementating the module (required)
30 * 'script' => 'resources/foo/foo.js',
31 * // List of scripts or lists of scripts to include based on the current language
33 * 'en-gb' => 'resources/foo/locales/en-gb.js',
35 * // Script or list of scripts to include only when in debug mode
36 * 'debug' => 'resources/foo/debug.js',
37 * // If this module is going to be loaded before the mediawiki module is ready such as jquery or the mediawiki
38 * // module itself, it can be included without special loader wrapping - this will also limit the module to not be
39 * // able to specify needs, custom loaders, styles, themes or messages (any of the options below) - raw scripts
40 * // get registered as 'ready' after the mediawiki module is ready, so they can be named as dependencies
42 * // Modules or list of modules which are needed and should be used when generating loader code
43 * 'needs' => 'resources/foo/foo.js',
44 * // Script or list of scripts which will cause loader code to not be generated - if you are doing something fancy
45 * // with your dependencies this gives you a way to use custom registration code
46 * 'loader' => 'resources/foo/loader.js',
47 * // Style-sheets or list of style-sheets to include
48 * 'style' => 'resources/foo/foo.css',
49 * // List of style-sheets or lists of style-sheets to include based on the skin - if no match is found for current
50 * // skin, 'default' is used - if default doesn't exist nothing is added
52 * 'default' => 'resources/foo/themes/default/foo.css',
53 * 'vector' => 'resources/foo/themes/vector.foo.css',
55 * // List of keys of messages to include
56 * 'messages' => array( 'foo-hello', 'foo-goodbye' ),
57 * // Subclass of ResourceLoaderModule to use for custom modules
58 * 'class' => 'ResourceLoaderSiteJSModule',
61 * // Responds to a resource loading request
62 * ResourceLoader::respond( $wgRequest, $wgServer . wfScript( 'load' ) );
64 class ResourceLoader
{
65 /* Protected Static Members */
67 // @var array list of module name/ResourceLoaderModule object pairs
68 protected static $modules = array();
70 /* Protected Static Methods */
73 * Runs text through a filter, caching the filtered result for future calls
75 * @param $filter String: name of filter to run
76 * @param $data String: text to filter, such as JavaScript or CSS text
77 * @param $file String: path to file being filtered, (optional: only required for CSS to resolve paths)
78 * @return String: filtered data
80 protected static function filter( $filter, $data ) {
83 // For empty or whitespace-only things, don't do any processing
84 if ( trim( $data ) === '' ) {
89 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
90 $cached = $wgMemc->get( $key );
92 if ( $cached !== false && $cached !== null ) {
100 $result = JSMin
::minify( $data );
103 $result = CSSMin
::minify( $data );
106 $result = CSSJanus
::transform( $data, true, false );
109 // Don't cache anything, just pass right through
112 } catch ( Exception
$exception ) {
113 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
117 $wgMemc->set( $key, $result );
125 * Registers a module with the ResourceLoader system.
127 * Note that registering the same object under multiple names is not supported and may silently fail in all
128 * kinds of interesting ways.
130 * @param $name Mixed: string of name of module or array of name/object pairs
131 * @param $object ResourceLoaderModule: module object (optional when using multiple-registration calling style)
132 * @return Boolean: false if there were any errors, in which case one or more modules were not registered
134 * @todo We need much more clever error reporting, not just in detailing what happened, but in bringing errors to
135 * the client in a way that they can easily see them if they want to, such as by using FireBug
137 public static function register( $name, ResourceLoaderModule
$object = null ) {
138 // Allow multiple modules to be registered in one call
139 if ( is_array( $name ) && !isset( $object ) ) {
140 foreach ( $name as $key => $value ) {
141 self
::register( $key, $value );
147 // Disallow duplicate registrations
148 if ( isset( self
::$modules[$name] ) ) {
149 // A module has already been registered by this name
150 throw new MWException( 'Another module has already been registered as ' . $name );
153 self
::$modules[$name] = $object;
154 $object->setName( $name );
158 * Gets a map of all modules and their options
160 * @return Array: array( modulename => ResourceLoaderModule )
162 public static function getModules() {
163 return self
::$modules;
167 * Get the ResourceLoaderModule object for a given module name
169 * @param $name String: module name
170 * @return mixed ResourceLoaderModule or null if not registered
172 public static function getModule( $name ) {
173 return isset( self
::$modules[$name] ) ? self
::$modules[$name] : null;
177 * Gets registration code for all modules, except pre-registered ones listed in self::$preRegisteredModules
179 * @param $context ResourceLoaderContext object
180 * @return String: JavaScript code for registering all modules with the client loader
182 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
184 $registrations = array();
186 foreach ( self
::$modules as $name => $module ) {
187 // Support module loader scripts
188 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
191 // Automatically register module
193 // Modules without dependencies pass two arguments (name, timestamp) to mediaWiki.loader.register()
194 if ( !count( $module->getDependencies() ) ) {
195 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
197 // Modules with dependencies pass three arguments (name, timestamp, dependencies) to mediaWiki.loader.register()
199 $registrations[] = array( $name, $module->getModifiedTime( $context ), $module->getDependencies() );
203 return $scripts . "mediaWiki.loader.register( " . FormatJson
::encode( $registrations ) . " );";
207 * Get the highest modification time of all modules, based on a given combination of language code,
208 * skin name and debug mode flag.
210 * @param $context ResourceLoaderContext object
211 * @return Integer: UNIX timestamp
213 public static function getHighestModifiedTime( ResourceLoaderContext
$context ) {
214 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
216 foreach ( self
::$modules as $module ) {
217 $time = max( $time, $module->getModifiedTime( $context ) );
224 * Outputs a response to a resource load-request, including a content-type header
226 * @param $context ResourceLoaderContext object
228 public static function respond( ResourceLoaderContext
$context ) {
229 // Split requested modules into two groups, modules and missing
233 foreach ( $context->getModules() as $name ) {
234 if ( isset( self
::$modules[$name] ) ) {
241 // Calculate the mtime and caching maxages for this request. We need this, 304 or no 304
243 $maxage = PHP_INT_MAX
;
244 $smaxage = PHP_INT_MAX
;
246 foreach ( $modules as $name ) {
247 $mtime = max( $mtime, self
::$modules[$name]->getModifiedTime( $context ) );
248 $maxage = min( $maxage, self
::$modules[$name]->getClientMaxage() );
249 $smaxage = min( $smaxage, self
::$modules[$name]->getServerMaxage() );
253 if ( $context->getOnly() === 'styles' ) {
254 header( 'Content-Type: text/css' );
256 header( 'Content-Type: text/javascript' );
259 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
260 $expires = wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() );
261 header( "Cache-Control: public, maxage=$maxage, s-maxage=$smaxage" );
262 header( "Expires: $expires" );
264 // Check if there's an If-Modified-Since header and respond with a 304 Not Modified if possible
265 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
267 if ( $ims !== false && wfTimestamp( TS_UNIX
, $ims ) == $mtime ) {
268 header( 'HTTP/1.0 304 Not Modified' );
269 header( 'Status: 304 Not Modified' );
273 // Use output buffering
277 $blobs = $context->shouldIncludeMessages() ?
278 MessageBlobStore
::get( $modules, $context->getLanguage() ) : array();
281 foreach ( $modules as $name ) {
285 if ( $context->shouldIncludeScripts() ) {
286 $scripts .= self
::$modules[$name]->getScript( $context );
293 $context->shouldIncludeStyles() &&
294 ( $styles .= self
::$modules[$name]->getStyle( $context ) ) !== ''
296 if ( self
::$modules[$name]->getFlip( $context ) ) {
297 $styles = self
::filter( 'flip-css', $styles );
299 $styles = $context->getDebug() ?
$styles : self
::filter( 'minify-css', $styles );
303 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
306 if ( $context->getOnly() === 'styles' ) {
308 } else if ( $context->getOnly() === 'scripts' ) {
310 } else if ( $context->getOnly() === 'messages' ) {
311 echo "mediaWiki.msg.set( $messages );\n";
313 $styles = Xml
::escapeJsString( $styles );
314 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n'$styles',\n$messages );\n";
318 // Update the status of script-only modules
319 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
322 foreach ( $modules as $name ) {
323 $statuses[$name] = 'ready';
326 $statuses = FormatJson
::encode( $statuses );
327 echo "mediaWiki.loader.state( $statuses );";
330 // Register missing modules
331 if ( $context->shouldIncludeScripts() ) {
332 foreach ( $missing as $name ) {
333 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
337 // Output the appropriate header
338 if ( $context->getOnly() !== 'styles' ) {
339 if ( $context->getDebug() ) {
342 echo self
::filter( 'minify-js', ob_get_clean() );
349 require_once "$IP/resources/Resources.php";