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();
51 protected $hasErrors = false;
53 /* Protected Methods */
56 * Loads information stored in the database about modules.
58 * This method grabs modules dependencies from the database and updates modules
61 * This is not inside the module code because it is much faster to
62 * request all of the information at once than it is to have each module
63 * requests its own information. This sacrifice of modularity yields a substantial
64 * performance improvement.
66 * @param array $modules List of module names to preload information for
67 * @param $context ResourceLoaderContext: Context to load the information within
69 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
70 if ( !count( $modules ) ) {
71 return; // or else Database*::select() will explode, plus it's cheaper!
73 $dbr = wfGetDB( DB_SLAVE
);
74 $skin = $context->getSkin();
75 $lang = $context->getLanguage();
77 // Get file dependency information
78 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
79 'md_module' => $modules,
84 // Set modules' dependencies
85 $modulesWithDeps = array();
86 foreach ( $res as $row ) {
87 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
88 FormatJson
::decode( $row->md_deps
, true )
90 $modulesWithDeps[] = $row->md_module
;
93 // Register the absence of a dependency row too
94 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
95 $this->getModule( $name )->setFileDependencies( $skin, array() );
98 // Get message blob mtimes. Only do this for modules with messages
99 $modulesWithMessages = array();
100 foreach ( $modules as $name ) {
101 if ( count( $this->getModule( $name )->getMessages() ) ) {
102 $modulesWithMessages[] = $name;
105 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
106 if ( count( $modulesWithMessages ) ) {
107 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
108 'mr_resource' => $modulesWithMessages,
112 foreach ( $res as $row ) {
113 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
114 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
115 unset( $modulesWithoutMessages[$row->mr_resource
] );
118 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
119 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
124 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
126 * Available filters are:
127 * - minify-js \see JavaScriptMinifier::minify
128 * - minify-css \see CSSMin::minify
130 * If $data is empty, only contains whitespace or the filter was unknown,
131 * $data is returned unmodified.
133 * @param string $filter Name of filter to run
134 * @param string $data Text to filter, such as JavaScript or CSS text
135 * @return String: Filtered data, or a comment containing an error message
137 protected function filter( $filter, $data ) {
138 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
139 wfProfileIn( __METHOD__
);
141 // For empty/whitespace-only data or for unknown filters, don't perform
142 // any caching or processing
143 if ( trim( $data ) === ''
144 ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
146 wfProfileOut( __METHOD__
);
151 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
152 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
153 $cache = wfGetCache( CACHE_ANYTHING
);
154 $cacheEntry = $cache->get( $key );
155 if ( is_string( $cacheEntry ) ) {
156 wfProfileOut( __METHOD__
);
161 // Run the filter - we've already verified one of these will work
165 $result = JavaScriptMinifier
::minify( $data,
166 $wgResourceLoaderMinifierStatementsOnOwnLine,
167 $wgResourceLoaderMinifierMaxLineLength
169 $result .= "\n/* cache key: $key */";
172 $result = CSSMin
::minify( $data );
173 $result .= "\n/* cache key: $key */";
177 // Save filtered text to Memcached
178 $cache->set( $key, $result );
179 } catch ( Exception
$exception ) {
180 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $exception" );
181 $this->hasErrors
= true;
182 // Return exception as a comment
183 $result = self
::formatException( $exception );
186 wfProfileOut( __METHOD__
);
194 * Registers core modules and runs registration hooks.
196 public function __construct() {
197 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
199 wfProfileIn( __METHOD__
);
201 // Add 'local' source first
202 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
205 $this->addSource( $wgResourceLoaderSources );
207 // Register core modules
208 $this->register( include "$IP/resources/Resources.php" );
209 // Register extension modules
210 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
211 $this->register( $wgResourceModules );
213 if ( $wgEnableJavaScriptTest === true ) {
214 $this->registerTestModules();
217 wfProfileOut( __METHOD__
);
221 * Registers a module with the ResourceLoader system.
223 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
224 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
225 * this may also be a ResourceLoaderModule object. Optional when using
226 * multiple-registration calling style.
227 * @throws MWException: If a duplicate module registration is attempted
228 * @throws MWException: If a module name contains illegal characters (pipes or commas)
229 * @throws MWException: If something other than a ResourceLoaderModule is being registered
230 * @return Boolean: False if there were any errors, in which case one or more modules were not
233 public function register( $name, $info = null ) {
234 wfProfileIn( __METHOD__
);
236 // Allow multiple modules to be registered in one call
237 $registrations = is_array( $name ) ?
$name : array( $name => $info );
238 foreach ( $registrations as $name => $info ) {
239 // Disallow duplicate registrations
240 if ( isset( $this->moduleInfos
[$name] ) ) {
241 wfProfileOut( __METHOD__
);
242 // A module has already been registered by this name
243 throw new MWException(
244 'ResourceLoader duplicate registration error. ' .
245 'Another module has already been registered as ' . $name
249 // Check $name for validity
250 if ( !self
::isValidModuleName( $name ) ) {
251 wfProfileOut( __METHOD__
);
252 throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" );
256 if ( is_object( $info ) ) {
257 // Old calling convention
258 // Validate the input
259 if ( !( $info instanceof ResourceLoaderModule
) ) {
260 wfProfileOut( __METHOD__
);
261 throw new MWException( 'ResourceLoader invalid module error. ' .
262 'Instances of ResourceLoaderModule expected.' );
265 $this->moduleInfos
[$name] = array( 'object' => $info );
266 $info->setName( $name );
267 $this->modules
[$name] = $info;
269 // New calling convention
270 $this->moduleInfos
[$name] = $info;
274 wfProfileOut( __METHOD__
);
279 public function registerTestModules() {
280 global $IP, $wgEnableJavaScriptTest;
282 if ( $wgEnableJavaScriptTest !== true ) {
283 throw new MWException( 'Attempt to register JavaScript test modules but <code>$wgEnableJavaScriptTest</code> is false. Edit your <code>LocalSettings.php</code> to enable it.' );
286 wfProfileIn( __METHOD__
);
288 // Get core test suites
289 $testModules = array();
290 $testModules['qunit'] = include "$IP/tests/qunit/QUnitTestResources.php";
291 // Get other test suites (e.g. from extensions)
292 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
294 // Add the testrunner (which configures QUnit) to the dependencies.
295 // Since it must be ready before any of the test suites are executed.
296 foreach ( $testModules['qunit'] as &$module ) {
297 // Make sure all test modules are top-loading so that when QUnit starts
298 // on document-ready, it will run once and finish. If some tests arrive
299 // later (possibly after QUnit has already finished) they will be ignored.
300 $module['position'] = 'top';
301 $module['dependencies'][] = 'mediawiki.tests.qunit.testrunner';
304 foreach ( $testModules as $id => $names ) {
305 // Register test modules
306 $this->register( $testModules[$id] );
308 // Keep track of their names so that they can be loaded together
309 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
312 wfProfileOut( __METHOD__
);
316 * Add a foreign source of modules.
319 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
321 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
322 * @param array $properties source properties
323 * @throws MWException
325 public function addSource( $id, $properties = null ) {
326 // Allow multiple sources to be registered in one call
327 if ( is_array( $id ) ) {
328 foreach ( $id as $key => $value ) {
329 $this->addSource( $key, $value );
334 // Disallow duplicates
335 if ( isset( $this->sources
[$id] ) ) {
336 throw new MWException(
337 'ResourceLoader duplicate source addition error. ' .
338 'Another source has already been registered as ' . $id
342 // Validate properties
343 foreach ( self
::$requiredSourceProperties as $prop ) {
344 if ( !isset( $properties[$prop] ) ) {
345 throw new MWException( "Required property $prop missing from source ID $id" );
349 $this->sources
[$id] = $properties;
353 * Get a list of module names
355 * @return Array: List of module names
357 public function getModuleNames() {
358 return array_keys( $this->moduleInfos
);
362 * Get a list of test module names for one (or all) frameworks.
363 * If the given framework id is unknkown, or if the in-object variable is not an array,
364 * then it will return an empty array.
366 * @param string $framework Optional. Get only the test module names for one
367 * particular framework.
370 public function getTestModuleNames( $framework = 'all' ) {
371 /// @todo api siteinfo prop testmodulenames modulenames
372 if ( $framework == 'all' ) {
373 return $this->testModuleNames
;
374 } elseif ( isset( $this->testModuleNames
[$framework] ) && is_array( $this->testModuleNames
[$framework] ) ) {
375 return $this->testModuleNames
[$framework];
382 * Get the ResourceLoaderModule object for a given module name.
384 * @param string $name Module name
385 * @return ResourceLoaderModule if module has been registered, null otherwise
387 public function getModule( $name ) {
388 if ( !isset( $this->modules
[$name] ) ) {
389 if ( !isset( $this->moduleInfos
[$name] ) ) {
393 // Construct the requested object
394 $info = $this->moduleInfos
[$name];
395 /** @var ResourceLoaderModule $object */
396 if ( isset( $info['object'] ) ) {
397 // Object given in info array
398 $object = $info['object'];
400 if ( !isset( $info['class'] ) ) {
401 $class = 'ResourceLoaderFileModule';
403 $class = $info['class'];
405 $object = new $class( $info );
407 $object->setName( $name );
408 $this->modules
[$name] = $object;
411 return $this->modules
[$name];
415 * Get the list of sources
417 * @return Array: array( id => array of properties, .. )
419 public function getSources() {
420 return $this->sources
;
424 * Outputs a response to a resource load-request, including a content-type header.
426 * @param $context ResourceLoaderContext: Context in which a response should be formed
428 public function respond( ResourceLoaderContext
$context ) {
429 global $wgCacheEpoch, $wgUseFileCache;
431 // Use file cache if enabled and available...
432 if ( $wgUseFileCache ) {
433 $fileCache = ResourceFileCache
::newFromContext( $context );
434 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
435 return; // output handled
439 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
440 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
441 // is used: ob_clean() will clear the GZIP header in that case and it won't come
442 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
443 // the whole thing in our own output buffer to be sure the active buffer
444 // doesn't use ob_gzhandler.
445 // See http://bugs.php.net/bug.php?id=36514
448 wfProfileIn( __METHOD__
);
451 // Split requested modules into two groups, modules and missing
454 foreach ( $context->getModules() as $name ) {
455 if ( isset( $this->moduleInfos
[$name] ) ) {
456 $module = $this->getModule( $name );
457 // Do not allow private modules to be loaded from the web.
458 // This is a security issue, see bug 34907.
459 if ( $module->getGroup() === 'private' ) {
460 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
461 $this->hasErrors
= true;
462 // Add exception to the output as a comment
463 $errors .= self
::makeComment( "Cannot show private module \"$name\"" );
467 $modules[$name] = $module;
473 // Preload information needed to the mtime calculation below
475 $this->preloadModuleInfo( array_keys( $modules ), $context );
476 } catch ( Exception
$e ) {
477 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
478 $this->hasErrors
= true;
479 // Add exception to the output as a comment
480 $errors .= self
::formatException( $e );
483 wfProfileIn( __METHOD__
. '-getModifiedTime' );
485 // To send Last-Modified and support If-Modified-Since, we need to detect
486 // the last modified time
487 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
488 foreach ( $modules as $module ) {
490 * @var $module ResourceLoaderModule
493 // Calculate maximum modified time
494 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
495 } catch ( Exception
$e ) {
496 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
497 $this->hasErrors
= true;
498 // Add exception to the output as a comment
499 $errors .= self
::formatException( $e );
503 wfProfileOut( __METHOD__
. '-getModifiedTime' );
505 // If there's an If-Modified-Since header, respond with a 304 appropriately
506 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
507 wfProfileOut( __METHOD__
);
508 return; // output handled (buffers cleared)
511 // Generate a response
512 $response = $this->makeModuleResponse( $context, $modules, $missing );
514 // Prepend comments indicating exceptions
515 $response = $errors . $response;
517 // Capture any PHP warnings from the output buffer and append them to the
518 // response in a comment if we're in debug mode.
519 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
520 $response = self
::makeComment( $warnings ) . $response;
521 $this->hasErrors
= true;
524 // Save response to file cache unless there are errors
525 if ( isset( $fileCache ) && !$errors && !$missing ) {
526 // Cache single modules...and other requests if there are enough hits
527 if ( ResourceFileCache
::useFileCache( $context ) ) {
528 if ( $fileCache->isCacheWorthy() ) {
529 $fileCache->saveText( $response );
531 $fileCache->incrMissesRecent( $context->getRequest() );
536 // Send content type and cache related headers
537 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
539 // Remove the output buffer and output the response
543 wfProfileOut( __METHOD__
);
547 * Send content type and last modified headers to the client.
548 * @param $context ResourceLoaderContext
549 * @param string $mtime TS_MW timestamp to use for last-modified
550 * @param bool $errors Whether there are commented-out errors in the response
553 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
554 global $wgResourceLoaderMaxage;
555 // If a version wasn't specified we need a shorter expiry time for updates
556 // to propagate to clients quickly
557 // If there were errors, we also need a shorter expiry time so we can recover quickly
558 if ( is_null( $context->getVersion() ) ||
$errors ) {
559 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
560 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
561 // If a version was specified we can use a longer expiry time since changing
562 // version numbers causes cache misses
564 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
565 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
567 if ( $context->getOnly() === 'styles' ) {
568 header( 'Content-Type: text/css; charset=utf-8' );
569 header( 'Access-Control-Allow-Origin: *' );
571 header( 'Content-Type: text/javascript; charset=utf-8' );
573 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
574 if ( $context->getDebug() ) {
575 // Do not cache debug responses
576 header( 'Cache-Control: private, no-cache, must-revalidate' );
577 header( 'Pragma: no-cache' );
579 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
580 $exp = min( $maxage, $smaxage );
581 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
586 * If there's an If-Modified-Since header, respond with a 304 appropriately
587 * and clear out the output buffer. If the client cache is too old then do nothing.
588 * @param $context ResourceLoaderContext
589 * @param string $mtime The TS_MW timestamp to check the header against
590 * @return bool True iff 304 header sent and output handled
592 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
593 // If there's an If-Modified-Since header, respond with a 304 appropriately
594 // Some clients send "timestamp;length=123". Strip the part after the first ';'
595 // so we get a valid timestamp.
596 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
597 // Never send 304s in debug mode
598 if ( $ims !== false && !$context->getDebug() ) {
599 $imsTS = strtok( $ims, ';' );
600 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
601 // There's another bug in ob_gzhandler (see also the comment at
602 // the top of this function) that causes it to gzip even empty
603 // responses, meaning it's impossible to produce a truly empty
604 // response (because the gzip header is always there). This is
605 // a problem because 304 responses have to be completely empty
606 // per the HTTP spec, and Firefox behaves buggily when they're not.
607 // See also http://bugs.php.net/bug.php?id=51579
608 // To work around this, we tear down all output buffering before
610 // On some setups, ob_get_level() doesn't seem to go down to zero
611 // no matter how often we call ob_get_clean(), so instead of doing
612 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
613 // we have to be safe here and avoid an infinite loop.
614 // Caching the level is not an option, need to allow it to
615 // shorten the loop on-the-fly (bug 46836)
616 for ( $i = 0; $i < ob_get_level(); $i++
) {
620 header( 'HTTP/1.0 304 Not Modified' );
621 header( 'Status: 304 Not Modified' );
629 * Send out code for a response from file cache if possible
631 * @param $fileCache ResourceFileCache: Cache object for this request URL
632 * @param $context ResourceLoaderContext: Context in which to generate a response
633 * @return bool If this found a cache file and handled the response
635 protected function tryRespondFromFileCache(
636 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
638 global $wgResourceLoaderMaxage;
639 // Buffer output to catch warnings.
641 // Get the maximum age the cache can be
642 $maxage = is_null( $context->getVersion() )
643 ?
$wgResourceLoaderMaxage['unversioned']['server']
644 : $wgResourceLoaderMaxage['versioned']['server'];
645 // Minimum timestamp the cache file must have
646 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
648 try { // RL always hits the DB on file cache miss...
650 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
651 $good = $fileCache->isCacheGood(); // cache existence check
655 $ts = $fileCache->cacheTimestamp();
656 // Send content type and cache headers
657 $this->sendResponseHeaders( $context, $ts, false );
658 // If there's an If-Modified-Since header, respond with a 304 appropriately
659 if ( $this->tryRespondLastModified( $context, $ts ) ) {
660 return false; // output handled (buffers cleared)
662 $response = $fileCache->fetchText();
663 // Capture any PHP warnings from the output buffer and append them to the
664 // response in a comment if we're in debug mode.
665 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
666 $response = "/*\n$warnings\n*/\n" . $response;
668 // Remove the output buffer and output the response
670 echo $response . "\n/* Cached {$ts} */";
671 return true; // cache hit
676 return false; // cache miss
680 * Generate a CSS or JS comment block. Only use this for public data,
681 * not error message details.
683 * @param $text string
686 public static function makeComment( $text ) {
687 $encText = str_replace( '*/', '* /', $text );
688 return "/*\n$encText\n*/\n";
692 * Handle exception display
694 * @param Exception $e to be shown to the user
695 * @return string sanitized text that can be returned to the user
697 public static function formatException( $e ) {
698 global $wgShowExceptionDetails;
700 if ( $wgShowExceptionDetails ) {
701 return self
::makeComment( $e->__toString() );
703 return self
::makeComment( wfMessage( 'internalerror' )->text() );
708 * Generates code for a response
710 * @param $context ResourceLoaderContext: Context in which to generate a response
711 * @param array $modules List of module objects keyed by module name
712 * @param array $missing List of unavailable modules (optional)
713 * @return String: Response data
715 public function makeModuleResponse( ResourceLoaderContext
$context,
716 array $modules, $missing = array()
720 if ( $modules === array() && $missing === array() ) {
721 return '/* No modules requested. Max made me put this here */';
724 wfProfileIn( __METHOD__
);
726 if ( $context->shouldIncludeMessages() ) {
728 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
729 } catch ( Exception
$e ) {
730 wfDebugLog( 'resourceloader', __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e" );
731 $this->hasErrors
= true;
732 // Add exception to the output as a comment
733 $exceptions .= self
::formatException( $e );
741 foreach ( $modules as $name => $module ) {
743 * @var $module ResourceLoaderModule
746 wfProfileIn( __METHOD__
. '-' . $name );
749 if ( $context->shouldIncludeScripts() ) {
750 // If we are in debug mode, we'll want to return an array of URLs if possible
751 // However, we can't do this if the module doesn't support it
752 // We also can't do this if there is an only= parameter, because we have to give
753 // the module a way to return a load.php URL without causing an infinite loop
754 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
755 $scripts = $module->getScriptURLsForDebug( $context );
757 $scripts = $module->getScript( $context );
758 if ( is_string( $scripts ) && strlen( $scripts ) && substr( $scripts, -1 ) !== ';' ) {
759 // bug 27054: Append semicolon to prevent weird bugs
760 // caused by files not terminating their statements right
767 if ( $context->shouldIncludeStyles() ) {
768 // Don't create empty stylesheets like array( '' => '' ) for modules
769 // that don't *have* any stylesheets (bug 38024).
770 $stylePairs = $module->getStyles( $context );
771 if ( count ( $stylePairs ) ) {
772 // If we are in debug mode without &only= set, we'll want to return an array of URLs
773 // See comment near shouldIncludeScripts() for more details
774 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
776 'url' => $module->getStyleURLsForDebug( $context )
779 // Minify CSS before embedding in mw.loader.implement call
780 // (unless in debug mode)
781 if ( !$context->getDebug() ) {
782 foreach ( $stylePairs as $media => $style ) {
783 // Can be either a string or an array of strings.
784 if ( is_array( $style ) ) {
785 $stylePairs[$media] = array();
786 foreach ( $style as $cssText ) {
787 if ( is_string( $cssText ) ) {
788 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
791 } elseif ( is_string( $style ) ) {
792 $stylePairs[$media] = $this->filter( 'minify-css', $style );
796 // Wrap styles into @media groups as needed and flatten into a numerical array
798 'css' => self
::makeCombinedStyles( $stylePairs )
805 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
808 switch ( $context->getOnly() ) {
810 if ( is_string( $scripts ) ) {
811 // Load scripts raw...
813 } elseif ( is_array( $scripts ) ) {
814 // ...except when $scripts is an array of URLs
815 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
819 // We no longer seperate into media, they are all combined now with
820 // custom media type groups into @media .. {} sections as part of the css string.
821 // Module returns either an empty array or a numerical array with css strings.
822 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
825 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
828 $out .= self
::makeLoaderImplementScript(
832 new XmlJsCode( $messagesBlob )
836 } catch ( Exception
$e ) {
837 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
838 $this->hasErrors
= true;
839 // Add exception to the output as a comment
840 $exceptions .= self
::formatException( $e );
842 // Register module as missing
844 unset( $modules[$name] );
846 $isRaw |
= $module->isRaw();
847 wfProfileOut( __METHOD__
. '-' . $name );
850 // Update module states
851 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
852 // Set the state of modules loaded as only scripts to ready
853 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
854 $out .= self
::makeLoaderStateScript(
855 array_fill_keys( array_keys( $modules ), 'ready' ) );
857 // Set the state of modules which were requested but unavailable as missing
858 if ( is_array( $missing ) && count( $missing ) ) {
859 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
863 if ( !$context->getDebug() ) {
864 if ( $context->getOnly() === 'styles' ) {
865 $out = $this->filter( 'minify-css', $out );
867 $out = $this->filter( 'minify-js', $out );
871 wfProfileOut( __METHOD__
);
872 return $exceptions . $out;
878 * Returns JS code to call to mw.loader.implement for a module with
881 * @param string $name Module name
882 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
883 * @param $styles Mixed: Array of CSS strings keyed by media type, or an array of lists of URLs to
884 * CSS files keyed by media type
885 * @param $messages Mixed: List of messages associated with this module. May either be an
886 * associative array mapping message key to value, or a JSON-encoded message blob containing
887 * the same data, wrapped in an XmlJsCode object.
889 * @throws MWException
892 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
893 if ( is_string( $scripts ) ) {
894 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
895 } elseif ( !is_array( $scripts ) ) {
896 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
898 return Xml
::encodeJsCall(
899 'mw.loader.implement',
903 // Force objects. mw.loader.implement requires them to be javascript objects.
904 // Although these variables are associative arrays, which become javascript
905 // objects through json_encode. In many cases they will be empty arrays, and
906 // PHP/json_encode() consider empty arrays to be numerical arrays and
907 // output javascript "[]" instead of "{}". This fixes that.
911 ResourceLoader
::inDebugMode()
916 * Returns JS code which, when called, will register a given list of messages.
918 * @param $messages Mixed: Either an associative array mapping message key to value, or a
919 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
923 public static function makeMessageSetScript( $messages ) {
924 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
928 * Combines an associative array mapping media type to CSS into a
929 * single stylesheet with "@media" blocks.
931 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings.
935 private static function makeCombinedStyles( array $stylePairs ) {
937 foreach ( $stylePairs as $media => $styles ) {
938 // ResourceLoaderFileModule::getStyle can return the styles
939 // as a string or an array of strings. This is to allow separation in
941 $styles = (array)$styles;
942 foreach ( $styles as $style ) {
943 $style = trim( $style );
944 // Don't output an empty "@media print { }" block (bug 40498)
945 if ( $style !== '' ) {
946 // Transform the media type based on request params and config
947 // The way that this relies on $wgRequest to propagate request params is slightly evil
948 $media = OutputPage
::transformCssMedia( $media );
950 if ( $media === '' ||
$media == 'all' ) {
952 } elseif ( is_string( $media ) ) {
953 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
963 * Returns a JS call to mw.loader.state, which sets the state of a
964 * module or modules to a given value. Has two calling conventions:
966 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
967 * Set the state of a single module called $name to $state
969 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
970 * Set the state of modules with the given names to the given states
972 * @param $name string
977 public static function makeLoaderStateScript( $name, $state = null ) {
978 if ( is_array( $name ) ) {
979 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
981 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
986 * Returns JS code which calls the script given by $script. The script will
987 * be called with local variables name, version, dependencies and group,
988 * which will have values corresponding to $name, $version, $dependencies
989 * and $group as supplied.
991 * @param string $name Module name
992 * @param $version Integer: Module version number as a timestamp
993 * @param array $dependencies List of module names on which this module depends
994 * @param string $group Group which the module is in.
995 * @param string $source Source of the module, or 'local' if not foreign.
996 * @param string $script JavaScript code
1000 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
1001 $script = str_replace( "\n", "\n\t", trim( $script ) );
1002 return Xml
::encodeJsCall(
1003 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1004 array( $name, $version, $dependencies, $group, $source ) );
1008 * Returns JS code which calls mw.loader.register with the given
1009 * parameters. Has three calling conventions:
1011 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
1012 * Register a single module.
1014 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1015 * Register modules with the given names.
1017 * - ResourceLoader::makeLoaderRegisterScript( array(
1018 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
1019 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
1022 * Registers modules with the given names and parameters.
1024 * @param string $name Module name
1025 * @param $version Integer: Module version number as a timestamp
1026 * @param array $dependencies List of module names on which this module depends
1027 * @param string $group group which the module is in.
1028 * @param string $source source of the module, or 'local' if not foreign
1032 public static function makeLoaderRegisterScript( $name, $version = null,
1033 $dependencies = null, $group = null, $source = null
1035 if ( is_array( $name ) ) {
1036 return Xml
::encodeJsCall( 'mw.loader.register', array( $name ) );
1038 $version = (int)$version > 1 ?
(int)$version : 1;
1039 return Xml
::encodeJsCall( 'mw.loader.register',
1040 array( $name, $version, $dependencies, $group, $source ) );
1045 * Returns JS code which calls mw.loader.addSource() with the given
1046 * parameters. Has two calling conventions:
1048 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1049 * Register a single source
1051 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1052 * Register sources with the given IDs and properties.
1054 * @param string $id source ID
1055 * @param array $properties source properties (see addSource())
1059 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1060 if ( is_array( $id ) ) {
1061 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id ) );
1063 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
1068 * Returns JS code which runs given JS code if the client-side framework is
1071 * @param string $script JavaScript code
1075 public static function makeLoaderConditionalScript( $script ) {
1076 return "if(window.mw){\n" . trim( $script ) . "\n}";
1080 * Returns JS code which will set the MediaWiki configuration array to
1083 * @param array $configuration List of configuration values keyed by variable name
1087 public static function makeConfigSetScript( array $configuration ) {
1088 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ), ResourceLoader
::inDebugMode() );
1092 * Convert an array of module names to a packed query string.
1094 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1095 * becomes 'foo.bar,baz|bar.baz,quux'
1096 * @param array $modules of module names (strings)
1097 * @return string Packed query string
1099 public static function makePackedModulesString( $modules ) {
1100 $groups = array(); // array( prefix => array( suffixes ) )
1101 foreach ( $modules as $module ) {
1102 $pos = strrpos( $module, '.' );
1103 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1104 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1105 $groups[$prefix][] = $suffix;
1109 foreach ( $groups as $prefix => $suffixes ) {
1110 $p = $prefix === '' ?
'' : $prefix . '.';
1111 $arr[] = $p . implode( ',', $suffixes );
1113 $str = implode( '|', $arr );
1118 * Determine whether debug mode was requested
1119 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1122 public static function inDebugMode() {
1123 global $wgRequest, $wgResourceLoaderDebug;
1124 static $retval = null;
1125 if ( !is_null( $retval ) ) {
1128 return $retval = $wgRequest->getFuzzyBool( 'debug',
1129 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1133 * Build a load.php URL
1134 * @param array $modules of module names (strings)
1135 * @param string $lang Language code
1136 * @param string $skin Skin name
1137 * @param string|null $user User name. If null, the &user= parameter is omitted
1138 * @param string|null $version Versioning timestamp
1139 * @param bool $debug Whether the request should be in debug mode
1140 * @param string|null $only &only= parameter
1141 * @param bool $printable Printable mode
1142 * @param bool $handheld Handheld mode
1143 * @param array $extraQuery Extra query parameters to add
1144 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1146 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1147 $printable = false, $handheld = false, $extraQuery = array() ) {
1148 global $wgLoadScript;
1149 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1150 $only, $printable, $handheld, $extraQuery
1153 // Prevent the IE6 extension check from being triggered (bug 28840)
1154 // by appending a character that's invalid in Windows extensions ('*')
1155 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1159 * Build a query array (array representation of query string) for load.php. Helper
1160 * function for makeLoaderURL().
1162 * @param array $modules
1163 * @param string $lang
1164 * @param string $skin
1165 * @param string $user
1166 * @param string $version
1167 * @param bool $debug
1168 * @param string $only
1169 * @param bool $printable
1170 * @param bool $handheld
1171 * @param array $extraQuery
1175 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1176 $printable = false, $handheld = false, $extraQuery = array() ) {
1178 'modules' => self
::makePackedModulesString( $modules ),
1181 'debug' => $debug ?
'true' : 'false',
1183 if ( $user !== null ) {
1184 $query['user'] = $user;
1186 if ( $version !== null ) {
1187 $query['version'] = $version;
1189 if ( $only !== null ) {
1190 $query['only'] = $only;
1193 $query['printable'] = 1;
1196 $query['handheld'] = 1;
1198 $query +
= $extraQuery;
1200 // Make queries uniform in order
1206 * Check a module name for validity.
1208 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1209 * at most 255 bytes.
1211 * @param string $moduleName Module name to check
1212 * @return bool Whether $moduleName is a valid module name
1214 public static function isValidModuleName( $moduleName ) {
1215 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;