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 = 7;
33 protected static $requiredSourceProperties = array( 'loadScript' );
35 /** Array: List of module name/ResourceLoaderModule object pairs */
36 protected $modules = array();
38 /** Associative array mapping module name to info associative array */
39 protected $moduleInfos = array();
41 /** Associative array mapping framework ids to a list of names of test suite modules */
42 /** like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. ) */
43 protected $testModuleNames = array();
45 /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
46 protected $sources = array();
48 /* Protected Methods */
51 * Loads information stored in the database about modules.
53 * This method grabs modules dependencies from the database and updates modules
56 * This is not inside the module code because it is much faster to
57 * request all of the information at once than it is to have each module
58 * requests its own information. This sacrifice of modularity yields a substantial
59 * performance improvement.
61 * @param $modules Array: List of module names to preload information for
62 * @param $context ResourceLoaderContext: Context to load the information within
64 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
65 if ( !count( $modules ) ) {
66 return; // or else Database*::select() will explode, plus it's cheaper!
68 $dbr = wfGetDB( DB_SLAVE
);
69 $skin = $context->getSkin();
70 $lang = $context->getLanguage();
72 // Get file dependency information
73 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
74 'md_module' => $modules,
79 // Set modules' dependencies
80 $modulesWithDeps = array();
81 foreach ( $res as $row ) {
82 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
83 FormatJson
::decode( $row->md_deps
, true )
85 $modulesWithDeps[] = $row->md_module
;
88 // Register the absence of a dependency row too
89 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
90 $this->getModule( $name )->setFileDependencies( $skin, array() );
93 // Get message blob mtimes. Only do this for modules with messages
94 $modulesWithMessages = array();
95 foreach ( $modules as $name ) {
96 if ( count( $this->getModule( $name )->getMessages() ) ) {
97 $modulesWithMessages[] = $name;
100 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
101 if ( count( $modulesWithMessages ) ) {
102 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
103 'mr_resource' => $modulesWithMessages,
107 foreach ( $res as $row ) {
108 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
109 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
110 unset( $modulesWithoutMessages[$row->mr_resource
] );
113 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
114 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
119 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
121 * Available filters are:
122 * - minify-js \see JavaScriptMinifier::minify
123 * - minify-css \see CSSMin::minify
125 * If $data is empty, only contains whitespace or the filter was unknown,
126 * $data is returned unmodified.
128 * @param $filter String: Name of filter to run
129 * @param $data String: Text to filter, such as JavaScript or CSS text
130 * @return String: Filtered data, or a comment containing an error message
132 protected function filter( $filter, $data ) {
133 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
134 wfProfileIn( __METHOD__
);
136 // For empty/whitespace-only data or for unknown filters, don't perform
137 // any caching or processing
138 if ( trim( $data ) === ''
139 ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
141 wfProfileOut( __METHOD__
);
146 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
147 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
148 $cache = wfGetCache( CACHE_ANYTHING
);
149 $cacheEntry = $cache->get( $key );
150 if ( is_string( $cacheEntry ) ) {
151 wfProfileOut( __METHOD__
);
156 // Run the filter - we've already verified one of these will work
160 $result = JavaScriptMinifier
::minify( $data,
161 $wgResourceLoaderMinifierStatementsOnOwnLine,
162 $wgResourceLoaderMinifierMaxLineLength
164 $result .= "\n\n/* cache key: $key */\n";
167 $result = CSSMin
::minify( $data );
168 $result .= "\n\n/* cache key: $key */\n";
172 // Save filtered text to Memcached
173 $cache->set( $key, $result );
174 } catch ( Exception
$exception ) {
175 // Return exception as a comment
176 $result = "/*\n{$exception->__toString()}\n*/\n";
179 wfProfileOut( __METHOD__
);
187 * Registers core modules and runs registration hooks.
189 public function __construct() {
190 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
192 wfProfileIn( __METHOD__
);
194 // Add 'local' source first
195 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
198 $this->addSource( $wgResourceLoaderSources );
200 // Register core modules
201 $this->register( include( "$IP/resources/Resources.php" ) );
202 // Register extension modules
203 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
204 $this->register( $wgResourceModules );
206 if ( $wgEnableJavaScriptTest === true ) {
207 $this->registerTestModules();
211 wfProfileOut( __METHOD__
);
215 * Registers a module with the ResourceLoader system.
217 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
218 * @param $info array Module info array. For backwards compatibility with 1.17alpha,
219 * this may also be a ResourceLoaderModule object. Optional when using
220 * multiple-registration calling style.
221 * @throws MWException: If a duplicate module registration is attempted
222 * @throws MWException: If a module name contains illegal characters (pipes or commas)
223 * @throws MWException: If something other than a ResourceLoaderModule is being registered
224 * @return Boolean: False if there were any errors, in which case one or more modules were not
227 public function register( $name, $info = null ) {
228 wfProfileIn( __METHOD__
);
230 // Allow multiple modules to be registered in one call
231 $registrations = is_array( $name ) ?
$name : array( $name => $info );
232 foreach ( $registrations as $name => $info ) {
233 // Disallow duplicate registrations
234 if ( isset( $this->moduleInfos
[$name] ) ) {
235 // A module has already been registered by this name
236 throw new MWException(
237 'ResourceLoader duplicate registration error. ' .
238 'Another module has already been registered as ' . $name
242 // Check $name for illegal characters
243 if ( preg_match( '/[|,!]/', $name ) ) {
244 throw new MWException( "ResourceLoader module name '$name' is invalid. Names may not contain pipes (|), commas (,) or exclamation marks (!)" );
248 if ( is_object( $info ) ) {
249 // Old calling convention
250 // Validate the input
251 if ( !( $info instanceof ResourceLoaderModule
) ) {
252 throw new MWException( 'ResourceLoader invalid module error. ' .
253 'Instances of ResourceLoaderModule expected.' );
256 $this->moduleInfos
[$name] = array( 'object' => $info );
257 $info->setName( $name );
258 $this->modules
[$name] = $info;
260 // New calling convention
261 $this->moduleInfos
[$name] = $info;
265 wfProfileOut( __METHOD__
);
270 public function registerTestModules() {
271 global $IP, $wgEnableJavaScriptTest;
273 if ( $wgEnableJavaScriptTest !== true ) {
274 throw new MWException( 'Attempt to register JavaScript test modules but <tt>$wgEnableJavaScriptTest</tt> is false. Edit your <tt>LocalSettings.php</tt> to enable it.' );
277 wfProfileIn( __METHOD__
);
279 // Get core test suites
280 $testModules = array();
281 $testModules['qunit'] = include( "$IP/tests/qunit/QUnitTestResources.php" );
282 // Get other test suites (e.g. from extensions)
283 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
285 // Add the testrunner (which configures QUnit) to the dependencies.
286 // Since it must be ready before any of the test suites are executed.
287 foreach( $testModules['qunit'] as $moduleName => $moduleProps ) {
288 $testModules['qunit'][$moduleName]['dependencies'][] = 'mediawiki.tests.qunit.testrunner';
291 foreach( $testModules as $id => $names ) {
292 // Register test modules
293 $this->register( $testModules[$id] );
295 // Keep track of their names so that they can be loaded together
296 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
299 wfProfileOut( __METHOD__
);
303 * Add a foreign source of modules.
306 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
308 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
309 * @param $properties Array: source properties
311 public function addSource( $id, $properties = null) {
312 // Allow multiple sources to be registered in one call
313 if ( is_array( $id ) ) {
314 foreach ( $id as $key => $value ) {
315 $this->addSource( $key, $value );
320 // Disallow duplicates
321 if ( isset( $this->sources
[$id] ) ) {
322 throw new MWException(
323 'ResourceLoader duplicate source addition error. ' .
324 'Another source has already been registered as ' . $id
328 // Validate properties
329 foreach ( self
::$requiredSourceProperties as $prop ) {
330 if ( !isset( $properties[$prop] ) ) {
331 throw new MWException( "Required property $prop missing from source ID $id" );
335 $this->sources
[$id] = $properties;
339 * Get a list of module names
341 * @return Array: List of module names
343 public function getModuleNames() {
344 return array_keys( $this->moduleInfos
);
348 * Get a list of test module names for one (or all) frameworks.
349 * If the given framework id is unknkown, or if the in-object variable is not an array,
350 * then it will return an empty array.
352 * @param $framework String: Optional. Get only the test module names for one
353 * particular framework.
356 public function getTestModuleNames( $framework = 'all' ) {
357 /// @TODO: api siteinfo prop testmodulenames modulenames
358 if ( $framework == 'all' ) {
359 return $this->testModuleNames
;
360 } elseif ( isset( $this->testModuleNames
[$framework] ) && is_array( $this->testModuleNames
[$framework] ) ) {
361 return $this->testModuleNames
[$framework];
368 * Get the ResourceLoaderModule object for a given module name.
370 * @param $name String: Module name
371 * @return ResourceLoaderModule if module has been registered, null otherwise
373 public function getModule( $name ) {
374 if ( !isset( $this->modules
[$name] ) ) {
375 if ( !isset( $this->moduleInfos
[$name] ) ) {
379 // Construct the requested object
380 $info = $this->moduleInfos
[$name];
381 if ( isset( $info['object'] ) ) {
382 // Object given in info array
383 $object = $info['object'];
385 if ( !isset( $info['class'] ) ) {
386 $class = 'ResourceLoaderFileModule';
388 $class = $info['class'];
390 $object = new $class( $info );
392 $object->setName( $name );
393 $this->modules
[$name] = $object;
396 return $this->modules
[$name];
400 * Get the list of sources
402 * @return Array: array( id => array of properties, .. )
404 public function getSources() {
405 return $this->sources
;
409 * Outputs a response to a resource load-request, including a content-type header.
411 * @param $context ResourceLoaderContext: Context in which a response should be formed
413 public function respond( ResourceLoaderContext
$context ) {
414 global $wgCacheEpoch, $wgUseFileCache;
416 // Use file cache if enabled and available...
417 if ( $wgUseFileCache ) {
418 $fileCache = ResourceFileCache
::newFromContext( $context );
419 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
420 return; // output handled
424 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
425 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
426 // is used: ob_clean() will clear the GZIP header in that case and it won't come
427 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
428 // the whole thing in our own output buffer to be sure the active buffer
429 // doesn't use ob_gzhandler.
430 // See http://bugs.php.net/bug.php?id=36514
433 wfProfileIn( __METHOD__
);
436 // Split requested modules into two groups, modules and missing
439 foreach ( $context->getModules() as $name ) {
440 if ( isset( $this->moduleInfos
[$name] ) ) {
441 $modules[$name] = $this->getModule( $name );
447 // Preload information needed to the mtime calculation below
449 $this->preloadModuleInfo( array_keys( $modules ), $context );
450 } catch( Exception
$e ) {
451 // Add exception to the output as a comment
452 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
455 wfProfileIn( __METHOD__
.'-getModifiedTime' );
458 // To send Last-Modified and support If-Modified-Since, we need to detect
459 // the last modified time
460 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
461 foreach ( $modules as $module ) {
463 * @var $module ResourceLoaderModule
466 // Bypass Squid and other shared caches if the request includes any private modules
467 if ( $module->getGroup() === 'private' ) {
470 // Calculate maximum modified time
471 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
472 } catch ( Exception
$e ) {
473 // Add exception to the output as a comment
474 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
478 wfProfileOut( __METHOD__
.'-getModifiedTime' );
480 // Send content type and cache related headers
481 $this->sendResponseHeaders( $context, $mtime, $private );
483 // If there's an If-Modified-Since header, respond with a 304 appropriately
484 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
485 wfProfileOut( __METHOD__
);
486 return; // output handled (buffers cleared)
489 // Generate a response
490 $response = $this->makeModuleResponse( $context, $modules, $missing );
492 // Prepend comments indicating exceptions
493 $response = $exceptions . $response;
495 // Capture any PHP warnings from the output buffer and append them to the
496 // response in a comment if we're in debug mode.
497 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
498 $response = "/*\n$warnings\n*/\n" . $response;
501 // Remove the output buffer and output the response
505 // Save response to file cache unless there are private modules or errors
506 if ( isset( $fileCache ) && !$private && !$exceptions && !$missing ) {
507 // Cache single modules...and other requests if there are enough hits
508 if ( ResourceFileCache
::useFileCache( $context ) ) {
509 if ( $fileCache->isCacheWorthy() ) {
510 $fileCache->saveText( $response );
512 $fileCache->incrMissesRecent( $context->getRequest() );
517 wfProfileOut( __METHOD__
);
521 * Send content type and last modified headers to the client.
522 * @param $context ResourceLoaderContext
523 * @param $mtime string TS_MW timestamp to use for last-modified
524 * @param $private bool True iff response contains any private modules
527 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $private ) {
528 global $wgResourceLoaderMaxage;
529 // If a version wasn't specified we need a shorter expiry time for updates
530 // to propagate to clients quickly
531 if ( is_null( $context->getVersion() ) ) {
532 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
533 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
534 // If a version was specified we can use a longer expiry time since changing
535 // version numbers causes cache misses
537 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
538 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
540 if ( $context->getOnly() === 'styles' ) {
541 header( 'Content-Type: text/css; charset=utf-8' );
543 header( 'Content-Type: text/javascript; charset=utf-8' );
545 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
546 if ( $context->getDebug() ) {
547 // Do not cache debug responses
548 header( 'Cache-Control: private, no-cache, must-revalidate' );
549 header( 'Pragma: no-cache' );
552 header( "Cache-Control: private, max-age=$maxage" );
555 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
556 $exp = min( $maxage, $smaxage );
558 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
563 * If there's an If-Modified-Since header, respond with a 304 appropriately
564 * and clear out the output buffer. If the client cache is too old then do nothing.
565 * @param $context ResourceLoaderContext
566 * @param $mtime string The TS_MW timestamp to check the header against
567 * @return bool True iff 304 header sent and output handled
569 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
570 // If there's an If-Modified-Since header, respond with a 304 appropriately
571 // Some clients send "timestamp;length=123". Strip the part after the first ';'
572 // so we get a valid timestamp.
573 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
574 // Never send 304s in debug mode
575 if ( $ims !== false && !$context->getDebug() ) {
576 $imsTS = strtok( $ims, ';' );
577 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
578 // There's another bug in ob_gzhandler (see also the comment at
579 // the top of this function) that causes it to gzip even empty
580 // responses, meaning it's impossible to produce a truly empty
581 // response (because the gzip header is always there). This is
582 // a problem because 304 responses have to be completely empty
583 // per the HTTP spec, and Firefox behaves buggily when they're not.
584 // See also http://bugs.php.net/bug.php?id=51579
585 // To work around this, we tear down all output buffering before
587 // On some setups, ob_get_level() doesn't seem to go down to zero
588 // no matter how often we call ob_get_clean(), so instead of doing
589 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
590 // we have to be safe here and avoid an infinite loop.
591 for ( $i = 0; $i < ob_get_level(); $i++
) {
595 header( 'HTTP/1.0 304 Not Modified' );
596 header( 'Status: 304 Not Modified' );
604 * Send out code for a response from file cache if possible
606 * @param $fileCache ObjectFileCache: Cache object for this request URL
607 * @param $context ResourceLoaderContext: Context in which to generate a response
608 * @return bool If this found a cache file and handled the response
610 protected function tryRespondFromFileCache(
611 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
613 global $wgResourceLoaderMaxage;
614 // Buffer output to catch warnings.
616 // Get the maximum age the cache can be
617 $maxage = is_null( $context->getVersion() )
618 ?
$wgResourceLoaderMaxage['unversioned']['server']
619 : $wgResourceLoaderMaxage['versioned']['server'];
620 // Minimum timestamp the cache file must have
621 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
623 try { // RL always hits the DB on file cache miss...
625 } catch( DBConnectionError
$e ) { // ...check if we need to fallback to cache
626 $good = $fileCache->isCacheGood(); // cache existence check
630 $ts = $fileCache->cacheTimestamp();
631 // Send content type and cache headers
632 $this->sendResponseHeaders( $context, $ts, false );
633 // If there's an If-Modified-Since header, respond with a 304 appropriately
634 if ( $this->tryRespondLastModified( $context, $ts ) ) {
635 return false; // output handled (buffers cleared)
637 $response = $fileCache->fetchText();
638 // Capture any PHP warnings from the output buffer and append them to the
639 // response in a comment if we're in debug mode.
640 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
641 $response = "/*\n$warnings\n*/\n" . $response;
643 // Remove the output buffer and output the response
645 echo $response . "\n/* Cached {$ts} */";
646 return true; // cache hit
651 return false; // cache miss
655 * Generates code for a response
657 * @param $context ResourceLoaderContext: Context in which to generate a response
658 * @param $modules Array: List of module objects keyed by module name
659 * @param $missing Array: List of unavailable modules (optional)
660 * @return String: Response data
662 public function makeModuleResponse( ResourceLoaderContext
$context,
663 array $modules, $missing = array() )
667 if ( $modules === array() && $missing === array() ) {
668 return '/* No modules requested. Max made me put this here */';
671 wfProfileIn( __METHOD__
);
673 if ( $context->shouldIncludeMessages() ) {
675 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
676 } catch ( Exception
$e ) {
677 // Add exception to the output as a comment
678 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
685 foreach ( $modules as $name => $module ) {
687 * @var $module ResourceLoaderModule
690 wfProfileIn( __METHOD__
. '-' . $name );
693 if ( $context->shouldIncludeScripts() ) {
694 // If we are in debug mode, we'll want to return an array of URLs if possible
695 // However, we can't do this if the module doesn't support it
696 // We also can't do this if there is an only= parameter, because we have to give
697 // the module a way to return a load.php URL without causing an infinite loop
698 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
699 $scripts = $module->getScriptURLsForDebug( $context );
701 $scripts = $module->getScript( $context );
702 if ( is_string( $scripts ) ) {
703 // bug 27054: Append semicolon to prevent weird bugs
704 // caused by files not terminating their statements right
711 if ( $context->shouldIncludeStyles() ) {
712 // If we are in debug mode, we'll want to return an array of URLs
713 // See comment near shouldIncludeScripts() for more details
714 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
715 $styles = $module->getStyleURLsForDebug( $context );
717 $styles = $module->getStyles( $context );
722 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
725 switch ( $context->getOnly() ) {
727 if ( is_string( $scripts ) ) {
728 // Load scripts raw...
730 } elseif ( is_array( $scripts ) ) {
731 // ...except when $scripts is an array of URLs
732 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
736 $out .= self
::makeCombinedStyles( $styles );
739 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
742 // Minify CSS before embedding in mw.loader.implement call
743 // (unless in debug mode)
744 if ( !$context->getDebug() ) {
745 foreach ( $styles as $media => $style ) {
746 if ( is_string( $style ) ) {
747 $styles[$media] = $this->filter( 'minify-css', $style );
751 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
752 new XmlJsCode( $messagesBlob ) );
755 } catch ( Exception
$e ) {
756 // Add exception to the output as a comment
757 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
759 // Register module as missing
761 unset( $modules[$name] );
763 wfProfileOut( __METHOD__
. '-' . $name );
766 // Update module states
767 if ( $context->shouldIncludeScripts() ) {
768 // Set the state of modules loaded as only scripts to ready
769 if ( count( $modules ) && $context->getOnly() === 'scripts'
770 && !isset( $modules['startup'] ) )
772 $out .= self
::makeLoaderStateScript(
773 array_fill_keys( array_keys( $modules ), 'ready' ) );
775 // Set the state of modules which were requested but unavailable as missing
776 if ( is_array( $missing ) && count( $missing ) ) {
777 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
781 if ( !$context->getDebug() ) {
782 if ( $context->getOnly() === 'styles' ) {
783 $out = $this->filter( 'minify-css', $out );
785 $out = $this->filter( 'minify-js', $out );
789 wfProfileOut( __METHOD__
);
790 return $exceptions . $out;
796 * Returns JS code to call to mw.loader.implement for a module with
799 * @param $name string Module name
800 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
801 * @param $styles Mixed: Array of CSS strings keyed by media type, or an array of lists of URLs to
802 * CSS files keyed by media type
803 * @param $messages Mixed: List of messages associated with this module. May either be an
804 * associative array mapping message key to value, or a JSON-encoded message blob containing
805 * the same data, wrapped in an XmlJsCode object.
809 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
810 if ( is_string( $scripts ) ) {
811 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
812 } elseif ( !is_array( $scripts ) ) {
813 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
815 return Xml
::encodeJsCall(
816 'mw.loader.implement',
820 // Force objects. mw.loader.implement requires them to be javascript objects.
821 // Although these variables are associative arrays, which become javascript
822 // objects through json_encode. In many cases they will be empty arrays, and
823 // PHP/json_encode() consider empty arrays to be numerical arrays and
824 // output javascript "[]" instead of "{}". This fixes that.
831 * Returns JS code which, when called, will register a given list of messages.
833 * @param $messages Mixed: Either an associative array mapping message key to value, or a
834 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
838 public static function makeMessageSetScript( $messages ) {
839 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
843 * Combines an associative array mapping media type to CSS into a
844 * single stylesheet with @media blocks.
846 * @param $styles Array: List of CSS strings keyed by media type
850 public static function makeCombinedStyles( array $styles ) {
852 foreach ( $styles as $media => $style ) {
853 // Transform the media type based on request params and config
854 // The way that this relies on $wgRequest to propagate request params is slightly evil
855 $media = OutputPage
::transformCssMedia( $media );
857 if ( $media === null ) {
859 } elseif ( $media === '' ||
$media == 'all' ) {
860 // Don't output invalid or frivolous @media statements
863 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
870 * Returns a JS call to mw.loader.state, which sets the state of a
871 * module or modules to a given value. Has two calling conventions:
873 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
874 * Set the state of a single module called $name to $state
876 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
877 * Set the state of modules with the given names to the given states
879 * @param $name string
884 public static function makeLoaderStateScript( $name, $state = null ) {
885 if ( is_array( $name ) ) {
886 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
888 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
893 * Returns JS code which calls the script given by $script. The script will
894 * be called with local variables name, version, dependencies and group,
895 * which will have values corresponding to $name, $version, $dependencies
896 * and $group as supplied.
898 * @param $name String: Module name
899 * @param $version Integer: Module version number as a timestamp
900 * @param $dependencies Array: List of module names on which this module depends
901 * @param $group String: Group which the module is in.
902 * @param $source String: Source of the module, or 'local' if not foreign.
903 * @param $script String: JavaScript code
907 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
908 $script = str_replace( "\n", "\n\t", trim( $script ) );
909 return Xml
::encodeJsCall(
910 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
911 array( $name, $version, $dependencies, $group, $source ) );
915 * Returns JS code which calls mw.loader.register with the given
916 * parameters. Has three calling conventions:
918 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
919 * Register a single module.
921 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
922 * Register modules with the given names.
924 * - ResourceLoader::makeLoaderRegisterScript( array(
925 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
926 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
929 * Registers modules with the given names and parameters.
931 * @param $name String: Module name
932 * @param $version Integer: Module version number as a timestamp
933 * @param $dependencies Array: List of module names on which this module depends
934 * @param $group String: group which the module is in.
935 * @param $source String: source of the module, or 'local' if not foreign
939 public static function makeLoaderRegisterScript( $name, $version = null,
940 $dependencies = null, $group = null, $source = null )
942 if ( is_array( $name ) ) {
943 return Xml
::encodeJsCall( 'mw.loader.register', array( $name ) );
945 $version = (int) $version > 1 ?
(int) $version : 1;
946 return Xml
::encodeJsCall( 'mw.loader.register',
947 array( $name, $version, $dependencies, $group, $source ) );
952 * Returns JS code which calls mw.loader.addSource() with the given
953 * parameters. Has two calling conventions:
955 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
956 * Register a single source
958 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
959 * Register sources with the given IDs and properties.
961 * @param $id String: source ID
962 * @param $properties Array: source properties (see addSource())
966 public static function makeLoaderSourcesScript( $id, $properties = null ) {
967 if ( is_array( $id ) ) {
968 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id ) );
970 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
975 * Returns JS code which runs given JS code if the client-side framework is
978 * @param $script String: JavaScript code
982 public static function makeLoaderConditionalScript( $script ) {
983 return "if(window.mw){\n".trim( $script )."\n}";
987 * Returns JS code which will set the MediaWiki configuration array to
990 * @param $configuration Array: List of configuration values keyed by variable name
994 public static function makeConfigSetScript( array $configuration ) {
995 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ) );
999 * Convert an array of module names to a packed query string.
1001 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1002 * becomes 'foo.bar,baz|bar.baz,quux'
1003 * @param $modules array of module names (strings)
1004 * @return string Packed query string
1006 public static function makePackedModulesString( $modules ) {
1007 $groups = array(); // array( prefix => array( suffixes ) )
1008 foreach ( $modules as $module ) {
1009 $pos = strrpos( $module, '.' );
1010 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1011 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1012 $groups[$prefix][] = $suffix;
1016 foreach ( $groups as $prefix => $suffixes ) {
1017 $p = $prefix === '' ?
'' : $prefix . '.';
1018 $arr[] = $p . implode( ',', $suffixes );
1020 $str = implode( '|', $arr );
1025 * Determine whether debug mode was requested
1026 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1029 public static function inDebugMode() {
1030 global $wgRequest, $wgResourceLoaderDebug;
1031 static $retval = null;
1032 if ( !is_null( $retval ) ) {
1035 return $retval = $wgRequest->getFuzzyBool( 'debug',
1036 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1040 * Build a load.php URL
1041 * @param $modules array of module names (strings)
1042 * @param $lang string Language code
1043 * @param $skin string Skin name
1044 * @param $user string|null User name. If null, the &user= parameter is omitted
1045 * @param $version string|null Versioning timestamp
1046 * @param $debug bool Whether the request should be in debug mode
1047 * @param $only string|null &only= parameter
1048 * @param $printable bool Printable mode
1049 * @param $handheld bool Handheld mode
1050 * @param $extraQuery array Extra query parameters to add
1051 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1053 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1054 $printable = false, $handheld = false, $extraQuery = array() ) {
1055 global $wgLoadScript;
1056 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1057 $only, $printable, $handheld, $extraQuery
1060 // Prevent the IE6 extension check from being triggered (bug 28840)
1061 // by appending a character that's invalid in Windows extensions ('*')
1062 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1066 * Build a query array (array representation of query string) for load.php. Helper
1067 * function for makeLoaderURL().
1070 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1071 $printable = false, $handheld = false, $extraQuery = array() ) {
1073 'modules' => self
::makePackedModulesString( $modules ),
1076 'debug' => $debug ?
'true' : 'false',
1078 if ( $user !== null ) {
1079 $query['user'] = $user;
1081 if ( $version !== null ) {
1082 $query['version'] = $version;
1084 if ( $only !== null ) {
1085 $query['only'] = $only;
1088 $query['printable'] = 1;
1091 $query['handheld'] = 1;
1093 $query +
= $extraQuery;
1095 // Make queries uniform in order