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
18 * @author Roan Kattouw
19 * @author Trevor Parscal
23 * Dynamic JavaScript and CSS resource loading system
26 * // Registers a module with the resource loading system
27 * ResourceLoader::register( 'foo', array(
28 * // Script or list of scripts to include when implementating the module (required)
29 * 'script' => 'resources/foo/foo.js',
30 * // List of scripts or lists of scripts to include based on the current language
32 * 'en-gb' => 'resources/foo/locales/en-gb.js',
34 * // Script or list of scripts to include only when in debug mode
35 * 'debug' => 'resources/foo/debug.js',
36 * // If this module is going to be loaded before the mediawiki module is ready such as jquery or the mediawiki
37 * // module itself, it can be included without special loader wrapping - this will also limit the module to not be
38 * // able to specify needs, custom loaders, styles, themes or messages (any of the options below) - raw scripts
39 * // get registered as 'ready' after the mediawiki module is ready, so they can be named as dependencies
41 * // Modules or list of modules which are needed and should be used when generating loader code
42 * 'needs' => 'resources/foo/foo.js',
43 * // Script or list of scripts which will cause loader code to not be generated - if you are doing something fancy
44 * // with your dependencies this gives you a way to use custom registration code
45 * 'loader' => 'resources/foo/loader.js',
46 * // Style-sheets or list of style-sheets to include
47 * 'style' => 'resources/foo/foo.css',
48 * // List of style-sheets or lists of style-sheets to include based on the skin - if no match is found for current
49 * // skin, 'default' is used - if default doesn't exist nothing is added
51 * 'default' => 'resources/foo/themes/default/foo.css',
52 * 'vector' => 'resources/foo/themes/vector.foo.css',
54 * // List of keys of messages to include
55 * 'messages' => array( 'foo-hello', 'foo-goodbye' ),
56 * // Subclass of ResourceLoaderModule to use for custom modules
57 * 'class' => 'ResourceLoaderSiteJSModule',
60 * // Responds to a resource loading request
61 * ResourceLoader::respond( $wgRequest, $wgServer . wfScript( 'load' ) );
63 class ResourceLoader
{
64 /* Protected Static Members */
66 // @var array list of module name/ResourceLoaderModule object pairs
67 protected static $modules = array();
69 /* Protected Static Methods */
72 * Runs text through a filter, caching the filtered result for future calls
74 * @param {string} $filter name of filter to run
75 * @param {string} $data text to filter, such as JavaScript or CSS text
76 * @param {string} $file path to file being filtered, (optional: only required for CSS to resolve paths)
77 * @return {string} filtered data
79 protected static function filter( $filter, $data ) {
82 // For empty or whitespace-only things, don't do any processing
83 if ( trim( $data ) === '' ) {
88 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
89 $cached = $wgMemc->get( $key );
91 if ( $cached !== false && $cached !== null ) {
99 $result = JSMin
::minify( $data );
102 $result = CSSMin
::minify( $data );
105 $result = CSSJanus
::transform( $data, true, false );
108 // Don't cache anything, just pass right through
111 } catch ( Exception
$exception ) {
112 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
116 $wgMemc->set( $key, $result );
124 * Registers a module with the ResourceLoader system.
126 * Note that registering the same object under multiple names is not supported and may silently fail in all
127 * kinds of interesting ways.
129 * @param {mixed} $name string of name of module or array of name/object pairs
130 * @param {ResourceLoaderModule} $object module object (optional when using multiple-registration calling style)
131 * @return {boolean} false if there were any errors, in which case one or more modules were not registered
133 * @todo We need much more clever error reporting, not just in detailing what happened, but in bringing errors to
134 * the client in a way that they can easily see them if they want to, such as by using FireBug
136 public static function register( $name, ResourceLoaderModule
$object = null ) {
137 // Allow multiple modules to be registered in one call
138 if ( is_array( $name ) && !isset( $object ) ) {
139 foreach ( $name as $key => $value ) {
140 self
::register( $key, $value );
146 // Disallow duplicate registrations
147 if ( isset( self
::$modules[$name] ) ) {
148 // A module has already been registered by this name
149 throw new MWException( 'Another module has already been registered as ' . $name );
152 self
::$modules[$name] = $object;
153 $object->setName( $name );
157 * Gets a map of all modules and their options
159 * @return {array} array( modulename => ResourceLoaderModule )
161 public static function getModules() {
162 return self
::$modules;
166 * Get the ResourceLoaderModule object for a given module name
167 * @param $name string Module name
168 * @return mixed ResourceLoaderModule or null if not registered
170 public static function getModule( $name ) {
171 return isset( self
::$modules[$name] ) ? self
::$modules[$name] : null;
175 * Gets registration code for all modules, except pre-registered ones listed in self::$preRegisteredModules
177 * The $lang, $skin and $debug parameters are used to calculate the last modified timestamps for each
179 * @param $lang string Language code
180 * @param $skin string Skin name
181 * @param $debug bool Debug mode flag
182 * @return {string} JavaScript code for registering all modules with the client loader
184 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
186 $registrations = array();
188 foreach ( self
::$modules as $name => $module ) {
189 // Support module loader scripts
190 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
193 // Automatically register module
195 // Modules without dependencies pass two arguments (name, timestamp) to mediaWiki.loader.register()
196 if ( !count( $module->getDependencies() ) ) {
197 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
199 // Modules with dependencies pass three arguments (name, timestamp, dependencies) to mediaWiki.loader.register()
201 $registrations[] = array( $name, $module->getModifiedTime( $context ), $module->getDependencies() );
205 return $scripts . "mediaWiki.loader.register( " . FormatJson
::encode( $registrations ) . " );";
209 * Get the highest modification time of all modules, based on a given combination of language code,
210 * skin name and debug mode flag.
211 * @param $lang string Language code
212 * @param $skin string Skin name
213 * @param $debug bool Debug mode flag
214 * @return int UNIX timestamp
216 public static function getHighestModifiedTime( ResourceLoaderContext
$context ) {
217 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
219 foreach ( self
::$modules as $module ) {
220 $time = max( $time, $module->getModifiedTime( $context ) );
229 * Outputs a response to a resource load-request, including a content-type header
231 * @param {WebRequest} $request web request object to respond to
232 * @param {string} $server web-accessible path to script server
236 * 'lang' => [string: language code, optional, code of default language by default],
237 * 'skin' => [string: name of skin, optional, name of default skin by default],
238 * 'dir' => [string: 'ltr' or 'rtl', optional, direction of lang by default],
239 * 'debug' => [boolean: true to include debug-only scripts, optional, false by default],
240 * 'only' => [string: 'scripts', 'styles' or 'messages', optional, if set only get part of the requested module]
243 public static function respond( ResourceLoaderContext
$context ) {
244 // Split requested modules into two groups, modules and missing
248 foreach ( $context->getModules() as $name ) {
249 if ( isset( self
::$modules[$name] ) ) {
256 // Calculate the mtime and caching maxages for this request. We need this, 304 or no 304
258 $maxage = PHP_INT_MAX
;
259 $smaxage = PHP_INT_MAX
;
261 foreach ( $modules as $name ) {
262 $mtime = max( $mtime, self
::$modules[$name]->getModifiedTime( $context ) );
263 $maxage = min( $maxage, self
::$modules[$name]->getClientMaxage() );
264 $smaxage = min( $smaxage, self
::$modules[$name]->getServerMaxage() );
268 if ( $context->getOnly() === 'styles' ) {
269 header( 'Content-Type: text/css' );
271 header( 'Content-Type: text/javascript' );
274 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
275 $expires = wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() );
276 header( "Cache-Control: public, maxage=$maxage, s-maxage=$smaxage" );
277 header( "Expires: $expires" );
279 // Check if there's an If-Modified-Since header and respond with a 304 Not Modified if possible
280 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
282 if ( $ims !== false && wfTimestamp( TS_UNIX
, $ims ) == $mtime ) {
283 header( 'HTTP/1.0 304 Not Modified' );
284 header( 'Status: 304 Not Modified' );
288 // Use output buffering
292 $blobs = $context->shouldIncludeMessages() ?
293 MessageBlobStore
::get( $modules, $context->getLanguage() ) : array();
296 foreach ( $modules as $name ) {
300 if ( $context->shouldIncludeScripts() ) {
301 $scripts .= self
::$modules[$name]->getScript( $context );
308 $context->shouldIncludeStyles() &&
309 ( $styles .= self
::$modules[$name]->getStyle( $context ) ) !== ''
311 if ( self
::$modules[$name]->getFlip( $context ) ) {
312 $styles = self
::filter( 'flip-css', $styles );
314 $styles = $context->getDebug() ?
$styles : self
::filter( 'minify-css', $styles );
318 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
321 if ( $context->getOnly() === 'styles' ) {
323 } else if ( $context->getOnly() === 'scripts' ) {
325 } else if ( $context->getOnly() === 'messages' ) {
326 echo "mediaWiki.msg.set( $messages );\n";
328 $styles = Xml
::escapeJsString( $styles );
329 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n'$styles',\n$messages );\n";
333 // Update the status of script-only modules
334 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
337 foreach ( $modules as $name ) {
338 $statuses[$name] = 'ready';
341 $statuses = FormatJson
::encode( $statuses );
342 echo "mediaWiki.loader.state( $statuses );";
345 // Register missing modules
346 if ( $context->shouldIncludeScripts() ) {
347 foreach ( $missing as $name ) {
348 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
352 // Output the appropriate header
353 if ( $context->getOnly() !== 'styles' ) {
354 if ( $context->getDebug() ) {
357 echo self
::filter( 'minify-js', ob_get_clean() );
364 require_once "$IP/resources/Resources.php";