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
25 use MediaWiki\MediaWikiServices
;
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
28 use Psr\Log\NullLogger
;
29 use WrappedString\WrappedString
;
30 use Wikimedia\Rdbms\DBConnectionError
;
33 * Dynamic JavaScript and CSS resource loading system.
35 * Most of the documentation is on the MediaWiki documentation wiki starting at:
36 * https://www.mediawiki.org/wiki/ResourceLoader
38 class ResourceLoader
implements LoggerAwareInterface
{
40 protected static $filterCacheVersion = 7;
43 protected static $debugMode = null;
46 private $lessVars = null;
49 * Module name/ResourceLoaderModule object pairs
52 protected $modules = [];
55 * Associative array mapping module name to info associative array
58 protected $moduleInfos = [];
60 /** @var Config $config */
64 * Associative array mapping framework ids to a list of names of test suite modules
65 * like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... ], ... ]
68 protected $testModuleNames = [];
71 * E.g. [ 'source-id' => 'http://.../load.php' ]
74 protected $sources = [];
77 * Errors accumulated during current respond() call.
80 protected $errors = [];
83 * @var MessageBlobStore
88 * @var LoggerInterface
92 /** @var string JavaScript / CSS pragma to disable minification. **/
93 const FILTER_NOMIN
= '/*@nomin*/';
96 * Load information stored in the database about modules.
98 * This method grabs modules dependencies from the database and updates modules
101 * This is not inside the module code because it is much faster to
102 * request all of the information at once than it is to have each module
103 * requests its own information. This sacrifice of modularity yields a substantial
104 * performance improvement.
106 * @param array $moduleNames List of module names to preload information for
107 * @param ResourceLoaderContext $context Context to load the information within
109 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext
$context ) {
110 if ( !$moduleNames ) {
111 // Or else Database*::select() will explode, plus it's cheaper!
114 $dbr = wfGetDB( DB_REPLICA
);
115 $skin = $context->getSkin();
116 $lang = $context->getLanguage();
118 // Batched version of ResourceLoaderModule::getFileDependencies
119 $vary = "$skin|$lang";
120 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
121 'md_module' => $moduleNames,
126 // Prime in-object cache for file dependencies
127 $modulesWithDeps = [];
128 foreach ( $res as $row ) {
129 $module = $this->getModule( $row->md_module
);
131 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
132 FormatJson
::decode( $row->md_deps
, true )
134 $modulesWithDeps[] = $row->md_module
;
137 // Register the absence of a dependency row too
138 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
139 $module = $this->getModule( $name );
141 $this->getModule( $name )->setFileDependencies( $context, [] );
145 // Batched version of ResourceLoaderWikiModule::getTitleInfo
146 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $moduleNames );
148 // Prime in-object cache for message blobs for modules with messages
150 foreach ( $moduleNames as $name ) {
151 $module = $this->getModule( $name );
152 if ( $module && $module->getMessages() ) {
153 $modules[$name] = $module;
156 $store = $this->getMessageBlobStore();
157 $blobs = $store->getBlobs( $modules, $lang );
158 foreach ( $blobs as $name => $blob ) {
159 $modules[$name]->setMessageBlob( $blob, $lang );
164 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
166 * Available filters are:
168 * - minify-js \see JavaScriptMinifier::minify
169 * - minify-css \see CSSMin::minify
171 * If $data is empty, only contains whitespace or the filter was unknown,
172 * $data is returned unmodified.
174 * @param string $filter Name of filter to run
175 * @param string $data Text to filter, such as JavaScript or CSS text
176 * @param array $options Keys:
177 * - (bool) cache: Whether to allow caching this data. Default: true.
178 * @return string Filtered data, or a comment containing an error message
180 public static function filter( $filter, $data, array $options = [] ) {
181 if ( strpos( $data, ResourceLoader
::FILTER_NOMIN
) !== false ) {
185 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
186 return self
::applyFilter( $filter, $data );
189 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
190 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
192 $key = $cache->makeGlobalKey(
196 self
::$filterCacheVersion, md5( $data )
199 $result = $cache->get( $key );
200 if ( $result === false ) {
201 $stats->increment( "resourceloader_cache.$filter.miss" );
202 $result = self
::applyFilter( $filter, $data );
203 $cache->set( $key, $result, 24 * 3600 );
205 $stats->increment( "resourceloader_cache.$filter.hit" );
207 if ( $result === null ) {
215 private static function applyFilter( $filter, $data ) {
216 $data = trim( $data );
219 $data = ( $filter === 'minify-css' )
220 ? CSSMin
::minify( $data )
221 : JavaScriptMinifier
::minify( $data );
222 } catch ( Exception
$e ) {
223 MWExceptionHandler
::logException( $e );
233 * Register core modules and runs registration hooks.
234 * @param Config $config [optional]
235 * @param LoggerInterface $logger [optional]
237 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
240 $this->logger
= $logger ?
: new NullLogger();
243 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
244 $config = MediaWikiServices
::getInstance()->getMainConfig();
246 $this->config
= $config;
248 // Add 'local' source first
249 $this->addSource( 'local', $config->get( 'LoadScript' ) );
252 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
254 // Register core modules
255 $this->register( include "$IP/resources/Resources.php" );
256 $this->register( include "$IP/resources/ResourcesOOUI.php" );
257 // Register extension modules
258 $this->register( $config->get( 'ResourceModules' ) );
260 // Avoid PHP 7.1 warning from passing $this by reference
262 Hooks
::run( 'ResourceLoaderRegisterModules', [ &$rl ] );
264 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
265 $this->registerTestModules();
268 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
274 public function getConfig() {
275 return $this->config
;
280 * @param LoggerInterface $logger
282 public function setLogger( LoggerInterface
$logger ) {
283 $this->logger
= $logger;
288 * @return LoggerInterface
290 public function getLogger() {
291 return $this->logger
;
296 * @return MessageBlobStore
298 public function getMessageBlobStore() {
299 return $this->blobStore
;
304 * @param MessageBlobStore $blobStore
306 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
307 $this->blobStore
= $blobStore;
311 * Register a module with the ResourceLoader system.
313 * @param mixed $name Name of module as a string or List of name/object pairs as an array
314 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
315 * this may also be a ResourceLoaderModule object. Optional when using
316 * multiple-registration calling style.
317 * @throws MWException If a duplicate module registration is attempted
318 * @throws MWException If a module name contains illegal characters (pipes or commas)
319 * @throws MWException If something other than a ResourceLoaderModule is being registered
320 * @return bool False if there were any errors, in which case one or more modules were
323 public function register( $name, $info = null ) {
324 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
326 // Allow multiple modules to be registered in one call
327 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
328 foreach ( $registrations as $name => $info ) {
329 // Warn on duplicate registrations
330 if ( isset( $this->moduleInfos
[$name] ) ) {
331 // A module has already been registered by this name
332 $this->logger
->warning(
333 'ResourceLoader duplicate registration warning. ' .
334 'Another module has already been registered as ' . $name
338 // Check $name for validity
339 if ( !self
::isValidModuleName( $name ) ) {
340 throw new MWException( "ResourceLoader module name '$name' is invalid, "
341 . "see ResourceLoader::isValidModuleName()" );
345 if ( $info instanceof ResourceLoaderModule
) {
346 $this->moduleInfos
[$name] = [ 'object' => $info ];
347 $info->setName( $name );
348 $this->modules
[$name] = $info;
349 } elseif ( is_array( $info ) ) {
350 // New calling convention
351 $this->moduleInfos
[$name] = $info;
353 throw new MWException(
354 'ResourceLoader module info type error for module \'' . $name .
355 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
359 // Last-minute changes
361 // Apply custom skin-defined styles to existing modules.
362 if ( $this->isFileModule( $name ) ) {
363 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
364 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
365 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
369 // If $name is preceded with a '+', the defined style files will be added to 'default'
370 // skinStyles, otherwise 'default' will be ignored as it normally would be.
371 if ( isset( $skinStyles[$name] ) ) {
372 $paths = (array)$skinStyles[$name];
374 } elseif ( isset( $skinStyles['+' . $name] ) ) {
375 $paths = (array)$skinStyles['+' . $name];
376 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
377 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
383 // Add new file paths, remapping them to refer to our directories and not use settings
384 // from the module we're modifying, which come from the base definition.
385 list( $localBasePath, $remoteBasePath ) =
386 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
388 foreach ( $paths as $path ) {
389 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
392 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
398 public function registerTestModules() {
401 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
402 throw new MWException( 'Attempt to register JavaScript test modules '
403 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
404 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
407 // Get core test suites
409 $testModules['qunit'] = [];
410 // Get other test suites (e.g. from extensions)
411 // Avoid PHP 7.1 warning from passing $this by reference
413 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
415 // Add the testrunner (which configures QUnit) to the dependencies.
416 // Since it must be ready before any of the test suites are executed.
417 foreach ( $testModules['qunit'] as &$module ) {
418 // Make sure all test modules are top-loading so that when QUnit starts
419 // on document-ready, it will run once and finish. If some tests arrive
420 // later (possibly after QUnit has already finished) they will be ignored.
421 $module['position'] = 'top';
422 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
425 $testModules['qunit'] =
426 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
428 foreach ( $testModules as $id => $names ) {
429 // Register test modules
430 $this->register( $testModules[$id] );
432 // Keep track of their names so that they can be loaded together
433 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
438 * Add a foreign source of modules.
440 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
442 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
443 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
444 * backwards-compatibility.
445 * @throws MWException
447 public function addSource( $id, $loadUrl = null ) {
448 // Allow multiple sources to be registered in one call
449 if ( is_array( $id ) ) {
450 foreach ( $id as $key => $value ) {
451 $this->addSource( $key, $value );
456 // Disallow duplicates
457 if ( isset( $this->sources
[$id] ) ) {
458 throw new MWException(
459 'ResourceLoader duplicate source addition error. ' .
460 'Another source has already been registered as ' . $id
464 // Pre 1.24 backwards-compatibility
465 if ( is_array( $loadUrl ) ) {
466 if ( !isset( $loadUrl['loadScript'] ) ) {
467 throw new MWException(
468 __METHOD__
. ' was passed an array with no "loadScript" key.'
472 $loadUrl = $loadUrl['loadScript'];
475 $this->sources
[$id] = $loadUrl;
479 * Get a list of module names.
481 * @return array List of module names
483 public function getModuleNames() {
484 return array_keys( $this->moduleInfos
);
488 * Get a list of test module names for one (or all) frameworks.
490 * If the given framework id is unknkown, or if the in-object variable is not an array,
491 * then it will return an empty array.
493 * @param string $framework Get only the test module names for one
494 * particular framework (optional)
497 public function getTestModuleNames( $framework = 'all' ) {
498 /** @todo api siteinfo prop testmodulenames modulenames */
499 if ( $framework == 'all' ) {
500 return $this->testModuleNames
;
501 } elseif ( isset( $this->testModuleNames
[$framework] )
502 && is_array( $this->testModuleNames
[$framework] )
504 return $this->testModuleNames
[$framework];
511 * Check whether a ResourceLoader module is registered
514 * @param string $name
517 public function isModuleRegistered( $name ) {
518 return isset( $this->moduleInfos
[$name] );
522 * Get the ResourceLoaderModule object for a given module name.
524 * If an array of module parameters exists but a ResourceLoaderModule object has not
525 * yet been instantiated, this method will instantiate and cache that object such that
526 * subsequent calls simply return the same object.
528 * @param string $name Module name
529 * @return ResourceLoaderModule|null If module has been registered, return a
530 * ResourceLoaderModule instance. Otherwise, return null.
532 public function getModule( $name ) {
533 if ( !isset( $this->modules
[$name] ) ) {
534 if ( !isset( $this->moduleInfos
[$name] ) ) {
538 // Construct the requested object
539 $info = $this->moduleInfos
[$name];
540 /** @var ResourceLoaderModule $object */
541 if ( isset( $info['object'] ) ) {
542 // Object given in info array
543 $object = $info['object'];
544 } elseif ( isset( $info['factory'] ) ) {
545 $object = call_user_func( $info['factory'], $info );
546 $object->setConfig( $this->getConfig() );
547 $object->setLogger( $this->logger
);
549 if ( !isset( $info['class'] ) ) {
550 $class = 'ResourceLoaderFileModule';
552 $class = $info['class'];
554 /** @var ResourceLoaderModule $object */
555 $object = new $class( $info );
556 $object->setConfig( $this->getConfig() );
557 $object->setLogger( $this->logger
);
559 $object->setName( $name );
560 $this->modules
[$name] = $object;
563 return $this->modules
[$name];
567 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
569 * @param string $name Module name
572 protected function isFileModule( $name ) {
573 if ( !isset( $this->moduleInfos
[$name] ) ) {
576 $info = $this->moduleInfos
[$name];
577 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
584 * Get the list of sources.
586 * @return array Like [ id => load.php url, ... ]
588 public function getSources() {
589 return $this->sources
;
593 * Get the URL to the load.php endpoint for the given
594 * ResourceLoader source
597 * @param string $source
598 * @throws MWException On an invalid $source name
601 public function getLoadScript( $source ) {
602 if ( !isset( $this->sources
[$source] ) ) {
603 throw new MWException( "The $source source was never registered in ResourceLoader." );
605 return $this->sources
[$source];
610 * @param string $value
611 * @return string Hash
613 public static function makeHash( $value ) {
614 $hash = hash( 'fnv132', $value );
615 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
619 * Add an error to the 'errors' array and log it.
621 * Should only be called from within respond().
624 * @param Exception $e
626 * @param array $context
628 protected function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
629 MWExceptionHandler
::logException( $e );
630 $this->logger
->warning(
632 $context +
[ 'exception' => $e ]
634 $this->errors
[] = self
::formatExceptionNoComment( $e );
638 * Helper method to get and combine versions of multiple modules.
641 * @param ResourceLoaderContext $context
642 * @param string[] $modules List of known module names
643 * @return string Hash
645 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
646 if ( !$moduleNames ) {
649 $hashes = array_map( function ( $module ) use ( $context ) {
651 return $this->getModule( $module )->getVersionHash( $context );
652 } catch ( Exception
$e ) {
653 // If modules fail to compute a version, do still consider the versions
654 // of other modules - don't set an empty string E-Tag for the whole request.
655 // See also T152266 and StartupModule::getModuleRegistrations().
656 $this->outputErrorAndLog( $e,
657 'Calculating version for "{module}" failed: {exception}',
665 return self
::makeHash( implode( '', $hashes ) );
669 * Get the expected value of the 'version' query parameter.
671 * This is used by respond() to set a short Cache-Control header for requests with
672 * information newer than the current server has. This avoids pollution of edge caches.
673 * Typically during deployment. (T117587)
675 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
678 * @param ResourceLoaderContext $context
679 * @param string[] $modules List of module names
680 * @return string Hash
682 public function makeVersionQuery( ResourceLoaderContext
$context ) {
683 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
684 // version hashes. There is no technical reason for this to be same, and for years the
685 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
686 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
687 // query parameter), then this method must continue to match the JS one.
689 foreach ( $context->getModules() as $name ) {
690 if ( !$this->getModule( $name ) ) {
691 // If a versioned request contains a missing module, the version is a mismatch
692 // as the client considered a module (and version) we don't have.
695 $moduleNames[] = $name;
697 return $this->getCombinedVersion( $context, $moduleNames );
701 * Output a response to a load request, including the content-type header.
703 * @param ResourceLoaderContext $context Context in which a response should be formed
705 public function respond( ResourceLoaderContext
$context ) {
706 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
707 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
708 // is used: ob_clean() will clear the GZIP header in that case and it won't come
709 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
710 // the whole thing in our own output buffer to be sure the active buffer
711 // doesn't use ob_gzhandler.
712 // See https://bugs.php.net/bug.php?id=36514
715 // Find out which modules are missing and instantiate the others
718 foreach ( $context->getModules() as $name ) {
719 $module = $this->getModule( $name );
721 // Do not allow private modules to be loaded from the web.
722 // This is a security issue, see T36907.
723 if ( $module->getGroup() === 'private' ) {
724 $this->logger
->debug( "Request for private module '$name' denied" );
725 $this->errors
[] = "Cannot show private module \"$name\"";
728 $modules[$name] = $module;
735 // Preload for getCombinedVersion() and for batch makeModuleResponse()
736 $this->preloadModuleInfo( array_keys( $modules ), $context );
737 } catch ( Exception
$e ) {
738 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
741 // Combine versions to propagate cache invalidation
744 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
745 } catch ( Exception
$e ) {
746 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
749 // See RFC 2616 § 3.11 Entity Tags
750 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
751 $etag = 'W/"' . $versionHash . '"';
753 // Try the client-side cache first
754 if ( $this->tryRespondNotModified( $context, $etag ) ) {
755 return; // output handled (buffers cleared)
758 // Use file cache if enabled and available...
759 if ( $this->config
->get( 'UseFileCache' ) ) {
760 $fileCache = ResourceFileCache
::newFromContext( $context );
761 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
762 return; // output handled
766 // Generate a response
767 $response = $this->makeModuleResponse( $context, $modules, $missing );
769 // Capture any PHP warnings from the output buffer and append them to the
770 // error list if we're in debug mode.
771 if ( $context->getDebug() ) {
772 $warnings = ob_get_contents();
773 if ( strlen( $warnings ) ) {
774 $this->errors
[] = $warnings;
778 // Save response to file cache unless there are errors
779 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
780 // Cache single modules and images...and other requests if there are enough hits
781 if ( ResourceFileCache
::useFileCache( $context ) ) {
782 if ( $fileCache->isCacheWorthy() ) {
783 $fileCache->saveText( $response );
785 $fileCache->incrMissesRecent( $context->getRequest() );
790 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
792 // Remove the output buffer and output the response
795 if ( $context->getImageObj() && $this->errors
) {
796 // We can't show both the error messages and the response when it's an image.
797 $response = implode( "\n\n", $this->errors
);
798 } elseif ( $this->errors
) {
799 $errorText = implode( "\n\n", $this->errors
);
800 $errorResponse = self
::makeComment( $errorText );
801 if ( $context->shouldIncludeScripts() ) {
802 $errorResponse .= 'if (window.console && console.error) {'
803 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
807 // Prepend error info to the response
808 $response = $errorResponse . $response;
816 * Send main response headers to the client.
818 * Deals with Content-Type, CORS (for stylesheets), and caching.
820 * @param ResourceLoaderContext $context
821 * @param string $etag ETag header value
822 * @param bool $errors Whether there are errors in the response
825 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
826 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
827 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
828 // Use a short cache expiry so that updates propagate to clients quickly, if:
829 // - No version specified (shared resources, e.g. stylesheets)
830 // - There were errors (recover quickly)
831 // - Version mismatch (T117587, T47877)
832 if ( is_null( $context->getVersion() )
834 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
836 $maxage = $rlMaxage['unversioned']['client'];
837 $smaxage = $rlMaxage['unversioned']['server'];
838 // If a version was specified we can use a longer expiry time since changing
839 // version numbers causes cache misses
841 $maxage = $rlMaxage['versioned']['client'];
842 $smaxage = $rlMaxage['versioned']['server'];
844 if ( $context->getImageObj() ) {
845 // Output different headers if we're outputting textual errors.
847 header( 'Content-Type: text/plain; charset=utf-8' );
849 $context->getImageObj()->sendResponseHeaders( $context );
851 } elseif ( $context->getOnly() === 'styles' ) {
852 header( 'Content-Type: text/css; charset=utf-8' );
853 header( 'Access-Control-Allow-Origin: *' );
855 header( 'Content-Type: text/javascript; charset=utf-8' );
857 // See RFC 2616 § 14.19 ETag
858 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
859 header( 'ETag: ' . $etag );
860 if ( $context->getDebug() ) {
861 // Do not cache debug responses
862 header( 'Cache-Control: private, no-cache, must-revalidate' );
863 header( 'Pragma: no-cache' );
865 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
866 $exp = min( $maxage, $smaxage );
867 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
872 * Respond with HTTP 304 Not Modified if appropiate.
874 * If there's an If-None-Match header, respond with a 304 appropriately
875 * and clear out the output buffer. If the client cache is too old then do nothing.
877 * @param ResourceLoaderContext $context
878 * @param string $etag ETag header value
879 * @return bool True if HTTP 304 was sent and output handled
881 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
882 // See RFC 2616 § 14.26 If-None-Match
883 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
884 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
885 // Never send 304s in debug mode
886 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
887 // There's another bug in ob_gzhandler (see also the comment at
888 // the top of this function) that causes it to gzip even empty
889 // responses, meaning it's impossible to produce a truly empty
890 // response (because the gzip header is always there). This is
891 // a problem because 304 responses have to be completely empty
892 // per the HTTP spec, and Firefox behaves buggily when they're not.
893 // See also https://bugs.php.net/bug.php?id=51579
894 // To work around this, we tear down all output buffering before
896 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
898 HttpStatus
::header( 304 );
900 $this->sendResponseHeaders( $context, $etag, false );
907 * Send out code for a response from file cache if possible.
909 * @param ResourceFileCache $fileCache Cache object for this request URL
910 * @param ResourceLoaderContext $context Context in which to generate a response
911 * @param string $etag ETag header value
912 * @return bool If this found a cache file and handled the response
914 protected function tryRespondFromFileCache(
915 ResourceFileCache
$fileCache,
916 ResourceLoaderContext
$context,
919 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
920 // Buffer output to catch warnings.
922 // Get the maximum age the cache can be
923 $maxage = is_null( $context->getVersion() )
924 ?
$rlMaxage['unversioned']['server']
925 : $rlMaxage['versioned']['server'];
926 // Minimum timestamp the cache file must have
927 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
929 try { // RL always hits the DB on file cache miss...
930 wfGetDB( DB_REPLICA
);
931 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
932 $good = $fileCache->isCacheGood(); // cache existence check
936 $ts = $fileCache->cacheTimestamp();
937 // Send content type and cache headers
938 $this->sendResponseHeaders( $context, $etag, false );
939 $response = $fileCache->fetchText();
940 // Capture any PHP warnings from the output buffer and append them to the
941 // response in a comment if we're in debug mode.
942 if ( $context->getDebug() ) {
943 $warnings = ob_get_contents();
944 if ( strlen( $warnings ) ) {
945 $response = self
::makeComment( $warnings ) . $response;
948 // Remove the output buffer and output the response
950 echo $response . "\n/* Cached {$ts} */";
951 return true; // cache hit
956 return false; // cache miss
960 * Generate a CSS or JS comment block.
962 * Only use this for public data, not error message details.
964 * @param string $text
967 public static function makeComment( $text ) {
968 $encText = str_replace( '*/', '* /', $text );
969 return "/*\n$encText\n*/\n";
973 * Handle exception display.
975 * @param Exception $e Exception to be shown to the user
976 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
978 public static function formatException( $e ) {
979 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
983 * Handle exception display.
986 * @param Exception $e Exception to be shown to the user
987 * @return string Sanitized text that can be returned to the user
989 protected static function formatExceptionNoComment( $e ) {
990 global $wgShowExceptionDetails;
992 if ( !$wgShowExceptionDetails ) {
993 return MWExceptionHandler
::getPublicLogMessage( $e );
996 return MWExceptionHandler
::getLogMessage( $e ) .
998 MWExceptionHandler
::getRedactedTraceAsString( $e );
1002 * Generate code for a response.
1004 * @param ResourceLoaderContext $context Context in which to generate a response
1005 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1006 * @param string[] $missing List of requested module names that are unregistered (optional)
1007 * @return string Response data
1009 public function makeModuleResponse( ResourceLoaderContext
$context,
1010 array $modules, array $missing = []
1015 if ( !count( $modules ) && !count( $missing ) ) {
1017 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1018 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1019 no modules were requested. Max made me put this here. */
1023 $image = $context->getImageObj();
1025 $data = $image->getImageData( $context );
1026 if ( $data === false ) {
1028 $this->errors
[] = 'Image generation failed';
1033 foreach ( $missing as $name ) {
1034 $states[$name] = 'missing';
1040 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1042 foreach ( $modules as $name => $module ) {
1044 $content = $module->getModuleContent( $context );
1045 $implementKey = $name . '@' . $module->getVersionHash( $context );
1049 switch ( $context->getOnly() ) {
1051 $scripts = $content['scripts'];
1052 if ( is_string( $scripts ) ) {
1053 // Load scripts raw...
1054 $strContent = $scripts;
1055 } elseif ( is_array( $scripts ) ) {
1056 // ...except when $scripts is an array of URLs
1057 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1061 $styles = $content['styles'];
1062 // We no longer seperate into media, they are all combined now with
1063 // custom media type groups into @media .. {} sections as part of the css string.
1064 // Module returns either an empty array or a numerical array with css strings.
1065 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1068 $scripts = isset( $content['scripts'] ) ?
$content['scripts'] : '';
1069 if ( is_string( $scripts ) ) {
1070 if ( $name === 'site' ||
$name === 'user' ) {
1071 // Legacy scripts that run in the global scope without a closure.
1072 // mw.loader.implement will use globalEval if scripts is a string.
1073 // Minify manually here, because general response minification is
1074 // not effective due it being a string literal, not a function.
1075 if ( !ResourceLoader
::inDebugMode() ) {
1076 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1079 $scripts = new XmlJsCode( $scripts );
1082 $strContent = self
::makeLoaderImplementScript(
1085 isset( $content['styles'] ) ?
$content['styles'] : [],
1086 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1087 isset( $content['templates'] ) ?
$content['templates'] : []
1092 if ( !$context->getDebug() ) {
1093 $strContent = self
::filter( $filter, $strContent );
1096 $out .= $strContent;
1098 } catch ( Exception
$e ) {
1099 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1101 // Respond to client with error-state instead of module implementation
1102 $states[$name] = 'error';
1103 unset( $modules[$name] );
1105 $isRaw |
= $module->isRaw();
1108 // Update module states
1109 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1110 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1111 // Set the state of modules loaded as only scripts to ready as
1112 // they don't have an mw.loader.implement wrapper that sets the state
1113 foreach ( $modules as $name => $module ) {
1114 $states[$name] = 'ready';
1118 // Set the state of modules we didn't respond to with mw.loader.implement
1119 if ( count( $states ) ) {
1120 $stateScript = self
::makeLoaderStateScript( $states );
1121 if ( !$context->getDebug() ) {
1122 $stateScript = self
::filter( 'minify-js', $stateScript );
1124 $out .= $stateScript;
1127 if ( count( $states ) ) {
1128 $this->errors
[] = 'Problematic modules: ' .
1129 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1137 * Get names of modules that use a certain message.
1139 * @param string $messageKey
1140 * @return array List of module names
1142 public function getModulesByMessage( $messageKey ) {
1144 foreach ( $this->getModuleNames() as $moduleName ) {
1145 $module = $this->getModule( $moduleName );
1146 if ( in_array( $messageKey, $module->getMessages() ) ) {
1147 $moduleNames[] = $moduleName;
1150 return $moduleNames;
1153 /* Static Methods */
1156 * Return JS code that calls mw.loader.implement with given module properties.
1158 * @param string $name Module name or implement key (format "`[name]@[version]`")
1159 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1160 * list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
1161 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1162 * to CSS files keyed by media type
1163 * @param mixed $messages List of messages associated with this module. May either be an
1164 * associative array mapping message key to value, or a JSON-encoded message blob containing
1165 * the same data, wrapped in an XmlJsCode object.
1166 * @param array $templates Keys are name of templates and values are the source of
1168 * @throws MWException
1171 protected static function makeLoaderImplementScript(
1172 $name, $scripts, $styles, $messages, $templates
1174 if ( $scripts instanceof XmlJsCode
) {
1175 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1176 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1177 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1179 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1180 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1181 // of "{}". Force them to objects.
1189 self
::trimArray( $module );
1191 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1195 * Returns JS code which, when called, will register a given list of messages.
1197 * @param mixed $messages Either an associative array mapping message key to value, or a
1198 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1201 public static function makeMessageSetScript( $messages ) {
1202 return Xml
::encodeJsCall(
1204 [ (object)$messages ],
1205 ResourceLoader
::inDebugMode()
1210 * Combines an associative array mapping media type to CSS into a
1211 * single stylesheet with "@media" blocks.
1213 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1216 public static function makeCombinedStyles( array $stylePairs ) {
1218 foreach ( $stylePairs as $media => $styles ) {
1219 // ResourceLoaderFileModule::getStyle can return the styles
1220 // as a string or an array of strings. This is to allow separation in
1222 $styles = (array)$styles;
1223 foreach ( $styles as $style ) {
1224 $style = trim( $style );
1225 // Don't output an empty "@media print { }" block (T42498)
1226 if ( $style !== '' ) {
1227 // Transform the media type based on request params and config
1228 // The way that this relies on $wgRequest to propagate request params is slightly evil
1229 $media = OutputPage
::transformCssMedia( $media );
1231 if ( $media === '' ||
$media == 'all' ) {
1233 } elseif ( is_string( $media ) ) {
1234 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1244 * Returns a JS call to mw.loader.state, which sets the state of a
1245 * module or modules to a given value. Has two calling conventions:
1247 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1248 * Set the state of a single module called $name to $state
1250 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1251 * Set the state of modules with the given names to the given states
1253 * @param string $name
1254 * @param string $state
1257 public static function makeLoaderStateScript( $name, $state = null ) {
1258 if ( is_array( $name ) ) {
1259 return Xml
::encodeJsCall(
1262 ResourceLoader
::inDebugMode()
1265 return Xml
::encodeJsCall(
1268 ResourceLoader
::inDebugMode()
1274 * Returns JS code which calls the script given by $script. The script will
1275 * be called with local variables name, version, dependencies and group,
1276 * which will have values corresponding to $name, $version, $dependencies
1277 * and $group as supplied.
1279 * @param string $name Module name
1280 * @param string $version Module version hash
1281 * @param array $dependencies List of module names on which this module depends
1282 * @param string $group Group which the module is in.
1283 * @param string $source Source of the module, or 'local' if not foreign.
1284 * @param string $script JavaScript code
1287 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1288 $group, $source, $script
1290 $script = str_replace( "\n", "\n\t", trim( $script ) );
1291 return Xml
::encodeJsCall(
1292 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1293 [ $name, $version, $dependencies, $group, $source ],
1294 ResourceLoader
::inDebugMode()
1298 private static function isEmptyObject( stdClass
$obj ) {
1299 foreach ( $obj as $key => $value ) {
1306 * Remove empty values from the end of an array.
1308 * Values considered empty:
1312 * - new XmlJsCode( '{}' )
1313 * - new stdClass() // (object) []
1315 * @param Array $array
1317 private static function trimArray( array &$array ) {
1318 $i = count( $array );
1320 if ( $array[$i] === null
1321 ||
$array[$i] === []
1322 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1323 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1325 unset( $array[$i] );
1333 * Returns JS code which calls mw.loader.register with the given
1334 * parameters. Has three calling conventions:
1336 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1337 * $dependencies, $group, $source, $skip
1339 * Register a single module.
1341 * - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
1342 * Register modules with the given names.
1344 * - ResourceLoader::makeLoaderRegisterScript( [
1345 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1346 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1349 * Registers modules with the given names and parameters.
1351 * @param string $name Module name
1352 * @param string $version Module version hash
1353 * @param array $dependencies List of module names on which this module depends
1354 * @param string $group Group which the module is in
1355 * @param string $source Source of the module, or 'local' if not foreign
1356 * @param string $skip Script body of the skip function
1359 public static function makeLoaderRegisterScript( $name, $version = null,
1360 $dependencies = null, $group = null, $source = null, $skip = null
1362 if ( is_array( $name ) ) {
1363 // Build module name index
1365 foreach ( $name as $i => &$module ) {
1366 $index[$module[0]] = $i;
1369 // Transform dependency names into indexes when possible, they will be resolved by
1370 // mw.loader.register on the other end
1371 foreach ( $name as &$module ) {
1372 if ( isset( $module[2] ) ) {
1373 foreach ( $module[2] as &$dependency ) {
1374 if ( isset( $index[$dependency] ) ) {
1375 $dependency = $index[$dependency];
1381 array_walk( $name, [ 'self', 'trimArray' ] );
1383 return Xml
::encodeJsCall(
1384 'mw.loader.register',
1386 ResourceLoader
::inDebugMode()
1389 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1390 self
::trimArray( $registration );
1391 return Xml
::encodeJsCall(
1392 'mw.loader.register',
1394 ResourceLoader
::inDebugMode()
1400 * Returns JS code which calls mw.loader.addSource() with the given
1401 * parameters. Has two calling conventions:
1403 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1404 * Register a single source
1406 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1407 * Register sources with the given IDs and properties.
1409 * @param string $id Source ID
1410 * @param string $loadUrl load.php url
1413 public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
1414 if ( is_array( $id ) ) {
1415 return Xml
::encodeJsCall(
1416 'mw.loader.addSource',
1418 ResourceLoader
::inDebugMode()
1421 return Xml
::encodeJsCall(
1422 'mw.loader.addSource',
1424 ResourceLoader
::inDebugMode()
1430 * Returns JS code which runs given JS code if the client-side framework is
1433 * @deprecated since 1.25; use makeInlineScript instead
1434 * @param string $script JavaScript code
1437 public static function makeLoaderConditionalScript( $script ) {
1438 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1439 trim( $script ) . '});';
1443 * Construct an inline script tag with given JS code.
1445 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1446 * only if the client has adequate support for MediaWiki JavaScript code.
1448 * @param string $script JavaScript code
1449 * @return WrappedString HTML
1451 public static function makeInlineScript( $script ) {
1452 $js = self
::makeLoaderConditionalScript( $script );
1453 return new WrappedString(
1454 Html
::inlineScript( $js ),
1455 '<script>(window.RLQ=window.RLQ||[]).push(function(){',
1461 * Returns JS code which will set the MediaWiki configuration array to
1464 * @param array $configuration List of configuration values keyed by variable name
1467 public static function makeConfigSetScript( array $configuration ) {
1468 return Xml
::encodeJsCall(
1471 ResourceLoader
::inDebugMode()
1476 * Convert an array of module names to a packed query string.
1478 * For example, [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]
1479 * becomes 'foo.bar,baz|bar.baz,quux'
1480 * @param array $modules List of module names (strings)
1481 * @return string Packed query string
1483 public static function makePackedModulesString( $modules ) {
1484 $groups = []; // [ prefix => [ suffixes ] ]
1485 foreach ( $modules as $module ) {
1486 $pos = strrpos( $module, '.' );
1487 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1488 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1489 $groups[$prefix][] = $suffix;
1493 foreach ( $groups as $prefix => $suffixes ) {
1494 $p = $prefix === '' ?
'' : $prefix . '.';
1495 $arr[] = $p . implode( ',', $suffixes );
1497 $str = implode( '|', $arr );
1502 * Determine whether debug mode was requested
1503 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1506 public static function inDebugMode() {
1507 if ( self
::$debugMode === null ) {
1508 global $wgRequest, $wgResourceLoaderDebug;
1509 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1510 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1513 return self
::$debugMode;
1517 * Reset static members used for caching.
1519 * Global state and $wgRequest are evil, but we're using it right
1520 * now and sometimes we need to be able to force ResourceLoader to
1521 * re-evaluate the context because it has changed (e.g. in the test suite).
1523 public static function clearCache() {
1524 self
::$debugMode = null;
1528 * Build a load.php URL
1531 * @param string $source Name of the ResourceLoader source
1532 * @param ResourceLoaderContext $context
1533 * @param array $extraQuery
1534 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1536 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1539 $query = self
::createLoaderQuery( $context, $extraQuery );
1540 $script = $this->getLoadScript( $source );
1542 return wfAppendQuery( $script, $query );
1546 * Helper for createLoaderURL()
1549 * @see makeLoaderQuery
1550 * @param ResourceLoaderContext $context
1551 * @param array $extraQuery
1554 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1555 return self
::makeLoaderQuery(
1556 $context->getModules(),
1557 $context->getLanguage(),
1558 $context->getSkin(),
1559 $context->getUser(),
1560 $context->getVersion(),
1561 $context->getDebug(),
1562 $context->getOnly(),
1563 $context->getRequest()->getBool( 'printable' ),
1564 $context->getRequest()->getBool( 'handheld' ),
1570 * Build a query array (array representation of query string) for load.php. Helper
1571 * function for createLoaderURL().
1573 * @param array $modules
1574 * @param string $lang
1575 * @param string $skin
1576 * @param string $user
1577 * @param string $version
1578 * @param bool $debug
1579 * @param string $only
1580 * @param bool $printable
1581 * @param bool $handheld
1582 * @param array $extraQuery
1586 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1587 $version = null, $debug = false, $only = null, $printable = false,
1588 $handheld = false, $extraQuery = []
1591 'modules' => self
::makePackedModulesString( $modules ),
1594 'debug' => $debug ?
'true' : 'false',
1596 if ( $user !== null ) {
1597 $query['user'] = $user;
1599 if ( $version !== null ) {
1600 $query['version'] = $version;
1602 if ( $only !== null ) {
1603 $query['only'] = $only;
1606 $query['printable'] = 1;
1609 $query['handheld'] = 1;
1611 $query +
= $extraQuery;
1613 // Make queries uniform in order
1619 * Check a module name for validity.
1621 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1622 * at most 255 bytes.
1624 * @param string $moduleName Module name to check
1625 * @return bool Whether $moduleName is a valid module name
1627 public static function isValidModuleName( $moduleName ) {
1628 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1632 * Returns LESS compiler set up for use with MediaWiki
1635 * @param array $extraVars Associative array of extra (i.e., other than the
1636 * globally-configured ones) that should be used for compilation.
1637 * @throws MWException
1638 * @return Less_Parser
1640 public function getLessCompiler( $extraVars = [] ) {
1641 // When called from the installer, it is possible that a required PHP extension
1642 // is missing (at least for now; see T49564). If this is the case, throw an
1643 // exception (caught by the installer) to prevent a fatal error later on.
1644 if ( !class_exists( 'Less_Parser' ) ) {
1645 throw new MWException( 'MediaWiki requires the less.php parser' );
1648 $parser = new Less_Parser
;
1649 $parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
1650 $parser->SetImportDirs(
1651 array_fill_keys( $this->config
->get( 'ResourceLoaderLESSImportPaths' ), '' )
1653 $parser->SetOption( 'relativeUrls', false );
1659 * Get global LESS variables.
1662 * @return array Map of variable names to string CSS values.
1664 public function getLessVars() {
1665 if ( !$this->lessVars
) {
1666 $lessVars = $this->config
->get( 'ResourceLoaderLESSVars' );
1667 Hooks
::run( 'ResourceLoaderGetLessVars', [ &$lessVars ] );
1668 $this->lessVars
= $lessVars;
1670 return $this->lessVars
;