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 = $this->makeComment( $exception->__toString() );
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 $module = $this->getModule( $name );
442 // Do not allow private modules to be loaded from the web.
443 // This is a security issue, see bug 34907.
444 if ( $module->getGroup() === 'private' ) {
445 $errors .= $this->makeComment( "Cannot show private module \"$name\"" );
448 $modules[$name] = $this->getModule( $name );
454 // Preload information needed to the mtime calculation below
456 $this->preloadModuleInfo( array_keys( $modules ), $context );
457 } catch( Exception
$e ) {
458 // Add exception to the output as a comment
459 $errors .= $this->makeComment( $e->__toString() );
462 wfProfileIn( __METHOD__
.'-getModifiedTime' );
464 // To send Last-Modified and support If-Modified-Since, we need to detect
465 // the last modified time
466 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
467 foreach ( $modules as $module ) {
469 * @var $module ResourceLoaderModule
472 // Calculate maximum modified time
473 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
474 } catch ( Exception
$e ) {
475 // Add exception to the output as a comment
476 $errors .= $this->makeComment( $e->__toString() );
480 wfProfileOut( __METHOD__
.'-getModifiedTime' );
482 // Send content type and cache related headers
483 $this->sendResponseHeaders( $context, $mtime );
485 // If there's an If-Modified-Since header, respond with a 304 appropriately
486 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
487 wfProfileOut( __METHOD__
);
488 return; // output handled (buffers cleared)
491 // Generate a response
492 $response = $this->makeModuleResponse( $context, $modules, $missing );
494 // Prepend comments indicating exceptions
495 $response = $errors . $response;
497 // Capture any PHP warnings from the output buffer and append them to the
498 // response in a comment if we're in debug mode.
499 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
500 $response = $this->makeComment( $warnings ) . $response;
503 // Remove the output buffer and output the response
507 // Save response to file cache unless there are errors
508 if ( isset( $fileCache ) && !$errors && !$missing ) {
509 // Cache single modules...and other requests if there are enough hits
510 if ( ResourceFileCache
::useFileCache( $context ) ) {
511 if ( $fileCache->isCacheWorthy() ) {
512 $fileCache->saveText( $response );
514 $fileCache->incrMissesRecent( $context->getRequest() );
519 wfProfileOut( __METHOD__
);
523 * Send content type and last modified headers to the client.
524 * @param $context ResourceLoaderContext
525 * @param $mtime string TS_MW timestamp to use for last-modified
528 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime ) {
529 global $wgResourceLoaderMaxage;
530 // If a version wasn't specified we need a shorter expiry time for updates
531 // to propagate to clients quickly
532 if ( is_null( $context->getVersion() ) ) {
533 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
534 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
535 // If a version was specified we can use a longer expiry time since changing
536 // version numbers causes cache misses
538 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
539 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
541 if ( $context->getOnly() === 'styles' ) {
542 header( 'Content-Type: text/css; charset=utf-8' );
544 header( 'Content-Type: text/javascript; charset=utf-8' );
546 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
547 if ( $context->getDebug() ) {
548 // Do not cache debug responses
549 header( 'Cache-Control: private, no-cache, must-revalidate' );
550 header( 'Pragma: no-cache' );
552 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
553 $exp = min( $maxage, $smaxage );
554 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
559 * If there's an If-Modified-Since header, respond with a 304 appropriately
560 * and clear out the output buffer. If the client cache is too old then do nothing.
561 * @param $context ResourceLoaderContext
562 * @param $mtime string The TS_MW timestamp to check the header against
563 * @return bool True iff 304 header sent and output handled
565 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
566 // If there's an If-Modified-Since header, respond with a 304 appropriately
567 // Some clients send "timestamp;length=123". Strip the part after the first ';'
568 // so we get a valid timestamp.
569 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
570 // Never send 304s in debug mode
571 if ( $ims !== false && !$context->getDebug() ) {
572 $imsTS = strtok( $ims, ';' );
573 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
574 // There's another bug in ob_gzhandler (see also the comment at
575 // the top of this function) that causes it to gzip even empty
576 // responses, meaning it's impossible to produce a truly empty
577 // response (because the gzip header is always there). This is
578 // a problem because 304 responses have to be completely empty
579 // per the HTTP spec, and Firefox behaves buggily when they're not.
580 // See also http://bugs.php.net/bug.php?id=51579
581 // To work around this, we tear down all output buffering before
583 // On some setups, ob_get_level() doesn't seem to go down to zero
584 // no matter how often we call ob_get_clean(), so instead of doing
585 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
586 // we have to be safe here and avoid an infinite loop.
587 for ( $i = 0; $i < ob_get_level(); $i++
) {
591 header( 'HTTP/1.0 304 Not Modified' );
592 header( 'Status: 304 Not Modified' );
600 * Send out code for a response from file cache if possible
602 * @param $fileCache ObjectFileCache: Cache object for this request URL
603 * @param $context ResourceLoaderContext: Context in which to generate a response
604 * @return bool If this found a cache file and handled the response
606 protected function tryRespondFromFileCache(
607 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
609 global $wgResourceLoaderMaxage;
610 // Buffer output to catch warnings.
612 // Get the maximum age the cache can be
613 $maxage = is_null( $context->getVersion() )
614 ?
$wgResourceLoaderMaxage['unversioned']['server']
615 : $wgResourceLoaderMaxage['versioned']['server'];
616 // Minimum timestamp the cache file must have
617 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
619 try { // RL always hits the DB on file cache miss...
621 } catch( DBConnectionError
$e ) { // ...check if we need to fallback to cache
622 $good = $fileCache->isCacheGood(); // cache existence check
626 $ts = $fileCache->cacheTimestamp();
627 // Send content type and cache headers
628 $this->sendResponseHeaders( $context, $ts, false );
629 // If there's an If-Modified-Since header, respond with a 304 appropriately
630 if ( $this->tryRespondLastModified( $context, $ts ) ) {
631 return false; // output handled (buffers cleared)
633 $response = $fileCache->fetchText();
634 // Capture any PHP warnings from the output buffer and append them to the
635 // response in a comment if we're in debug mode.
636 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
637 $response = "/*\n$warnings\n*/\n" . $response;
639 // Remove the output buffer and output the response
641 echo $response . "\n/* Cached {$ts} */";
642 return true; // cache hit
647 return false; // cache miss
650 protected function makeComment( $text ) {
651 $encText = str_replace( '*/', '* /', $text );
652 return "/*\n$encText\n*/\n";
656 * Generates code for a response
658 * @param $context ResourceLoaderContext: Context in which to generate a response
659 * @param $modules Array: List of module objects keyed by module name
660 * @param $missing Array: List of unavailable modules (optional)
661 * @return String: Response data
663 public function makeModuleResponse( ResourceLoaderContext
$context,
664 array $modules, $missing = array() )
668 if ( $modules === array() && $missing === array() ) {
669 return '/* No modules requested. Max made me put this here */';
672 wfProfileIn( __METHOD__
);
674 if ( $context->shouldIncludeMessages() ) {
676 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
677 } catch ( Exception
$e ) {
678 // Add exception to the output as a comment
679 $exceptions .= $this->makeComment( $e->__toString() );
686 foreach ( $modules as $name => $module ) {
688 * @var $module ResourceLoaderModule
691 wfProfileIn( __METHOD__
. '-' . $name );
694 if ( $context->shouldIncludeScripts() ) {
695 // If we are in debug mode, we'll want to return an array of URLs if possible
696 // However, we can't do this if the module doesn't support it
697 // We also can't do this if there is an only= parameter, because we have to give
698 // the module a way to return a load.php URL without causing an infinite loop
699 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
700 $scripts = $module->getScriptURLsForDebug( $context );
702 $scripts = $module->getScript( $context );
703 if ( is_string( $scripts ) ) {
704 // bug 27054: Append semicolon to prevent weird bugs
705 // caused by files not terminating their statements right
712 if ( $context->shouldIncludeStyles() ) {
713 // If we are in debug mode, we'll want to return an array of URLs
714 // See comment near shouldIncludeScripts() for more details
715 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
716 $styles = $module->getStyleURLsForDebug( $context );
718 $styles = $module->getStyles( $context );
723 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
726 switch ( $context->getOnly() ) {
728 if ( is_string( $scripts ) ) {
729 // Load scripts raw...
731 } elseif ( is_array( $scripts ) ) {
732 // ...except when $scripts is an array of URLs
733 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
737 $out .= self
::makeCombinedStyles( $styles );
740 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
743 // Minify CSS before embedding in mw.loader.implement call
744 // (unless in debug mode)
745 if ( !$context->getDebug() ) {
746 foreach ( $styles as $media => $style ) {
747 if ( is_string( $style ) ) {
748 $styles[$media] = $this->filter( 'minify-css', $style );
752 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
753 new XmlJsCode( $messagesBlob ) );
756 } catch ( Exception
$e ) {
757 // Add exception to the output as a comment
758 $exceptions .= $this->makeComment( $e->__toString() );
760 // Register module as missing
762 unset( $modules[$name] );
764 wfProfileOut( __METHOD__
. '-' . $name );
767 // Update module states
768 if ( $context->shouldIncludeScripts() ) {
769 // Set the state of modules loaded as only scripts to ready
770 if ( count( $modules ) && $context->getOnly() === 'scripts'
771 && !isset( $modules['startup'] ) )
773 $out .= self
::makeLoaderStateScript(
774 array_fill_keys( array_keys( $modules ), 'ready' ) );
776 // Set the state of modules which were requested but unavailable as missing
777 if ( is_array( $missing ) && count( $missing ) ) {
778 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
782 if ( !$context->getDebug() ) {
783 if ( $context->getOnly() === 'styles' ) {
784 $out = $this->filter( 'minify-css', $out );
786 $out = $this->filter( 'minify-js', $out );
790 wfProfileOut( __METHOD__
);
791 return $exceptions . $out;
797 * Returns JS code to call to mw.loader.implement for a module with
800 * @param $name string Module name
801 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
802 * @param $styles Mixed: Array of CSS strings keyed by media type, or an array of lists of URLs to
803 * CSS files keyed by media type
804 * @param $messages Mixed: List of messages associated with this module. May either be an
805 * associative array mapping message key to value, or a JSON-encoded message blob containing
806 * the same data, wrapped in an XmlJsCode object.
810 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
811 if ( is_string( $scripts ) ) {
812 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
813 } elseif ( !is_array( $scripts ) ) {
814 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
816 return Xml
::encodeJsCall(
817 'mw.loader.implement',
821 // Force objects. mw.loader.implement requires them to be javascript objects.
822 // Although these variables are associative arrays, which become javascript
823 // objects through json_encode. In many cases they will be empty arrays, and
824 // PHP/json_encode() consider empty arrays to be numerical arrays and
825 // output javascript "[]" instead of "{}". This fixes that.
832 * Returns JS code which, when called, will register a given list of messages.
834 * @param $messages Mixed: Either an associative array mapping message key to value, or a
835 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
839 public static function makeMessageSetScript( $messages ) {
840 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
844 * Combines an associative array mapping media type to CSS into a
845 * single stylesheet with @media blocks.
847 * @param $styles Array: List of CSS strings keyed by media type
851 public static function makeCombinedStyles( array $styles ) {
853 foreach ( $styles as $media => $style ) {
854 // Transform the media type based on request params and config
855 // The way that this relies on $wgRequest to propagate request params is slightly evil
856 $media = OutputPage
::transformCssMedia( $media );
858 if ( $media === null ) {
860 } elseif ( $media === '' ||
$media == 'all' ) {
861 // Don't output invalid or frivolous @media statements
864 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
871 * Returns a JS call to mw.loader.state, which sets the state of a
872 * module or modules to a given value. Has two calling conventions:
874 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
875 * Set the state of a single module called $name to $state
877 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
878 * Set the state of modules with the given names to the given states
880 * @param $name string
885 public static function makeLoaderStateScript( $name, $state = null ) {
886 if ( is_array( $name ) ) {
887 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
889 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
894 * Returns JS code which calls the script given by $script. The script will
895 * be called with local variables name, version, dependencies and group,
896 * which will have values corresponding to $name, $version, $dependencies
897 * and $group as supplied.
899 * @param $name String: Module name
900 * @param $version Integer: Module version number as a timestamp
901 * @param $dependencies Array: List of module names on which this module depends
902 * @param $group String: Group which the module is in.
903 * @param $source String: Source of the module, or 'local' if not foreign.
904 * @param $script String: JavaScript code
908 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
909 $script = str_replace( "\n", "\n\t", trim( $script ) );
910 return Xml
::encodeJsCall(
911 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
912 array( $name, $version, $dependencies, $group, $source ) );
916 * Returns JS code which calls mw.loader.register with the given
917 * parameters. Has three calling conventions:
919 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
920 * Register a single module.
922 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
923 * Register modules with the given names.
925 * - ResourceLoader::makeLoaderRegisterScript( array(
926 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
927 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
930 * Registers modules with the given names and parameters.
932 * @param $name String: Module name
933 * @param $version Integer: Module version number as a timestamp
934 * @param $dependencies Array: List of module names on which this module depends
935 * @param $group String: group which the module is in.
936 * @param $source String: source of the module, or 'local' if not foreign
940 public static function makeLoaderRegisterScript( $name, $version = null,
941 $dependencies = null, $group = null, $source = null )
943 if ( is_array( $name ) ) {
944 return Xml
::encodeJsCall( 'mw.loader.register', array( $name ) );
946 $version = (int) $version > 1 ?
(int) $version : 1;
947 return Xml
::encodeJsCall( 'mw.loader.register',
948 array( $name, $version, $dependencies, $group, $source ) );
953 * Returns JS code which calls mw.loader.addSource() with the given
954 * parameters. Has two calling conventions:
956 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
957 * Register a single source
959 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
960 * Register sources with the given IDs and properties.
962 * @param $id String: source ID
963 * @param $properties Array: source properties (see addSource())
967 public static function makeLoaderSourcesScript( $id, $properties = null ) {
968 if ( is_array( $id ) ) {
969 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id ) );
971 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
976 * Returns JS code which runs given JS code if the client-side framework is
979 * @param $script String: JavaScript code
983 public static function makeLoaderConditionalScript( $script ) {
984 return "if(window.mw){\n" . trim( $script ) . "\n}";
988 * Returns JS code which will set the MediaWiki configuration array to
991 * @param $configuration Array: List of configuration values keyed by variable name
995 public static function makeConfigSetScript( array $configuration ) {
996 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ) );
1000 * Convert an array of module names to a packed query string.
1002 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1003 * becomes 'foo.bar,baz|bar.baz,quux'
1004 * @param $modules array of module names (strings)
1005 * @return string Packed query string
1007 public static function makePackedModulesString( $modules ) {
1008 $groups = array(); // array( prefix => array( suffixes ) )
1009 foreach ( $modules as $module ) {
1010 $pos = strrpos( $module, '.' );
1011 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1012 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1013 $groups[$prefix][] = $suffix;
1017 foreach ( $groups as $prefix => $suffixes ) {
1018 $p = $prefix === '' ?
'' : $prefix . '.';
1019 $arr[] = $p . implode( ',', $suffixes );
1021 $str = implode( '|', $arr );
1026 * Determine whether debug mode was requested
1027 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1030 public static function inDebugMode() {
1031 global $wgRequest, $wgResourceLoaderDebug;
1032 static $retval = null;
1033 if ( !is_null( $retval ) ) {
1036 return $retval = $wgRequest->getFuzzyBool( 'debug',
1037 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1041 * Build a load.php URL
1042 * @param $modules array of module names (strings)
1043 * @param $lang string Language code
1044 * @param $skin string Skin name
1045 * @param $user string|null User name. If null, the &user= parameter is omitted
1046 * @param $version string|null Versioning timestamp
1047 * @param $debug bool Whether the request should be in debug mode
1048 * @param $only string|null &only= parameter
1049 * @param $printable bool Printable mode
1050 * @param $handheld bool Handheld mode
1051 * @param $extraQuery array Extra query parameters to add
1052 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1054 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1055 $printable = false, $handheld = false, $extraQuery = array() ) {
1056 global $wgLoadScript;
1057 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1058 $only, $printable, $handheld, $extraQuery
1061 // Prevent the IE6 extension check from being triggered (bug 28840)
1062 // by appending a character that's invalid in Windows extensions ('*')
1063 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1067 * Build a query array (array representation of query string) for load.php. Helper
1068 * function for makeLoaderURL().
1071 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1072 $printable = false, $handheld = false, $extraQuery = array() ) {
1074 'modules' => self
::makePackedModulesString( $modules ),
1077 'debug' => $debug ?
'true' : 'false',
1079 if ( $user !== null ) {
1080 $query['user'] = $user;
1082 if ( $version !== null ) {
1083 $query['version'] = $version;
1085 if ( $only !== null ) {
1086 $query['only'] = $only;
1089 $query['printable'] = 1;
1092 $query['handheld'] = 1;
1094 $query +
= $extraQuery;
1096 // Make queries uniform in order