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 $modules = array();
35 /* Protected Methods */
38 * Loads information stored in the database about modules
40 * This is not inside the module code because it's so much more performant to request all of the information at once
41 * than it is to have each module requests it's own information.
43 * @param $modules array list of module names to preload information for
44 * @param $context ResourceLoaderContext context to load the information within
46 protected function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
47 if ( !count( $modules ) ) {
48 return; # or Database*::select() will explode
50 $dbr = wfGetDb( DB_SLAVE
);
51 $skin = $context->getSkin();
52 $lang = $context->getLanguage();
54 // Get file dependency information
55 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
56 'md_module' => $modules,
57 'md_skin' => $context->getSkin()
61 $modulesWithDeps = array();
62 foreach ( $res as $row ) {
63 $this->modules
[$row->md_module
]->setFileDependencies( $skin,
64 FormatJson
::decode( $row->md_deps
, true )
66 $modulesWithDeps[] = $row->md_module
;
68 // Register the absence of a dependencies row too
69 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
70 $this->modules
[$name]->setFileDependencies( $skin, array() );
73 // Get message blob mtimes. Only do this for modules with messages
74 $modulesWithMessages = array();
75 $modulesWithoutMessages = array();
76 foreach ( $modules as $name ) {
77 if ( count( $this->modules
[$name]->getMessages() ) ) {
78 $modulesWithMessages[] = $name;
80 $modulesWithoutMessages[] = $name;
83 if ( count( $modulesWithMessages ) ) {
84 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
85 'mr_resource' => $modulesWithMessages,
89 foreach ( $res as $row ) {
90 $this->modules
[$row->mr_resource
]->setMsgBlobMtime( $lang, $row->mr_timestamp
);
93 foreach ( $modulesWithoutMessages as $name ) {
94 $this->modules
[$name]->setMsgBlobMtime( $lang, 0 );
99 * Runs text through a filter, caching the filtered result for future calls
101 * @param $filter String: name of filter to run
102 * @param $data String: text to filter, such as JavaScript or CSS text
103 * @param $file String: path to file being filtered, (optional: only required for CSS to resolve paths)
104 * @return String: filtered data
106 protected function filter( $filter, $data ) {
108 wfProfileIn( __METHOD__
);
110 // For empty or whitespace-only things, don't do any processing
111 if ( trim( $data ) === '' ) {
112 wfProfileOut( __METHOD__
);
117 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
118 $cached = $wgMemc->get( $key );
120 if ( $cached !== false && $cached !== null ) {
121 wfProfileOut( __METHOD__
);
129 $result = JSMin
::minify( $data );
132 $result = CSSMin
::minify( $data );
135 $result = CSSJanus
::transform( $data, true, false );
138 // Don't cache anything, just pass right through
139 wfProfileOut( __METHOD__
);
142 } catch ( Exception
$exception ) {
143 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
147 $wgMemc->set( $key, $result );
149 wfProfileOut( __METHOD__
);
156 * Registers core modules and runs registration hooks
158 public function __construct() {
161 wfProfileIn( __METHOD__
);
163 // Register core modules
164 $this->register( include( "$IP/resources/Resources.php" ) );
165 // Register extension modules
166 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
168 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 function register( $name, ResourceLoaderModule
$object = null ) {
188 wfProfileIn( __METHOD__
);
190 // Allow multiple modules to be registered in one call
191 if ( is_array( $name ) && !isset( $object ) ) {
192 foreach ( $name as $key => $value ) {
193 $this->register( $key, $value );
196 wfProfileOut( __METHOD__
);
200 // Disallow duplicate registrations
201 if ( isset( $this->modules
[$name] ) ) {
202 // A module has already been registered by this name
203 throw new MWException( 'Another module has already been registered as ' . $name );
206 // Validate the input (type hinting lets null through)
207 if ( !( $object instanceof ResourceLoaderModule
) ) {
208 throw new MWException( 'Invalid ResourceLoader module error. Instances of ResourceLoaderModule expected.' );
212 $this->modules
[$name] = $object;
213 $object->setName( $name );
215 wfProfileOut( __METHOD__
);
219 * Gets a map of all modules and their options
221 * @return Array: array( modulename => ResourceLoaderModule )
223 public function getModules() {
224 return $this->modules
;
228 * Get the ResourceLoaderModule object for a given module name
230 * @param $name String: module name
231 * @return mixed ResourceLoaderModule or null if not registered
233 public function getModule( $name ) {
234 return isset( $this->modules
[$name] ) ?
$this->modules
[$name] : null;
238 * Outputs a response to a resource load-request, including a content-type header
240 * @param $context ResourceLoaderContext object
242 public function respond( ResourceLoaderContext
$context ) {
243 global $wgResourceLoaderMaxage;
245 wfProfileIn( __METHOD__
);
247 // Split requested modules into two groups, modules and missing
251 foreach ( $context->getModules() as $name ) {
252 if ( isset( $this->modules
[$name] ) ) {
253 $modules[$name] = $this->modules
[$name];
259 // If a version wasn't specified we need a shorter expiry time for updates to
260 // propagate to clients quickly
261 if ( is_null( $context->getVersion() ) ) {
262 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
263 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
265 // If a version was specified we can use a longer expiry time since changing
266 // version numbers causes cache misses
268 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
269 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
272 // Preload information needed to the mtime calculation below
273 $this->preloadModuleInfo( array_keys( $modules ), $context );
275 // To send Last-Modified and support If-Modified-Since, we need to detect
276 // the last modified time
277 wfProfileIn( __METHOD__
.'-getModifiedTime' );
279 foreach ( $modules as $module ) {
280 // Bypass squid cache if the request includes any private modules
281 if ( $module->getGroup() === 'private' ) {
284 // Calculate maximum modified time
285 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
287 wfProfileOut( __METHOD__
.'-getModifiedTime' );
289 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ?
'text/css' : 'text/javascript' ) );
290 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
291 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
292 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
294 // If there's an If-Modified-Since header, respond with a 304 appropriately
295 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
296 if ( $ims !== false && $mtime <= wfTimestamp( TS_UNIX
, $ims ) ) {
297 header( 'HTTP/1.0 304 Not Modified' );
298 header( 'Status: 304 Not Modified' );
299 wfProfileOut( __METHOD__
);
303 echo $this->makeModuleResponse( $context, $modules, $missing );
305 wfProfileOut( __METHOD__
);
308 public function makeModuleResponse( ResourceLoaderContext
$context, array $modules, $missing = null ) {
310 $blobs = $context->shouldIncludeMessages() ?
311 MessageBlobStore
::get( $this, $modules, $context->getLanguage() ) : array();
315 foreach ( $modules as $name => $module ) {
316 wfProfileIn( __METHOD__
. '-' . $name );
320 if ( $context->shouldIncludeScripts() ) {
321 $scripts .= $module->getScript( $context ) . "\n";
327 $context->shouldIncludeStyles() &&
328 ( count( $styles = $module->getStyles( $context ) ) )
330 // Flip CSS on a per-module basis
331 if ( $this->modules
[$name]->getFlip( $context ) ) {
332 foreach ( $styles as $media => $style ) {
333 $styles[$media] = $this->filter( 'flip-css', $style );
339 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
342 switch ( $context->getOnly() ) {
347 $out .= self
::makeCombinedStyles( $styles );
350 $out .= self
::makeMessageSetScript( $messages );
353 // Minify CSS before embedding in mediaWiki.loader.implement call (unless in debug mode)
354 if ( !$context->getDebug() ) {
355 foreach ( $styles as $media => $style ) {
356 $styles[$media] = $this->filter( 'minify-css', $style );
359 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles, $messages );
363 wfProfileOut( __METHOD__
. '-' . $name );
366 // Update module states
367 if ( $context->shouldIncludeScripts() ) {
368 // Set the state of modules loaded as only scripts to ready
369 if ( count( $modules ) && $context->getOnly() === 'scripts' && !isset( $modules['startup'] ) ) {
370 $out .= self
::makeLoaderStateScript( array_fill_keys( array_keys( $modules ), 'ready' ) );
372 // Set the state of modules which were requested but unavailable as missing
373 if ( is_array( $missing ) && count( $missing ) ) {
374 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
378 if ( $context->getDebug() ) {
381 if ( $context->getOnly() === 'styles' ) {
382 return $this->filter( 'minify-css', $out );
384 return $this->filter( 'minify-js', $out );
391 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
392 if ( is_array( $scripts ) ) {
393 $scripts = implode( $scripts, "\n" );
395 if ( is_array( $styles ) ) {
396 $styles = count( $styles ) ? FormatJson
::encode( $styles ) : 'null';
398 if ( is_array( $messages ) ) {
399 $messages = count( $messages ) ? FormatJson
::encode( $messages ) : 'null';
401 return "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
404 public static function makeMessageSetScript( $messages ) {
405 if ( is_array( $messages ) ) {
406 $messages = count( $messages ) ? FormatJson
::encode( $messages ) : 'null';
408 return "mediaWiki.msg.set( $messages );\n";
411 public static function makeCombinedStyles( array $styles ) {
413 foreach ( $styles as $media => $style ) {
414 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
419 public static function makeLoaderStateScript( $name, $state = null ) {
420 if ( is_array( $name ) ) {
421 $statuses = FormatJson
::encode( $name );
422 return "mediaWiki.loader.state( $statuses );\n";
424 $name = Xml
::escapeJsString( $name );
425 $state = Xml
::escapeJsString( $state );
426 return "mediaWiki.loader.state( '$name', '$state' );\n";
430 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
431 $name = Xml
::escapeJsString( $name );
432 $version = (int) $version > 1 ?
(int) $version : 1;
433 if ( is_array( $dependencies ) ) {
434 $dependencies = FormatJson
::encode( $dependencies );
435 } else if ( is_string( $dependencies ) ) {
436 $dependencies = "'" . Xml
::escapeJsString( $dependencies ) . "'";
438 $dependencies = 'null';
440 if ( is_string( $group ) ) {
441 $group = "'" . Xml
::escapeJsString( $group ) . "'";
445 $script = str_replace( "\n", "\n\t", trim( $script ) );
446 return "( function( name, version, dependencies, group ) {\n\t$script\n} )" .
447 "( '$name', $version, $dependencies, $group );\n";
450 public static function makeLoaderRegisterScript( $name, $version = null, $dependencies = null, $group = null ) {
451 if ( is_array( $name ) ) {
452 $registrations = FormatJson
::encode( $name );
453 return "mediaWiki.loader.register( $registrations );\n";
455 $name = Xml
::escapeJsString( $name );
456 $version = (int) $version > 1 ?
(int) $version : 1;
457 if ( is_array( $dependencies ) ) {
458 $dependencies = FormatJson
::encode( $dependencies );
459 } else if ( is_string( $dependencies ) ) {
460 $dependencies = "'" . Xml
::escapeJsString( $dependencies ) . "'";
462 $dependencies = 'null';
464 if ( is_string( $group ) ) {
465 $group = "'" . Xml
::escapeJsString( $group ) . "'";
469 return "mediaWiki.loader.register( '$name', $version, $dependencies, $group );\n";
473 public static function makeLoaderConditionalScript( $script ) {
474 $script = str_replace( "\n", "\n\t", trim( $script ) );
475 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
478 public static function makeConfigSetScript( array $configuration ) {
479 $configuration = FormatJson
::encode( $configuration );
480 return "mediaWiki.config.set( $configuration );\n";