3 * Base class for resource loading system.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Roan Kattouw
22 * @author Trevor Parscal
26 * Dynamic JavaScript and CSS resource loading system.
28 * Most of the documention is on the MediaWiki documentation wiki starting at:
29 * http://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader
{
33 /* Protected Static Members */
34 protected static $filterCacheVersion = 7;
35 protected static $requiredSourceProperties = array( 'loadScript' );
37 /** Array: List of module name/ResourceLoaderModule object pairs */
38 protected $modules = array();
40 /** Associative array mapping module name to info associative array */
41 protected $moduleInfos = array();
43 /** Associative array mapping framework ids to a list of names of test suite modules */
44 /** like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. ) */
45 protected $testModuleNames = array();
47 /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
48 protected $sources = array();
50 /* Protected Methods */
53 * Loads information stored in the database about modules.
55 * This method grabs modules dependencies from the database and updates modules
58 * This is not inside the module code because it is much faster to
59 * request all of the information at once than it is to have each module
60 * requests its own information. This sacrifice of modularity yields a substantial
61 * performance improvement.
63 * @param $modules Array: List of module names to preload information for
64 * @param $context ResourceLoaderContext: Context to load the information within
66 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
67 if ( !count( $modules ) ) {
68 return; // or else Database*::select() will explode, plus it's cheaper!
70 $dbr = wfGetDB( DB_SLAVE
);
71 $skin = $context->getSkin();
72 $lang = $context->getLanguage();
74 // Get file dependency information
75 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
76 'md_module' => $modules,
81 // Set modules' dependencies
82 $modulesWithDeps = array();
83 foreach ( $res as $row ) {
84 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
85 FormatJson
::decode( $row->md_deps
, true )
87 $modulesWithDeps[] = $row->md_module
;
90 // Register the absence of a dependency row too
91 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
92 $this->getModule( $name )->setFileDependencies( $skin, array() );
95 // Get message blob mtimes. Only do this for modules with messages
96 $modulesWithMessages = array();
97 foreach ( $modules as $name ) {
98 if ( count( $this->getModule( $name )->getMessages() ) ) {
99 $modulesWithMessages[] = $name;
102 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
103 if ( count( $modulesWithMessages ) ) {
104 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
105 'mr_resource' => $modulesWithMessages,
109 foreach ( $res as $row ) {
110 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
111 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
112 unset( $modulesWithoutMessages[$row->mr_resource
] );
115 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
116 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
121 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
123 * Available filters are:
124 * - minify-js \see JavaScriptMinifier::minify
125 * - minify-css \see CSSMin::minify
127 * If $data is empty, only contains whitespace or the filter was unknown,
128 * $data is returned unmodified.
130 * @param $filter String: Name of filter to run
131 * @param $data String: Text to filter, such as JavaScript or CSS text
132 * @return String: Filtered data, or a comment containing an error message
134 protected function filter( $filter, $data ) {
135 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
136 wfProfileIn( __METHOD__
);
138 // For empty/whitespace-only data or for unknown filters, don't perform
139 // any caching or processing
140 if ( trim( $data ) === ''
141 ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
143 wfProfileOut( __METHOD__
);
148 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
149 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
150 $cache = wfGetCache( CACHE_ANYTHING
);
151 $cacheEntry = $cache->get( $key );
152 if ( is_string( $cacheEntry ) ) {
153 wfProfileOut( __METHOD__
);
158 // Run the filter - we've already verified one of these will work
162 $result = JavaScriptMinifier
::minify( $data,
163 $wgResourceLoaderMinifierStatementsOnOwnLine,
164 $wgResourceLoaderMinifierMaxLineLength
166 $result .= "\n/* cache key: $key */";
169 $result = CSSMin
::minify( $data );
170 $result .= "\n/* cache key: $key */";
174 // Save filtered text to Memcached
175 $cache->set( $key, $result );
176 } catch ( Exception
$exception ) {
177 // Return exception as a comment
178 $result = $this->makeComment( $exception->__toString() );
179 $this->hasErrors
= true;
182 wfProfileOut( __METHOD__
);
190 * Registers core modules and runs registration hooks.
192 public function __construct() {
193 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
195 wfProfileIn( __METHOD__
);
197 // Add 'local' source first
198 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
201 $this->addSource( $wgResourceLoaderSources );
203 // Register core modules
204 $this->register( include( "$IP/resources/Resources.php" ) );
205 // Register extension modules
206 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
207 $this->register( $wgResourceModules );
209 if ( $wgEnableJavaScriptTest === true ) {
210 $this->registerTestModules();
214 wfProfileOut( __METHOD__
);
218 * Registers a module with the ResourceLoader system.
220 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
221 * @param $info array Module info array. For backwards compatibility with 1.17alpha,
222 * this may also be a ResourceLoaderModule object. Optional when using
223 * multiple-registration calling style.
224 * @throws MWException: If a duplicate module registration is attempted
225 * @throws MWException: If a module name contains illegal characters (pipes or commas)
226 * @throws MWException: If something other than a ResourceLoaderModule is being registered
227 * @return Boolean: False if there were any errors, in which case one or more modules were not
230 public function register( $name, $info = null ) {
231 wfProfileIn( __METHOD__
);
233 // Allow multiple modules to be registered in one call
234 $registrations = is_array( $name ) ?
$name : array( $name => $info );
235 foreach ( $registrations as $name => $info ) {
236 // Disallow duplicate registrations
237 if ( isset( $this->moduleInfos
[$name] ) ) {
238 // A module has already been registered by this name
239 throw new MWException(
240 'ResourceLoader duplicate registration error. ' .
241 'Another module has already been registered as ' . $name
245 // Check $name for validity
246 if ( !self
::isValidModuleName( $name ) ) {
247 throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" );
251 if ( is_object( $info ) ) {
252 // Old calling convention
253 // Validate the input
254 if ( !( $info instanceof ResourceLoaderModule
) ) {
255 throw new MWException( 'ResourceLoader invalid module error. ' .
256 'Instances of ResourceLoaderModule expected.' );
259 $this->moduleInfos
[$name] = array( 'object' => $info );
260 $info->setName( $name );
261 $this->modules
[$name] = $info;
263 // New calling convention
264 $this->moduleInfos
[$name] = $info;
268 wfProfileOut( __METHOD__
);
273 public function registerTestModules() {
274 global $IP, $wgEnableJavaScriptTest;
276 if ( $wgEnableJavaScriptTest !== true ) {
277 throw new MWException( 'Attempt to register JavaScript test modules but <tt>$wgEnableJavaScriptTest</tt> is false. Edit your <tt>LocalSettings.php</tt> to enable it.' );
280 wfProfileIn( __METHOD__
);
282 // Get core test suites
283 $testModules = array();
284 $testModules['qunit'] = include( "$IP/tests/qunit/QUnitTestResources.php" );
285 // Get other test suites (e.g. from extensions)
286 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
288 // Add the testrunner (which configures QUnit) to the dependencies.
289 // Since it must be ready before any of the test suites are executed.
290 foreach( $testModules['qunit'] as $moduleName => $moduleProps ) {
291 $testModules['qunit'][$moduleName]['dependencies'][] = 'mediawiki.tests.qunit.testrunner';
294 foreach( $testModules as $id => $names ) {
295 // Register test modules
296 $this->register( $testModules[$id] );
298 // Keep track of their names so that they can be loaded together
299 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
302 wfProfileOut( __METHOD__
);
306 * Add a foreign source of modules.
309 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
311 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
312 * @param $properties Array: source properties
313 * @throws MWException
315 public function addSource( $id, $properties = null) {
316 // Allow multiple sources to be registered in one call
317 if ( is_array( $id ) ) {
318 foreach ( $id as $key => $value ) {
319 $this->addSource( $key, $value );
324 // Disallow duplicates
325 if ( isset( $this->sources
[$id] ) ) {
326 throw new MWException(
327 'ResourceLoader duplicate source addition error. ' .
328 'Another source has already been registered as ' . $id
332 // Validate properties
333 foreach ( self
::$requiredSourceProperties as $prop ) {
334 if ( !isset( $properties[$prop] ) ) {
335 throw new MWException( "Required property $prop missing from source ID $id" );
339 $this->sources
[$id] = $properties;
343 * Get a list of module names
345 * @return Array: List of module names
347 public function getModuleNames() {
348 return array_keys( $this->moduleInfos
);
352 * Get a list of test module names for one (or all) frameworks.
353 * If the given framework id is unknkown, or if the in-object variable is not an array,
354 * then it will return an empty array.
356 * @param $framework String: Optional. Get only the test module names for one
357 * particular framework.
360 public function getTestModuleNames( $framework = 'all' ) {
361 /// @TODO: api siteinfo prop testmodulenames modulenames
362 if ( $framework == 'all' ) {
363 return $this->testModuleNames
;
364 } elseif ( isset( $this->testModuleNames
[$framework] ) && is_array( $this->testModuleNames
[$framework] ) ) {
365 return $this->testModuleNames
[$framework];
372 * Get the ResourceLoaderModule object for a given module name.
374 * @param $name String: Module name
375 * @return ResourceLoaderModule if module has been registered, null otherwise
377 public function getModule( $name ) {
378 if ( !isset( $this->modules
[$name] ) ) {
379 if ( !isset( $this->moduleInfos
[$name] ) ) {
383 // Construct the requested object
384 $info = $this->moduleInfos
[$name];
385 if ( isset( $info['object'] ) ) {
386 // Object given in info array
387 $object = $info['object'];
389 if ( !isset( $info['class'] ) ) {
390 $class = 'ResourceLoaderFileModule';
392 $class = $info['class'];
394 $object = new $class( $info );
396 $object->setName( $name );
397 $this->modules
[$name] = $object;
400 return $this->modules
[$name];
404 * Get the list of sources
406 * @return Array: array( id => array of properties, .. )
408 public function getSources() {
409 return $this->sources
;
413 * Outputs a response to a resource load-request, including a content-type header.
415 * @param $context ResourceLoaderContext: Context in which a response should be formed
417 public function respond( ResourceLoaderContext
$context ) {
418 global $wgCacheEpoch, $wgUseFileCache;
420 // Use file cache if enabled and available...
421 if ( $wgUseFileCache ) {
422 $fileCache = ResourceFileCache
::newFromContext( $context );
423 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
424 return; // output handled
428 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
429 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
430 // is used: ob_clean() will clear the GZIP header in that case and it won't come
431 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
432 // the whole thing in our own output buffer to be sure the active buffer
433 // doesn't use ob_gzhandler.
434 // See http://bugs.php.net/bug.php?id=36514
437 wfProfileIn( __METHOD__
);
439 $this->hasErrors
= false;
441 // Split requested modules into two groups, modules and missing
444 foreach ( $context->getModules() as $name ) {
445 if ( isset( $this->moduleInfos
[$name] ) ) {
446 $module = $this->getModule( $name );
447 // Do not allow private modules to be loaded from the web.
448 // This is a security issue, see bug 34907.
449 if ( $module->getGroup() === 'private' ) {
450 $errors .= $this->makeComment( "Cannot show private module \"$name\"" );
451 $this->hasErrors
= true;
454 $modules[$name] = $this->getModule( $name );
460 // Preload information needed to the mtime calculation below
462 $this->preloadModuleInfo( array_keys( $modules ), $context );
463 } catch( Exception
$e ) {
464 // Add exception to the output as a comment
465 $errors .= $this->makeComment( $e->__toString() );
466 $this->hasErrors
= true;
469 wfProfileIn( __METHOD__
.'-getModifiedTime' );
471 // To send Last-Modified and support If-Modified-Since, we need to detect
472 // the last modified time
473 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
474 foreach ( $modules as $module ) {
476 * @var $module ResourceLoaderModule
479 // Calculate maximum modified time
480 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
481 } catch ( Exception
$e ) {
482 // Add exception to the output as a comment
483 $errors .= $this->makeComment( $e->__toString() );
484 $this->hasErrors
= true;
488 wfProfileOut( __METHOD__
.'-getModifiedTime' );
490 // If there's an If-Modified-Since header, respond with a 304 appropriately
491 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
492 wfProfileOut( __METHOD__
);
493 return; // output handled (buffers cleared)
496 // Generate a response
497 $response = $this->makeModuleResponse( $context, $modules, $missing );
499 // Prepend comments indicating exceptions
500 $response = $errors . $response;
502 // Capture any PHP warnings from the output buffer and append them to the
503 // response in a comment if we're in debug mode.
504 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
505 $response = $this->makeComment( $warnings ) . $response;
506 $this->hasErrors
= true;
509 // Save response to file cache unless there are errors
510 if ( isset( $fileCache ) && !$errors && !$missing ) {
511 // Cache single modules...and other requests if there are enough hits
512 if ( ResourceFileCache
::useFileCache( $context ) ) {
513 if ( $fileCache->isCacheWorthy() ) {
514 $fileCache->saveText( $response );
516 $fileCache->incrMissesRecent( $context->getRequest() );
521 // Send content type and cache related headers
522 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
524 // Remove the output buffer and output the response
528 wfProfileOut( __METHOD__
);
532 * Send content type and last modified headers to the client.
533 * @param $context ResourceLoaderContext
534 * @param $mtime string TS_MW timestamp to use for last-modified
535 * @param $error bool Whether there are commented-out errors in the response
538 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
539 global $wgResourceLoaderMaxage;
540 // If a version wasn't specified we need a shorter expiry time for updates
541 // to propagate to clients quickly
542 // If there were errors, we also need a shorter expiry time so we can recover quickly
543 if ( is_null( $context->getVersion() ) ||
$errors ) {
544 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
545 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
546 // If a version was specified we can use a longer expiry time since changing
547 // version numbers causes cache misses
549 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
550 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
552 if ( $context->getOnly() === 'styles' ) {
553 header( 'Content-Type: text/css; charset=utf-8' );
555 header( 'Content-Type: text/javascript; charset=utf-8' );
557 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
558 if ( $context->getDebug() ) {
559 // Do not cache debug responses
560 header( 'Cache-Control: private, no-cache, must-revalidate' );
561 header( 'Pragma: no-cache' );
563 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
564 $exp = min( $maxage, $smaxage );
565 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
570 * If there's an If-Modified-Since header, respond with a 304 appropriately
571 * and clear out the output buffer. If the client cache is too old then do nothing.
572 * @param $context ResourceLoaderContext
573 * @param $mtime string The TS_MW timestamp to check the header against
574 * @return bool True iff 304 header sent and output handled
576 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
577 // If there's an If-Modified-Since header, respond with a 304 appropriately
578 // Some clients send "timestamp;length=123". Strip the part after the first ';'
579 // so we get a valid timestamp.
580 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
581 // Never send 304s in debug mode
582 if ( $ims !== false && !$context->getDebug() ) {
583 $imsTS = strtok( $ims, ';' );
584 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
585 // There's another bug in ob_gzhandler (see also the comment at
586 // the top of this function) that causes it to gzip even empty
587 // responses, meaning it's impossible to produce a truly empty
588 // response (because the gzip header is always there). This is
589 // a problem because 304 responses have to be completely empty
590 // per the HTTP spec, and Firefox behaves buggily when they're not.
591 // See also http://bugs.php.net/bug.php?id=51579
592 // To work around this, we tear down all output buffering before
594 // On some setups, ob_get_level() doesn't seem to go down to zero
595 // no matter how often we call ob_get_clean(), so instead of doing
596 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
597 // we have to be safe here and avoid an infinite loop.
598 for ( $i = 0; $i < ob_get_level(); $i++
) {
602 header( 'HTTP/1.0 304 Not Modified' );
603 header( 'Status: 304 Not Modified' );
611 * Send out code for a response from file cache if possible
613 * @param $fileCache ResourceFileCache: Cache object for this request URL
614 * @param $context ResourceLoaderContext: Context in which to generate a response
615 * @return bool If this found a cache file and handled the response
617 protected function tryRespondFromFileCache(
618 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
620 global $wgResourceLoaderMaxage;
621 // Buffer output to catch warnings.
623 // Get the maximum age the cache can be
624 $maxage = is_null( $context->getVersion() )
625 ?
$wgResourceLoaderMaxage['unversioned']['server']
626 : $wgResourceLoaderMaxage['versioned']['server'];
627 // Minimum timestamp the cache file must have
628 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
630 try { // RL always hits the DB on file cache miss...
632 } catch( DBConnectionError
$e ) { // ...check if we need to fallback to cache
633 $good = $fileCache->isCacheGood(); // cache existence check
637 $ts = $fileCache->cacheTimestamp();
638 // Send content type and cache headers
639 $this->sendResponseHeaders( $context, $ts, false );
640 // If there's an If-Modified-Since header, respond with a 304 appropriately
641 if ( $this->tryRespondLastModified( $context, $ts ) ) {
642 return false; // output handled (buffers cleared)
644 $response = $fileCache->fetchText();
645 // Capture any PHP warnings from the output buffer and append them to the
646 // response in a comment if we're in debug mode.
647 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
648 $response = "/*\n$warnings\n*/\n" . $response;
650 // Remove the output buffer and output the response
652 echo $response . "\n/* Cached {$ts} */";
653 return true; // cache hit
658 return false; // cache miss
661 protected function makeComment( $text ) {
662 $encText = str_replace( '*/', '* /', $text );
663 return "/*\n$encText\n*/\n";
667 * Generates code for a response
669 * @param $context ResourceLoaderContext: Context in which to generate a response
670 * @param $modules Array: List of module objects keyed by module name
671 * @param $missing Array: List of unavailable modules (optional)
672 * @return String: Response data
674 public function makeModuleResponse( ResourceLoaderContext
$context,
675 array $modules, $missing = array() )
679 if ( $modules === array() && $missing === array() ) {
680 return '/* No modules requested. Max made me put this here */';
683 wfProfileIn( __METHOD__
);
685 if ( $context->shouldIncludeMessages() ) {
687 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
688 } catch ( Exception
$e ) {
689 // Add exception to the output as a comment
690 $exceptions .= $this->makeComment( $e->__toString() );
691 $this->hasErrors
= true;
699 foreach ( $modules as $name => $module ) {
701 * @var $module ResourceLoaderModule
704 wfProfileIn( __METHOD__
. '-' . $name );
707 if ( $context->shouldIncludeScripts() ) {
708 // If we are in debug mode, we'll want to return an array of URLs if possible
709 // However, we can't do this if the module doesn't support it
710 // We also can't do this if there is an only= parameter, because we have to give
711 // the module a way to return a load.php URL without causing an infinite loop
712 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
713 $scripts = $module->getScriptURLsForDebug( $context );
715 $scripts = $module->getScript( $context );
716 if ( is_string( $scripts ) && strlen( $scripts ) && substr( $scripts, -1 ) !== ';' ) {
717 // bug 27054: Append semicolon to prevent weird bugs
718 // caused by files not terminating their statements right
725 if ( $context->shouldIncludeStyles() ) {
726 // Don't create empty stylesheets like array( '' => '' ) for modules
727 // that don't *have* any stylesheets (bug 38024).
728 $stylePairs = $module->getStyles( $context );
729 if ( count ( $stylePairs ) ) {
730 // If we are in debug mode without &only= set, we'll want to return an array of URLs
731 // See comment near shouldIncludeScripts() for more details
732 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
734 'url' => $module->getStyleURLsForDebug( $context )
737 // Minify CSS before embedding in mw.loader.implement call
738 // (unless in debug mode)
739 if ( !$context->getDebug() ) {
740 foreach ( $stylePairs as $media => $style ) {
741 // Can be either a string or an array of strings.
742 if ( is_array( $style ) ) {
743 $stylePairs[$media] = array();
744 foreach ( $style as $cssText ) {
745 if ( is_string( $cssText ) ) {
746 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
749 } elseif ( is_string( $style ) ) {
750 $stylePairs[$media] = $this->filter( 'minify-css', $style );
754 // Wrap styles into @media groups as needed and flatten into a numerical array
756 'css' => self
::makeCombinedStyles( $stylePairs )
763 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
766 switch ( $context->getOnly() ) {
768 if ( is_string( $scripts ) ) {
769 // Load scripts raw...
771 } elseif ( is_array( $scripts ) ) {
772 // ...except when $scripts is an array of URLs
773 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
777 // We no longer seperate into media, they are all combined now with
778 // custom media type groups into @media .. {} sections as part of the css string.
779 // Module returns either an empty array or a numerical array with css strings.
780 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
783 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
786 $out .= self
::makeLoaderImplementScript(
790 new XmlJsCode( $messagesBlob )
794 } catch ( Exception
$e ) {
795 // Add exception to the output as a comment
796 $exceptions .= $this->makeComment( $e->__toString() );
797 $this->hasErrors
= true;
799 // Register module as missing
801 unset( $modules[$name] );
803 $isRaw |
= $module->isRaw();
804 wfProfileOut( __METHOD__
. '-' . $name );
807 // Update module states
808 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
809 // Set the state of modules loaded as only scripts to ready
810 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
811 $out .= self
::makeLoaderStateScript(
812 array_fill_keys( array_keys( $modules ), 'ready' ) );
814 // Set the state of modules which were requested but unavailable as missing
815 if ( is_array( $missing ) && count( $missing ) ) {
816 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
820 if ( !$context->getDebug() ) {
821 if ( $context->getOnly() === 'styles' ) {
822 $out = $this->filter( 'minify-css', $out );
824 $out = $this->filter( 'minify-js', $out );
828 wfProfileOut( __METHOD__
);
829 return $exceptions . $out;
835 * Returns JS code to call to mw.loader.implement for a module with
838 * @param $name string Module name
839 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
840 * @param $styles Mixed: Array of CSS strings keyed by media type, or an array of lists of URLs to
841 * CSS files keyed by media type
842 * @param $messages Mixed: List of messages associated with this module. May either be an
843 * associative array mapping message key to value, or a JSON-encoded message blob containing
844 * the same data, wrapped in an XmlJsCode object.
846 * @throws MWException
849 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
850 if ( is_string( $scripts ) ) {
851 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
852 } elseif ( !is_array( $scripts ) ) {
853 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
855 return Xml
::encodeJsCall(
856 'mw.loader.implement',
860 // Force objects. mw.loader.implement requires them to be javascript objects.
861 // Although these variables are associative arrays, which become javascript
862 // objects through json_encode. In many cases they will be empty arrays, and
863 // PHP/json_encode() consider empty arrays to be numerical arrays and
864 // output javascript "[]" instead of "{}". This fixes that.
871 * Returns JS code which, when called, will register a given list of messages.
873 * @param $messages Mixed: Either an associative array mapping message key to value, or a
874 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
878 public static function makeMessageSetScript( $messages ) {
879 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
883 * Combines an associative array mapping media type to CSS into a
884 * single stylesheet with "@media" blocks.
886 * @param $stylePairs Array: Array keyed by media type containing (arrays of) CSS strings.
890 private static function makeCombinedStyles( array $stylePairs ) {
892 foreach ( $stylePairs as $media => $styles ) {
893 // ResourceLoaderFileModule::getStyle can return the styles
894 // as a string or an array of strings. This is to allow separation in
896 $styles = (array) $styles;
897 foreach ( $styles as $style ) {
898 $style = trim( $style );
899 // Don't output an empty "@media print { }" block (bug 40498)
900 if ( $style !== '' ) {
901 // Transform the media type based on request params and config
902 // The way that this relies on $wgRequest to propagate request params is slightly evil
903 $media = OutputPage
::transformCssMedia( $media );
905 if ( $media === '' ||
$media == 'all' ) {
907 } else if ( is_string( $media ) ) {
908 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
918 * Returns a JS call to mw.loader.state, which sets the state of a
919 * module or modules to a given value. Has two calling conventions:
921 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
922 * Set the state of a single module called $name to $state
924 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
925 * Set the state of modules with the given names to the given states
927 * @param $name string
932 public static function makeLoaderStateScript( $name, $state = null ) {
933 if ( is_array( $name ) ) {
934 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
936 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
941 * Returns JS code which calls the script given by $script. The script will
942 * be called with local variables name, version, dependencies and group,
943 * which will have values corresponding to $name, $version, $dependencies
944 * and $group as supplied.
946 * @param $name String: Module name
947 * @param $version Integer: Module version number as a timestamp
948 * @param $dependencies Array: List of module names on which this module depends
949 * @param $group String: Group which the module is in.
950 * @param $source String: Source of the module, or 'local' if not foreign.
951 * @param $script String: JavaScript code
955 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
956 $script = str_replace( "\n", "\n\t", trim( $script ) );
957 return Xml
::encodeJsCall(
958 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
959 array( $name, $version, $dependencies, $group, $source ) );
963 * Returns JS code which calls mw.loader.register with the given
964 * parameters. Has three calling conventions:
966 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
967 * Register a single module.
969 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
970 * Register modules with the given names.
972 * - ResourceLoader::makeLoaderRegisterScript( array(
973 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
974 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
977 * Registers modules with the given names and parameters.
979 * @param $name String: Module name
980 * @param $version Integer: Module version number as a timestamp
981 * @param $dependencies Array: List of module names on which this module depends
982 * @param $group String: group which the module is in.
983 * @param $source String: source of the module, or 'local' if not foreign
987 public static function makeLoaderRegisterScript( $name, $version = null,
988 $dependencies = null, $group = null, $source = null )
990 if ( is_array( $name ) ) {
991 return Xml
::encodeJsCall( 'mw.loader.register', array( $name ) );
993 $version = (int) $version > 1 ?
(int) $version : 1;
994 return Xml
::encodeJsCall( 'mw.loader.register',
995 array( $name, $version, $dependencies, $group, $source ) );
1000 * Returns JS code which calls mw.loader.addSource() with the given
1001 * parameters. Has two calling conventions:
1003 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1004 * Register a single source
1006 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1007 * Register sources with the given IDs and properties.
1009 * @param $id String: source ID
1010 * @param $properties Array: source properties (see addSource())
1014 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1015 if ( is_array( $id ) ) {
1016 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id ) );
1018 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
1023 * Returns JS code which runs given JS code if the client-side framework is
1026 * @param $script String: JavaScript code
1030 public static function makeLoaderConditionalScript( $script ) {
1031 return "if(window.mw){\n" . trim( $script ) . "\n}";
1035 * Returns JS code which will set the MediaWiki configuration array to
1038 * @param $configuration Array: List of configuration values keyed by variable name
1042 public static function makeConfigSetScript( array $configuration ) {
1043 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ) );
1047 * Convert an array of module names to a packed query string.
1049 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1050 * becomes 'foo.bar,baz|bar.baz,quux'
1051 * @param $modules array of module names (strings)
1052 * @return string Packed query string
1054 public static function makePackedModulesString( $modules ) {
1055 $groups = array(); // array( prefix => array( suffixes ) )
1056 foreach ( $modules as $module ) {
1057 $pos = strrpos( $module, '.' );
1058 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1059 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1060 $groups[$prefix][] = $suffix;
1064 foreach ( $groups as $prefix => $suffixes ) {
1065 $p = $prefix === '' ?
'' : $prefix . '.';
1066 $arr[] = $p . implode( ',', $suffixes );
1068 $str = implode( '|', $arr );
1073 * Determine whether debug mode was requested
1074 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1077 public static function inDebugMode() {
1078 global $wgRequest, $wgResourceLoaderDebug;
1079 static $retval = null;
1080 if ( !is_null( $retval ) ) {
1083 return $retval = $wgRequest->getFuzzyBool( 'debug',
1084 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1088 * Build a load.php URL
1089 * @param $modules array of module names (strings)
1090 * @param $lang string Language code
1091 * @param $skin string Skin name
1092 * @param $user string|null User name. If null, the &user= parameter is omitted
1093 * @param $version string|null Versioning timestamp
1094 * @param $debug bool Whether the request should be in debug mode
1095 * @param $only string|null &only= parameter
1096 * @param $printable bool Printable mode
1097 * @param $handheld bool Handheld mode
1098 * @param $extraQuery array Extra query parameters to add
1099 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1101 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1102 $printable = false, $handheld = false, $extraQuery = array() ) {
1103 global $wgLoadScript;
1104 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1105 $only, $printable, $handheld, $extraQuery
1108 // Prevent the IE6 extension check from being triggered (bug 28840)
1109 // by appending a character that's invalid in Windows extensions ('*')
1110 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1114 * Build a query array (array representation of query string) for load.php. Helper
1115 * function for makeLoaderURL().
1118 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1119 $printable = false, $handheld = false, $extraQuery = array() ) {
1121 'modules' => self
::makePackedModulesString( $modules ),
1124 'debug' => $debug ?
'true' : 'false',
1126 if ( $user !== null ) {
1127 $query['user'] = $user;
1129 if ( $version !== null ) {
1130 $query['version'] = $version;
1132 if ( $only !== null ) {
1133 $query['only'] = $only;
1136 $query['printable'] = 1;
1139 $query['handheld'] = 1;
1141 $query +
= $extraQuery;
1143 // Make queries uniform in order
1149 * Check a module name for validity.
1151 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1152 * at most 255 bytes.
1154 * @param $moduleName string Module name to check
1155 * @return bool Whether $moduleName is a valid module name
1157 public static function isValidModuleName( $moduleName ) {
1158 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;