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
;
32 * Dynamic JavaScript and CSS resource loading system.
34 * Most of the documentation is on the MediaWiki documentation wiki starting at:
35 * https://www.mediawiki.org/wiki/ResourceLoader
37 class ResourceLoader
implements LoggerAwareInterface
{
39 protected static $filterCacheVersion = 7;
42 protected static $debugMode = null;
45 private $lessVars = null;
48 * Module name/ResourceLoaderModule object pairs
51 protected $modules = [];
54 * Associative array mapping module name to info associative array
57 protected $moduleInfos = [];
59 /** @var Config $config */
63 * Associative array mapping framework ids to a list of names of test suite modules
64 * like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... ], ... ]
67 protected $testModuleNames = [];
70 * E.g. [ 'source-id' => 'http://.../load.php' ]
73 protected $sources = [];
76 * Errors accumulated during current respond() call.
79 protected $errors = [];
82 * @var MessageBlobStore
87 * @var LoggerInterface
91 /** @var string JavaScript / CSS pragma to disable minification. **/
92 const FILTER_NOMIN
= '/*@nomin*/';
95 * Load information stored in the database about modules.
97 * This method grabs modules dependencies from the database and updates modules
100 * This is not inside the module code because it is much faster to
101 * request all of the information at once than it is to have each module
102 * requests its own information. This sacrifice of modularity yields a substantial
103 * performance improvement.
105 * @param array $moduleNames List of module names to preload information for
106 * @param ResourceLoaderContext $context Context to load the information within
108 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext
$context ) {
109 if ( !$moduleNames ) {
110 // Or else Database*::select() will explode, plus it's cheaper!
113 $dbr = wfGetDB( DB_REPLICA
);
114 $skin = $context->getSkin();
115 $lang = $context->getLanguage();
117 // Batched version of ResourceLoaderModule::getFileDependencies
118 $vary = "$skin|$lang";
119 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
120 'md_module' => $moduleNames,
125 // Prime in-object cache for file dependencies
126 $modulesWithDeps = [];
127 foreach ( $res as $row ) {
128 $module = $this->getModule( $row->md_module
);
130 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
131 FormatJson
::decode( $row->md_deps
, true )
133 $modulesWithDeps[] = $row->md_module
;
136 // Register the absence of a dependency row too
137 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
138 $module = $this->getModule( $name );
140 $this->getModule( $name )->setFileDependencies( $context, [] );
144 // Batched version of ResourceLoaderWikiModule::getTitleInfo
145 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $moduleNames );
147 // Prime in-object cache for message blobs for modules with messages
149 foreach ( $moduleNames as $name ) {
150 $module = $this->getModule( $name );
151 if ( $module && $module->getMessages() ) {
152 $modules[$name] = $module;
155 $store = $this->getMessageBlobStore();
156 $blobs = $store->getBlobs( $modules, $lang );
157 foreach ( $blobs as $name => $blob ) {
158 $modules[$name]->setMessageBlob( $blob, $lang );
163 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
165 * Available filters are:
167 * - minify-js \see JavaScriptMinifier::minify
168 * - minify-css \see CSSMin::minify
170 * If $data is empty, only contains whitespace or the filter was unknown,
171 * $data is returned unmodified.
173 * @param string $filter Name of filter to run
174 * @param string $data Text to filter, such as JavaScript or CSS text
175 * @param array $options Keys:
176 * - (bool) cache: Whether to allow caching this data. Default: true.
177 * @return string Filtered data, or a comment containing an error message
179 public static function filter( $filter, $data, array $options = [] ) {
180 if ( strpos( $data, ResourceLoader
::FILTER_NOMIN
) !== false ) {
184 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
185 return self
::applyFilter( $filter, $data );
188 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
189 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
191 $key = $cache->makeGlobalKey(
195 self
::$filterCacheVersion, md5( $data )
198 $result = $cache->get( $key );
199 if ( $result === false ) {
200 $stats->increment( "resourceloader_cache.$filter.miss" );
201 $result = self
::applyFilter( $filter, $data );
202 $cache->set( $key, $result, 24 * 3600 );
204 $stats->increment( "resourceloader_cache.$filter.hit" );
206 if ( $result === null ) {
214 private static function applyFilter( $filter, $data ) {
215 $data = trim( $data );
218 $data = ( $filter === 'minify-css' )
219 ? CSSMin
::minify( $data )
220 : JavaScriptMinifier
::minify( $data );
221 } catch ( Exception
$e ) {
222 MWExceptionHandler
::logException( $e );
232 * Register core modules and runs registration hooks.
233 * @param Config $config [optional]
234 * @param LoggerInterface $logger [optional]
236 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
239 $this->logger
= $logger ?
: new NullLogger();
242 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
243 $config = MediaWikiServices
::getInstance()->getMainConfig();
245 $this->config
= $config;
247 // Add 'local' source first
248 $this->addSource( 'local', $config->get( 'LoadScript' ) );
251 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
253 // Register core modules
254 $this->register( include "$IP/resources/Resources.php" );
255 $this->register( include "$IP/resources/ResourcesOOUI.php" );
256 // Register extension modules
257 $this->register( $config->get( 'ResourceModules' ) );
259 // Avoid PHP 7.1 warning from passing $this by reference
261 Hooks
::run( 'ResourceLoaderRegisterModules', [ &$rl ] );
263 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
264 $this->registerTestModules();
267 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
273 public function getConfig() {
274 return $this->config
;
279 * @param LoggerInterface $logger
281 public function setLogger( LoggerInterface
$logger ) {
282 $this->logger
= $logger;
287 * @return LoggerInterface
289 public function getLogger() {
290 return $this->logger
;
295 * @return MessageBlobStore
297 public function getMessageBlobStore() {
298 return $this->blobStore
;
303 * @param MessageBlobStore $blobStore
305 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
306 $this->blobStore
= $blobStore;
310 * Register a module with the ResourceLoader system.
312 * @param mixed $name Name of module as a string or List of name/object pairs as an array
313 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
314 * this may also be a ResourceLoaderModule object. Optional when using
315 * multiple-registration calling style.
316 * @throws MWException If a duplicate module registration is attempted
317 * @throws MWException If a module name contains illegal characters (pipes or commas)
318 * @throws MWException If something other than a ResourceLoaderModule is being registered
319 * @return bool False if there were any errors, in which case one or more modules were
322 public function register( $name, $info = null ) {
323 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
325 // Allow multiple modules to be registered in one call
326 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
327 foreach ( $registrations as $name => $info ) {
328 // Warn on duplicate registrations
329 if ( isset( $this->moduleInfos
[$name] ) ) {
330 // A module has already been registered by this name
331 $this->logger
->warning(
332 'ResourceLoader duplicate registration warning. ' .
333 'Another module has already been registered as ' . $name
337 // Check $name for validity
338 if ( !self
::isValidModuleName( $name ) ) {
339 throw new MWException( "ResourceLoader module name '$name' is invalid, "
340 . "see ResourceLoader::isValidModuleName()" );
344 if ( $info instanceof ResourceLoaderModule
) {
345 $this->moduleInfos
[$name] = [ 'object' => $info ];
346 $info->setName( $name );
347 $this->modules
[$name] = $info;
348 } elseif ( is_array( $info ) ) {
349 // New calling convention
350 $this->moduleInfos
[$name] = $info;
352 throw new MWException(
353 'ResourceLoader module info type error for module \'' . $name .
354 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
358 // Last-minute changes
360 // Apply custom skin-defined styles to existing modules.
361 if ( $this->isFileModule( $name ) ) {
362 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
363 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
364 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
368 // If $name is preceded with a '+', the defined style files will be added to 'default'
369 // skinStyles, otherwise 'default' will be ignored as it normally would be.
370 if ( isset( $skinStyles[$name] ) ) {
371 $paths = (array)$skinStyles[$name];
373 } elseif ( isset( $skinStyles['+' . $name] ) ) {
374 $paths = (array)$skinStyles['+' . $name];
375 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
376 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
382 // Add new file paths, remapping them to refer to our directories and not use settings
383 // from the module we're modifying, which come from the base definition.
384 list( $localBasePath, $remoteBasePath ) =
385 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
387 foreach ( $paths as $path ) {
388 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
391 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
397 public function registerTestModules() {
400 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
401 throw new MWException( 'Attempt to register JavaScript test modules '
402 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
403 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
406 // Get core test suites
408 $testModules['qunit'] = [];
409 // Get other test suites (e.g. from extensions)
410 // Avoid PHP 7.1 warning from passing $this by reference
412 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
414 // Add the testrunner (which configures QUnit) to the dependencies.
415 // Since it must be ready before any of the test suites are executed.
416 foreach ( $testModules['qunit'] as &$module ) {
417 // Make sure all test modules are top-loading so that when QUnit starts
418 // on document-ready, it will run once and finish. If some tests arrive
419 // later (possibly after QUnit has already finished) they will be ignored.
420 $module['position'] = 'top';
421 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
424 $testModules['qunit'] =
425 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
427 foreach ( $testModules as $id => $names ) {
428 // Register test modules
429 $this->register( $testModules[$id] );
431 // Keep track of their names so that they can be loaded together
432 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
437 * Add a foreign source of modules.
439 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
441 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
442 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
443 * backwards-compatibility.
444 * @throws MWException
446 public function addSource( $id, $loadUrl = null ) {
447 // Allow multiple sources to be registered in one call
448 if ( is_array( $id ) ) {
449 foreach ( $id as $key => $value ) {
450 $this->addSource( $key, $value );
455 // Disallow duplicates
456 if ( isset( $this->sources
[$id] ) ) {
457 throw new MWException(
458 'ResourceLoader duplicate source addition error. ' .
459 'Another source has already been registered as ' . $id
463 // Pre 1.24 backwards-compatibility
464 if ( is_array( $loadUrl ) ) {
465 if ( !isset( $loadUrl['loadScript'] ) ) {
466 throw new MWException(
467 __METHOD__
. ' was passed an array with no "loadScript" key.'
471 $loadUrl = $loadUrl['loadScript'];
474 $this->sources
[$id] = $loadUrl;
478 * Get a list of module names.
480 * @return array List of module names
482 public function getModuleNames() {
483 return array_keys( $this->moduleInfos
);
487 * Get a list of test module names for one (or all) frameworks.
489 * If the given framework id is unknkown, or if the in-object variable is not an array,
490 * then it will return an empty array.
492 * @param string $framework Get only the test module names for one
493 * particular framework (optional)
496 public function getTestModuleNames( $framework = 'all' ) {
497 /** @todo api siteinfo prop testmodulenames modulenames */
498 if ( $framework == 'all' ) {
499 return $this->testModuleNames
;
500 } elseif ( isset( $this->testModuleNames
[$framework] )
501 && is_array( $this->testModuleNames
[$framework] )
503 return $this->testModuleNames
[$framework];
510 * Check whether a ResourceLoader module is registered
513 * @param string $name
516 public function isModuleRegistered( $name ) {
517 return isset( $this->moduleInfos
[$name] );
521 * Get the ResourceLoaderModule object for a given module name.
523 * If an array of module parameters exists but a ResourceLoaderModule object has not
524 * yet been instantiated, this method will instantiate and cache that object such that
525 * subsequent calls simply return the same object.
527 * @param string $name Module name
528 * @return ResourceLoaderModule|null If module has been registered, return a
529 * ResourceLoaderModule instance. Otherwise, return null.
531 public function getModule( $name ) {
532 if ( !isset( $this->modules
[$name] ) ) {
533 if ( !isset( $this->moduleInfos
[$name] ) ) {
537 // Construct the requested object
538 $info = $this->moduleInfos
[$name];
539 /** @var ResourceLoaderModule $object */
540 if ( isset( $info['object'] ) ) {
541 // Object given in info array
542 $object = $info['object'];
544 if ( !isset( $info['class'] ) ) {
545 $class = 'ResourceLoaderFileModule';
547 $class = $info['class'];
549 /** @var ResourceLoaderModule $object */
550 $object = new $class( $info );
551 $object->setConfig( $this->getConfig() );
552 $object->setLogger( $this->logger
);
554 $object->setName( $name );
555 $this->modules
[$name] = $object;
558 return $this->modules
[$name];
562 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
564 * @param string $name Module name
567 protected function isFileModule( $name ) {
568 if ( !isset( $this->moduleInfos
[$name] ) ) {
571 $info = $this->moduleInfos
[$name];
572 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
579 * Get the list of sources.
581 * @return array Like [ id => load.php url, ... ]
583 public function getSources() {
584 return $this->sources
;
588 * Get the URL to the load.php endpoint for the given
589 * ResourceLoader source
592 * @param string $source
593 * @throws MWException On an invalid $source name
596 public function getLoadScript( $source ) {
597 if ( !isset( $this->sources
[$source] ) ) {
598 throw new MWException( "The $source source was never registered in ResourceLoader." );
600 return $this->sources
[$source];
605 * @param string $value
606 * @return string Hash
608 public static function makeHash( $value ) {
609 $hash = hash( 'fnv132', $value );
610 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
614 * Add an error to the 'errors' array and log it.
616 * Should only be called from within respond().
619 * @param Exception $e
621 * @param array $context
623 protected function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
624 MWExceptionHandler
::logException( $e );
625 $this->logger
->warning(
627 $context +
[ 'exception' => $e ]
629 $this->errors
[] = self
::formatExceptionNoComment( $e );
633 * Helper method to get and combine versions of multiple modules.
636 * @param ResourceLoaderContext $context
637 * @param string[] $modules List of known module names
638 * @return string Hash
640 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
641 if ( !$moduleNames ) {
644 $hashes = array_map( function ( $module ) use ( $context ) {
646 return $this->getModule( $module )->getVersionHash( $context );
647 } catch ( Exception
$e ) {
648 // If modules fail to compute a version, do still consider the versions
649 // of other modules - don't set an empty string E-Tag for the whole request.
650 // See also T152266 and StartupModule::getModuleRegistrations().
651 $this->outputErrorAndLog( $e,
652 'Calculating version for "{module}" failed: {exception}',
660 return self
::makeHash( implode( '', $hashes ) );
664 * Get the expected value of the 'version' query parameter.
666 * This is used by respond() to set a short Cache-Control header for requests with
667 * information newer than the current server has. This avoids pollution of edge caches.
668 * Typically during deployment. (T117587)
670 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
673 * @param ResourceLoaderContext $context
674 * @param string[] $modules List of module names
675 * @return string Hash
677 public function makeVersionQuery( ResourceLoaderContext
$context ) {
678 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
679 // version hashes. There is no technical reason for this to be same, and for years the
680 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
681 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
682 // query parameter), then this method must continue to match the JS one.
684 foreach ( $context->getModules() as $name ) {
685 if ( !$this->getModule( $name ) ) {
686 // If a versioned request contains a missing module, the version is a mismatch
687 // as the client considered a module (and version) we don't have.
690 $moduleNames[] = $name;
692 return $this->getCombinedVersion( $context, $moduleNames );
696 * Output a response to a load request, including the content-type header.
698 * @param ResourceLoaderContext $context Context in which a response should be formed
700 public function respond( ResourceLoaderContext
$context ) {
701 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
702 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
703 // is used: ob_clean() will clear the GZIP header in that case and it won't come
704 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
705 // the whole thing in our own output buffer to be sure the active buffer
706 // doesn't use ob_gzhandler.
707 // See https://bugs.php.net/bug.php?id=36514
710 // Find out which modules are missing and instantiate the others
713 foreach ( $context->getModules() as $name ) {
714 $module = $this->getModule( $name );
716 // Do not allow private modules to be loaded from the web.
717 // This is a security issue, see T36907.
718 if ( $module->getGroup() === 'private' ) {
719 $this->logger
->debug( "Request for private module '$name' denied" );
720 $this->errors
[] = "Cannot show private module \"$name\"";
723 $modules[$name] = $module;
730 // Preload for getCombinedVersion() and for batch makeModuleResponse()
731 $this->preloadModuleInfo( array_keys( $modules ), $context );
732 } catch ( Exception
$e ) {
733 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
736 // Combine versions to propagate cache invalidation
739 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
740 } catch ( Exception
$e ) {
741 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
744 // See RFC 2616 § 3.11 Entity Tags
745 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
746 $etag = 'W/"' . $versionHash . '"';
748 // Try the client-side cache first
749 if ( $this->tryRespondNotModified( $context, $etag ) ) {
750 return; // output handled (buffers cleared)
753 // Use file cache if enabled and available...
754 if ( $this->config
->get( 'UseFileCache' ) ) {
755 $fileCache = ResourceFileCache
::newFromContext( $context );
756 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
757 return; // output handled
761 // Generate a response
762 $response = $this->makeModuleResponse( $context, $modules, $missing );
764 // Capture any PHP warnings from the output buffer and append them to the
765 // error list if we're in debug mode.
766 if ( $context->getDebug() ) {
767 $warnings = ob_get_contents();
768 if ( strlen( $warnings ) ) {
769 $this->errors
[] = $warnings;
773 // Save response to file cache unless there are errors
774 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
775 // Cache single modules and images...and other requests if there are enough hits
776 if ( ResourceFileCache
::useFileCache( $context ) ) {
777 if ( $fileCache->isCacheWorthy() ) {
778 $fileCache->saveText( $response );
780 $fileCache->incrMissesRecent( $context->getRequest() );
785 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
787 // Remove the output buffer and output the response
790 if ( $context->getImageObj() && $this->errors
) {
791 // We can't show both the error messages and the response when it's an image.
792 $response = implode( "\n\n", $this->errors
);
793 } elseif ( $this->errors
) {
794 $errorText = implode( "\n\n", $this->errors
);
795 $errorResponse = self
::makeComment( $errorText );
796 if ( $context->shouldIncludeScripts() ) {
797 $errorResponse .= 'if (window.console && console.error) {'
798 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
802 // Prepend error info to the response
803 $response = $errorResponse . $response;
811 * Send main response headers to the client.
813 * Deals with Content-Type, CORS (for stylesheets), and caching.
815 * @param ResourceLoaderContext $context
816 * @param string $etag ETag header value
817 * @param bool $errors Whether there are errors in the response
820 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
821 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
822 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
823 // Use a short cache expiry so that updates propagate to clients quickly, if:
824 // - No version specified (shared resources, e.g. stylesheets)
825 // - There were errors (recover quickly)
826 // - Version mismatch (T117587, T47877)
827 if ( is_null( $context->getVersion() )
829 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
831 $maxage = $rlMaxage['unversioned']['client'];
832 $smaxage = $rlMaxage['unversioned']['server'];
833 // If a version was specified we can use a longer expiry time since changing
834 // version numbers causes cache misses
836 $maxage = $rlMaxage['versioned']['client'];
837 $smaxage = $rlMaxage['versioned']['server'];
839 if ( $context->getImageObj() ) {
840 // Output different headers if we're outputting textual errors.
842 header( 'Content-Type: text/plain; charset=utf-8' );
844 $context->getImageObj()->sendResponseHeaders( $context );
846 } elseif ( $context->getOnly() === 'styles' ) {
847 header( 'Content-Type: text/css; charset=utf-8' );
848 header( 'Access-Control-Allow-Origin: *' );
850 header( 'Content-Type: text/javascript; charset=utf-8' );
852 // See RFC 2616 § 14.19 ETag
853 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
854 header( 'ETag: ' . $etag );
855 if ( $context->getDebug() ) {
856 // Do not cache debug responses
857 header( 'Cache-Control: private, no-cache, must-revalidate' );
858 header( 'Pragma: no-cache' );
860 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
861 $exp = min( $maxage, $smaxage );
862 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
867 * Respond with HTTP 304 Not Modified if appropiate.
869 * If there's an If-None-Match header, respond with a 304 appropriately
870 * and clear out the output buffer. If the client cache is too old then do nothing.
872 * @param ResourceLoaderContext $context
873 * @param string $etag ETag header value
874 * @return bool True if HTTP 304 was sent and output handled
876 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
877 // See RFC 2616 § 14.26 If-None-Match
878 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
879 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
880 // Never send 304s in debug mode
881 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
882 // There's another bug in ob_gzhandler (see also the comment at
883 // the top of this function) that causes it to gzip even empty
884 // responses, meaning it's impossible to produce a truly empty
885 // response (because the gzip header is always there). This is
886 // a problem because 304 responses have to be completely empty
887 // per the HTTP spec, and Firefox behaves buggily when they're not.
888 // See also https://bugs.php.net/bug.php?id=51579
889 // To work around this, we tear down all output buffering before
891 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
893 HttpStatus
::header( 304 );
895 $this->sendResponseHeaders( $context, $etag, false );
902 * Send out code for a response from file cache if possible.
904 * @param ResourceFileCache $fileCache Cache object for this request URL
905 * @param ResourceLoaderContext $context Context in which to generate a response
906 * @param string $etag ETag header value
907 * @return bool If this found a cache file and handled the response
909 protected function tryRespondFromFileCache(
910 ResourceFileCache
$fileCache,
911 ResourceLoaderContext
$context,
914 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
915 // Buffer output to catch warnings.
917 // Get the maximum age the cache can be
918 $maxage = is_null( $context->getVersion() )
919 ?
$rlMaxage['unversioned']['server']
920 : $rlMaxage['versioned']['server'];
921 // Minimum timestamp the cache file must have
922 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
924 try { // RL always hits the DB on file cache miss...
925 wfGetDB( DB_REPLICA
);
926 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
927 $good = $fileCache->isCacheGood(); // cache existence check
931 $ts = $fileCache->cacheTimestamp();
932 // Send content type and cache headers
933 $this->sendResponseHeaders( $context, $etag, false );
934 $response = $fileCache->fetchText();
935 // Capture any PHP warnings from the output buffer and append them to the
936 // response in a comment if we're in debug mode.
937 if ( $context->getDebug() ) {
938 $warnings = ob_get_contents();
939 if ( strlen( $warnings ) ) {
940 $response = self
::makeComment( $warnings ) . $response;
943 // Remove the output buffer and output the response
945 echo $response . "\n/* Cached {$ts} */";
946 return true; // cache hit
951 return false; // cache miss
955 * Generate a CSS or JS comment block.
957 * Only use this for public data, not error message details.
959 * @param string $text
962 public static function makeComment( $text ) {
963 $encText = str_replace( '*/', '* /', $text );
964 return "/*\n$encText\n*/\n";
968 * Handle exception display.
970 * @param Exception $e Exception to be shown to the user
971 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
973 public static function formatException( $e ) {
974 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
978 * Handle exception display.
981 * @param Exception $e Exception to be shown to the user
982 * @return string Sanitized text that can be returned to the user
984 protected static function formatExceptionNoComment( $e ) {
985 global $wgShowExceptionDetails;
987 if ( !$wgShowExceptionDetails ) {
988 return MWExceptionHandler
::getPublicLogMessage( $e );
991 return MWExceptionHandler
::getLogMessage( $e ) .
993 MWExceptionHandler
::getRedactedTraceAsString( $e );
997 * Generate code for a response.
999 * @param ResourceLoaderContext $context Context in which to generate a response
1000 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1001 * @param string[] $missing List of requested module names that are unregistered (optional)
1002 * @return string Response data
1004 public function makeModuleResponse( ResourceLoaderContext
$context,
1005 array $modules, array $missing = []
1010 if ( !count( $modules ) && !count( $missing ) ) {
1012 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1013 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1014 no modules were requested. Max made me put this here. */
1018 $image = $context->getImageObj();
1020 $data = $image->getImageData( $context );
1021 if ( $data === false ) {
1023 $this->errors
[] = 'Image generation failed';
1028 foreach ( $missing as $name ) {
1029 $states[$name] = 'missing';
1035 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1037 foreach ( $modules as $name => $module ) {
1039 $content = $module->getModuleContent( $context );
1040 $implementKey = $name . '@' . $module->getVersionHash( $context );
1044 switch ( $context->getOnly() ) {
1046 $scripts = $content['scripts'];
1047 if ( is_string( $scripts ) ) {
1048 // Load scripts raw...
1049 $strContent = $scripts;
1050 } elseif ( is_array( $scripts ) ) {
1051 // ...except when $scripts is an array of URLs
1052 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1056 $styles = $content['styles'];
1057 // We no longer seperate into media, they are all combined now with
1058 // custom media type groups into @media .. {} sections as part of the css string.
1059 // Module returns either an empty array or a numerical array with css strings.
1060 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1063 $scripts = isset( $content['scripts'] ) ?
$content['scripts'] : '';
1064 if ( is_string( $scripts ) ) {
1065 if ( $name === 'site' ||
$name === 'user' ) {
1066 // Legacy scripts that run in the global scope without a closure.
1067 // mw.loader.implement will use globalEval if scripts is a string.
1068 // Minify manually here, because general response minification is
1069 // not effective due it being a string literal, not a function.
1070 if ( !ResourceLoader
::inDebugMode() ) {
1071 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1074 $scripts = new XmlJsCode( $scripts );
1077 $strContent = self
::makeLoaderImplementScript(
1080 isset( $content['styles'] ) ?
$content['styles'] : [],
1081 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1082 isset( $content['templates'] ) ?
$content['templates'] : []
1087 if ( !$context->getDebug() ) {
1088 $strContent = self
::filter( $filter, $strContent );
1091 $out .= $strContent;
1093 } catch ( Exception
$e ) {
1094 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1096 // Respond to client with error-state instead of module implementation
1097 $states[$name] = 'error';
1098 unset( $modules[$name] );
1100 $isRaw |
= $module->isRaw();
1103 // Update module states
1104 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1105 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1106 // Set the state of modules loaded as only scripts to ready as
1107 // they don't have an mw.loader.implement wrapper that sets the state
1108 foreach ( $modules as $name => $module ) {
1109 $states[$name] = 'ready';
1113 // Set the state of modules we didn't respond to with mw.loader.implement
1114 if ( count( $states ) ) {
1115 $stateScript = self
::makeLoaderStateScript( $states );
1116 if ( !$context->getDebug() ) {
1117 $stateScript = self
::filter( 'minify-js', $stateScript );
1119 $out .= $stateScript;
1122 if ( count( $states ) ) {
1123 $this->errors
[] = 'Problematic modules: ' .
1124 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1132 * Get names of modules that use a certain message.
1134 * @param string $messageKey
1135 * @return array List of module names
1137 public function getModulesByMessage( $messageKey ) {
1139 foreach ( $this->getModuleNames() as $moduleName ) {
1140 $module = $this->getModule( $moduleName );
1141 if ( in_array( $messageKey, $module->getMessages() ) ) {
1142 $moduleNames[] = $moduleName;
1145 return $moduleNames;
1148 /* Static Methods */
1151 * Return JS code that calls mw.loader.implement with given module properties.
1153 * @param string $name Module name or implement key (format "`[name]@[version]`")
1154 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1155 * list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
1156 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1157 * to CSS files keyed by media type
1158 * @param mixed $messages List of messages associated with this module. May either be an
1159 * associative array mapping message key to value, or a JSON-encoded message blob containing
1160 * the same data, wrapped in an XmlJsCode object.
1161 * @param array $templates Keys are name of templates and values are the source of
1163 * @throws MWException
1166 protected static function makeLoaderImplementScript(
1167 $name, $scripts, $styles, $messages, $templates
1169 if ( $scripts instanceof XmlJsCode
) {
1170 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1171 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1172 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1174 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1175 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1176 // of "{}". Force them to objects.
1184 self
::trimArray( $module );
1186 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1190 * Returns JS code which, when called, will register a given list of messages.
1192 * @param mixed $messages Either an associative array mapping message key to value, or a
1193 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1196 public static function makeMessageSetScript( $messages ) {
1197 return Xml
::encodeJsCall(
1199 [ (object)$messages ],
1200 ResourceLoader
::inDebugMode()
1205 * Combines an associative array mapping media type to CSS into a
1206 * single stylesheet with "@media" blocks.
1208 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1211 public static function makeCombinedStyles( array $stylePairs ) {
1213 foreach ( $stylePairs as $media => $styles ) {
1214 // ResourceLoaderFileModule::getStyle can return the styles
1215 // as a string or an array of strings. This is to allow separation in
1217 $styles = (array)$styles;
1218 foreach ( $styles as $style ) {
1219 $style = trim( $style );
1220 // Don't output an empty "@media print { }" block (T42498)
1221 if ( $style !== '' ) {
1222 // Transform the media type based on request params and config
1223 // The way that this relies on $wgRequest to propagate request params is slightly evil
1224 $media = OutputPage
::transformCssMedia( $media );
1226 if ( $media === '' ||
$media == 'all' ) {
1228 } elseif ( is_string( $media ) ) {
1229 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1239 * Returns a JS call to mw.loader.state, which sets the state of a
1240 * module or modules to a given value. Has two calling conventions:
1242 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1243 * Set the state of a single module called $name to $state
1245 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1246 * Set the state of modules with the given names to the given states
1248 * @param string $name
1249 * @param string $state
1252 public static function makeLoaderStateScript( $name, $state = null ) {
1253 if ( is_array( $name ) ) {
1254 return Xml
::encodeJsCall(
1257 ResourceLoader
::inDebugMode()
1260 return Xml
::encodeJsCall(
1263 ResourceLoader
::inDebugMode()
1269 * Returns JS code which calls the script given by $script. The script will
1270 * be called with local variables name, version, dependencies and group,
1271 * which will have values corresponding to $name, $version, $dependencies
1272 * and $group as supplied.
1274 * @param string $name Module name
1275 * @param string $version Module version hash
1276 * @param array $dependencies List of module names on which this module depends
1277 * @param string $group Group which the module is in.
1278 * @param string $source Source of the module, or 'local' if not foreign.
1279 * @param string $script JavaScript code
1282 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1283 $group, $source, $script
1285 $script = str_replace( "\n", "\n\t", trim( $script ) );
1286 return Xml
::encodeJsCall(
1287 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1288 [ $name, $version, $dependencies, $group, $source ],
1289 ResourceLoader
::inDebugMode()
1293 private static function isEmptyObject( stdClass
$obj ) {
1294 foreach ( $obj as $key => $value ) {
1301 * Remove empty values from the end of an array.
1303 * Values considered empty:
1307 * - new XmlJsCode( '{}' )
1308 * - new stdClass() // (object) []
1310 * @param Array $array
1312 private static function trimArray( array &$array ) {
1313 $i = count( $array );
1315 if ( $array[$i] === null
1316 ||
$array[$i] === []
1317 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1318 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1320 unset( $array[$i] );
1328 * Returns JS code which calls mw.loader.register with the given
1329 * parameters. Has three calling conventions:
1331 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1332 * $dependencies, $group, $source, $skip
1334 * Register a single module.
1336 * - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
1337 * Register modules with the given names.
1339 * - ResourceLoader::makeLoaderRegisterScript( [
1340 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1341 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1344 * Registers modules with the given names and parameters.
1346 * @param string $name Module name
1347 * @param string $version Module version hash
1348 * @param array $dependencies List of module names on which this module depends
1349 * @param string $group Group which the module is in
1350 * @param string $source Source of the module, or 'local' if not foreign
1351 * @param string $skip Script body of the skip function
1354 public static function makeLoaderRegisterScript( $name, $version = null,
1355 $dependencies = null, $group = null, $source = null, $skip = null
1357 if ( is_array( $name ) ) {
1358 // Build module name index
1360 foreach ( $name as $i => &$module ) {
1361 $index[$module[0]] = $i;
1364 // Transform dependency names into indexes when possible, they will be resolved by
1365 // mw.loader.register on the other end
1366 foreach ( $name as &$module ) {
1367 if ( isset( $module[2] ) ) {
1368 foreach ( $module[2] as &$dependency ) {
1369 if ( isset( $index[$dependency] ) ) {
1370 $dependency = $index[$dependency];
1376 array_walk( $name, [ 'self', 'trimArray' ] );
1378 return Xml
::encodeJsCall(
1379 'mw.loader.register',
1381 ResourceLoader
::inDebugMode()
1384 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1385 self
::trimArray( $registration );
1386 return Xml
::encodeJsCall(
1387 'mw.loader.register',
1389 ResourceLoader
::inDebugMode()
1395 * Returns JS code which calls mw.loader.addSource() with the given
1396 * parameters. Has two calling conventions:
1398 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1399 * Register a single source
1401 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1402 * Register sources with the given IDs and properties.
1404 * @param string $id Source ID
1405 * @param string $loadUrl load.php url
1408 public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
1409 if ( is_array( $id ) ) {
1410 return Xml
::encodeJsCall(
1411 'mw.loader.addSource',
1413 ResourceLoader
::inDebugMode()
1416 return Xml
::encodeJsCall(
1417 'mw.loader.addSource',
1419 ResourceLoader
::inDebugMode()
1425 * Returns JS code which runs given JS code if the client-side framework is
1428 * @deprecated since 1.25; use makeInlineScript instead
1429 * @param string $script JavaScript code
1432 public static function makeLoaderConditionalScript( $script ) {
1433 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1434 trim( $script ) . '});';
1438 * Construct an inline script tag with given JS code.
1440 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1441 * only if the client has adequate support for MediaWiki JavaScript code.
1443 * @param string $script JavaScript code
1444 * @return WrappedString HTML
1446 public static function makeInlineScript( $script ) {
1447 $js = self
::makeLoaderConditionalScript( $script );
1448 return new WrappedString(
1449 Html
::inlineScript( $js ),
1450 '<script>(window.RLQ=window.RLQ||[]).push(function(){',
1456 * Returns JS code which will set the MediaWiki configuration array to
1459 * @param array $configuration List of configuration values keyed by variable name
1462 public static function makeConfigSetScript( array $configuration ) {
1463 return Xml
::encodeJsCall(
1466 ResourceLoader
::inDebugMode()
1471 * Convert an array of module names to a packed query string.
1473 * For example, [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]
1474 * becomes 'foo.bar,baz|bar.baz,quux'
1475 * @param array $modules List of module names (strings)
1476 * @return string Packed query string
1478 public static function makePackedModulesString( $modules ) {
1479 $groups = []; // [ prefix => [ suffixes ] ]
1480 foreach ( $modules as $module ) {
1481 $pos = strrpos( $module, '.' );
1482 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1483 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1484 $groups[$prefix][] = $suffix;
1488 foreach ( $groups as $prefix => $suffixes ) {
1489 $p = $prefix === '' ?
'' : $prefix . '.';
1490 $arr[] = $p . implode( ',', $suffixes );
1492 $str = implode( '|', $arr );
1497 * Determine whether debug mode was requested
1498 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1501 public static function inDebugMode() {
1502 if ( self
::$debugMode === null ) {
1503 global $wgRequest, $wgResourceLoaderDebug;
1504 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1505 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1508 return self
::$debugMode;
1512 * Reset static members used for caching.
1514 * Global state and $wgRequest are evil, but we're using it right
1515 * now and sometimes we need to be able to force ResourceLoader to
1516 * re-evaluate the context because it has changed (e.g. in the test suite).
1518 public static function clearCache() {
1519 self
::$debugMode = null;
1523 * Build a load.php URL
1526 * @param string $source Name of the ResourceLoader source
1527 * @param ResourceLoaderContext $context
1528 * @param array $extraQuery
1529 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1531 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1534 $query = self
::createLoaderQuery( $context, $extraQuery );
1535 $script = $this->getLoadScript( $source );
1537 return wfAppendQuery( $script, $query );
1541 * Helper for createLoaderURL()
1544 * @see makeLoaderQuery
1545 * @param ResourceLoaderContext $context
1546 * @param array $extraQuery
1549 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1550 return self
::makeLoaderQuery(
1551 $context->getModules(),
1552 $context->getLanguage(),
1553 $context->getSkin(),
1554 $context->getUser(),
1555 $context->getVersion(),
1556 $context->getDebug(),
1557 $context->getOnly(),
1558 $context->getRequest()->getBool( 'printable' ),
1559 $context->getRequest()->getBool( 'handheld' ),
1565 * Build a query array (array representation of query string) for load.php. Helper
1566 * function for createLoaderURL().
1568 * @param array $modules
1569 * @param string $lang
1570 * @param string $skin
1571 * @param string $user
1572 * @param string $version
1573 * @param bool $debug
1574 * @param string $only
1575 * @param bool $printable
1576 * @param bool $handheld
1577 * @param array $extraQuery
1581 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1582 $version = null, $debug = false, $only = null, $printable = false,
1583 $handheld = false, $extraQuery = []
1586 'modules' => self
::makePackedModulesString( $modules ),
1589 'debug' => $debug ?
'true' : 'false',
1591 if ( $user !== null ) {
1592 $query['user'] = $user;
1594 if ( $version !== null ) {
1595 $query['version'] = $version;
1597 if ( $only !== null ) {
1598 $query['only'] = $only;
1601 $query['printable'] = 1;
1604 $query['handheld'] = 1;
1606 $query +
= $extraQuery;
1608 // Make queries uniform in order
1614 * Check a module name for validity.
1616 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1617 * at most 255 bytes.
1619 * @param string $moduleName Module name to check
1620 * @return bool Whether $moduleName is a valid module name
1622 public static function isValidModuleName( $moduleName ) {
1623 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1627 * Returns LESS compiler set up for use with MediaWiki
1630 * @param array $extraVars Associative array of extra (i.e., other than the
1631 * globally-configured ones) that should be used for compilation.
1632 * @throws MWException
1633 * @return Less_Parser
1635 public function getLessCompiler( $extraVars = [] ) {
1636 // When called from the installer, it is possible that a required PHP extension
1637 // is missing (at least for now; see T49564). If this is the case, throw an
1638 // exception (caught by the installer) to prevent a fatal error later on.
1639 if ( !class_exists( 'Less_Parser' ) ) {
1640 throw new MWException( 'MediaWiki requires the less.php parser' );
1643 $parser = new Less_Parser
;
1644 $parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
1645 $parser->SetImportDirs(
1646 array_fill_keys( $this->config
->get( 'ResourceLoaderLESSImportPaths' ), '' )
1648 $parser->SetOption( 'relativeUrls', false );
1654 * Get global LESS variables.
1657 * @return array Map of variable names to string CSS values.
1659 public function getLessVars() {
1660 if ( !$this->lessVars
) {
1661 $lessVars = $this->config
->get( 'ResourceLoaderLESSVars' );
1662 Hooks
::run( 'ResourceLoaderGetLessVars', [ &$lessVars ] );
1663 $this->lessVars
= $lessVars;
1665 return $this->lessVars
;