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
23 defined( 'MEDIAWIKI' ) ||
die( 1 );
26 * Dynamic JavaScript and CSS resource loading system
28 class ResourceLoader
{
30 /* Protected Static Members */
32 // @var array list of module name/ResourceLoaderModule object pairs
33 protected static $modules = array();
34 protected static $initialized = false;
36 /* Protected Static Methods */
39 * Registers core modules and runs registration hooks
41 protected static function initialize() {
44 // Safety check - this should never be called more than once
45 if ( !self
::$initialized ) {
46 wfProfileIn( __METHOD__
);
47 // This needs to be first, because hooks might call ResourceLoader
48 // public interfaces which will call this
49 self
::$initialized = true;
50 self
::register( include( "$IP/resources/Resources.php" ) );
51 wfRunHooks( 'ResourceLoaderRegisterModules' );
52 wfProfileOut( __METHOD__
);
57 * Loads information stored in the database about modules
59 * This is not inside the module code because it's so much more performant to request all of the information at once
60 * than it is to have each module requests it's own information.
62 * @param $modules array list of module names to preload information for
63 * @param $context ResourceLoaderContext context to load the information within
65 protected static function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
66 $dbr = wfGetDb( DB_SLAVE
);
67 $skin = $context->getSkin();
68 $lang = $context->getLanguage();
70 // Get file dependency information
71 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
72 'md_module' => $modules,
73 'md_skin' => $context->getSkin()
77 $modulesWithDeps = array();
78 foreach ( $res as $row ) {
79 self
::$modules[$row->md_module
]->setFileDependencies( $skin,
80 FormatJson
::decode( $row->md_deps
, true )
82 $modulesWithDeps[] = $row->md_module
;
84 // Register the absence of a dependencies row too
85 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
86 self
::$modules[$name]->setFileDependencies( $skin, array() );
89 // Get message blob mtimes. Only do this for modules with messages
90 $modulesWithMessages = array();
91 $modulesWithoutMessages = array();
92 foreach ( $modules as $name ) {
93 if ( count( self
::$modules[$name]->getMessages() ) ) {
94 $modulesWithMessages[] = $name;
96 $modulesWithoutMessages[] = $name;
99 if ( count( $modulesWithMessages ) ) {
100 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
101 'mr_resource' => $modulesWithMessages,
105 foreach ( $res as $row ) {
106 self
::$modules[$row->mr_resource
]->setMsgBlobMtime( $lang, $row->mr_timestamp
);
109 foreach ( $modulesWithoutMessages as $name ) {
110 self
::$modules[$name]->setMsgBlobMtime( $lang, 0 );
115 * Runs text through a filter, caching the filtered result for future calls
117 * @param $filter String: name of filter to run
118 * @param $data String: text to filter, such as JavaScript or CSS text
119 * @param $file String: path to file being filtered, (optional: only required for CSS to resolve paths)
120 * @return String: filtered data
122 protected static function filter( $filter, $data ) {
124 wfProfileIn( __METHOD__
);
126 // For empty or whitespace-only things, don't do any processing
127 if ( trim( $data ) === '' ) {
128 wfProfileOut( __METHOD__
);
133 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
134 $cached = $wgMemc->get( $key );
136 if ( $cached !== false && $cached !== null ) {
137 wfProfileOut( __METHOD__
);
145 $result = JSMin
::minify( $data );
148 $result = CSSMin
::minify( $data );
151 $result = CSSJanus
::transform( $data, true, false );
154 // Don't cache anything, just pass right through
155 wfProfileOut( __METHOD__
);
158 } catch ( Exception
$exception ) {
159 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
163 $wgMemc->set( $key, $result );
165 wfProfileOut( __METHOD__
);
172 * Registers a module with the ResourceLoader system.
174 * Note that registering the same object under multiple names is not supported
175 * and may silently fail in all kinds of interesting ways.
177 * @param $name Mixed: string of name of module or array of name/object pairs
178 * @param $object ResourceLoaderModule: module object (optional when using
179 * multiple-registration calling style)
180 * @return Boolean: false if there were any errors, in which case one or more
181 * modules were not registered
183 * @todo We need much more clever error reporting, not just in detailing what
184 * happened, but in bringing errors to the client in a way that they can
185 * easily see them if they want to, such as by using FireBug
187 public static function register( $name, ResourceLoaderModule
$object = null ) {
188 wfProfileIn( __METHOD__
);
191 // Allow multiple modules to be registered in one call
192 if ( is_array( $name ) && !isset( $object ) ) {
193 foreach ( $name as $key => $value ) {
194 self
::register( $key, $value );
197 wfProfileOut( __METHOD__
);
201 // Disallow duplicate registrations
202 if ( isset( self
::$modules[$name] ) ) {
203 // A module has already been registered by this name
204 throw new MWException( 'Another module has already been registered as ' . $name );
207 self
::$modules[$name] = $object;
208 $object->setName( $name );
209 wfProfileOut( __METHOD__
);
213 * Gets a map of all modules and their options
215 * @return Array: array( modulename => ResourceLoaderModule )
217 public static function getModules() {
221 return self
::$modules;
225 * Get the ResourceLoaderModule object for a given module name
227 * @param $name String: module name
228 * @return mixed ResourceLoaderModule or null if not registered
230 public static function getModule( $name ) {
234 return isset( self
::$modules[$name] ) ? self
::$modules[$name] : null;
238 * Get the highest modification time of all modules, based on a given
239 * combination of language code, skin name and debug mode flag.
241 * @param $context ResourceLoaderContext object
242 * @return Integer: UNIX timestamp
244 public static function getHighestModifiedTime( ResourceLoaderContext
$context ) {
248 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
250 foreach ( self
::$modules as $module ) {
251 $time = max( $time, $module->getModifiedTime( $context ) );
258 * Outputs a response to a resource load-request, including a content-type header
260 * @param $context ResourceLoaderContext object
262 public static function respond( ResourceLoaderContext
$context ) {
263 global $wgResourceLoaderMaxage;
265 wfProfileIn( __METHOD__
);
268 // Split requested modules into two groups, modules and missing
272 foreach ( $context->getModules() as $name ) {
273 if ( isset( self
::$modules[$name] ) ) {
274 $modules[$name] = self
::$modules[$name];
280 // If a version wasn't specified we need a shorter expiry time for updates to
281 // propagate to clients quickly
282 if ( is_null( $context->getVersion() ) ) {
283 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
284 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
286 // If a version was specified we can use a longer expiry time since changing
287 // version numbers causes cache misses
289 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
290 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
293 // Preload information needed to the mtime calculation below
294 self
::preloadModuleInfo( array_keys( $modules ), $context );
296 // To send Last-Modified and support If-Modified-Since, we need to detect
297 // the last modified time
298 wfProfileIn( __METHOD__
.'-getModifiedTime' );
300 foreach ( $modules as $module ) {
301 // Bypass squid cache if the request includes any private modules
302 if ( $module->getGroup() === 'private' ) {
305 // Calculate maximum modified time
306 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
308 wfProfileOut( __METHOD__
.'-getModifiedTime' );
310 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ?
'text/css' : 'text/javascript' ) );
311 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
312 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
313 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
315 // If there's an If-Modified-Since header, respond with a 304 appropriately
316 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
317 if ( $ims !== false && $mtime >= wfTimestamp( TS_UNIX
, $ims ) ) {
318 header( 'HTTP/1.0 304 Not Modified' );
319 header( 'Status: 304 Not Modified' );
320 wfProfileOut( __METHOD__
);
324 echo self
::makeModuleResponse( $context, $modules, $missing );
326 wfProfileOut( __METHOD__
);
329 public static function makeModuleResponse( ResourceLoaderContext
$context, array $modules, $missing = null ) {
333 $blobs = $context->shouldIncludeMessages() ?
334 MessageBlobStore
::get( array_keys( $modules ), $context->getLanguage() ) : array();
338 foreach ( $modules as $name => $module ) {
339 wfProfileIn( __METHOD__
. '-' . $name );
343 if ( $context->shouldIncludeScripts() ) {
344 $scripts .= $module->getScript( $context ) . "\n";
350 $context->shouldIncludeStyles() &&
351 ( count( $styles = $module->getStyles( $context ) ) )
353 // Flip CSS on a per-module basis
354 if ( self
::$modules[$name]->getFlip( $context ) ) {
355 foreach ( $styles as $media => $style ) {
356 $styles[$media] = self
::filter( 'flip-css', $style );
362 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
365 switch ( $context->getOnly() ) {
370 $out .= self
::makeCombinedStyles( $styles );
373 $out .= self
::makeMessageSetScript( $messages );
376 // Minify CSS before embedding in mediaWiki.loader.implement call (unless in debug mode)
377 if ( !$context->getDebug() ) {
378 foreach ( $styles as $media => $style ) {
379 $styles[$media] = self
::filter( 'minify-css', $style );
382 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles, $messages );
386 wfProfileOut( __METHOD__
. '-' . $name );
389 // Update module states
390 if ( $context->shouldIncludeScripts() ) {
391 // Set the state of modules loaded as only scripts to ready
392 if ( count( $modules ) && $context->getOnly() === 'scripts' && !isset( $modules['startup'] ) ) {
393 $out .= self
::makeLoaderStateScript( array_fill_keys( array_keys( $modules ), 'ready' ) );
395 // Set the state of modules which were requested but unavailable as missing
396 if ( is_array( $missing ) && count( $missing ) ) {
397 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
401 if ( $context->getDebug() ) {
404 if ( $context->getOnly() === 'styles' ) {
405 return self
::filter( 'minify-css', $out );
407 return self
::filter( 'minify-js', $out );
412 // Client code generation methods
414 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
415 if ( is_array( $scripts ) ) {
416 $scripts = implode( $scripts, "\n" );
418 if ( is_array( $styles ) ) {
419 $styles = count( $styles ) ? FormatJson
::encode( $styles ) : 'null';
421 if ( is_array( $messages ) ) {
422 $messages = count( $messages ) ? FormatJson
::encode( $messages ) : 'null';
424 return "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
427 public static function makeMessageSetScript( $messages ) {
428 if ( is_array( $messages ) ) {
429 $messages = count( $messages ) ? FormatJson
::encode( $messages ) : 'null';
431 return "mediaWiki.msg.set( $messages );\n";
434 public static function makeCombinedStyles( array $styles ) {
436 foreach ( $styles as $media => $style ) {
437 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
442 public static function makeLoaderStateScript( $name, $state = null ) {
443 if ( is_array( $name ) ) {
444 $statuses = FormatJson
::encode( $name );
445 return "mediaWiki.loader.state( $statuses );\n";
447 $name = Xml
::escapeJsString( $name );
448 $name = Xml
::escapeJsString( $state );
449 return "mediaWiki.loader.state( '$name', '$state' );\n";
453 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
454 $name = Xml
::escapeJsString( $name );
455 $version = (int) $version > 1 ?
(int) $version : 1;
456 if ( is_array( $dependencies ) ) {
457 $dependencies = FormatJson
::encode( $dependencies );
458 } else if ( is_string( $dependencies ) ) {
459 $dependencies = "'" . Xml
::escapeJsString( $dependencies ) . "'";
461 $dependencies = 'null';
463 if ( is_string( $group ) ) {
464 $group = "'" . Xml
::escapeJsString( $group ) . "'";
468 $script = str_replace( "\n", "\n\t", trim( $script ) );
469 return "( function( name, version, dependencies ) {\n\t$script\n} )" .
470 "( '$name', $version, $dependencies, $group );\n";
473 public static function makeLoaderRegisterScript( $name, $version = null, $dependencies = null, $group = null ) {
474 if ( is_array( $name ) ) {
475 $registrations = FormatJson
::encode( $name );
476 return "mediaWiki.loader.register( $registrations );\n";
478 $name = Xml
::escapeJsString( $name );
479 $version = (int) $version > 1 ?
(int) $version : 1;
480 if ( is_array( $dependencies ) ) {
481 $dependencies = FormatJson
::encode( $dependencies );
482 } else if ( is_string( $dependencies ) ) {
483 $dependencies = "'" . Xml
::escapeJsString( $dependencies ) . "'";
485 $dependencies = 'null';
487 if ( is_string( $group ) ) {
488 $group = "'" . Xml
::escapeJsString( $group ) . "'";
492 return "mediaWiki.loader.register( '$name', $version, $dependencies, $group );\n";
496 public static function makeLoaderConditionalScript( $script ) {
497 $script = str_replace( "\n", "\n\t", trim( $script ) );
498 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
501 public static function makeConfigSetScript( array $configuration ) {
502 $configuration = FormatJson
::encode( $configuration );
503 return "mediaWiki.config.set( $configuration );\n";