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 */
32 protected static $filterCacheVersion = 4;
34 /** Array: List of module name/ResourceLoaderModule object pairs */
35 protected $modules = array();
36 /** Associative array mapping module name to info associative array */
37 protected $moduleInfos = array();
39 /* Protected Methods */
42 * Loads information stored in the database about modules.
44 * This method grabs modules dependencies from the database and updates modules
47 * This is not inside the module code because it is much faster to
48 * request all of the information at once than it is to have each module
49 * requests its own information. This sacrifice of modularity yields a substantial
50 * performance improvement.
52 * @param $modules Array: List of module names to preload information for
53 * @param $context ResourceLoaderContext: Context to load the information within
55 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
56 if ( !count( $modules ) ) {
57 return; // or else Database*::select() will explode, plus it's cheaper!
59 $dbr = wfGetDB( DB_SLAVE
);
60 $skin = $context->getSkin();
61 $lang = $context->getLanguage();
63 // Get file dependency information
64 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
65 'md_module' => $modules,
70 // Set modules' dependencies
71 $modulesWithDeps = array();
72 foreach ( $res as $row ) {
73 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
74 FormatJson
::decode( $row->md_deps
, true )
76 $modulesWithDeps[] = $row->md_module
;
79 // Register the absence of a dependency row too
80 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
81 $this->getModule( $name )->setFileDependencies( $skin, array() );
84 // Get message blob mtimes. Only do this for modules with messages
85 $modulesWithMessages = array();
86 foreach ( $modules as $name ) {
87 if ( count( $this->getModule( $name )->getMessages() ) ) {
88 $modulesWithMessages[] = $name;
91 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
92 if ( count( $modulesWithMessages ) ) {
93 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
94 'mr_resource' => $modulesWithMessages,
98 foreach ( $res as $row ) {
99 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
100 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
101 unset( $modulesWithoutMessages[$row->mr_resource
] );
104 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
105 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
110 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
112 * Available filters are:
113 * - minify-js \see JavaScriptMinifier::minify
114 * - minify-css \see CSSMin::minify
116 * If $data is empty, only contains whitespace or the filter was unknown,
117 * $data is returned unmodified.
119 * @param $filter String: Name of filter to run
120 * @param $data String: Text to filter, such as JavaScript or CSS text
121 * @return String: Filtered data, or a comment containing an error message
123 protected function filter( $filter, $data ) {
124 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
125 wfProfileIn( __METHOD__
);
127 // For empty/whitespace-only data or for unknown filters, don't perform
128 // any caching or processing
129 if ( trim( $data ) === ''
130 ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
132 wfProfileOut( __METHOD__
);
137 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
138 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
139 $cache = wfGetCache( CACHE_ANYTHING
);
140 $cacheEntry = $cache->get( $key );
141 if ( is_string( $cacheEntry ) ) {
142 wfProfileOut( __METHOD__
);
147 // Run the filter - we've already verified one of these will work
151 $result = JavaScriptMinifier
::minify( $data,
152 $wgResourceLoaderMinifierStatementsOnOwnLine,
153 $wgResourceLoaderMinifierMaxLineLength
155 $result .= "\n\n/* cache key: $key */\n";
158 $result = CSSMin
::minify( $data );
159 $result .= "\n\n/* cache key: $key */\n";
163 // Save filtered text to Memcached
164 $cache->set( $key, $result );
165 } catch ( Exception
$exception ) {
166 // Return exception as a comment
167 $result = "/*\n{$exception->__toString()}\n*/\n";
170 wfProfileOut( __METHOD__
);
178 * Registers core modules and runs registration hooks.
180 public function __construct() {
181 global $IP, $wgResourceModules;
183 wfProfileIn( __METHOD__
);
185 // Register core modules
186 $this->register( include( "$IP/resources/Resources.php" ) );
187 // Register extension modules
188 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
189 $this->register( $wgResourceModules );
191 wfProfileOut( __METHOD__
);
195 * Registers a module with the ResourceLoader system.
197 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
198 * @param $info Module info array. For backwards compatibility with 1.17alpha,
199 * this may also be a ResourceLoaderModule object. Optional when using
200 * multiple-registration calling style.
201 * @throws MWException: If a duplicate module registration is attempted
202 * @throws MWException: If a module name contains illegal characters (pipes or commas)
203 * @throws MWException: If something other than a ResourceLoaderModule is being registered
204 * @return Boolean: False if there were any errors, in which case one or more modules were not
207 public function register( $name, $info = null ) {
208 wfProfileIn( __METHOD__
);
210 // Allow multiple modules to be registered in one call
211 if ( is_array( $name ) ) {
212 foreach ( $name as $key => $value ) {
213 $this->register( $key, $value );
215 wfProfileOut( __METHOD__
);
219 // Disallow duplicate registrations
220 if ( isset( $this->moduleInfos
[$name] ) ) {
221 // A module has already been registered by this name
222 throw new MWException(
223 'ResourceLoader duplicate registration error. ' .
224 'Another module has already been registered as ' . $name
228 // Check $name for illegal characters
229 if ( preg_match( '/[|,!]/', $name ) ) {
230 throw new MWException( "ResourceLoader module name '$name' is invalid. Names may not contain pipes (|), commas (,) or exclamation marks (!)" );
234 if ( is_object( $info ) ) {
235 // Old calling convention
236 // Validate the input
237 if ( !( $info instanceof ResourceLoaderModule
) ) {
238 throw new MWException( 'ResourceLoader invalid module error. ' .
239 'Instances of ResourceLoaderModule expected.' );
242 $this->moduleInfos
[$name] = array( 'object' => $info );
243 $info->setName( $name );
244 $this->modules
[$name] = $info;
246 // New calling convention
247 $this->moduleInfos
[$name] = $info;
250 wfProfileOut( __METHOD__
);
254 * Get a list of module names
256 * @return Array: List of module names
258 public function getModuleNames() {
259 return array_keys( $this->moduleInfos
);
263 * Get the ResourceLoaderModule object for a given module name.
265 * @param $name String: Module name
266 * @return ResourceLoaderModule if module has been registered, null otherwise
268 public function getModule( $name ) {
269 if ( !isset( $this->modules
[$name] ) ) {
270 if ( !isset( $this->moduleInfos
[$name] ) ) {
274 // Construct the requested object
275 $info = $this->moduleInfos
[$name];
276 if ( isset( $info['object'] ) ) {
277 // Object given in info array
278 $object = $info['object'];
280 if ( !isset( $info['class'] ) ) {
281 $class = 'ResourceLoaderFileModule';
283 $class = $info['class'];
285 $object = new $class( $info );
287 $object->setName( $name );
288 $this->modules
[$name] = $object;
291 return $this->modules
[$name];
295 * Outputs a response to a resource load-request, including a content-type header.
297 * @param $context ResourceLoaderContext: Context in which a response should be formed
299 public function respond( ResourceLoaderContext
$context ) {
300 global $wgResourceLoaderMaxage, $wgCacheEpoch;
302 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
303 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
304 // is used: ob_clean() will clear the GZIP header in that case and it won't come
305 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
306 // the whole thing in our own output buffer to be sure the active buffer
307 // doesn't use ob_gzhandler.
308 // See http://bugs.php.net/bug.php?id=36514
311 wfProfileIn( __METHOD__
);
314 // Split requested modules into two groups, modules and missing
317 foreach ( $context->getModules() as $name ) {
318 if ( isset( $this->moduleInfos
[$name] ) ) {
319 $modules[$name] = $this->getModule( $name );
325 // If a version wasn't specified we need a shorter expiry time for updates
326 // to propagate to clients quickly
327 if ( is_null( $context->getVersion() ) ) {
328 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
329 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
331 // If a version was specified we can use a longer expiry time since changing
332 // version numbers causes cache misses
334 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
335 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
338 // Preload information needed to the mtime calculation below
340 $this->preloadModuleInfo( array_keys( $modules ), $context );
341 } catch( Exception
$e ) {
342 // Add exception to the output as a comment
343 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
346 wfProfileIn( __METHOD__
.'-getModifiedTime' );
349 // To send Last-Modified and support If-Modified-Since, we need to detect
350 // the last modified time
351 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
352 foreach ( $modules as $module ) {
354 // Bypass Squid and other shared caches if the request includes any private modules
355 if ( $module->getGroup() === 'private' ) {
358 // Calculate maximum modified time
359 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
360 } catch ( Exception
$e ) {
361 // Add exception to the output as a comment
362 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
366 wfProfileOut( __METHOD__
.'-getModifiedTime' );
368 if ( $context->getOnly() === 'styles' ) {
369 header( 'Content-Type: text/css; charset=utf-8' );
371 header( 'Content-Type: text/javascript; charset=utf-8' );
373 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
374 if ( $context->getDebug() ) {
375 // Do not cache debug responses
376 header( 'Cache-Control: private, no-cache, must-revalidate' );
377 header( 'Pragma: no-cache' );
380 header( "Cache-Control: private, max-age=$maxage" );
383 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
384 $exp = min( $maxage, $smaxage );
386 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
389 // If there's an If-Modified-Since header, respond with a 304 appropriately
390 // Some clients send "timestamp;length=123". Strip the part after the first ';'
391 // so we get a valid timestamp.
392 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
393 // Never send 304s in debug mode
394 if ( $ims !== false && !$context->getDebug() ) {
395 $imsTS = strtok( $ims, ';' );
396 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
397 // There's another bug in ob_gzhandler (see also the comment at
398 // the top of this function) that causes it to gzip even empty
399 // responses, meaning it's impossible to produce a truly empty
400 // response (because the gzip header is always there). This is
401 // a problem because 304 responses have to be completely empty
402 // per the HTTP spec, and Firefox behaves buggily when they're not.
403 // See also http://bugs.php.net/bug.php?id=51579
404 // To work around this, we tear down all output buffering before
406 // On some setups, ob_get_level() doesn't seem to go down to zero
407 // no matter how often we call ob_get_clean(), so instead of doing
408 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
409 // we have to be safe here and avoid an infinite loop.
410 for ( $i = 0; $i < ob_get_level(); $i++
) {
414 header( 'HTTP/1.0 304 Not Modified' );
415 header( 'Status: 304 Not Modified' );
416 wfProfileOut( __METHOD__
);
421 // Generate a response
422 $response = $this->makeModuleResponse( $context, $modules, $missing );
424 // Prepend comments indicating exceptions
425 $response = $exceptions . $response;
427 // Capture any PHP warnings from the output buffer and append them to the
428 // response in a comment if we're in debug mode.
429 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
430 $response = "/*\n$warnings\n*/\n" . $response;
433 // Remove the output buffer and output the response
437 wfProfileOut( __METHOD__
);
441 * Generates code for a response
443 * @param $context ResourceLoaderContext: Context in which to generate a response
444 * @param $modules Array: List of module objects keyed by module name
445 * @param $missing Array: List of unavailable modules (optional)
446 * @return String: Response data
448 public function makeModuleResponse( ResourceLoaderContext
$context,
449 array $modules, $missing = array() )
453 if ( $modules === array() && $missing === array() ) {
454 return '/* No modules requested. Max made me put this here */';
457 wfProfileIn( __METHOD__
);
459 if ( $context->shouldIncludeMessages() ) {
461 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
462 } catch ( Exception
$e ) {
463 // Add exception to the output as a comment
464 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
471 foreach ( $modules as $name => $module ) {
472 wfProfileIn( __METHOD__
. '-' . $name );
475 if ( $context->shouldIncludeScripts() ) {
476 $scripts = $module->getScript( $context );
477 if ( is_string( $scripts ) ) {
478 // bug 27054: Append semicolon to prevent weird bugs
479 // caused by files not terminating their statements right
485 if ( $context->shouldIncludeStyles() ) {
486 $styles = $module->getStyles( $context );
490 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
493 switch ( $context->getOnly() ) {
495 if ( is_string( $scripts ) ) {
497 } else if ( is_array( $scripts ) ) {
498 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
502 $out .= self
::makeCombinedStyles( $styles );
505 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
508 // Minify CSS before embedding in mw.loader.implement call
509 // (unless in debug mode)
510 if ( !$context->getDebug() ) {
511 foreach ( $styles as $media => $style ) {
512 if ( is_string( $style ) ) {
513 $styles[$media] = $this->filter( 'minify-css', $style );
517 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
518 new XmlJsCode( $messagesBlob ) );
521 } catch ( Exception
$e ) {
522 // Add exception to the output as a comment
523 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
525 // Register module as missing
527 unset( $modules[$name] );
529 wfProfileOut( __METHOD__
. '-' . $name );
532 // Update module states
533 if ( $context->shouldIncludeScripts() ) {
534 // Set the state of modules loaded as only scripts to ready
535 if ( count( $modules ) && $context->getOnly() === 'scripts'
536 && !isset( $modules['startup'] ) )
538 $out .= self
::makeLoaderStateScript(
539 array_fill_keys( array_keys( $modules ), 'ready' ) );
541 // Set the state of modules which were requested but unavailable as missing
542 if ( is_array( $missing ) && count( $missing ) ) {
543 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
547 if ( !$context->getDebug() ) {
548 if ( $context->getOnly() === 'styles' ) {
549 $out = $this->filter( 'minify-css', $out );
551 $out = $this->filter( 'minify-js', $out );
555 wfProfileOut( __METHOD__
);
556 return $exceptions . $out;
562 * Returns JS code to call to mw.loader.implement for a module with
565 * @param $name Module name
566 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
567 * @param $styles Mixed: List of CSS strings keyed by media type, or list of lists of URLs to
568 * CSS files keyed by media type
569 * @param $messages Mixed: List of messages associated with this module. May either be an
570 * associative array mapping message key to value, or a JSON-encoded message blob containing
571 * the same data, wrapped in an XmlJsCode object.
575 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
576 if ( is_string( $scripts ) ) {
577 $scripts = new XmlJsCode( "function( $ ) {{$scripts}}" );
578 } else if ( !is_array( $scripts ) ) {
579 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
581 return Xml
::encodeJsCall(
582 'mw.loader.implement',
592 * Returns JS code which, when called, will register a given list of messages.
594 * @param $messages Mixed: Either an associative array mapping message key to value, or a
595 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
599 public static function makeMessageSetScript( $messages ) {
600 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
604 * Combines an associative array mapping media type to CSS into a
605 * single stylesheet with @media blocks.
607 * @param $styles Array: List of CSS strings keyed by media type
611 public static function makeCombinedStyles( array $styles ) {
613 foreach ( $styles as $media => $style ) {
614 // Transform the media type based on request params and config
615 // The way that this relies on $wgRequest to propagate request params is slightly evil
616 $media = OutputPage
::transformCssMedia( $media );
618 if ( $media === null ) {
620 } else if ( $media === '' ||
$media == 'all' ) {
621 // Don't output invalid or frivolous @media statements
624 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
631 * Returns a JS call to mw.loader.state, which sets the state of a
632 * module or modules to a given value. Has two calling conventions:
634 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
635 * Set the state of a single module called $name to $state
637 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
638 * Set the state of modules with the given names to the given states
640 * @param $name string
645 public static function makeLoaderStateScript( $name, $state = null ) {
646 if ( is_array( $name ) ) {
647 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
649 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
654 * Returns JS code which calls the script given by $script. The script will
655 * be called with local variables name, version, dependencies and group,
656 * which will have values corresponding to $name, $version, $dependencies
657 * and $group as supplied.
659 * @param $name String: Module name
660 * @param $version Integer: Module version number as a timestamp
661 * @param $dependencies Array: List of module names on which this module depends
662 * @param $group String: Group which the module is in.
663 * @param $script String: JavaScript code
667 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
668 $script = str_replace( "\n", "\n\t", trim( $script ) );
669 return Xml
::encodeJsCall(
670 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
671 array( $name, $version, $dependencies, $group ) );
675 * Returns JS code which calls mw.loader.register with the given
676 * parameters. Has three calling conventions:
678 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
679 * Register a single module.
681 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
682 * Register modules with the given names.
684 * - ResourceLoader::makeLoaderRegisterScript( array(
685 * array( $name1, $version1, $dependencies1, $group1 ),
686 * array( $name2, $version2, $dependencies1, $group2 ),
689 * Registers modules with the given names and parameters.
691 * @param $name String: Module name
692 * @param $version Integer: Module version number as a timestamp
693 * @param $dependencies Array: List of module names on which this module depends
694 * @param $group String: group which the module is in.
698 public static function makeLoaderRegisterScript( $name, $version = null,
699 $dependencies = null, $group = null )
701 if ( is_array( $name ) ) {
702 return Xml
::encodeJsCall( 'mw.loader.register', array( $name ) );
704 $version = (int) $version > 1 ?
(int) $version : 1;
705 return Xml
::encodeJsCall( 'mw.loader.register',
706 array( $name, $version, $dependencies, $group ) );
711 * Returns JS code which runs given JS code if the client-side framework is
714 * @param $script String: JavaScript code
718 public static function makeLoaderConditionalScript( $script ) {
719 $script = str_replace( "\n", "\n\t", trim( $script ) );
720 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
724 * Returns JS code which will set the MediaWiki configuration array to
727 * @param $configuration Array: List of configuration values keyed by variable name
731 public static function makeConfigSetScript( array $configuration ) {
732 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ) );
736 * Convert an array of module names to a packed query string.
738 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
739 * becomes 'foo!bar,baz|bar!baz,quux'
740 * The ! is for IE6 being stupid with extensions.
741 * @param $modules array of module names (strings)
742 * @return string Packed query string
744 public static function makePackedModulesString( $modules ) {
745 $groups = array(); // array( prefix => array( suffixes ) )
746 foreach ( $modules as $module ) {
747 $pos = strrpos( $module, '.' );
748 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
749 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
750 $groups[$prefix][] = $suffix;
754 foreach ( $groups as $prefix => $suffixes ) {
755 $p = $prefix === '' ?
'' : $prefix . '.';
756 $arr[] = $p . implode( ',', $suffixes );
758 $str = implode( '|', $arr );
759 return str_replace( ".", "!", $str ); # bug 28840
763 * Determine whether debug mode was requested
764 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
767 public static function inDebugMode() {
768 global $wgRequest, $wgResourceLoaderDebug;
769 static $retval = null;
770 if ( !is_null( $retval ) ) {
773 return $retval = $wgRequest->getFuzzyBool( 'debug',
774 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );