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 . $wgScriptPath . '/load.php' );
63 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 {string} $filter name of filter to run
76 * @param {string} $data text to filter, such as JavaScript or CSS text
77 * @param {string} $file 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 ) {
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 );
90 if ( $cached !== false && $cached !== null ) {
98 $result = JSMin
::minify( $data );
101 $result = CSSMin
::minify( $data );
104 $result = CSSJanus
::transform( $data, true, false );
107 // Don't cache anything, just pass right through
110 } catch ( Exception
$exception ) {
111 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
115 $wgMemc->set( $key, $result );
122 * Registers a module with the ResourceLoader system.
124 * Note that registering the same object under multiple names is not supported and may silently fail in all
125 * kinds of interesting ways.
127 * @param {mixed} $name string of name of module or array of name/object pairs
128 * @param {ResourceLoaderModule} $object module object (optional when using multiple-registration calling style)
129 * @return {boolean} false if there were any errors, in which case one or more modules were not registered
131 * @todo We need much more clever error reporting, not just in detailing what happened, but in bringing errors to
132 * the client in a way that they can easily see them if they want to, such as by using FireBug
134 public static function register( $name, ResourceLoaderModule
$object = null ) {
135 // Allow multiple modules to be registered in one call
136 if ( is_array( $name ) && !isset( $object ) ) {
137 foreach ( $name as $key => $value ) {
138 self
::register( $key, $value );
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 );
153 * Gets a map of all modules and their options
155 * @return {array} array( modulename => ResourceLoaderModule )
157 public static function getModules() {
158 return self
::$modules;
162 * Get the ResourceLoaderModule object for a given module name
163 * @param $name string Module name
164 * @return mixed ResourceLoaderModule or null if not registered
166 public static function getModule( $name ) {
167 return isset( self
::$modules[$name] ) ? self
::$modules[$name] : null;
171 * Gets registration code for all modules, except pre-registered ones listed in self::$preRegisteredModules
173 * The $lang, $skin and $debug parameters are used to calculate the last modified timestamps for each
175 * @param $lang string Language code
176 * @param $skin string Skin name
177 * @param $debug bool Debug mode flag
178 * @return {string} JavaScript code for registering all modules with the client loader
180 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
182 $registrations = array();
183 foreach ( self
::$modules as $name => $module ) {
184 // Support module loader scripts
185 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
188 // Automatically register module
190 // Modules without dependencies pass two arguments (name, timestamp) to mediaWiki.loader.register()
191 if ( !count( $module->getDependencies() ) ) {
192 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
194 // Modules with dependencies pass three arguments (name, timestamp, dependencies) to mediaWiki.loader.register()
196 $registrations[] = array( $name, $module->getModifiedTime( $context ), $module->getDependencies() );
200 return $scripts . "mediaWiki.loader.register( " . FormatJson
::encode( $registrations ) . " );";
204 * Get the highest modification time of all modules, based on a given combination of language code,
205 * skin name and debug mode flag.
206 * @param $lang string Language code
207 * @param $skin string Skin name
208 * @param $debug bool Debug mode flag
209 * @return int UNIX timestamp
211 public static function getHighestModifiedTime( ResourceLoaderContext
$context ) {
212 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
213 foreach ( self
::$modules as $module ) {
214 $time = max( $time, $module->getModifiedTime( $context ) );
222 * Outputs a response to a resource load-request, including a content-type header
224 * @param {WebRequest} $request web request object to respond to
225 * @param {string} $server web-accessible path to script server
229 * 'lang' => [string: language code, optional, code of default language by default],
230 * 'skin' => [string: name of skin, optional, name of default skin by default],
231 * 'dir' => [string: 'ltr' or 'rtl', optional, direction of lang by default],
232 * 'debug' => [boolean: true to include debug-only scripts, optional, false by default],
233 * 'only' => [string: 'scripts', 'styles' or 'messages', optional, if set only get part of the requested module]
236 public static function respond( ResourceLoaderContext
$context ) {
237 // Split requested modules into two groups, modules and missing
240 foreach ( $context->getModules() as $name ) {
241 if ( isset( self
::$modules[$name] ) ) {
248 // Calculate the mtime and caching maxages for this request. We need this, 304 or no 304
250 $maxage = PHP_INT_MAX
;
251 $smaxage = PHP_INT_MAX
;
252 foreach ( $modules as $name ) {
253 $mtime = max( $mtime, self
::$modules[$name]->getModifiedTime( $context ) );
254 $maxage = min( $maxage, self
::$modules[$name]->getClientMaxage() );
255 $smaxage = min( $smaxage, self
::$modules[$name]->getServerMaxage() );
259 if ( $context->getOnly() === 'styles' ) {
260 header( 'Content-Type: text/css' );
262 header( 'Content-Type: text/javascript' );
264 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
265 $expires = wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() );
266 header( "Cache-Control: public, maxage=$maxage, s-maxage=$smaxage" );
267 header( "Expires: $expires" );
269 // Check if there's an If-Modified-Since header and respond with a 304 Not Modified if possible
270 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
271 if ( $ims !== false && wfTimestamp( TS_UNIX
, $ims ) == $mtime ) {
272 header( 'HTTP/1.0 304 Not Modified' );
273 header( 'Status: 304 Not Modified' );
277 // Use output buffering
281 $blobs = $context->shouldIncludeMessages() ?
282 MessageBlobStore
::get( $modules, $context->getLanguage() ) : array();
285 foreach ( $modules as $name ) {
288 if ( $context->shouldIncludeScripts() ) {
289 $scripts .= self
::$modules[$name]->getScript( $context );
294 $context->shouldIncludeStyles() &&
295 ( $styles .= self
::$modules[$name]->getStyle( $context ) ) !== ''
297 if ( $context->getDirection() == 'rtl' ) {
298 $styles = self
::filter( 'flip-css', $styles );
300 $styles = $context->getDebug() ?
$styles : self
::filter( 'minify-css', $styles );
303 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
305 if ( $context->getOnly() === 'styles' ) {
307 } else if ( $context->getOnly() === 'scripts' ) {
309 } else if ( $context->getOnly() === 'messages' ) {
310 echo "mediaWiki.msg.set( $messages );\n";
312 $styles = Xml
::escapeJsString( $styles );
313 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n'$styles',\n$messages );\n";
316 // Update the status of script-only modules
317 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
319 foreach ( $modules as $name ) {
320 $statuses[$name] = 'ready';
322 $statuses = FormatJson
::encode( $statuses );
323 echo "mediaWiki.loader.state( $statuses );";
325 // Register missing modules
326 if ( $context->shouldIncludeScripts() ) {
327 foreach ( $missing as $name ) {
328 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
331 // Output the appropriate header
332 if ( $context->getOnly() !== 'styles' ) {
333 if ( $context->getDebug() ) {
336 echo self
::filter( 'minify-js', ob_get_clean() );
343 require_once "$IP/resources/Resources.php";