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 documentation is on the MediaWiki documentation wiki starting at:
29 * https://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader
{
33 protected static $filterCacheVersion = 7;
36 protected static $debugMode = null;
39 * Module name/ResourceLoaderModule object pairs
42 protected $modules = array();
45 * Associative array mapping module name to info associative array
48 protected $moduleInfos = array();
50 /** @var Config $config */
54 * Associative array mapping framework ids to a list of names of test suite modules
55 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
58 protected $testModuleNames = array();
61 * E.g. array( 'source-id' => 'http://.../load.php' )
64 protected $sources = array();
67 * Errors accumulated during current respond() call.
70 protected $errors = array();
73 * Load information stored in the database about modules.
75 * This method grabs modules dependencies from the database and updates modules
78 * This is not inside the module code because it is much faster to
79 * request all of the information at once than it is to have each module
80 * requests its own information. This sacrifice of modularity yields a substantial
81 * performance improvement.
83 * @param array $modules List of module names to preload information for
84 * @param ResourceLoaderContext $context Context to load the information within
86 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
87 if ( !count( $modules ) ) {
88 // Or else Database*::select() will explode, plus it's cheaper!
91 $dbr = wfGetDB( DB_SLAVE
);
92 $skin = $context->getSkin();
93 $lang = $context->getLanguage();
95 // Get file dependency information
96 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
97 'md_module' => $modules,
102 // Set modules' dependencies
103 $modulesWithDeps = array();
104 foreach ( $res as $row ) {
105 $module = $this->getModule( $row->md_module
);
107 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
108 $modulesWithDeps[] = $row->md_module
;
112 // Register the absence of a dependency row too
113 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
114 $module = $this->getModule( $name );
116 $this->getModule( $name )->setFileDependencies( $skin, array() );
120 // Get message blob mtimes. Only do this for modules with messages
121 $modulesWithMessages = array();
122 foreach ( $modules as $name ) {
123 $module = $this->getModule( $name );
124 if ( $module && count( $module->getMessages() ) ) {
125 $modulesWithMessages[] = $name;
128 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
129 if ( count( $modulesWithMessages ) ) {
130 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
131 'mr_resource' => $modulesWithMessages,
135 foreach ( $res as $row ) {
136 $module = $this->getModule( $row->mr_resource
);
138 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
139 unset( $modulesWithoutMessages[$row->mr_resource
] );
143 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
144 $module = $this->getModule( $name );
146 $module->setMsgBlobMtime( $lang, 1 );
152 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
154 * Available filters are:
156 * - minify-js \see JavaScriptMinifier::minify
157 * - minify-css \see CSSMin::minify
159 * If $data is empty, only contains whitespace or the filter was unknown,
160 * $data is returned unmodified.
162 * @param string $filter Name of filter to run
163 * @param string $data Text to filter, such as JavaScript or CSS text
164 * @param string $cacheReport Whether to include the cache key report
165 * @return string Filtered data, or a comment containing an error message
167 public function filter( $filter, $data, $cacheReport = true ) {
169 // For empty/whitespace-only data or for unknown filters, don't perform
170 // any caching or processing
171 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
176 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
177 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
178 $cache = wfGetCache( CACHE_ANYTHING
);
179 $cacheEntry = $cache->get( $key );
180 if ( is_string( $cacheEntry ) ) {
181 wfIncrStats( "rl-$filter-cache-hits" );
186 // Run the filter - we've already verified one of these will work
188 wfIncrStats( "rl-$filter-cache-misses" );
191 $result = JavaScriptMinifier
::minify( $data,
192 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
193 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
195 if ( $cacheReport ) {
196 $result .= "\n/* cache key: $key */";
200 $result = CSSMin
::minify( $data );
201 if ( $cacheReport ) {
202 $result .= "\n/* cache key: $key */";
207 // Save filtered text to Memcached
208 $cache->set( $key, $result );
209 } catch ( Exception
$e ) {
210 MWExceptionHandler
::logException( $e );
211 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
212 $this->errors
[] = self
::formatExceptionNoComment( $e );
222 * Register core modules and runs registration hooks.
223 * @param Config|null $config
225 public function __construct( Config
$config = null ) {
229 if ( $config === null ) {
230 wfDebug( __METHOD__
. ' was called without providing a Config instance' );
231 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
234 $this->config
= $config;
236 // Add 'local' source first
237 $this->addSource( 'local', wfScript( 'load' ) );
240 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
242 // Register core modules
243 $this->register( include "$IP/resources/Resources.php" );
244 // Register extension modules
245 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
246 $this->register( $config->get( 'ResourceModules' ) );
248 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
249 $this->registerTestModules();
257 public function getConfig() {
258 return $this->config
;
262 * Register a module with the ResourceLoader system.
264 * @param mixed $name Name of module as a string or List of name/object pairs as an array
265 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
266 * this may also be a ResourceLoaderModule object. Optional when using
267 * multiple-registration calling style.
268 * @throws MWException If a duplicate module registration is attempted
269 * @throws MWException If a module name contains illegal characters (pipes or commas)
270 * @throws MWException If something other than a ResourceLoaderModule is being registered
271 * @return bool False if there were any errors, in which case one or more modules were
274 public function register( $name, $info = null ) {
276 // Allow multiple modules to be registered in one call
277 $registrations = is_array( $name ) ?
$name : array( $name => $info );
278 foreach ( $registrations as $name => $info ) {
279 // Disallow duplicate registrations
280 if ( isset( $this->moduleInfos
[$name] ) ) {
281 // A module has already been registered by this name
282 throw new MWException(
283 'ResourceLoader duplicate registration error. ' .
284 'Another module has already been registered as ' . $name
288 // Check $name for validity
289 if ( !self
::isValidModuleName( $name ) ) {
290 throw new MWException( "ResourceLoader module name '$name' is invalid, "
291 . "see ResourceLoader::isValidModuleName()" );
295 if ( $info instanceof ResourceLoaderModule
) {
296 $this->moduleInfos
[$name] = array( 'object' => $info );
297 $info->setName( $name );
298 $this->modules
[$name] = $info;
299 } elseif ( is_array( $info ) ) {
300 // New calling convention
301 $this->moduleInfos
[$name] = $info;
303 throw new MWException(
304 'ResourceLoader module info type error for module \'' . $name .
305 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
309 // Last-minute changes
311 // Apply custom skin-defined styles to existing modules.
312 if ( $this->isFileModule( $name ) ) {
313 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
314 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
315 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
319 // If $name is preceded with a '+', the defined style files will be added to 'default'
320 // skinStyles, otherwise 'default' will be ignored as it normally would be.
321 if ( isset( $skinStyles[$name] ) ) {
322 $paths = (array)$skinStyles[$name];
323 $styleFiles = array();
324 } elseif ( isset( $skinStyles['+' . $name] ) ) {
325 $paths = (array)$skinStyles['+' . $name];
326 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
327 $this->moduleInfos
[$name]['skinStyles']['default'] :
333 // Add new file paths, remapping them to refer to our directories and not use settings
334 // from the module we're modifying. These can come from the base definition or be defined
336 list( $localBasePath, $remoteBasePath ) =
337 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
338 list( $localBasePath, $remoteBasePath ) =
339 ResourceLoaderFileModule
::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
341 foreach ( $paths as $path ) {
342 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
345 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
354 public function registerTestModules() {
357 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
358 throw new MWException( 'Attempt to register JavaScript test modules '
359 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
360 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
364 // Get core test suites
365 $testModules = array();
366 $testModules['qunit'] = array();
367 // Get other test suites (e.g. from extensions)
368 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
370 // Add the testrunner (which configures QUnit) to the dependencies.
371 // Since it must be ready before any of the test suites are executed.
372 foreach ( $testModules['qunit'] as &$module ) {
373 // Make sure all test modules are top-loading so that when QUnit starts
374 // on document-ready, it will run once and finish. If some tests arrive
375 // later (possibly after QUnit has already finished) they will be ignored.
376 $module['position'] = 'top';
377 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
380 $testModules['qunit'] =
381 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
383 foreach ( $testModules as $id => $names ) {
384 // Register test modules
385 $this->register( $testModules[$id] );
387 // Keep track of their names so that they can be loaded together
388 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
394 * Add a foreign source of modules.
396 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
397 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
398 * backwards-compatibility.
399 * @throws MWException
401 public function addSource( $id, $loadUrl = null ) {
402 // Allow multiple sources to be registered in one call
403 if ( is_array( $id ) ) {
404 foreach ( $id as $key => $value ) {
405 $this->addSource( $key, $value );
410 // Disallow duplicates
411 if ( isset( $this->sources
[$id] ) ) {
412 throw new MWException(
413 'ResourceLoader duplicate source addition error. ' .
414 'Another source has already been registered as ' . $id
418 // Pre 1.24 backwards-compatibility
419 if ( is_array( $loadUrl ) ) {
420 if ( !isset( $loadUrl['loadScript'] ) ) {
421 throw new MWException(
422 __METHOD__
. ' was passed an array with no "loadScript" key.'
426 $loadUrl = $loadUrl['loadScript'];
429 $this->sources
[$id] = $loadUrl;
433 * Get a list of module names.
435 * @return array List of module names
437 public function getModuleNames() {
438 return array_keys( $this->moduleInfos
);
442 * Get a list of test module names for one (or all) frameworks.
444 * If the given framework id is unknkown, or if the in-object variable is not an array,
445 * then it will return an empty array.
447 * @param string $framework Get only the test module names for one
448 * particular framework (optional)
451 public function getTestModuleNames( $framework = 'all' ) {
452 /** @todo api siteinfo prop testmodulenames modulenames */
453 if ( $framework == 'all' ) {
454 return $this->testModuleNames
;
455 } elseif ( isset( $this->testModuleNames
[$framework] )
456 && is_array( $this->testModuleNames
[$framework] )
458 return $this->testModuleNames
[$framework];
465 * Get the ResourceLoaderModule object for a given module name.
467 * If an array of module parameters exists but a ResourceLoaderModule object has not
468 * yet been instantiated, this method will instantiate and cache that object such that
469 * subsequent calls simply return the same object.
471 * @param string $name Module name
472 * @return ResourceLoaderModule|null If module has been registered, return a
473 * ResourceLoaderModule instance. Otherwise, return null.
475 public function getModule( $name ) {
476 if ( !isset( $this->modules
[$name] ) ) {
477 if ( !isset( $this->moduleInfos
[$name] ) ) {
481 // Construct the requested object
482 $info = $this->moduleInfos
[$name];
483 /** @var ResourceLoaderModule $object */
484 if ( isset( $info['object'] ) ) {
485 // Object given in info array
486 $object = $info['object'];
488 if ( !isset( $info['class'] ) ) {
489 $class = 'ResourceLoaderFileModule';
491 $class = $info['class'];
493 /** @var ResourceLoaderModule $object */
494 $object = new $class( $info );
495 $object->setConfig( $this->getConfig() );
497 $object->setName( $name );
498 $this->modules
[$name] = $object;
501 return $this->modules
[$name];
505 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
507 * @param string $name Module name
510 protected function isFileModule( $name ) {
511 if ( !isset( $this->moduleInfos
[$name] ) ) {
514 $info = $this->moduleInfos
[$name];
515 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
522 * Get the list of sources.
524 * @return array Like array( id => load.php url, .. )
526 public function getSources() {
527 return $this->sources
;
531 * Get the URL to the load.php endpoint for the given
532 * ResourceLoader source
535 * @param string $source
536 * @throws MWException On an invalid $source name
539 public function getLoadScript( $source ) {
540 if ( !isset( $this->sources
[$source] ) ) {
541 throw new MWException( "The $source source was never registered in ResourceLoader." );
543 return $this->sources
[$source];
547 * Output a response to a load request, including the content-type header.
549 * @param ResourceLoaderContext $context Context in which a response should be formed
551 public function respond( ResourceLoaderContext
$context ) {
552 // Use file cache if enabled and available...
553 if ( $this->config
->get( 'UseFileCache' ) ) {
554 $fileCache = ResourceFileCache
::newFromContext( $context );
555 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
556 return; // output handled
560 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
561 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
562 // is used: ob_clean() will clear the GZIP header in that case and it won't come
563 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
564 // the whole thing in our own output buffer to be sure the active buffer
565 // doesn't use ob_gzhandler.
566 // See http://bugs.php.net/bug.php?id=36514
570 // Find out which modules are missing and instantiate the others
573 foreach ( $context->getModules() as $name ) {
574 $module = $this->getModule( $name );
576 // Do not allow private modules to be loaded from the web.
577 // This is a security issue, see bug 34907.
578 if ( $module->getGroup() === 'private' ) {
579 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
580 $this->errors
[] = "Cannot show private module \"$name\"";
583 $modules[$name] = $module;
589 // Preload information needed to the mtime calculation below
591 $this->preloadModuleInfo( array_keys( $modules ), $context );
592 } catch ( Exception
$e ) {
593 MWExceptionHandler
::logException( $e );
594 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
595 $this->errors
[] = self
::formatExceptionNoComment( $e );
598 wfProfileIn( __METHOD__
. '-getModifiedTime' );
600 // To send Last-Modified and support If-Modified-Since, we need to detect
601 // the last modified time
602 $mtime = wfTimestamp( TS_UNIX
, $this->config
->get( 'CacheEpoch' ) );
603 foreach ( $modules as $module ) {
605 * @var $module ResourceLoaderModule
608 // Calculate maximum modified time
609 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
610 } catch ( Exception
$e ) {
611 MWExceptionHandler
::logException( $e );
612 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
613 $this->errors
[] = self
::formatExceptionNoComment( $e );
617 wfProfileOut( __METHOD__
. '-getModifiedTime' );
619 // If there's an If-Modified-Since header, respond with a 304 appropriately
620 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
621 return; // output handled (buffers cleared)
624 // Generate a response
625 $response = $this->makeModuleResponse( $context, $modules, $missing );
627 // Capture any PHP warnings from the output buffer and append them to the
628 // error list if we're in debug mode.
629 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
630 $this->errors
[] = $warnings;
633 // Save response to file cache unless there are errors
634 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
635 // Cache single modules and images...and other requests if there are enough hits
636 if ( ResourceFileCache
::useFileCache( $context ) ) {
637 if ( $fileCache->isCacheWorthy() ) {
638 $fileCache->saveText( $response );
640 $fileCache->incrMissesRecent( $context->getRequest() );
645 // Send content type and cache related headers
646 $this->sendResponseHeaders( $context, $mtime, (bool)$this->errors
);
648 // Remove the output buffer and output the response
651 if ( $context->getImageObj() && $this->errors
) {
652 // We can't show both the error messages and the response when it's an image.
654 foreach ( $this->errors
as $error ) {
655 $errorText .= $error . "\n";
657 $response = $errorText;
658 } elseif ( $this->errors
) {
659 // Prepend comments indicating errors
661 foreach ( $this->errors
as $error ) {
662 $errorText .= self
::makeComment( $error );
664 $response = $errorText . $response;
667 $this->errors
= array();
673 * Send content type and last modified headers to the client.
674 * @param ResourceLoaderContext $context
675 * @param string $mtime TS_MW timestamp to use for last-modified
676 * @param bool $errors Whether there are errors in the response
679 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
680 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
681 // If a version wasn't specified we need a shorter expiry time for updates
682 // to propagate to clients quickly
683 // If there were errors, we also need a shorter expiry time so we can recover quickly
684 if ( is_null( $context->getVersion() ) ||
$errors ) {
685 $maxage = $rlMaxage['unversioned']['client'];
686 $smaxage = $rlMaxage['unversioned']['server'];
687 // If a version was specified we can use a longer expiry time since changing
688 // version numbers causes cache misses
690 $maxage = $rlMaxage['versioned']['client'];
691 $smaxage = $rlMaxage['versioned']['server'];
693 if ( $context->getImageObj() ) {
694 // Output different headers if we're outputting textual errors.
696 header( 'Content-Type: text/plain; charset=utf-8' );
698 $context->getImageObj()->sendResponseHeaders( $context );
700 } elseif ( $context->getOnly() === 'styles' ) {
701 header( 'Content-Type: text/css; charset=utf-8' );
702 header( 'Access-Control-Allow-Origin: *' );
704 header( 'Content-Type: text/javascript; charset=utf-8' );
706 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
707 if ( $context->getDebug() ) {
708 // Do not cache debug responses
709 header( 'Cache-Control: private, no-cache, must-revalidate' );
710 header( 'Pragma: no-cache' );
712 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
713 $exp = min( $maxage, $smaxage );
714 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
719 * Respond with 304 Last Modified if appropiate.
721 * If there's an If-Modified-Since header, respond with a 304 appropriately
722 * and clear out the output buffer. If the client cache is too old then do nothing.
724 * @param ResourceLoaderContext $context
725 * @param string $mtime The TS_MW timestamp to check the header against
726 * @return bool True if 304 header sent and output handled
728 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
729 // If there's an If-Modified-Since header, respond with a 304 appropriately
730 // Some clients send "timestamp;length=123". Strip the part after the first ';'
731 // so we get a valid timestamp.
732 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
733 // Never send 304s in debug mode
734 if ( $ims !== false && !$context->getDebug() ) {
735 $imsTS = strtok( $ims, ';' );
736 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
737 // There's another bug in ob_gzhandler (see also the comment at
738 // the top of this function) that causes it to gzip even empty
739 // responses, meaning it's impossible to produce a truly empty
740 // response (because the gzip header is always there). This is
741 // a problem because 304 responses have to be completely empty
742 // per the HTTP spec, and Firefox behaves buggily when they're not.
743 // See also http://bugs.php.net/bug.php?id=51579
744 // To work around this, we tear down all output buffering before
746 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
748 header( 'HTTP/1.0 304 Not Modified' );
749 header( 'Status: 304 Not Modified' );
757 * Send out code for a response from file cache if possible.
759 * @param ResourceFileCache $fileCache Cache object for this request URL
760 * @param ResourceLoaderContext $context Context in which to generate a response
761 * @return bool If this found a cache file and handled the response
763 protected function tryRespondFromFileCache(
764 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
766 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
767 // Buffer output to catch warnings.
769 // Get the maximum age the cache can be
770 $maxage = is_null( $context->getVersion() )
771 ?
$rlMaxage['unversioned']['server']
772 : $rlMaxage['versioned']['server'];
773 // Minimum timestamp the cache file must have
774 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
776 try { // RL always hits the DB on file cache miss...
778 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
779 $good = $fileCache->isCacheGood(); // cache existence check
783 $ts = $fileCache->cacheTimestamp();
784 // Send content type and cache headers
785 $this->sendResponseHeaders( $context, $ts, false );
786 // If there's an If-Modified-Since header, respond with a 304 appropriately
787 if ( $this->tryRespondLastModified( $context, $ts ) ) {
788 return false; // output handled (buffers cleared)
790 $response = $fileCache->fetchText();
791 // Capture any PHP warnings from the output buffer and append them to the
792 // response in a comment if we're in debug mode.
793 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
794 $response = "/*\n$warnings\n*/\n" . $response;
796 // Remove the output buffer and output the response
798 echo $response . "\n/* Cached {$ts} */";
799 return true; // cache hit
804 return false; // cache miss
808 * Generate a CSS or JS comment block.
810 * Only use this for public data, not error message details.
812 * @param string $text
815 public static function makeComment( $text ) {
816 $encText = str_replace( '*/', '* /', $text );
817 return "/*\n$encText\n*/\n";
821 * Handle exception display.
823 * @param Exception $e Exception to be shown to the user
824 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
826 public static function formatException( $e ) {
827 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
831 * Handle exception display.
834 * @param Exception $e Exception to be shown to the user
835 * @return string Sanitized text that can be returned to the user
837 protected static function formatExceptionNoComment( $e ) {
838 global $wgShowExceptionDetails;
840 if ( $wgShowExceptionDetails ) {
841 return $e->__toString();
843 return wfMessage( 'internalerror' )->text();
848 * Generate code for a response.
850 * @param ResourceLoaderContext $context Context in which to generate a response
851 * @param array $modules List of module objects keyed by module name
852 * @param array $missing List of requested module names that are unregistered (optional)
853 * @return string Response data
855 public function makeModuleResponse( ResourceLoaderContext
$context,
856 array $modules, array $missing = array()
861 if ( !count( $modules ) && !count( $missing ) ) {
862 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
863 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
864 no modules were requested. Max made me put this here. */";
868 $image = $context->getImageObj();
870 $data = $image->getImageData( $context );
871 if ( $data === false ) {
873 $this->errors
[] = 'Image generation failed';
879 if ( $context->shouldIncludeMessages() ) {
881 $blobs = MessageBlobStore
::getInstance()->get( $this, $modules, $context->getLanguage() );
882 } catch ( Exception
$e ) {
883 MWExceptionHandler
::logException( $e );
886 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
888 $this->errors
[] = self
::formatExceptionNoComment( $e );
894 foreach ( $missing as $name ) {
895 $states[$name] = 'missing';
900 foreach ( $modules as $name => $module ) {
902 * @var $module ResourceLoaderModule
905 wfProfileIn( __METHOD__
. '-' . $name );
908 if ( $context->shouldIncludeScripts() ) {
909 // If we are in debug mode, we'll want to return an array of URLs if possible
910 // However, we can't do this if the module doesn't support it
911 // We also can't do this if there is an only= parameter, because we have to give
912 // the module a way to return a load.php URL without causing an infinite loop
913 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
914 $scripts = $module->getScriptURLsForDebug( $context );
916 $scripts = $module->getScript( $context );
917 // rtrim() because there are usually a few line breaks
918 // after the last ';'. A new line at EOF, a new line
919 // added by ResourceLoaderFileModule::readScriptFiles, etc.
920 if ( is_string( $scripts )
921 && strlen( $scripts )
922 && substr( rtrim( $scripts ), -1 ) !== ';'
924 // Append semicolon to prevent weird bugs caused by files not
925 // terminating their statements right (bug 27054)
932 if ( $context->shouldIncludeStyles() ) {
933 // Don't create empty stylesheets like array( '' => '' ) for modules
934 // that don't *have* any stylesheets (bug 38024).
935 $stylePairs = $module->getStyles( $context );
936 if ( count( $stylePairs ) ) {
937 // If we are in debug mode without &only= set, we'll want to return an array of URLs
938 // See comment near shouldIncludeScripts() for more details
939 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
941 'url' => $module->getStyleURLsForDebug( $context )
944 // Minify CSS before embedding in mw.loader.implement call
945 // (unless in debug mode)
946 if ( !$context->getDebug() ) {
947 foreach ( $stylePairs as $media => $style ) {
948 // Can be either a string or an array of strings.
949 if ( is_array( $style ) ) {
950 $stylePairs[$media] = array();
951 foreach ( $style as $cssText ) {
952 if ( is_string( $cssText ) ) {
953 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
956 } elseif ( is_string( $style ) ) {
957 $stylePairs[$media] = $this->filter( 'minify-css', $style );
961 // Wrap styles into @media groups as needed and flatten into a numerical array
963 'css' => self
::makeCombinedStyles( $stylePairs )
970 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
973 switch ( $context->getOnly() ) {
975 if ( is_string( $scripts ) ) {
976 // Load scripts raw...
978 } elseif ( is_array( $scripts ) ) {
979 // ...except when $scripts is an array of URLs
980 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
984 // We no longer seperate into media, they are all combined now with
985 // custom media type groups into @media .. {} sections as part of the css string.
986 // Module returns either an empty array or a numerical array with css strings.
987 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
990 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
993 $out .= Xml
::encodeJsCall(
995 array( $name, (object)$module->getTemplates() ),
996 ResourceLoader
::inDebugMode()
1000 $out .= self
::makeLoaderImplementScript(
1004 new XmlJsCode( $messagesBlob ),
1005 $module->getTemplates()
1009 } catch ( Exception
$e ) {
1010 MWExceptionHandler
::logException( $e );
1011 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
1012 $this->errors
[] = self
::formatExceptionNoComment( $e );
1014 // Respond to client with error-state instead of module implementation
1015 $states[$name] = 'error';
1016 unset( $modules[$name] );
1018 $isRaw |
= $module->isRaw();
1019 wfProfileOut( __METHOD__
. '-' . $name );
1022 // Update module states
1023 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1024 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1025 // Set the state of modules loaded as only scripts to ready as
1026 // they don't have an mw.loader.implement wrapper that sets the state
1027 foreach ( $modules as $name => $module ) {
1028 $states[$name] = 'ready';
1032 // Set the state of modules we didn't respond to with mw.loader.implement
1033 if ( count( $states ) ) {
1034 $out .= self
::makeLoaderStateScript( $states );
1037 if ( count( $states ) ) {
1038 $this->errors
[] = 'Problematic modules: ' .
1039 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1043 if ( !$context->getDebug() ) {
1044 if ( $context->getOnly() === 'styles' ) {
1045 $out = $this->filter( 'minify-css', $out );
1047 $out = $this->filter( 'minify-js', $out );
1054 /* Static Methods */
1057 * Return JS code that calls mw.loader.implement with given module properties.
1059 * @param string $name Module name
1060 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1061 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1062 * to CSS files keyed by media type
1063 * @param mixed $messages List of messages associated with this module. May either be an
1064 * associative array mapping message key to value, or a JSON-encoded message blob containing
1065 * the same data, wrapped in an XmlJsCode object.
1066 * @param array $templates Keys are name of templates and values are the source of
1068 * @throws MWException
1071 public static function makeLoaderImplementScript( $name, $scripts, $styles,
1072 $messages, $templates
1074 if ( is_string( $scripts ) ) {
1075 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1076 } elseif ( !is_array( $scripts ) ) {
1077 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1080 return Xml
::encodeJsCall(
1081 'mw.loader.implement',
1085 // Force objects. mw.loader.implement requires them to be javascript objects.
1086 // Although these variables are associative arrays, which become javascript
1087 // objects through json_encode. In many cases they will be empty arrays, and
1088 // PHP/json_encode() consider empty arrays to be numerical arrays and
1089 // output javascript "[]" instead of "{}". This fixes that.
1094 ResourceLoader
::inDebugMode()
1099 * Returns JS code which, when called, will register a given list of messages.
1101 * @param mixed $messages Either an associative array mapping message key to value, or a
1102 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1105 public static function makeMessageSetScript( $messages ) {
1106 return Xml
::encodeJsCall(
1108 array( (object)$messages ),
1109 ResourceLoader
::inDebugMode()
1114 * Combines an associative array mapping media type to CSS into a
1115 * single stylesheet with "@media" blocks.
1117 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1120 public static function makeCombinedStyles( array $stylePairs ) {
1122 foreach ( $stylePairs as $media => $styles ) {
1123 // ResourceLoaderFileModule::getStyle can return the styles
1124 // as a string or an array of strings. This is to allow separation in
1126 $styles = (array)$styles;
1127 foreach ( $styles as $style ) {
1128 $style = trim( $style );
1129 // Don't output an empty "@media print { }" block (bug 40498)
1130 if ( $style !== '' ) {
1131 // Transform the media type based on request params and config
1132 // The way that this relies on $wgRequest to propagate request params is slightly evil
1133 $media = OutputPage
::transformCssMedia( $media );
1135 if ( $media === '' ||
$media == 'all' ) {
1137 } elseif ( is_string( $media ) ) {
1138 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1148 * Returns a JS call to mw.loader.state, which sets the state of a
1149 * module or modules to a given value. Has two calling conventions:
1151 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1152 * Set the state of a single module called $name to $state
1154 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1155 * Set the state of modules with the given names to the given states
1157 * @param string $name
1158 * @param string $state
1161 public static function makeLoaderStateScript( $name, $state = null ) {
1162 if ( is_array( $name ) ) {
1163 return Xml
::encodeJsCall(
1166 ResourceLoader
::inDebugMode()
1169 return Xml
::encodeJsCall(
1171 array( $name, $state ),
1172 ResourceLoader
::inDebugMode()
1178 * Returns JS code which calls the script given by $script. The script will
1179 * be called with local variables name, version, dependencies and group,
1180 * which will have values corresponding to $name, $version, $dependencies
1181 * and $group as supplied.
1183 * @param string $name Module name
1184 * @param int $version Module version number as a timestamp
1185 * @param array $dependencies List of module names on which this module depends
1186 * @param string $group Group which the module is in.
1187 * @param string $source Source of the module, or 'local' if not foreign.
1188 * @param string $script JavaScript code
1191 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1192 $group, $source, $script
1194 $script = str_replace( "\n", "\n\t", trim( $script ) );
1195 return Xml
::encodeJsCall(
1196 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1197 array( $name, $version, $dependencies, $group, $source ),
1198 ResourceLoader
::inDebugMode()
1203 * Remove empty values from the end of an array.
1205 * Values considered empty:
1210 * @param Array $array
1212 private static function trimArray( Array &$array ) {
1213 $i = count( $array );
1215 if ( $array[$i] === null ||
$array[$i] === array() ) {
1216 unset( $array[$i] );
1224 * Returns JS code which calls mw.loader.register with the given
1225 * parameters. Has three calling conventions:
1227 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1228 * $dependencies, $group, $source, $skip
1230 * Register a single module.
1232 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1233 * Register modules with the given names.
1235 * - ResourceLoader::makeLoaderRegisterScript( array(
1236 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1237 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1240 * Registers modules with the given names and parameters.
1242 * @param string $name Module name
1243 * @param int $version Module version number as a timestamp
1244 * @param array $dependencies List of module names on which this module depends
1245 * @param string $group Group which the module is in
1246 * @param string $source Source of the module, or 'local' if not foreign
1247 * @param string $skip Script body of the skip function
1250 public static function makeLoaderRegisterScript( $name, $version = null,
1251 $dependencies = null, $group = null, $source = null, $skip = null
1253 if ( is_array( $name ) ) {
1254 // Build module name index
1256 foreach ( $name as $i => &$module ) {
1257 $index[$module[0]] = $i;
1260 // Transform dependency names into indexes when possible, they will be resolved by
1261 // mw.loader.register on the other end
1262 foreach ( $name as &$module ) {
1263 if ( isset( $module[2] ) ) {
1264 foreach ( $module[2] as &$dependency ) {
1265 if ( isset( $index[$dependency] ) ) {
1266 $dependency = $index[$dependency];
1272 array_walk( $name, array( 'self', 'trimArray' ) );
1274 return Xml
::encodeJsCall(
1275 'mw.loader.register',
1277 ResourceLoader
::inDebugMode()
1280 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1281 self
::trimArray( $registration );
1282 return Xml
::encodeJsCall(
1283 'mw.loader.register',
1285 ResourceLoader
::inDebugMode()
1291 * Returns JS code which calls mw.loader.addSource() with the given
1292 * parameters. Has two calling conventions:
1294 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1295 * Register a single source
1297 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1298 * Register sources with the given IDs and properties.
1300 * @param string $id Source ID
1301 * @param array $properties Source properties (see addSource())
1304 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1305 if ( is_array( $id ) ) {
1306 return Xml
::encodeJsCall(
1307 'mw.loader.addSource',
1309 ResourceLoader
::inDebugMode()
1312 return Xml
::encodeJsCall(
1313 'mw.loader.addSource',
1314 array( $id, $properties ),
1315 ResourceLoader
::inDebugMode()
1321 * Returns JS code which runs given JS code if the client-side framework is
1324 * @param string $script JavaScript code
1327 public static function makeLoaderConditionalScript( $script ) {
1328 return "if(window.mw){\n" . trim( $script ) . "\n}";
1332 * Returns JS code which will set the MediaWiki configuration array to
1335 * @param array $configuration List of configuration values keyed by variable name
1338 public static function makeConfigSetScript( array $configuration ) {
1339 return Xml
::encodeJsCall(
1341 array( $configuration ),
1342 ResourceLoader
::inDebugMode()
1347 * Convert an array of module names to a packed query string.
1349 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1350 * becomes 'foo.bar,baz|bar.baz,quux'
1351 * @param array $modules List of module names (strings)
1352 * @return string Packed query string
1354 public static function makePackedModulesString( $modules ) {
1355 $groups = array(); // array( prefix => array( suffixes ) )
1356 foreach ( $modules as $module ) {
1357 $pos = strrpos( $module, '.' );
1358 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1359 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1360 $groups[$prefix][] = $suffix;
1364 foreach ( $groups as $prefix => $suffixes ) {
1365 $p = $prefix === '' ?
'' : $prefix . '.';
1366 $arr[] = $p . implode( ',', $suffixes );
1368 $str = implode( '|', $arr );
1373 * Determine whether debug mode was requested
1374 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1377 public static function inDebugMode() {
1378 if ( self
::$debugMode === null ) {
1379 global $wgRequest, $wgResourceLoaderDebug;
1380 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1381 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1384 return self
::$debugMode;
1388 * Reset static members used for caching.
1390 * Global state and $wgRequest are evil, but we're using it right
1391 * now and sometimes we need to be able to force ResourceLoader to
1392 * re-evaluate the context because it has changed (e.g. in the test suite).
1394 public static function clearCache() {
1395 self
::$debugMode = null;
1399 * Build a load.php URL
1402 * @param string $source Name of the ResourceLoader source
1403 * @param ResourceLoaderContext $context
1404 * @param array $extraQuery
1405 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1407 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1408 $extraQuery = array()
1410 $query = self
::createLoaderQuery( $context, $extraQuery );
1411 $script = $this->getLoadScript( $source );
1413 // Prevent the IE6 extension check from being triggered (bug 28840)
1414 // by appending a character that's invalid in Windows extensions ('*')
1415 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1419 * Build a load.php URL
1420 * @deprecated since 1.24, use createLoaderURL instead
1421 * @param array $modules Array of module names (strings)
1422 * @param string $lang Language code
1423 * @param string $skin Skin name
1424 * @param string|null $user User name. If null, the &user= parameter is omitted
1425 * @param string|null $version Versioning timestamp
1426 * @param bool $debug Whether the request should be in debug mode
1427 * @param string|null $only &only= parameter
1428 * @param bool $printable Printable mode
1429 * @param bool $handheld Handheld mode
1430 * @param array $extraQuery Extra query parameters to add
1431 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1433 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1434 $version = null, $debug = false, $only = null, $printable = false,
1435 $handheld = false, $extraQuery = array()
1437 global $wgLoadScript;
1439 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1440 $only, $printable, $handheld, $extraQuery
1443 // Prevent the IE6 extension check from being triggered (bug 28840)
1444 // by appending a character that's invalid in Windows extensions ('*')
1445 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1449 * Helper for createLoaderURL()
1452 * @see makeLoaderQuery
1453 * @param ResourceLoaderContext $context
1454 * @param array $extraQuery
1457 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1458 return self
::makeLoaderQuery(
1459 $context->getModules(),
1460 $context->getLanguage(),
1461 $context->getSkin(),
1462 $context->getUser(),
1463 $context->getVersion(),
1464 $context->getDebug(),
1465 $context->getOnly(),
1466 $context->getRequest()->getBool( 'printable' ),
1467 $context->getRequest()->getBool( 'handheld' ),
1473 * Build a query array (array representation of query string) for load.php. Helper
1474 * function for makeLoaderURL().
1476 * @param array $modules
1477 * @param string $lang
1478 * @param string $skin
1479 * @param string $user
1480 * @param string $version
1481 * @param bool $debug
1482 * @param string $only
1483 * @param bool $printable
1484 * @param bool $handheld
1485 * @param array $extraQuery
1489 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1490 $version = null, $debug = false, $only = null, $printable = false,
1491 $handheld = false, $extraQuery = array()
1494 'modules' => self
::makePackedModulesString( $modules ),
1497 'debug' => $debug ?
'true' : 'false',
1499 if ( $user !== null ) {
1500 $query['user'] = $user;
1502 if ( $version !== null ) {
1503 $query['version'] = $version;
1505 if ( $only !== null ) {
1506 $query['only'] = $only;
1509 $query['printable'] = 1;
1512 $query['handheld'] = 1;
1514 $query +
= $extraQuery;
1516 // Make queries uniform in order
1522 * Check a module name for validity.
1524 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1525 * at most 255 bytes.
1527 * @param string $moduleName Module name to check
1528 * @return bool Whether $moduleName is a valid module name
1530 public static function isValidModuleName( $moduleName ) {
1531 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1535 * Returns LESS compiler set up for use with MediaWiki
1537 * @param Config $config
1538 * @throws MWException
1542 public static function getLessCompiler( Config
$config ) {
1543 // When called from the installer, it is possible that a required PHP extension
1544 // is missing (at least for now; see bug 47564). If this is the case, throw an
1545 // exception (caught by the installer) to prevent a fatal error later on.
1546 if ( !class_exists( 'lessc' ) ) {
1547 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1549 if ( !function_exists( 'ctype_digit' ) ) {
1550 throw new MWException( 'lessc requires the Ctype extension' );
1553 $less = new lessc();
1554 $less->setPreserveComments( true );
1555 $less->setVariables( self
::getLessVars( $config ) );
1556 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1557 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1558 $less->registerFunction( $name, $func );
1564 * Get global LESS variables.
1566 * @param Config $config
1568 * @return array Map of variable names to string CSS values.
1570 public static function getLessVars( Config
$config ) {
1571 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1572 // Sort by key to ensure consistent hashing for cache lookups.