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 Wikimedia\Rdbms\DBConnectionError
;
30 use Wikimedia\WrappedString
;
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 const CACHE_VERSION
= 8;
43 protected static $debugMode = null;
46 * Module name/ResourceLoaderModule object pairs
49 protected $modules = [];
52 * Associative array mapping module name to info associative array
55 protected $moduleInfos = [];
57 /** @var Config $config */
61 * Associative array mapping framework ids to a list of names of test suite modules
62 * like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... ], ... ]
65 protected $testModuleNames = [];
68 * E.g. [ 'source-id' => 'http://.../load.php' ]
71 protected $sources = [];
74 * Errors accumulated during current respond() call.
77 protected $errors = [];
80 * List of extra HTTP response headers provided by loaded modules.
82 * Populated by makeModuleResponse().
86 protected $extraHeaders = [];
89 * @var MessageBlobStore
94 * @var LoggerInterface
98 /** @var string JavaScript / CSS pragma to disable minification. **/
99 const FILTER_NOMIN
= '/*@nomin*/';
102 * Load information stored in the database about modules.
104 * This method grabs modules dependencies from the database and updates modules
107 * This is not inside the module code because it is much faster to
108 * request all of the information at once than it is to have each module
109 * requests its own information. This sacrifice of modularity yields a substantial
110 * performance improvement.
112 * @param array $moduleNames List of module names to preload information for
113 * @param ResourceLoaderContext $context Context to load the information within
115 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext
$context ) {
116 if ( !$moduleNames ) {
117 // Or else Database*::select() will explode, plus it's cheaper!
120 $dbr = wfGetDB( DB_REPLICA
);
121 $lang = $context->getLanguage();
123 // Batched version of ResourceLoaderModule::getFileDependencies
124 $vary = ResourceLoaderModule
::getVary( $context );
125 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
126 'md_module' => $moduleNames,
131 // Prime in-object cache for file dependencies
132 $modulesWithDeps = [];
133 foreach ( $res as $row ) {
134 $module = $this->getModule( $row->md_module
);
136 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
137 json_decode( $row->md_deps
, true )
139 $modulesWithDeps[] = $row->md_module
;
142 // Register the absence of a dependency row too
143 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
144 $module = $this->getModule( $name );
146 $this->getModule( $name )->setFileDependencies( $context, [] );
150 // Batched version of ResourceLoaderWikiModule::getTitleInfo
151 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $moduleNames );
153 // Prime in-object cache for message blobs for modules with messages
155 foreach ( $moduleNames as $name ) {
156 $module = $this->getModule( $name );
157 if ( $module && $module->getMessages() ) {
158 $modules[$name] = $module;
161 $store = $this->getMessageBlobStore();
162 $blobs = $store->getBlobs( $modules, $lang );
163 foreach ( $blobs as $name => $blob ) {
164 $modules[$name]->setMessageBlob( $blob, $lang );
169 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
171 * Available filters are:
173 * - minify-js \see JavaScriptMinifier::minify
174 * - minify-css \see CSSMin::minify
176 * If $data is empty, only contains whitespace or the filter was unknown,
177 * $data is returned unmodified.
179 * @param string $filter Name of filter to run
180 * @param string $data Text to filter, such as JavaScript or CSS text
181 * @param array $options Keys:
182 * - (bool) cache: Whether to allow caching this data. Default: true.
183 * @return string Filtered data, or a comment containing an error message
185 public static function filter( $filter, $data, array $options = [] ) {
186 if ( strpos( $data, self
::FILTER_NOMIN
) !== false ) {
190 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
191 return self
::applyFilter( $filter, $data );
194 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
195 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
197 $key = $cache->makeGlobalKey(
198 'resourceloader-filter',
204 $result = $cache->get( $key );
205 if ( $result === false ) {
206 $stats->increment( "resourceloader_cache.$filter.miss" );
207 $result = self
::applyFilter( $filter, $data );
208 $cache->set( $key, $result, 24 * 3600 );
210 $stats->increment( "resourceloader_cache.$filter.hit" );
212 if ( $result === null ) {
220 private static function applyFilter( $filter, $data ) {
221 $data = trim( $data );
224 $data = ( $filter === 'minify-css' )
225 ? CSSMin
::minify( $data )
226 : JavaScriptMinifier
::minify( $data );
227 } catch ( Exception
$e ) {
228 MWExceptionHandler
::logException( $e );
236 * Register core modules and runs registration hooks.
237 * @param Config|null $config
238 * @param LoggerInterface|null $logger [optional]
240 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
241 $this->logger
= $logger ?
: new NullLogger();
244 wfDeprecated( __METHOD__
. ' without a Config instance', '1.34' );
245 $config = MediaWikiServices
::getInstance()->getMainConfig();
247 $this->config
= $config;
249 // Add 'local' source first
250 $this->addSource( 'local', $config->get( 'LoadScript' ) );
252 // Special module that always exists
253 $this->register( 'startup', [ 'class' => ResourceLoaderStartUpModule
::class ] );
255 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
261 public function getConfig() {
262 return $this->config
;
267 * @param LoggerInterface $logger
269 public function setLogger( LoggerInterface
$logger ) {
270 $this->logger
= $logger;
275 * @return LoggerInterface
277 public function getLogger() {
278 return $this->logger
;
283 * @return MessageBlobStore
285 public function getMessageBlobStore() {
286 return $this->blobStore
;
291 * @param MessageBlobStore $blobStore
293 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
294 $this->blobStore
= $blobStore;
298 * Register a module with the ResourceLoader system.
300 * @param string|array[] $name Module name as a string or, array of module info arrays
302 * @param array|null $info Module info array. When using the first parameter to register
303 * multiple modules at once, this parameter is optional.
304 * @throws MWException If a duplicate module registration is attempted
305 * @throws MWException If a module name contains illegal characters (pipes or commas)
306 * @throws InvalidArgumentException If the module info is not an array
308 public function register( $name, $info = null ) {
309 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
311 // Allow multiple modules to be registered in one call
312 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
313 foreach ( $registrations as $name => $info ) {
314 // Warn on duplicate registrations
315 if ( isset( $this->moduleInfos
[$name] ) ) {
316 // A module has already been registered by this name
317 $this->logger
->warning(
318 'ResourceLoader duplicate registration warning. ' .
319 'Another module has already been registered as ' . $name
324 if ( !self
::isValidModuleName( $name ) ) {
325 throw new MWException( "ResourceLoader module name '$name' is invalid, "
326 . "see ResourceLoader::isValidModuleName()" );
328 if ( !is_array( $info ) ) {
329 throw new InvalidArgumentException(
330 'Invalid module info for "' . $name . '": expected array, got ' . gettype( $info )
335 $this->moduleInfos
[$name] = $info;
337 // Last-minute changes
338 // Apply custom skin-defined styles to existing modules.
339 if ( $this->isFileModule( $name ) ) {
340 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
341 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
342 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
346 // If $name is preceded with a '+', the defined style files will be added to 'default'
347 // skinStyles, otherwise 'default' will be ignored as it normally would be.
348 if ( isset( $skinStyles[$name] ) ) {
349 $paths = (array)$skinStyles[$name];
351 } elseif ( isset( $skinStyles['+' . $name] ) ) {
352 $paths = (array)$skinStyles['+' . $name];
353 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
354 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
360 // Add new file paths, remapping them to refer to our directories and not use settings
361 // from the module we're modifying, which come from the base definition.
362 list( $localBasePath, $remoteBasePath ) =
363 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
365 foreach ( $paths as $path ) {
366 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
369 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
376 * @internal For use by ServiceWiring only
378 public function registerTestModules() {
381 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
382 throw new MWException( 'Attempt to register JavaScript test modules '
383 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
384 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
391 // Get test suites from extensions
392 // Avoid PHP 7.1 warning from passing $this by reference
394 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
395 $extRegistry = ExtensionRegistry
::getInstance();
396 // In case of conflict, the deprecated hook has precedence.
397 $testModules['qunit'] +
= $extRegistry->getAttribute( 'QUnitTestModules' );
399 // Add the QUnit testrunner as implicit dependency to extension test suites.
400 foreach ( $testModules['qunit'] as &$module ) {
401 // Shuck any single-module dependency as an array
402 if ( isset( $module['dependencies'] ) && is_string( $module['dependencies'] ) ) {
403 $module['dependencies'] = [ $module['dependencies'] ];
406 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
409 // Get core test suites
410 $testModules['qunit'] =
411 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
413 foreach ( $testModules as $id => $names ) {
414 // Register test modules
415 $this->register( $testModules[$id] );
417 // Keep track of their names so that they can be loaded together
418 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
423 * Add a foreign source of modules.
425 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
427 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
428 * @param string|array|null $loadUrl load.php url (string), or array with loadUrl key for
429 * backwards-compatibility.
430 * @throws MWException
432 public function addSource( $id, $loadUrl = null ) {
433 // Allow multiple sources to be registered in one call
434 if ( is_array( $id ) ) {
435 foreach ( $id as $key => $value ) {
436 $this->addSource( $key, $value );
441 // Disallow duplicates
442 if ( isset( $this->sources
[$id] ) ) {
443 throw new MWException(
444 'ResourceLoader duplicate source addition error. ' .
445 'Another source has already been registered as ' . $id
449 // Pre 1.24 backwards-compatibility
450 if ( is_array( $loadUrl ) ) {
451 if ( !isset( $loadUrl['loadScript'] ) ) {
452 throw new MWException(
453 __METHOD__
. ' was passed an array with no "loadScript" key.'
457 $loadUrl = $loadUrl['loadScript'];
460 $this->sources
[$id] = $loadUrl;
464 * Get a list of module names.
466 * @return array List of module names
468 public function getModuleNames() {
469 return array_keys( $this->moduleInfos
);
473 * Get a list of test module names for one (or all) frameworks.
475 * If the given framework id is unknkown, or if the in-object variable is not an array,
476 * then it will return an empty array.
478 * @param string $framework Get only the test module names for one
479 * particular framework (optional)
482 public function getTestModuleNames( $framework = 'all' ) {
483 if ( $framework == 'all' ) {
484 return $this->testModuleNames
;
485 } elseif ( isset( $this->testModuleNames
[$framework] )
486 && is_array( $this->testModuleNames
[$framework] )
488 return $this->testModuleNames
[$framework];
495 * Check whether a ResourceLoader module is registered
498 * @param string $name
501 public function isModuleRegistered( $name ) {
502 return isset( $this->moduleInfos
[$name] );
506 * Get the ResourceLoaderModule object for a given module name.
508 * If an array of module parameters exists but a ResourceLoaderModule object has not
509 * yet been instantiated, this method will instantiate and cache that object such that
510 * subsequent calls simply return the same object.
512 * @param string $name Module name
513 * @return ResourceLoaderModule|null If module has been registered, return a
514 * ResourceLoaderModule instance. Otherwise, return null.
516 public function getModule( $name ) {
517 if ( !isset( $this->modules
[$name] ) ) {
518 if ( !isset( $this->moduleInfos
[$name] ) ) {
522 // Construct the requested module object
523 $info = $this->moduleInfos
[$name];
524 if ( isset( $info['factory'] ) ) {
525 /** @var ResourceLoaderModule $object */
526 $object = call_user_func( $info['factory'], $info );
528 $class = $info['class'] ?? ResourceLoaderFileModule
::class;
529 /** @var ResourceLoaderModule $object */
530 $object = new $class( $info );
532 $object->setConfig( $this->getConfig() );
533 $object->setLogger( $this->logger
);
534 $object->setName( $name );
535 $this->modules
[$name] = $object;
538 return $this->modules
[$name];
542 * Whether the module is a ResourceLoaderFileModule (including subclasses).
544 * @param string $name Module name
547 protected function isFileModule( $name ) {
548 if ( !isset( $this->moduleInfos
[$name] ) ) {
551 $info = $this->moduleInfos
[$name];
552 return !isset( $info['factory'] ) && (
553 // The implied default for 'class' is ResourceLoaderFileModule
554 !isset( $info['class'] ) ||
556 $info['class'] === ResourceLoaderFileModule
::class ||
557 is_subclass_of( $info['class'], ResourceLoaderFileModule
::class )
562 * Get the list of sources.
564 * @return array Like [ id => load.php url, ... ]
566 public function getSources() {
567 return $this->sources
;
571 * Get the URL to the load.php endpoint for the given
572 * ResourceLoader source
575 * @param string $source
576 * @throws MWException On an invalid $source name
579 public function getLoadScript( $source ) {
580 if ( !isset( $this->sources
[$source] ) ) {
581 throw new MWException( "The $source source was never registered in ResourceLoader." );
583 return $this->sources
[$source];
588 * @param string $value
589 * @return string Hash
591 public static function makeHash( $value ) {
592 $hash = hash( 'fnv132', $value );
593 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
597 * Add an error to the 'errors' array and log it.
599 * @private For internal use by ResourceLoader and ResourceLoaderStartUpModule.
601 * @param Exception $e
603 * @param array $context
605 public function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
606 MWExceptionHandler
::logException( $e );
607 $this->logger
->warning(
609 $context +
[ 'exception' => $e ]
611 $this->errors
[] = self
::formatExceptionNoComment( $e );
615 * Helper method to get and combine versions of multiple modules.
618 * @param ResourceLoaderContext $context
619 * @param string[] $moduleNames List of known module names
620 * @return string Hash
622 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
623 if ( !$moduleNames ) {
626 $hashes = array_map( function ( $module ) use ( $context ) {
628 return $this->getModule( $module )->getVersionHash( $context );
629 } catch ( Exception
$e ) {
630 // If modules fail to compute a version, don't fail the request (T152266)
631 // and still compute versions of other modules.
632 $this->outputErrorAndLog( $e,
633 'Calculating version for "{module}" failed: {exception}',
641 return self
::makeHash( implode( '', $hashes ) );
645 * Get the expected value of the 'version' query parameter.
647 * This is used by respond() to set a short Cache-Control header for requests with
648 * information newer than the current server has. This avoids pollution of edge caches.
649 * Typically during deployment. (T117587)
651 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
654 * @param ResourceLoaderContext $context
655 * @return string Hash
657 public function makeVersionQuery( ResourceLoaderContext
$context ) {
658 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
659 // version hashes. There is no technical reason for this to be same, and for years the
660 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
661 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
662 // query parameter), then this method must continue to match the JS one.
664 foreach ( $context->getModules() as $name ) {
665 if ( !$this->getModule( $name ) ) {
666 // If a versioned request contains a missing module, the version is a mismatch
667 // as the client considered a module (and version) we don't have.
670 $moduleNames[] = $name;
672 return $this->getCombinedVersion( $context, $moduleNames );
676 * Output a response to a load request, including the content-type header.
678 * @param ResourceLoaderContext $context Context in which a response should be formed
680 public function respond( ResourceLoaderContext
$context ) {
681 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
682 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
683 // is used: ob_clean() will clear the GZIP header in that case and it won't come
684 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
685 // the whole thing in our own output buffer to be sure the active buffer
686 // doesn't use ob_gzhandler.
687 // See https://bugs.php.net/bug.php?id=36514
690 $this->measureResponseTime( RequestContext
::getMain()->getTiming() );
692 // Find out which modules are missing and instantiate the others
695 foreach ( $context->getModules() as $name ) {
696 $module = $this->getModule( $name );
698 // Do not allow private modules to be loaded from the web.
699 // This is a security issue, see T36907.
700 if ( $module->getGroup() === 'private' ) {
701 $this->logger
->debug( "Request for private module '$name' denied" );
702 $this->errors
[] = "Cannot show private module \"$name\"";
705 $modules[$name] = $module;
712 // Preload for getCombinedVersion() and for batch makeModuleResponse()
713 $this->preloadModuleInfo( array_keys( $modules ), $context );
714 } catch ( Exception
$e ) {
715 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
718 // Combine versions to propagate cache invalidation
721 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
722 } catch ( Exception
$e ) {
723 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
726 // See RFC 2616 § 3.11 Entity Tags
727 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
728 $etag = 'W/"' . $versionHash . '"';
730 // Try the client-side cache first
731 if ( $this->tryRespondNotModified( $context, $etag ) ) {
732 return; // output handled (buffers cleared)
735 // Use file cache if enabled and available...
736 if ( $this->config
->get( 'UseFileCache' ) ) {
737 $fileCache = ResourceFileCache
::newFromContext( $context );
738 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
739 return; // output handled
743 // Generate a response
744 $response = $this->makeModuleResponse( $context, $modules, $missing );
746 // Capture any PHP warnings from the output buffer and append them to the
747 // error list if we're in debug mode.
748 if ( $context->getDebug() ) {
749 $warnings = ob_get_contents();
750 if ( strlen( $warnings ) ) {
751 $this->errors
[] = $warnings;
755 // Save response to file cache unless there are errors
756 if ( isset( $fileCache ) && !$this->errors
&& $missing === [] ) {
757 // Cache single modules and images...and other requests if there are enough hits
758 if ( ResourceFileCache
::useFileCache( $context ) ) {
759 if ( $fileCache->isCacheWorthy() ) {
760 $fileCache->saveText( $response );
762 $fileCache->incrMissesRecent( $context->getRequest() );
767 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
, $this->extraHeaders
);
769 // Remove the output buffer and output the response
772 if ( $context->getImageObj() && $this->errors
) {
773 // We can't show both the error messages and the response when it's an image.
774 $response = implode( "\n\n", $this->errors
);
775 } elseif ( $this->errors
) {
776 $errorText = implode( "\n\n", $this->errors
);
777 $errorResponse = self
::makeComment( $errorText );
778 if ( $context->shouldIncludeScripts() ) {
779 $errorResponse .= 'if (window.console && console.error) {'
780 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
784 // Prepend error info to the response
785 $response = $errorResponse . $response;
792 protected function measureResponseTime( Timing
$timing ) {
793 DeferredUpdates
::addCallableUpdate( function () use ( $timing ) {
794 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
795 if ( $measure !== false ) {
796 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
797 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
803 * Send main response headers to the client.
805 * Deals with Content-Type, CORS (for stylesheets), and caching.
807 * @param ResourceLoaderContext $context
808 * @param string $etag ETag header value
809 * @param bool $errors Whether there are errors in the response
810 * @param string[] $extra Array of extra HTTP response headers
813 protected function sendResponseHeaders(
814 ResourceLoaderContext
$context, $etag, $errors, array $extra = []
816 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
817 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
818 // Use a short cache expiry so that updates propagate to clients quickly, if:
819 // - No version specified (shared resources, e.g. stylesheets)
820 // - There were errors (recover quickly)
821 // - Version mismatch (T117587, T47877)
822 if ( is_null( $context->getVersion() )
824 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
826 $maxage = $rlMaxage['unversioned']['client'];
827 $smaxage = $rlMaxage['unversioned']['server'];
828 // If a version was specified we can use a longer expiry time since changing
829 // version numbers causes cache misses
831 $maxage = $rlMaxage['versioned']['client'];
832 $smaxage = $rlMaxage['versioned']['server'];
834 if ( $context->getImageObj() ) {
835 // Output different headers if we're outputting textual errors.
837 header( 'Content-Type: text/plain; charset=utf-8' );
839 $context->getImageObj()->sendResponseHeaders( $context );
841 } elseif ( $context->getOnly() === 'styles' ) {
842 header( 'Content-Type: text/css; charset=utf-8' );
843 header( 'Access-Control-Allow-Origin: *' );
845 header( 'Content-Type: text/javascript; charset=utf-8' );
847 // See RFC 2616 § 14.19 ETag
848 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
849 header( 'ETag: ' . $etag );
850 if ( $context->getDebug() ) {
851 // Do not cache debug responses
852 header( 'Cache-Control: private, no-cache, must-revalidate' );
853 header( 'Pragma: no-cache' );
855 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
856 $exp = min( $maxage, $smaxage );
857 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
859 foreach ( $extra as $header ) {
865 * Respond with HTTP 304 Not Modified if appropiate.
867 * If there's an If-None-Match header, respond with a 304 appropriately
868 * and clear out the output buffer. If the client cache is too old then do nothing.
870 * @param ResourceLoaderContext $context
871 * @param string $etag ETag header value
872 * @return bool True if HTTP 304 was sent and output handled
874 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
875 // See RFC 2616 § 14.26 If-None-Match
876 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
877 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
878 // Never send 304s in debug mode
879 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
880 // There's another bug in ob_gzhandler (see also the comment at
881 // the top of this function) that causes it to gzip even empty
882 // responses, meaning it's impossible to produce a truly empty
883 // response (because the gzip header is always there). This is
884 // a problem because 304 responses have to be completely empty
885 // per the HTTP spec, and Firefox behaves buggily when they're not.
886 // See also https://bugs.php.net/bug.php?id=51579
887 // To work around this, we tear down all output buffering before
889 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
891 HttpStatus
::header( 304 );
893 $this->sendResponseHeaders( $context, $etag, false );
900 * Send out code for a response from file cache if possible.
902 * @param ResourceFileCache $fileCache Cache object for this request URL
903 * @param ResourceLoaderContext $context Context in which to generate a response
904 * @param string $etag ETag header value
905 * @return bool If this found a cache file and handled the response
907 protected function tryRespondFromFileCache(
908 ResourceFileCache
$fileCache,
909 ResourceLoaderContext
$context,
912 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
913 // Buffer output to catch warnings.
915 // Get the maximum age the cache can be
916 $maxage = is_null( $context->getVersion() )
917 ?
$rlMaxage['unversioned']['server']
918 : $rlMaxage['versioned']['server'];
919 // Minimum timestamp the cache file must have
920 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
922 try { // RL always hits the DB on file cache miss...
923 wfGetDB( DB_REPLICA
);
924 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
925 $good = $fileCache->isCacheGood(); // cache existence check
929 $ts = $fileCache->cacheTimestamp();
930 // Send content type and cache headers
931 $this->sendResponseHeaders( $context, $etag, false );
932 $response = $fileCache->fetchText();
933 // Capture any PHP warnings from the output buffer and append them to the
934 // response in a comment if we're in debug mode.
935 if ( $context->getDebug() ) {
936 $warnings = ob_get_contents();
937 if ( strlen( $warnings ) ) {
938 $response = self
::makeComment( $warnings ) . $response;
941 // Remove the output buffer and output the response
943 echo $response . "\n/* Cached {$ts} */";
944 return true; // cache hit
949 return false; // cache miss
953 * Generate a CSS or JS comment block.
955 * Only use this for public data, not error message details.
957 * @param string $text
960 public static function makeComment( $text ) {
961 $encText = str_replace( '*/', '* /', $text );
962 return "/*\n$encText\n*/\n";
966 * Handle exception display.
968 * @param Exception $e Exception to be shown to the user
969 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
971 public static function formatException( $e ) {
972 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
976 * Handle exception display.
979 * @param Exception $e Exception to be shown to the user
980 * @return string Sanitized text that can be returned to the user
982 protected static function formatExceptionNoComment( $e ) {
983 global $wgShowExceptionDetails;
985 if ( !$wgShowExceptionDetails ) {
986 return MWExceptionHandler
::getPublicLogMessage( $e );
989 return MWExceptionHandler
::getLogMessage( $e ) .
991 MWExceptionHandler
::getRedactedTraceAsString( $e );
995 * Generate code for a response.
997 * Calling this method also populates the `errors` and `headers` members,
998 * later used by respond().
1000 * @param ResourceLoaderContext $context Context in which to generate a response
1001 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1002 * @param string[] $missing List of requested module names that are unregistered (optional)
1003 * @return string Response data
1005 public function makeModuleResponse( ResourceLoaderContext
$context,
1006 array $modules, array $missing = []
1011 if ( $modules === [] && $missing === [] ) {
1013 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1014 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1015 no modules were requested. Max made me put this here. */
1019 $image = $context->getImageObj();
1021 $data = $image->getImageData( $context );
1022 if ( $data === false ) {
1024 $this->errors
[] = 'Image generation failed';
1029 foreach ( $missing as $name ) {
1030 $states[$name] = 'missing';
1033 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1035 foreach ( $modules as $name => $module ) {
1037 $content = $module->getModuleContent( $context );
1038 $implementKey = $name . '@' . $module->getVersionHash( $context );
1041 if ( isset( $content['headers'] ) ) {
1042 $this->extraHeaders
= array_merge( $this->extraHeaders
, $content['headers'] );
1046 switch ( $context->getOnly() ) {
1048 $scripts = $content['scripts'];
1049 if ( is_string( $scripts ) ) {
1050 // Load scripts raw...
1051 $strContent = $scripts;
1052 } elseif ( is_array( $scripts ) ) {
1053 // ...except when $scripts is an array of URLs or an associative array
1054 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1058 $styles = $content['styles'];
1059 // We no longer separate into media, they are all combined now with
1060 // custom media type groups into @media .. {} sections as part of the css string.
1061 // Module returns either an empty array or a numerical array with css strings.
1062 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1065 $scripts = $content['scripts'] ??
'';
1066 if ( is_string( $scripts ) ) {
1067 if ( $name === 'site' ||
$name === 'user' ) {
1068 // Legacy scripts that run in the global scope without a closure.
1069 // mw.loader.implement will use globalEval if scripts is a string.
1070 // Minify manually here, because general response minification is
1071 // not effective due it being a string literal, not a function.
1072 if ( !$context->getDebug() ) {
1073 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1076 $scripts = new XmlJsCode( $scripts );
1079 $strContent = self
::makeLoaderImplementScript(
1082 $content['styles'] ??
[],
1083 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1084 $content['templates'] ??
[]
1089 if ( !$context->getDebug() ) {
1090 $strContent = self
::filter( $filter, $strContent );
1092 // In debug mode, separate each response by a new line.
1093 // For example, between 'mw.loader.implement();' statements.
1094 $strContent = $this->ensureNewline( $strContent );
1097 if ( $context->getOnly() === 'scripts' ) {
1098 // Use a linebreak between module scripts (T162719)
1099 $out .= $this->ensureNewline( $strContent );
1101 $out .= $strContent;
1104 } catch ( Exception
$e ) {
1105 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1107 // Respond to client with error-state instead of module implementation
1108 $states[$name] = 'error';
1109 unset( $modules[$name] );
1113 // Update module states
1114 if ( $context->shouldIncludeScripts() && !$context->getRaw() ) {
1115 if ( $modules && $context->getOnly() === 'scripts' ) {
1116 // Set the state of modules loaded as only scripts to ready as
1117 // they don't have an mw.loader.implement wrapper that sets the state
1118 foreach ( $modules as $name => $module ) {
1119 $states[$name] = 'ready';
1123 // Set the state of modules we didn't respond to with mw.loader.implement
1125 $stateScript = self
::makeLoaderStateScript( $states );
1126 if ( !$context->getDebug() ) {
1127 $stateScript = self
::filter( 'minify-js', $stateScript );
1129 // Use a linebreak between module script and state script (T162719)
1130 $out = $this->ensureNewline( $out ) . $stateScript;
1132 } elseif ( $states ) {
1133 $this->errors
[] = 'Problematic modules: '
1134 . self
::encodeJsonForScript( $states );
1141 * Ensure the string is either empty or ends in a line break
1142 * @param string $str
1145 private function ensureNewline( $str ) {
1146 $end = substr( $str, -1 );
1147 if ( $end === false ||
$end === '' ||
$end === "\n" ) {
1154 * Get names of modules that use a certain message.
1156 * @param string $messageKey
1157 * @return array List of module names
1159 public function getModulesByMessage( $messageKey ) {
1161 foreach ( $this->getModuleNames() as $moduleName ) {
1162 $module = $this->getModule( $moduleName );
1163 if ( in_array( $messageKey, $module->getMessages() ) ) {
1164 $moduleNames[] = $moduleName;
1167 return $moduleNames;
1171 * Return JS code that calls mw.loader.implement with given module properties.
1173 * @param string $name Module name or implement key (format "`[name]@[version]`")
1174 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1175 * list of URLs to JavaScript files, string of JavaScript for `$.globalEval`, or array with
1176 * 'files' and 'main' properties (see ResourceLoaderModule::getScript())
1177 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1178 * to CSS files keyed by media type
1179 * @param mixed $messages List of messages associated with this module. May either be an
1180 * associative array mapping message key to value, or a JSON-encoded message blob containing
1181 * the same data, wrapped in an XmlJsCode object.
1182 * @param array $templates Keys are name of templates and values are the source of
1184 * @throws MWException
1185 * @return string JavaScript code
1187 protected static function makeLoaderImplementScript(
1188 $name, $scripts, $styles, $messages, $templates
1190 if ( $scripts instanceof XmlJsCode
) {
1191 if ( $scripts->value
=== '' ) {
1193 } elseif ( self
::inDebugMode() ) {
1194 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1196 $scripts = new XmlJsCode( 'function($,jQuery,require,module){' . $scripts->value
. '}' );
1198 } elseif ( is_array( $scripts ) && isset( $scripts['files'] ) ) {
1199 $files = $scripts['files'];
1200 foreach ( $files as $path => &$file ) {
1201 // $file is changed (by reference) from a descriptor array to the content of the file
1202 // All of these essentially do $file = $file['content'];, some just have wrapping around it
1203 if ( $file['type'] === 'script' ) {
1204 // Multi-file modules only get two parameters ($ and jQuery are being phased out)
1205 if ( self
::inDebugMode() ) {
1206 $file = new XmlJsCode( "function ( require, module ) {\n{$file['content']}\n}" );
1208 $file = new XmlJsCode( 'function(require,module){' . $file['content'] . '}' );
1211 $file = $file['content'];
1214 $scripts = XmlJsCode
::encodeObject( [
1215 'main' => $scripts['main'],
1216 'files' => XmlJsCode
::encodeObject( $files, self
::inDebugMode() )
1217 ], self
::inDebugMode() );
1218 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1219 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1222 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1223 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1224 // of "{}". Force them to objects.
1232 self
::trimArray( $module );
1234 return Xml
::encodeJsCall( 'mw.loader.implement', $module, self
::inDebugMode() );
1238 * Returns JS code which, when called, will register a given list of messages.
1240 * @param mixed $messages Either an associative array mapping message key to value, or a
1241 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1242 * @return string JavaScript code
1244 public static function makeMessageSetScript( $messages ) {
1245 return 'mw.messages.set('
1246 . self
::encodeJsonForScript( (object)$messages )
1251 * Combines an associative array mapping media type to CSS into a
1252 * single stylesheet with "@media" blocks.
1254 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1257 public static function makeCombinedStyles( array $stylePairs ) {
1259 foreach ( $stylePairs as $media => $styles ) {
1260 // ResourceLoaderFileModule::getStyle can return the styles
1261 // as a string or an array of strings. This is to allow separation in
1263 $styles = (array)$styles;
1264 foreach ( $styles as $style ) {
1265 $style = trim( $style );
1266 // Don't output an empty "@media print { }" block (T42498)
1267 if ( $style !== '' ) {
1268 // Transform the media type based on request params and config
1269 // The way that this relies on $wgRequest to propagate request params is slightly evil
1270 $media = OutputPage
::transformCssMedia( $media );
1272 if ( $media === '' ||
$media == 'all' ) {
1274 } elseif ( is_string( $media ) ) {
1275 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1285 * Wrapper around json_encode that avoids needless escapes,
1286 * and pretty-prints in debug mode.
1290 * @param bool|string|array $data
1291 * @return string JSON
1293 public static function encodeJsonForScript( $data ) {
1294 // Keep output as small as possible by disabling needless escape modes
1295 // that PHP uses by default.
1296 // However, while most module scripts are only served on HTTP responses
1297 // for JavaScript, some modules can also be embedded in the HTML as inline
1298 // scripts. This, and the fact that we sometimes need to export strings
1299 // containing user-generated content and labels that may genuinely contain
1300 // a sequences like "</script>", we need to encode either '/' or '<'.
1301 // By default PHP escapes '/'. Let's escape '<' instead which is less common
1302 // and allows URLs to mostly remain readable.
1303 $jsonFlags = JSON_UNESCAPED_SLASHES |
1304 JSON_UNESCAPED_UNICODE |
1307 if ( self
::inDebugMode() ) {
1308 $jsonFlags |
= JSON_PRETTY_PRINT
;
1310 return json_encode( $data, $jsonFlags );
1314 * Returns a JS call to mw.loader.state, which sets the state of one
1315 * ore more modules to a given value. Has two calling conventions:
1317 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1318 * Set the state of a single module called $name to $state
1320 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1321 * Set the state of modules with the given names to the given states
1323 * @param array|string $states
1324 * @param string|null $state
1325 * @return string JavaScript code
1327 public static function makeLoaderStateScript( $states, $state = null ) {
1328 if ( !is_array( $states ) ) {
1329 $states = [ $states => $state ];
1331 return 'mw.loader.state('
1332 . self
::encodeJsonForScript( $states )
1336 private static function isEmptyObject( stdClass
$obj ) {
1337 foreach ( $obj as $key => $value ) {
1344 * Remove empty values from the end of an array.
1346 * Values considered empty:
1350 * - new XmlJsCode( '{}' )
1351 * - new stdClass() // (object) []
1353 * @param array $array
1355 private static function trimArray( array &$array ) {
1356 $i = count( $array );
1358 if ( $array[$i] === null
1359 ||
$array[$i] === []
1360 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1361 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1363 unset( $array[$i] );
1371 * Returns JS code which calls mw.loader.register with the given
1377 * ResourceLoader::makeLoaderRegisterScript( [
1378 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1379 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1386 * @param array $modules Array of module registration arrays, each containing
1387 * - string: module name
1388 * - string: module version
1389 * - array|null: List of dependencies (optional)
1390 * - string|null: Module group (optional)
1391 * - string|null: Name of foreign module source, or 'local' (optional)
1392 * - string|null: Script body of a skip function (optional)
1393 * @return string JavaScript code
1395 public static function makeLoaderRegisterScript( array $modules ) {
1396 // Optimisation: Transform dependency names into indexes when possible
1397 // to produce smaller output. They are expanded by mw.loader.register on
1398 // the other end using resolveIndexedDependencies().
1400 foreach ( $modules as $i => &$module ) {
1401 // Build module name index
1402 $index[$module[0]] = $i;
1404 foreach ( $modules as &$module ) {
1405 if ( isset( $module[2] ) ) {
1406 foreach ( $module[2] as &$dependency ) {
1407 if ( isset( $index[$dependency] ) ) {
1408 // Replace module name in dependency list with index
1409 $dependency = $index[$dependency];
1415 array_walk( $modules, [ self
::class, 'trimArray' ] );
1417 return 'mw.loader.register('
1418 . self
::encodeJsonForScript( $modules )
1423 * Returns JS code which calls mw.loader.addSource() with the given
1424 * parameters. Has two calling conventions:
1426 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1427 * Register a single source
1429 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1430 * Register sources with the given IDs and properties.
1432 * @param string|array $sources Source ID
1433 * @param string|null $loadUrl load.php url
1434 * @return string JavaScript code
1436 public static function makeLoaderSourcesScript( $sources, $loadUrl = null ) {
1437 if ( !is_array( $sources ) ) {
1438 $sources = [ $sources => $loadUrl ];
1440 return 'mw.loader.addSource('
1441 . self
::encodeJsonForScript( $sources )
1446 * Wraps JavaScript code to run after the startup module.
1448 * @param string $script JavaScript code
1449 * @return string JavaScript code
1451 public static function makeLoaderConditionalScript( $script ) {
1452 // Adds a function to lazy-created RLQ
1453 return '(RLQ=window.RLQ||[]).push(function(){' .
1454 trim( $script ) . '});';
1458 * Wraps JavaScript code to run after a required module.
1461 * @param string|string[] $modules Module name(s)
1462 * @param string $script JavaScript code
1463 * @return string JavaScript code
1465 public static function makeInlineCodeWithModule( $modules, $script ) {
1466 // Adds an array to lazy-created RLQ
1467 return '(RLQ=window.RLQ||[]).push(['
1468 . self
::encodeJsonForScript( $modules ) . ','
1469 . 'function(){' . trim( $script ) . '}'
1474 * Returns an HTML script tag that runs given JS code after startup and base modules.
1476 * The code will be wrapped in a closure, and it will be executed by ResourceLoader's
1477 * startup module if the client has adequate support for MediaWiki JavaScript code.
1479 * @param string $script JavaScript code
1480 * @param string|null $nonce [optional] Content-Security-Policy nonce
1481 * (from OutputPage::getCSPNonce)
1482 * @return string|WrappedString HTML
1484 public static function makeInlineScript( $script, $nonce = null ) {
1485 $js = self
::makeLoaderConditionalScript( $script );
1487 if ( $nonce === null ) {
1488 wfWarn( __METHOD__
. " did not get nonce. Will break CSP" );
1489 } elseif ( $nonce !== false ) {
1490 // If it was false, CSP is disabled, so no nonce attribute.
1491 // Nonce should be only base64 characters, so should be safe,
1492 // but better to be safely escaped than sorry.
1493 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1496 return new WrappedString(
1497 Html
::inlineScript( $js, $nonce ),
1498 "<script$escNonce>(RLQ=window.RLQ||[]).push(function(){",
1504 * Returns JS code which will set the MediaWiki configuration array to
1507 * @param array $configuration List of configuration values keyed by variable name
1508 * @return string JavaScript code
1511 public static function makeConfigSetScript( array $configuration ) {
1512 $js = Xml
::encodeJsCall(
1517 if ( $js === false ) {
1519 'JSON serialization of config data failed. ' .
1520 'This usually means the config data is not valid UTF-8.'
1522 MWExceptionHandler
::logException( $e );
1523 $js = Xml
::encodeJsCall( 'mw.log.error', [ $e->__toString() ] );
1529 * Convert an array of module names to a packed query string.
1531 * For example, `[ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]`
1532 * becomes `'foo.bar,baz|bar.baz,quux'`.
1534 * This process is reversed by ResourceLoader::expandModuleNames().
1535 * See also mw.loader#buildModulesString() which is a port of this, used
1536 * on the client-side.
1538 * @param array $modules List of module names (strings)
1539 * @return string Packed query string
1541 public static function makePackedModulesString( $modules ) {
1542 $moduleMap = []; // [ prefix => [ suffixes ] ]
1543 foreach ( $modules as $module ) {
1544 $pos = strrpos( $module, '.' );
1545 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1546 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1547 $moduleMap[$prefix][] = $suffix;
1551 foreach ( $moduleMap as $prefix => $suffixes ) {
1552 $p = $prefix === '' ?
'' : $prefix . '.';
1553 $arr[] = $p . implode( ',', $suffixes );
1555 return implode( '|', $arr );
1559 * Expand a string of the form `jquery.foo,bar|jquery.ui.baz,quux` to
1560 * an array of module names like `[ 'jquery.foo', 'jquery.bar',
1561 * 'jquery.ui.baz', 'jquery.ui.quux' ]`.
1563 * This process is reversed by ResourceLoader::makePackedModulesString().
1566 * @param string $modules Packed module name list
1567 * @return array Array of module names
1569 public static function expandModuleNames( $modules ) {
1571 $exploded = explode( '|', $modules );
1572 foreach ( $exploded as $group ) {
1573 if ( strpos( $group, ',' ) === false ) {
1574 // This is not a set of modules in foo.bar,baz notation
1575 // but a single module
1578 // This is a set of modules in foo.bar,baz notation
1579 $pos = strrpos( $group, '.' );
1580 if ( $pos === false ) {
1581 // Prefixless modules, i.e. without dots
1582 $retval = array_merge( $retval, explode( ',', $group ) );
1584 // We have a prefix and a bunch of suffixes
1585 $prefix = substr( $group, 0, $pos ); // 'foo'
1586 $suffixes = explode( ',', substr( $group, $pos +
1 ) ); // [ 'bar', 'baz' ]
1587 foreach ( $suffixes as $suffix ) {
1588 $retval[] = "$prefix.$suffix";
1597 * Determine whether debug mode was requested
1598 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1601 public static function inDebugMode() {
1602 if ( self
::$debugMode === null ) {
1603 global $wgRequest, $wgResourceLoaderDebug;
1604 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1605 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1608 return self
::$debugMode;
1612 * Reset static members used for caching.
1614 * Global state and $wgRequest are evil, but we're using it right
1615 * now and sometimes we need to be able to force ResourceLoader to
1616 * re-evaluate the context because it has changed (e.g. in the test suite).
1618 * @internal For use by unit tests
1619 * @codeCoverageIgnore
1621 public static function clearCache() {
1622 self
::$debugMode = null;
1626 * Build a load.php URL
1629 * @param string $source Name of the ResourceLoader source
1630 * @param ResourceLoaderContext $context
1631 * @param array $extraQuery
1632 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1634 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1637 $query = self
::createLoaderQuery( $context, $extraQuery );
1638 $script = $this->getLoadScript( $source );
1640 return wfAppendQuery( $script, $query );
1644 * Helper for createLoaderURL()
1647 * @see makeLoaderQuery
1648 * @param ResourceLoaderContext $context
1649 * @param array $extraQuery
1652 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1653 return self
::makeLoaderQuery(
1654 $context->getModules(),
1655 $context->getLanguage(),
1656 $context->getSkin(),
1657 $context->getUser(),
1658 $context->getVersion(),
1659 $context->getDebug(),
1660 $context->getOnly(),
1661 $context->getRequest()->getBool( 'printable' ),
1662 $context->getRequest()->getBool( 'handheld' ),
1668 * Build a query array (array representation of query string) for load.php. Helper
1669 * function for createLoaderURL().
1671 * @param array $modules
1672 * @param string $lang
1673 * @param string $skin
1674 * @param string|null $user
1675 * @param string|null $version
1676 * @param bool $debug
1677 * @param string|null $only
1678 * @param bool $printable
1679 * @param bool $handheld
1680 * @param array $extraQuery
1683 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1684 $version = null, $debug = false, $only = null, $printable = false,
1685 $handheld = false, $extraQuery = []
1688 'modules' => self
::makePackedModulesString( $modules ),
1690 // Keep urls short by omitting query parameters that
1691 // match the defaults assumed by ResourceLoaderContext.
1692 // Note: This relies on the defaults either being insignificant or forever constant,
1693 // as otherwise cached urls could change in meaning when the defaults change.
1694 if ( $lang !== ResourceLoaderContext
::DEFAULT_LANG
) {
1695 $query['lang'] = $lang;
1697 if ( $skin !== ResourceLoaderContext
::DEFAULT_SKIN
) {
1698 $query['skin'] = $skin;
1700 if ( $debug === true ) {
1701 $query['debug'] = 'true';
1703 if ( $user !== null ) {
1704 $query['user'] = $user;
1706 if ( $version !== null ) {
1707 $query['version'] = $version;
1709 if ( $only !== null ) {
1710 $query['only'] = $only;
1713 $query['printable'] = 1;
1716 $query['handheld'] = 1;
1718 $query +
= $extraQuery;
1720 // Make queries uniform in order
1726 * Check a module name for validity.
1728 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1729 * at most 255 bytes.
1731 * @param string $moduleName Module name to check
1732 * @return bool Whether $moduleName is a valid module name
1734 public static function isValidModuleName( $moduleName ) {
1735 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1739 * Returns LESS compiler set up for use with MediaWiki
1742 * @param array $vars Associative array of variables that should be used
1743 * for compilation. Since 1.32, this method no longer automatically includes
1744 * global LESS vars from ResourceLoader::getLessVars (T191937).
1745 * @throws MWException
1746 * @return Less_Parser
1748 public function getLessCompiler( $vars = [] ) {
1750 // When called from the installer, it is possible that a required PHP extension
1751 // is missing (at least for now; see T49564). If this is the case, throw an
1752 // exception (caught by the installer) to prevent a fatal error later on.
1753 if ( !class_exists( 'Less_Parser' ) ) {
1754 throw new MWException( 'MediaWiki requires the less.php parser' );
1757 $parser = new Less_Parser
;
1758 $parser->ModifyVars( $vars );
1759 $parser->SetImportDirs( [
1760 "$IP/resources/src/mediawiki.less/" => '',
1762 $parser->SetOption( 'relativeUrls', false );
1768 * Get global LESS variables.
1771 * @deprecated since 1.32 Use ResourceLoderModule::getLessVars() instead.
1772 * @return array Map of variable names to string CSS values.
1774 public function getLessVars() {