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 = 1;
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,
66 'md_skin' => $context->getSkin()
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 JavaScriptDistiller::stripWhiteSpace
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 $wgResourceLoaderMinifyJSVerticalSpace;
126 wfProfileIn( __METHOD__
);
128 // For empty/whitespace-only data or for unknown filters, don't perform
129 // any caching or processing
130 if ( trim( $data ) === ''
131 ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
133 wfProfileOut( __METHOD__
);
138 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
139 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
140 $cache = wfGetCache( CACHE_ANYTHING
);
141 $cacheEntry = $cache->get( $key );
142 if ( is_string( $cacheEntry ) ) {
143 wfProfileOut( __METHOD__
);
148 // Run the filter - we've already verified one of these will work
152 $result = JavaScriptDistiller
::stripWhiteSpace(
153 $data, $wgResourceLoaderMinifyJSVerticalSpace
157 $result = CSSMin
::minify( $data );
161 // Save filtered text to Memcached
162 $cache->set( $key, $result );
163 } catch ( Exception
$exception ) {
164 // Return exception as a comment
165 $result = "/*\n{$exception->__toString()}\n*/\n";
168 wfProfileOut( __METHOD__
);
176 * Registers core modules and runs registration hooks.
178 public function __construct() {
179 global $IP, $wgResourceModules;
181 wfProfileIn( __METHOD__
);
183 // Register core modules
184 $this->register( include( "$IP/resources/Resources.php" ) );
185 // Register extension modules
186 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
187 $this->register( $wgResourceModules );
189 wfProfileOut( __METHOD__
);
193 * Registers a module with the ResourceLoader system.
195 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
196 * @param $info Module info array. For backwards compatibility with 1.17alpha,
197 * this may also be a ResourceLoaderModule object. Optional when using
198 * multiple-registration calling style.
199 * @throws MWException: If a duplicate module registration is attempted
200 * @throws MWException: If something other than a ResourceLoaderModule is being registered
201 * @return Boolean: False if there were any errors, in which case one or more modules were not
204 public function register( $name, $info = null ) {
205 wfProfileIn( __METHOD__
);
207 // Allow multiple modules to be registered in one call
208 if ( is_array( $name ) ) {
209 foreach ( $name as $key => $value ) {
210 $this->register( $key, $value );
212 wfProfileOut( __METHOD__
);
216 // Disallow duplicate registrations
217 if ( isset( $this->moduleInfos
[$name] ) ) {
218 // A module has already been registered by this name
219 throw new MWException(
220 'ResourceLoader duplicate registration error. ' .
221 'Another module has already been registered as ' . $name
226 if ( is_object( $info ) ) {
227 // Old calling convention
228 // Validate the input
229 if ( !( $info instanceof ResourceLoaderModule
) ) {
230 throw new MWException( 'ResourceLoader invalid module error. ' .
231 'Instances of ResourceLoaderModule expected.' );
234 $this->moduleInfos
[$name] = array( 'object' => $info );
235 $info->setName( $name );
236 $this->modules
[$name] = $info;
238 // New calling convention
239 $this->moduleInfos
[$name] = $info;
242 wfProfileOut( __METHOD__
);
246 * Get a list of module names
248 * @return Array: List of module names
250 public function getModuleNames() {
251 return array_keys( $this->moduleInfos
);
255 * Get the ResourceLoaderModule object for a given module name.
257 * @param $name String: Module name
258 * @return ResourceLoaderModule if module has been registered, null otherwise
260 public function getModule( $name ) {
261 if ( !isset( $this->modules
[$name] ) ) {
262 if ( !isset( $this->moduleInfos
[$name] ) ) {
266 // Construct the requested object
267 $info = $this->moduleInfos
[$name];
268 if ( isset( $info['object'] ) ) {
269 // Object given in info array
270 $object = $info['object'];
272 if ( !isset( $info['class'] ) ) {
273 $class = 'ResourceLoaderFileModule';
275 $class = $info['class'];
277 $object = new $class( $info );
279 $object->setName( $name );
280 $this->modules
[$name] = $object;
283 return $this->modules
[$name];
287 * Outputs a response to a resource load-request, including a content-type header.
289 * @param $context ResourceLoaderContext: Context in which a response should be formed
291 public function respond( ResourceLoaderContext
$context ) {
292 global $wgResourceLoaderMaxage, $wgCacheEpoch;
294 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
295 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
296 // is used: ob_clean() will clear the GZIP header in that case and it won't come
297 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
298 // the whole thing in our own output buffer to be sure the active buffer
299 // doesn't use ob_gzhandler.
300 // See http://bugs.php.net/bug.php?id=36514
303 wfProfileIn( __METHOD__
);
306 // Split requested modules into two groups, modules and missing
309 foreach ( $context->getModules() as $name ) {
310 if ( isset( $this->moduleInfos
[$name] ) ) {
311 $modules[$name] = $this->getModule( $name );
317 // If a version wasn't specified we need a shorter expiry time for updates
318 // to propagate to clients quickly
319 if ( is_null( $context->getVersion() ) ) {
320 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
321 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
323 // If a version was specified we can use a longer expiry time since changing
324 // version numbers causes cache misses
326 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
327 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
330 // Preload information needed to the mtime calculation below
332 $this->preloadModuleInfo( array_keys( $modules ), $context );
333 } catch( Exception
$e ) {
334 // Add exception to the output as a comment
335 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
338 wfProfileIn( __METHOD__
.'-getModifiedTime' );
341 // To send Last-Modified and support If-Modified-Since, we need to detect
342 // the last modified time
343 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
344 foreach ( $modules as $module ) {
346 // Bypass Squid and other shared caches if the request includes any private modules
347 if ( $module->getGroup() === 'private' ) {
350 // Calculate maximum modified time
351 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
352 } catch ( Exception
$e ) {
353 // Add exception to the output as a comment
354 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
358 wfProfileOut( __METHOD__
.'-getModifiedTime' );
360 if ( $context->getOnly() === 'styles' ) {
361 header( 'Content-Type: text/css' );
363 header( 'Content-Type: text/javascript' );
365 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
366 if ( $context->getDebug() ) {
367 // Do not cache debug responses
368 header( 'Cache-Control: private, no-cache, must-revalidate' );
369 header( 'Pragma: no-cache' );
372 header( "Cache-Control: private, max-age=$maxage" );
375 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
376 $exp = min( $maxage, $smaxage );
378 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
381 // If there's an If-Modified-Since header, respond with a 304 appropriately
382 // Some clients send "timestamp;length=123". Strip the part after the first ';'
383 // so we get a valid timestamp.
384 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
385 // Never send 304s in debug mode
386 if ( $ims !== false && !$context->getDebug() ) {
387 $imsTS = strtok( $ims, ';' );
388 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
389 // There's another bug in ob_gzhandler (see also the comment at
390 // the top of this function) that causes it to gzip even empty
391 // responses, meaning it's impossible to produce a truly empty
392 // response (because the gzip header is always there). This is
393 // a problem because 304 responses have to be completely empty
394 // per the HTTP spec, and Firefox behaves buggily when they're not.
395 // See also http://bugs.php.net/bug.php?id=51579
396 // To work around this, we tear down all output buffering before
398 // On some setups, ob_get_level() doesn't seem to go down to zero
399 // no matter how often we call ob_get_clean(), so instead of doing
400 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
401 // we have to be safe here and avoid an infinite loop.
402 for ( $i = 0; $i < ob_get_level(); $i++
) {
406 header( 'HTTP/1.0 304 Not Modified' );
407 header( 'Status: 304 Not Modified' );
408 wfProfileOut( __METHOD__
);
413 // Generate a response
414 $response = $this->makeModuleResponse( $context, $modules, $missing );
416 // Prepend comments indicating exceptions
417 $response = $exceptions . $response;
419 // Capture any PHP warnings from the output buffer and append them to the
420 // response in a comment if we're in debug mode.
421 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
422 $response = "/*\n$warnings\n*/\n" . $response;
425 // Remove the output buffer and output the response
429 wfProfileOut( __METHOD__
);
433 * Generates code for a response
435 * @param $context ResourceLoaderContext: Context in which to generate a response
436 * @param $modules Array: List of module objects keyed by module name
437 * @param $missing Array: List of unavailable modules (optional)
438 * @return String: Response data
440 public function makeModuleResponse( ResourceLoaderContext
$context,
441 array $modules, $missing = array() )
445 if ( $modules === array() && $missing === array() ) {
446 return '/* No modules requested. Max made me put this here */';
449 wfProfileIn( __METHOD__
);
451 if ( $context->shouldIncludeMessages() ) {
453 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
454 } catch ( Exception
$e ) {
455 // Add exception to the output as a comment
456 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
463 foreach ( $modules as $name => $module ) {
464 wfProfileIn( __METHOD__
. '-' . $name );
468 if ( $context->shouldIncludeScripts() ) {
469 $scripts .= $module->getScript( $context ) . "\n";
474 if ( $context->shouldIncludeStyles() ) {
475 $styles = $module->getStyles( $context );
479 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
482 switch ( $context->getOnly() ) {
487 $out .= self
::makeCombinedStyles( $styles );
490 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
493 // Minify CSS before embedding in mediaWiki.loader.implement call
494 // (unless in debug mode)
495 if ( !$context->getDebug() ) {
496 foreach ( $styles as $media => $style ) {
497 $styles[$media] = $this->filter( 'minify-css', $style );
500 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
501 new XmlJsCode( $messagesBlob ) );
504 } catch ( Exception
$e ) {
505 // Add exception to the output as a comment
506 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
508 // Register module as missing
510 unset( $modules[$name] );
512 wfProfileOut( __METHOD__
. '-' . $name );
515 // Update module states
516 if ( $context->shouldIncludeScripts() ) {
517 // Set the state of modules loaded as only scripts to ready
518 if ( count( $modules ) && $context->getOnly() === 'scripts'
519 && !isset( $modules['startup'] ) )
521 $out .= self
::makeLoaderStateScript(
522 array_fill_keys( array_keys( $modules ), 'ready' ) );
524 // Set the state of modules which were requested but unavailable as missing
525 if ( is_array( $missing ) && count( $missing ) ) {
526 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
530 if ( !$context->getDebug() ) {
531 if ( $context->getOnly() === 'styles' ) {
532 $out = $this->filter( 'minify-css', $out );
534 $out = $this->filter( 'minify-js', $out );
538 wfProfileOut( __METHOD__
);
539 return $exceptions . $out;
545 * Returns JS code to call to mediaWiki.loader.implement for a module with
548 * @param $name Module name
549 * @param $scripts Array: List of JavaScript code snippets to be executed after the
551 * @param $styles Array: List of CSS strings keyed by media type
552 * @param $messages Mixed: List of messages associated with this module. May either be an
553 * associative array mapping message key to value, or a JSON-encoded message blob containing
554 * the same data, wrapped in an XmlJsCode object.
556 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
557 if ( is_array( $scripts ) ) {
558 $scripts = implode( $scripts, "\n" );
560 return Xml
::encodeJsCall(
561 'mediaWiki.loader.implement',
564 new XmlJsCode( "function( $, mw ) {{$scripts}}" ),
571 * Returns JS code which, when called, will register a given list of messages.
573 * @param $messages Mixed: Either an associative array mapping message key to value, or a
574 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
576 public static function makeMessageSetScript( $messages ) {
577 return Xml
::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
581 * Combines an associative array mapping media type to CSS into a
582 * single stylesheet with @media blocks.
584 * @param $styles Array: List of CSS strings keyed by media type
586 public static function makeCombinedStyles( array $styles ) {
588 foreach ( $styles as $media => $style ) {
589 // Transform the media type based on request params and config
590 // The way that this relies on $wgRequest to propagate request params is slightly evil
591 $media = OutputPage
::transformCssMedia( $media );
593 if ( $media === null ) {
595 } else if ( $media === '' ||
$media == 'all' ) {
596 // Don't output invalid or frivolous @media statements
599 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
606 * Returns a JS call to mediaWiki.loader.state, which sets the state of a
607 * module or modules to a given value. Has two calling conventions:
609 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
610 * Set the state of a single module called $name to $state
612 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
613 * Set the state of modules with the given names to the given states
615 public static function makeLoaderStateScript( $name, $state = null ) {
616 if ( is_array( $name ) ) {
617 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name ) );
619 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name, $state ) );
624 * Returns JS code which calls the script given by $script. The script will
625 * be called with local variables name, version, dependencies and group,
626 * which will have values corresponding to $name, $version, $dependencies
627 * and $group as supplied.
629 * @param $name String: Module name
630 * @param $version Integer: Module version number as a timestamp
631 * @param $dependencies Array: List of module names on which this module depends
632 * @param $group String: Group which the module is in.
633 * @param $script String: JavaScript code
635 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
636 $script = str_replace( "\n", "\n\t", trim( $script ) );
637 return Xml
::encodeJsCall(
638 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
639 array( $name, $version, $dependencies, $group ) );
643 * Returns JS code which calls mediaWiki.loader.register with the given
644 * parameters. Has three calling conventions:
646 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
647 * Register a single module.
649 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
650 * Register modules with the given names.
652 * - ResourceLoader::makeLoaderRegisterScript( array(
653 * array( $name1, $version1, $dependencies1, $group1 ),
654 * array( $name2, $version2, $dependencies1, $group2 ),
657 * Registers modules with the given names and parameters.
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.
664 public static function makeLoaderRegisterScript( $name, $version = null,
665 $dependencies = null, $group = null )
667 if ( is_array( $name ) ) {
668 return Xml
::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
670 $version = (int) $version > 1 ?
(int) $version : 1;
671 return Xml
::encodeJsCall( 'mediaWiki.loader.register',
672 array( $name, $version, $dependencies, $group ) );
677 * Returns JS code which runs given JS code if the client-side framework is
680 * @param $script String: JavaScript code
682 public static function makeLoaderConditionalScript( $script ) {
683 $script = str_replace( "\n", "\n\t", trim( $script ) );
684 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
688 * Returns JS code which will set the MediaWiki configuration array to
691 * @param $configuration Array: List of configuration values keyed by variable name
693 public static function makeConfigSetScript( array $configuration ) {
694 return Xml
::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
698 * Determine whether debug mode was requested
699 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
702 public static function inDebugMode() {
703 global $wgRequest, $wgResourceLoaderDebug;
704 static $retval = null;
705 if ( !is_null( $retval ) )
707 return $retval = $wgRequest->getFuzzyBool( 'debug',
708 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );