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
24 * Dynamic JavaScript and CSS resource loading system.
26 * Most of the documention is on the MediaWiki documentation wiki starting at:
27 * http://www.mediawiki.org/wiki/ResourceLoader
29 class ResourceLoader
{
31 /* Protected Static Members */
33 /** Array: List of module name/ResourceLoaderModule object pairs */
34 protected $modules = array();
36 /* Protected Methods */
39 * Loads information stored in the database about modules.
41 * This method grabs modules dependencies from the database and updates modules
44 * This is not inside the module code because it's so much more performant to
45 * request all of the information at once than it is to have each module
46 * requests its own information. This sacrifice of modularity yields a profound
47 * performance improvement.
49 * @param $modules Array: List of module names to preload information for
50 * @param $context ResourceLoaderContext: Context to load the information within
52 protected function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
53 if ( !count( $modules ) ) {
54 return; // or else Database*::select() will explode, plus it's cheaper!
56 $dbr = wfGetDB( DB_SLAVE
);
57 $skin = $context->getSkin();
58 $lang = $context->getLanguage();
60 // Get file dependency information
61 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
62 'md_module' => $modules,
63 'md_skin' => $context->getSkin()
67 // Set modules' dependecies
68 $modulesWithDeps = array();
69 foreach ( $res as $row ) {
70 $this->modules
[$row->md_module
]->setFileDependencies( $skin,
71 FormatJson
::decode( $row->md_deps
, true )
73 $modulesWithDeps[] = $row->md_module
;
76 // Register the absence of a dependency row too
77 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
78 $this->modules
[$name]->setFileDependencies( $skin, array() );
81 // Get message blob mtimes. Only do this for modules with messages
82 $modulesWithMessages = array();
83 $modulesWithoutMessages = array();
84 foreach ( $modules as $name ) {
85 if ( count( $this->modules
[$name]->getMessages() ) ) {
86 $modulesWithMessages[] = $name;
88 $modulesWithoutMessages[] = $name;
91 if ( count( $modulesWithMessages ) ) {
92 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
93 'mr_resource' => $modulesWithMessages,
97 foreach ( $res as $row ) {
98 $this->modules
[$row->mr_resource
]->setMsgBlobMtime( $lang, $row->mr_timestamp
);
101 foreach ( $modulesWithoutMessages as $name ) {
102 $this->modules
[$name]->setMsgBlobMtime( $lang, 0 );
107 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
109 * Available filters are:
110 * - minify-js \see JSMin::minify
111 * - minify-css \see CSSMin::minify
112 * - flip-css \see CSSJanus::transform
114 * If $data is empty, only contains whitespace or the filter was unknown,
115 * $data is returned unmodified.
117 * @param $filter String: Name of filter to run
118 * @param $data String: Text to filter, such as JavaScript or CSS text
119 * @return String: Filtered data
121 protected function filter( $filter, $data ) {
122 wfProfileIn( __METHOD__
);
124 // For empty/whitespace-only data or for unknown filters, don't perform
125 // any caching or processing
126 if ( trim( $data ) === ''
127 ||
!in_array( $filter, array( 'minify-js', 'minify-css', 'flip-css' ) ) )
129 wfProfileOut( __METHOD__
);
134 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
135 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
136 $cache = wfGetCache( CACHE_ANYTHING
);
137 $cacheEntry = $cache->get( $key );
138 if ( is_string( $cacheEntry ) ) {
139 wfProfileOut( __METHOD__
);
143 // Run the filter - we've already verified one of these will work
147 $result = JSMin
::minify( $data );
150 $result = CSSMin
::minify( $data );
153 $result = CSSJanus
::transform( $data, true, false );
156 } catch ( Exception
$exception ) {
157 throw new MWException( 'ResourceLoader filter error. ' .
158 'Exception was thrown: ' . $exception->getMessage() );
161 // Save filtered text to Memcached
162 $cache->set( $key, $result );
164 wfProfileOut( __METHOD__
);
172 * Registers core modules and runs registration hooks.
174 public function __construct() {
177 wfProfileIn( __METHOD__
);
179 // Register core modules
180 $this->register( include( "$IP/resources/Resources.php" ) );
181 // Register extension modules
182 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
184 wfProfileOut( __METHOD__
);
188 * Registers a module with the ResourceLoader system.
190 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
191 * @param $object ResourceLoaderModule: Module object (optional when using
192 * multiple-registration calling style)
193 * @throws MWException: If a duplicate module registration is attempted
194 * @throws MWException: If something other than a ResourceLoaderModule is being registered
195 * @return Boolean: False if there were any errors, in which case one or more modules were not
198 public function register( $name, ResourceLoaderModule
$object = null ) {
200 wfProfileIn( __METHOD__
);
202 // Allow multiple modules to be registered in one call
203 if ( is_array( $name ) && !isset( $object ) ) {
204 foreach ( $name as $key => $value ) {
205 $this->register( $key, $value );
208 wfProfileOut( __METHOD__
);
213 // Disallow duplicate registrations
214 if ( isset( $this->modules
[$name] ) ) {
215 // A module has already been registered by this name
216 throw new MWException(
217 'ResourceLoader duplicate registration error. ' .
218 'Another module has already been registered as ' . $name
222 // Validate the input (type hinting lets null through)
223 if ( !( $object instanceof ResourceLoaderModule
) ) {
224 throw new MWException( 'ResourceLoader invalid module error. ' .
225 'Instances of ResourceLoaderModule expected.' );
229 $this->modules
[$name] = $object;
230 $object->setName( $name );
232 wfProfileOut( __METHOD__
);
236 * Gets a map of all modules and their options
238 * @return Array: List of modules keyed by module name
240 public function getModules() {
241 return $this->modules
;
245 * Get the ResourceLoaderModule object for a given module name.
247 * @param $name String: Module name
248 * @return Mixed: ResourceLoaderModule if module has been registered, null otherwise
250 public function getModule( $name ) {
251 return isset( $this->modules
[$name] ) ?
$this->modules
[$name] : null;
255 * Outputs a response to a resource load-request, including a content-type header.
257 * @param $context ResourceLoaderContext: Context in which a response should be formed
259 public function respond( ResourceLoaderContext
$context ) {
260 global $wgResourceLoaderMaxage, $wgCacheEpoch;
262 wfProfileIn( __METHOD__
);
264 // Split requested modules into two groups, modules and missing
267 foreach ( $context->getModules() as $name ) {
268 if ( isset( $this->modules
[$name] ) ) {
269 $modules[$name] = $this->modules
[$name];
275 // If a version wasn't specified we need a shorter expiry time for updates
276 // to propagate to clients quickly
277 if ( is_null( $context->getVersion() ) ) {
278 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
279 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
281 // If a version was specified we can use a longer expiry time since changing
282 // version numbers causes cache misses
284 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
285 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
288 // Preload information needed to the mtime calculation below
289 $this->preloadModuleInfo( array_keys( $modules ), $context );
291 wfProfileIn( __METHOD__
.'-getModifiedTime' );
293 // To send Last-Modified and support If-Modified-Since, we need to detect
294 // the last modified time
295 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
296 foreach ( $modules as $module ) {
297 // Bypass squid cache if the request includes any private modules
298 if ( $module->getGroup() === 'private' ) {
301 // Calculate maximum modified time
302 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
305 wfProfileOut( __METHOD__
.'-getModifiedTime' );
307 if ( $context->getOnly() === 'styles' ) {
308 header( 'Content-Type: text/css' );
310 header( 'Content-Type: text/javascript' );
312 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
313 if ( $context->getDebug() ) {
314 header( 'Cache-Control: must-revalidate' );
316 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
317 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
320 // If there's an If-Modified-Since header, respond with a 304 appropriately
321 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
322 if ( $ims !== false && $mtime <= wfTimestamp( TS_UNIX
, $ims ) ) {
323 header( 'HTTP/1.0 304 Not Modified' );
324 header( 'Status: 304 Not Modified' );
325 wfProfileOut( __METHOD__
);
329 // Generate a response
330 $response = $this->makeModuleResponse( $context, $modules, $missing );
332 // Tack on PHP warnings as a comment in debug mode
333 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
334 $response .= "/*\n$warnings\n*/";
337 // Clear any warnings from the buffer
341 wfProfileOut( __METHOD__
);
345 * Generates code for a response
347 * @param $context ResourceLoaderContext: Context in which to generate a response
348 * @param $modules Array: List of module objects keyed by module name
349 * @param $missing Array: List of unavailable modules (optional)
350 * @return String: Response data
352 public function makeModuleResponse( ResourceLoaderContext
$context,
353 array $modules, $missing = array() )
356 if ( $context->shouldIncludeMessages() ) {
357 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
364 foreach ( $modules as $name => $module ) {
366 wfProfileIn( __METHOD__
. '-' . $name );
370 if ( $context->shouldIncludeScripts() ) {
371 $scripts .= $module->getScript( $context ) . "\n";
376 if ( $context->shouldIncludeStyles() ) {
377 $styles = $module->getStyles( $context );
378 // Flip CSS on a per-module basis
379 if ( $styles && $this->modules
[$name]->getFlip( $context ) ) {
380 foreach ( $styles as $media => $style ) {
381 $styles[$media] = $this->filter( 'flip-css', $style );
387 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : array();
390 switch ( $context->getOnly() ) {
395 $out .= self
::makeCombinedStyles( $styles );
398 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
401 // Minify CSS before embedding in mediaWiki.loader.implement call
402 // (unless in debug mode)
403 if ( !$context->getDebug() ) {
404 foreach ( $styles as $media => $style ) {
405 $styles[$media] = $this->filter( 'minify-css', $style );
408 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
409 new XmlJsCode( $messagesBlob ) );
413 wfProfileOut( __METHOD__
. '-' . $name );
416 // Update module states
417 if ( $context->shouldIncludeScripts() ) {
418 // Set the state of modules loaded as only scripts to ready
419 if ( count( $modules ) && $context->getOnly() === 'scripts'
420 && !isset( $modules['startup'] ) )
422 $out .= self
::makeLoaderStateScript(
423 array_fill_keys( array_keys( $modules ), 'ready' ) );
425 // Set the state of modules which were requested but unavailable as missing
426 if ( is_array( $missing ) && count( $missing ) ) {
427 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
431 if ( $context->getDebug() ) {
434 if ( $context->getOnly() === 'styles' ) {
435 return $this->filter( 'minify-css', $out );
437 return $this->filter( 'minify-js', $out );
445 * Returns JS code to call to mediaWiki.loader.implement for a module with
448 * @param $name Module name
449 * @param $scripts Array: List of JavaScript code snippets to be executed after the
451 * @param $styles Array: List of CSS strings keyed by media type
452 * @param $messages Mixed: List of messages associated with this module. May either be an
453 * associative array mapping message key to value, or a JSON-encoded message blob containing
454 * the same data, wrapped in an XmlJsCode object.
456 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
457 if ( is_array( $scripts ) ) {
458 $scripts = implode( $scripts, "\n" );
460 return Xml
::encodeJsCall(
461 'mediaWiki.loader.implement',
464 new XmlJsCode( "function() {{$scripts}}" ),
471 * Returns JS code which, when called, will register a given list of messages.
473 * @param $messages Mixed: Either an associative array mapping message key to value, or a
474 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
476 public static function makeMessageSetScript( $messages ) {
477 return Xml
::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
481 * Combines an associative array mapping media type to CSS into a
482 * single stylesheet with @media blocks.
484 * @param $styles Array: List of CSS strings keyed by media type
486 public static function makeCombinedStyles( array $styles ) {
488 foreach ( $styles as $media => $style ) {
489 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
495 * Returns a JS call to mediaWiki.loader.state, which sets the state of a
496 * module or modules to a given value. Has two calling conventions:
498 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
499 * Set the state of a single module called $name to $state
501 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
502 * Set the state of modules with the given names to the given states
504 public static function makeLoaderStateScript( $name, $state = null ) {
505 if ( is_array( $name ) ) {
506 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name ) );
508 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name, $state ) );
513 * Returns JS code which calls the script given by $script. The script will
514 * be called with local variables name, version, dependencies and group,
515 * which will have values corresponding to $name, $version, $dependencies
516 * and $group as supplied.
518 * @param $name String: Module name
519 * @param $version Integer: Module version number as a timestamp
520 * @param $dependencies Array: List of module names on which this module depends
521 * @param $group String: Group which the module is in.
522 * @param $script String: JavaScript code
524 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
525 $script = str_replace( "\n", "\n\t", trim( $script ) );
526 return Xml
::encodeJsCall(
527 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
528 array( $name, $version, $dependencies, $group ) );
532 * Returns JS code which calls mediaWiki.loader.register with the given
533 * parameters. Has three calling conventions:
535 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
536 * Register a single module.
538 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
539 * Register modules with the given names.
541 * - ResourceLoader::makeLoaderRegisterScript( array(
542 * array( $name1, $version1, $dependencies1, $group1 ),
543 * array( $name2, $version2, $dependencies1, $group2 ),
546 * Registers modules with the given names and parameters.
548 * @param $name String: Module name
549 * @param $version Integer: Module version number as a timestamp
550 * @param $dependencies Array: List of module names on which this module depends
551 * @param $group String: group which the module is in.
553 public static function makeLoaderRegisterScript( $name, $version = null,
554 $dependencies = null, $group = null )
556 if ( is_array( $name ) ) {
557 return Xml
::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
559 $version = (int) $version > 1 ?
(int) $version : 1;
560 return Xml
::encodeJsCall( 'mediaWiki.loader.register',
561 array( $name, $version, $dependencies, $group ) );
566 * Returns JS code which runs given JS code if the client-side framework is
569 * @param $script String: JavaScript code
571 public static function makeLoaderConditionalScript( $script ) {
572 $script = str_replace( "\n", "\n\t", trim( $script ) );
573 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
577 * Returns JS code which will set the MediaWiki configuration array to
580 * @param $configuration Array: List of configuration values keyed by variable name
582 public static function makeConfigSetScript( array $configuration ) {
583 return Xml
::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
587 * Determine whether debug mode was requested
588 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
591 public static function inDebugMode() {
592 global $wgRequest, $wgResourceLoaderDebug;
593 static $retval = null;
594 if ( !is_null( $retval ) )
596 return $retval = $wgRequest->getFuzzyBool( 'debug',
597 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );