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 $dbr = wfGetDb( DB_SLAVE
);
48 $skin = $context->getSkin();
49 $lang = $context->getLanguage();
51 // Get file dependency information
52 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
53 'md_module' => $modules,
54 'md_skin' => $context->getSkin()
58 $modulesWithDeps = array();
59 foreach ( $res as $row ) {
60 $this->modules
[$row->md_module
]->setFileDependencies( $skin,
61 FormatJson
::decode( $row->md_deps
, true )
63 $modulesWithDeps[] = $row->md_module
;
65 // Register the absence of a dependencies row too
66 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
67 $this->modules
[$name]->setFileDependencies( $skin, array() );
70 // Get message blob mtimes. Only do this for modules with messages
71 $modulesWithMessages = array();
72 $modulesWithoutMessages = array();
73 foreach ( $modules as $name ) {
74 if ( count( $this->modules
[$name]->getMessages() ) ) {
75 $modulesWithMessages[] = $name;
77 $modulesWithoutMessages[] = $name;
80 if ( count( $modulesWithMessages ) ) {
81 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
82 'mr_resource' => $modulesWithMessages,
86 foreach ( $res as $row ) {
87 $this->modules
[$row->mr_resource
]->setMsgBlobMtime( $lang, $row->mr_timestamp
);
90 foreach ( $modulesWithoutMessages as $name ) {
91 $this->modules
[$name]->setMsgBlobMtime( $lang, 0 );
96 * Runs text through a filter, caching the filtered result for future calls
98 * @param $filter String: name of filter to run
99 * @param $data String: text to filter, such as JavaScript or CSS text
100 * @param $file String: path to file being filtered, (optional: only required for CSS to resolve paths)
101 * @return String: filtered data
103 protected function filter( $filter, $data ) {
105 wfProfileIn( __METHOD__
);
107 // For empty or whitespace-only things, don't do any processing
108 if ( trim( $data ) === '' ) {
109 wfProfileOut( __METHOD__
);
114 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
115 $cached = $wgMemc->get( $key );
117 if ( $cached !== false && $cached !== null ) {
118 wfProfileOut( __METHOD__
);
126 $result = JSMin
::minify( $data );
129 $result = CSSMin
::minify( $data );
132 $result = CSSJanus
::transform( $data, true, false );
135 // Don't cache anything, just pass right through
136 wfProfileOut( __METHOD__
);
139 } catch ( Exception
$exception ) {
140 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
144 $wgMemc->set( $key, $result );
146 wfProfileOut( __METHOD__
);
153 * Registers core modules and runs registration hooks
155 public function __construct() {
158 wfProfileIn( __METHOD__
);
160 // Register core modules
161 $this->register( include( "$IP/resources/Resources.php" ) );
162 // Register extension modules
163 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
165 wfProfileOut( __METHOD__
);
169 * Registers a module with the ResourceLoader system.
171 * Note that registering the same object under multiple names is not supported
172 * and may silently fail in all kinds of interesting ways.
174 * @param $name Mixed: string of name of module or array of name/object pairs
175 * @param $object ResourceLoaderModule: module object (optional when using
176 * multiple-registration calling style)
177 * @return Boolean: false if there were any errors, in which case one or more
178 * modules were not registered
180 * @todo We need much more clever error reporting, not just in detailing what
181 * happened, but in bringing errors to the client in a way that they can
182 * easily see them if they want to, such as by using FireBug
184 public function register( $name, ResourceLoaderModule
$object = null ) {
185 wfProfileIn( __METHOD__
);
187 // Allow multiple modules to be registered in one call
188 if ( is_array( $name ) && !isset( $object ) ) {
189 foreach ( $name as $key => $value ) {
190 $this->register( $key, $value );
193 wfProfileOut( __METHOD__
);
197 // Disallow duplicate registrations
198 if ( isset( $this->modules
[$name] ) ) {
199 // A module has already been registered by this name
200 throw new MWException( 'Another module has already been registered as ' . $name );
203 $this->modules
[$name] = $object;
204 $object->setName( $name );
206 wfProfileOut( __METHOD__
);
210 * Gets a map of all modules and their options
212 * @return Array: array( modulename => ResourceLoaderModule )
214 public function getModules() {
215 return $this->modules
;
219 * Get the ResourceLoaderModule object for a given module name
221 * @param $name String: module name
222 * @return mixed ResourceLoaderModule or null if not registered
224 public function getModule( $name ) {
225 return isset( $this->modules
[$name] ) ?
$this->modules
[$name] : null;
229 * Outputs a response to a resource load-request, including a content-type header
231 * @param $context ResourceLoaderContext object
233 public function respond( ResourceLoaderContext
$context ) {
234 global $wgResourceLoaderMaxage;
236 wfProfileIn( __METHOD__
);
238 // Split requested modules into two groups, modules and missing
242 foreach ( $context->getModules() as $name ) {
243 if ( isset( $this->modules
[$name] ) ) {
244 $modules[$name] = $this->modules
[$name];
250 // If a version wasn't specified we need a shorter expiry time for updates to
251 // propagate to clients quickly
252 if ( is_null( $context->getVersion() ) ) {
253 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
254 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
256 // If a version was specified we can use a longer expiry time since changing
257 // version numbers causes cache misses
259 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
260 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
263 // Preload information needed to the mtime calculation below
264 $this->preloadModuleInfo( array_keys( $modules ), $context );
266 // To send Last-Modified and support If-Modified-Since, we need to detect
267 // the last modified time
268 wfProfileIn( __METHOD__
.'-getModifiedTime' );
270 foreach ( $modules as $module ) {
271 // Bypass squid cache if the request includes any private modules
272 if ( $module->getGroup() === 'private' ) {
275 // Calculate maximum modified time
276 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
278 wfProfileOut( __METHOD__
.'-getModifiedTime' );
280 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ?
'text/css' : 'text/javascript' ) );
281 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
282 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
283 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
285 // If there's an If-Modified-Since header, respond with a 304 appropriately
286 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
287 if ( $ims !== false && $mtime >= wfTimestamp( TS_UNIX
, $ims ) ) {
288 header( 'HTTP/1.0 304 Not Modified' );
289 header( 'Status: 304 Not Modified' );
290 wfProfileOut( __METHOD__
);
294 echo self
::makeModuleResponse( $context, $modules, $missing );
296 wfProfileOut( __METHOD__
);
299 public function makeModuleResponse( ResourceLoaderContext
$context, array $modules, $missing = null ) {
301 $blobs = $context->shouldIncludeMessages() ?
302 MessageBlobStore
::get( $modules, $context->getLanguage() ) : array();
306 foreach ( $modules as $name => $module ) {
307 wfProfileIn( __METHOD__
. '-' . $name );
311 if ( $context->shouldIncludeScripts() ) {
312 $scripts .= $module->getScript( $context ) . "\n";
318 $context->shouldIncludeStyles() &&
319 ( count( $styles = $module->getStyles( $context ) ) )
321 // Flip CSS on a per-module basis
322 if ( $this->modules
[$name]->getFlip( $context ) ) {
323 foreach ( $styles as $media => $style ) {
324 $styles[$media] = $this->filter( 'flip-css', $style );
330 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
333 switch ( $context->getOnly() ) {
338 $out .= self
::makeCombinedStyles( $styles );
341 $out .= self
::makeMessageSetScript( $messages );
344 // Minify CSS before embedding in mediaWiki.loader.implement call (unless in debug mode)
345 if ( !$context->getDebug() ) {
346 foreach ( $styles as $media => $style ) {
347 $styles[$media] = $this->filter( 'minify-css', $style );
350 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles, $messages );
354 wfProfileOut( __METHOD__
. '-' . $name );
357 // Update module states
358 if ( $context->shouldIncludeScripts() ) {
359 // Set the state of modules loaded as only scripts to ready
360 if ( count( $modules ) && $context->getOnly() === 'scripts' && !isset( $modules['startup'] ) ) {
361 $out .= self
::makeLoaderStateScript( array_fill_keys( array_keys( $modules ), 'ready' ) );
363 // Set the state of modules which were requested but unavailable as missing
364 if ( is_array( $missing ) && count( $missing ) ) {
365 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
369 if ( $context->getDebug() ) {
372 if ( $context->getOnly() === 'styles' ) {
373 return $this->filter( 'minify-css', $out );
375 return $this->filter( 'minify-js', $out );
382 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
383 if ( is_array( $scripts ) ) {
384 $scripts = implode( $scripts, "\n" );
386 if ( is_array( $styles ) ) {
387 $styles = count( $styles ) ? FormatJson
::encode( $styles ) : 'null';
389 if ( is_array( $messages ) ) {
390 $messages = count( $messages ) ? FormatJson
::encode( $messages ) : 'null';
392 return "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
395 public static function makeMessageSetScript( $messages ) {
396 if ( is_array( $messages ) ) {
397 $messages = count( $messages ) ? FormatJson
::encode( $messages ) : 'null';
399 return "mediaWiki.msg.set( $messages );\n";
402 public static function makeCombinedStyles( array $styles ) {
404 foreach ( $styles as $media => $style ) {
405 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
410 public static function makeLoaderStateScript( $name, $state = null ) {
411 if ( is_array( $name ) ) {
412 $statuses = FormatJson
::encode( $name );
413 return "mediaWiki.loader.state( $statuses );\n";
415 $name = Xml
::escapeJsString( $name );
416 $name = Xml
::escapeJsString( $state );
417 return "mediaWiki.loader.state( '$name', '$state' );\n";
421 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
422 $name = Xml
::escapeJsString( $name );
423 $version = (int) $version > 1 ?
(int) $version : 1;
424 if ( is_array( $dependencies ) ) {
425 $dependencies = FormatJson
::encode( $dependencies );
426 } else if ( is_string( $dependencies ) ) {
427 $dependencies = "'" . Xml
::escapeJsString( $dependencies ) . "'";
429 $dependencies = 'null';
431 if ( is_string( $group ) ) {
432 $group = "'" . Xml
::escapeJsString( $group ) . "'";
436 $script = str_replace( "\n", "\n\t", trim( $script ) );
437 return "( function( name, version, dependencies ) {\n\t$script\n} )" .
438 "( '$name', $version, $dependencies, $group );\n";
441 public static function makeLoaderRegisterScript( $name, $version = null, $dependencies = null, $group = null ) {
442 if ( is_array( $name ) ) {
443 $registrations = FormatJson
::encode( $name );
444 return "mediaWiki.loader.register( $registrations );\n";
446 $name = Xml
::escapeJsString( $name );
447 $version = (int) $version > 1 ?
(int) $version : 1;
448 if ( is_array( $dependencies ) ) {
449 $dependencies = FormatJson
::encode( $dependencies );
450 } else if ( is_string( $dependencies ) ) {
451 $dependencies = "'" . Xml
::escapeJsString( $dependencies ) . "'";
453 $dependencies = 'null';
455 if ( is_string( $group ) ) {
456 $group = "'" . Xml
::escapeJsString( $group ) . "'";
460 return "mediaWiki.loader.register( '$name', $version, $dependencies, $group );\n";
464 public static function makeLoaderConditionalScript( $script ) {
465 $script = str_replace( "\n", "\n\t", trim( $script ) );
466 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
469 public static function makeConfigSetScript( array $configuration ) {
470 $configuration = FormatJson
::encode( $configuration );
471 return "mediaWiki.config.set( $configuration );\n";