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 $skin = $context->getSkin();
122 $lang = $context->getLanguage();
124 // Batched version of ResourceLoaderModule::getFileDependencies
125 $vary = "$skin|$lang";
126 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
127 'md_module' => $moduleNames,
132 // Prime in-object cache for file dependencies
133 $modulesWithDeps = [];
134 foreach ( $res as $row ) {
135 $module = $this->getModule( $row->md_module
);
137 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
138 json_decode( $row->md_deps
, true )
140 $modulesWithDeps[] = $row->md_module
;
143 // Register the absence of a dependency row too
144 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
145 $module = $this->getModule( $name );
147 $this->getModule( $name )->setFileDependencies( $context, [] );
151 // Batched version of ResourceLoaderWikiModule::getTitleInfo
152 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $moduleNames );
154 // Prime in-object cache for message blobs for modules with messages
156 foreach ( $moduleNames as $name ) {
157 $module = $this->getModule( $name );
158 if ( $module && $module->getMessages() ) {
159 $modules[$name] = $module;
162 $store = $this->getMessageBlobStore();
163 $blobs = $store->getBlobs( $modules, $lang );
164 foreach ( $blobs as $name => $blob ) {
165 $modules[$name]->setMessageBlob( $blob, $lang );
170 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
172 * Available filters are:
174 * - minify-js \see JavaScriptMinifier::minify
175 * - minify-css \see CSSMin::minify
177 * If $data is empty, only contains whitespace or the filter was unknown,
178 * $data is returned unmodified.
180 * @param string $filter Name of filter to run
181 * @param string $data Text to filter, such as JavaScript or CSS text
182 * @param array $options Keys:
183 * - (bool) cache: Whether to allow caching this data. Default: true.
184 * @return string Filtered data, or a comment containing an error message
186 public static function filter( $filter, $data, array $options = [] ) {
187 if ( strpos( $data, self
::FILTER_NOMIN
) !== false ) {
191 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
192 return self
::applyFilter( $filter, $data );
195 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
196 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
198 $key = $cache->makeGlobalKey(
206 $result = $cache->get( $key );
207 if ( $result === false ) {
208 $stats->increment( "resourceloader_cache.$filter.miss" );
209 $result = self
::applyFilter( $filter, $data );
210 $cache->set( $key, $result, 24 * 3600 );
212 $stats->increment( "resourceloader_cache.$filter.hit" );
214 if ( $result === null ) {
222 private static function applyFilter( $filter, $data ) {
223 $data = trim( $data );
226 $data = ( $filter === 'minify-css' )
227 ? CSSMin
::minify( $data )
228 : JavaScriptMinifier
::minify( $data );
229 } catch ( Exception
$e ) {
230 MWExceptionHandler
::logException( $e );
238 * Register core modules and runs registration hooks.
239 * @param Config|null $config
240 * @param LoggerInterface|null $logger [optional]
242 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
243 $this->logger
= $logger ?
: new NullLogger();
246 wfDeprecated( __METHOD__
. ' without a Config instance', '1.34' );
247 $config = MediaWikiServices
::getInstance()->getMainConfig();
249 $this->config
= $config;
251 // Add 'local' source first
252 $this->addSource( 'local', $config->get( 'LoadScript' ) );
254 // Special module that always exists
255 $this->register( 'startup', [ 'class' => ResourceLoaderStartUpModule
::class ] );
257 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
263 public function getConfig() {
264 return $this->config
;
269 * @param LoggerInterface $logger
271 public function setLogger( LoggerInterface
$logger ) {
272 $this->logger
= $logger;
277 * @return LoggerInterface
279 public function getLogger() {
280 return $this->logger
;
285 * @return MessageBlobStore
287 public function getMessageBlobStore() {
288 return $this->blobStore
;
293 * @param MessageBlobStore $blobStore
295 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
296 $this->blobStore
= $blobStore;
300 * Register a module with the ResourceLoader system.
302 * @param mixed $name Name of module as a string or List of name/object pairs as an array
303 * @param array|null $info Module info array. For backwards compatibility with 1.17alpha,
304 * this may also be a ResourceLoaderModule object. Optional when using
305 * multiple-registration calling style.
306 * @throws MWException If a duplicate module registration is attempted
307 * @throws MWException If a module name contains illegal characters (pipes or commas)
308 * @throws MWException If something other than a ResourceLoaderModule is being registered
310 public function register( $name, $info = null ) {
311 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
313 // Allow multiple modules to be registered in one call
314 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
315 foreach ( $registrations as $name => $info ) {
316 // Warn on duplicate registrations
317 if ( isset( $this->moduleInfos
[$name] ) ) {
318 // A module has already been registered by this name
319 $this->logger
->warning(
320 'ResourceLoader duplicate registration warning. ' .
321 'Another module has already been registered as ' . $name
325 // Check $name for validity
326 if ( !self
::isValidModuleName( $name ) ) {
327 throw new MWException( "ResourceLoader module name '$name' is invalid, "
328 . "see ResourceLoader::isValidModuleName()" );
332 if ( $info instanceof ResourceLoaderModule
) {
333 $this->moduleInfos
[$name] = [ 'object' => $info ];
334 $info->setName( $name );
335 $this->modules
[$name] = $info;
336 } elseif ( is_array( $info ) ) {
337 // New calling convention
338 $this->moduleInfos
[$name] = $info;
340 throw new MWException(
341 'ResourceLoader module info type error for module \'' . $name .
342 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
346 // Last-minute changes
348 // Apply custom skin-defined styles to existing modules.
349 if ( $this->isFileModule( $name ) ) {
350 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
351 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
352 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
356 // If $name is preceded with a '+', the defined style files will be added to 'default'
357 // skinStyles, otherwise 'default' will be ignored as it normally would be.
358 if ( isset( $skinStyles[$name] ) ) {
359 $paths = (array)$skinStyles[$name];
361 } elseif ( isset( $skinStyles['+' . $name] ) ) {
362 $paths = (array)$skinStyles['+' . $name];
363 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
364 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
370 // Add new file paths, remapping them to refer to our directories and not use settings
371 // from the module we're modifying, which come from the base definition.
372 list( $localBasePath, $remoteBasePath ) =
373 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
375 foreach ( $paths as $path ) {
376 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
379 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
386 * @internal For use by ServiceWiring only
388 public function registerTestModules() {
391 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
392 throw new MWException( 'Attempt to register JavaScript test modules '
393 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
394 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
401 // Get test suites from extensions
402 // Avoid PHP 7.1 warning from passing $this by reference
404 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
405 $extRegistry = ExtensionRegistry
::getInstance();
406 // In case of conflict, the deprecated hook has precedence.
407 $testModules['qunit'] +
= $extRegistry->getAttribute( 'QUnitTestModules' );
409 // Add the QUnit testrunner as implicit dependency to extension test suites.
410 foreach ( $testModules['qunit'] as &$module ) {
411 // Shuck any single-module dependency as an array
412 if ( isset( $module['dependencies'] ) && is_string( $module['dependencies'] ) ) {
413 $module['dependencies'] = [ $module['dependencies'] ];
416 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
419 // Get core test suites
420 $testModules['qunit'] =
421 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
423 foreach ( $testModules as $id => $names ) {
424 // Register test modules
425 $this->register( $testModules[$id] );
427 // Keep track of their names so that they can be loaded together
428 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
433 * Add a foreign source of modules.
435 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
437 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
438 * @param string|array|null $loadUrl load.php url (string), or array with loadUrl key for
439 * backwards-compatibility.
440 * @throws MWException
442 public function addSource( $id, $loadUrl = null ) {
443 // Allow multiple sources to be registered in one call
444 if ( is_array( $id ) ) {
445 foreach ( $id as $key => $value ) {
446 $this->addSource( $key, $value );
451 // Disallow duplicates
452 if ( isset( $this->sources
[$id] ) ) {
453 throw new MWException(
454 'ResourceLoader duplicate source addition error. ' .
455 'Another source has already been registered as ' . $id
459 // Pre 1.24 backwards-compatibility
460 if ( is_array( $loadUrl ) ) {
461 if ( !isset( $loadUrl['loadScript'] ) ) {
462 throw new MWException(
463 __METHOD__
. ' was passed an array with no "loadScript" key.'
467 $loadUrl = $loadUrl['loadScript'];
470 $this->sources
[$id] = $loadUrl;
474 * Get a list of module names.
476 * @return array List of module names
478 public function getModuleNames() {
479 return array_keys( $this->moduleInfos
);
483 * Get a list of test module names for one (or all) frameworks.
485 * If the given framework id is unknkown, or if the in-object variable is not an array,
486 * then it will return an empty array.
488 * @param string $framework Get only the test module names for one
489 * particular framework (optional)
492 public function getTestModuleNames( $framework = 'all' ) {
493 /** @todo api siteinfo prop testmodulenames modulenames */
494 if ( $framework == 'all' ) {
495 return $this->testModuleNames
;
496 } elseif ( isset( $this->testModuleNames
[$framework] )
497 && is_array( $this->testModuleNames
[$framework] )
499 return $this->testModuleNames
[$framework];
506 * Check whether a ResourceLoader module is registered
509 * @param string $name
512 public function isModuleRegistered( $name ) {
513 return isset( $this->moduleInfos
[$name] );
517 * Get the ResourceLoaderModule object for a given module name.
519 * If an array of module parameters exists but a ResourceLoaderModule object has not
520 * yet been instantiated, this method will instantiate and cache that object such that
521 * subsequent calls simply return the same object.
523 * @param string $name Module name
524 * @return ResourceLoaderModule|null If module has been registered, return a
525 * ResourceLoaderModule instance. Otherwise, return null.
527 public function getModule( $name ) {
528 if ( !isset( $this->modules
[$name] ) ) {
529 if ( !isset( $this->moduleInfos
[$name] ) ) {
533 // Construct the requested object
534 $info = $this->moduleInfos
[$name];
535 /** @var ResourceLoaderModule $object */
536 if ( isset( $info['object'] ) ) {
537 // Object given in info array
538 $object = $info['object'];
539 } elseif ( isset( $info['factory'] ) ) {
540 $object = call_user_func( $info['factory'], $info );
541 $object->setConfig( $this->getConfig() );
542 $object->setLogger( $this->logger
);
544 $class = $info['class'] ?? ResourceLoaderFileModule
::class;
545 /** @var ResourceLoaderModule $object */
546 $object = new $class( $info );
547 $object->setConfig( $this->getConfig() );
548 $object->setLogger( $this->logger
);
550 $object->setName( $name );
551 $this->modules
[$name] = $object;
554 return $this->modules
[$name];
558 * Whether the module is a ResourceLoaderFileModule (including subclasses).
560 * @param string $name Module name
563 protected function isFileModule( $name ) {
564 if ( !isset( $this->moduleInfos
[$name] ) ) {
567 $info = $this->moduleInfos
[$name];
568 if ( isset( $info['object'] ) ) {
572 // The implied default for 'class' is ResourceLoaderFileModule
573 !isset( $info['class'] ) ||
575 $info['class'] === ResourceLoaderFileModule
::class ||
576 is_subclass_of( $info['class'], ResourceLoaderFileModule
::class )
581 * Get the list of sources.
583 * @return array Like [ id => load.php url, ... ]
585 public function getSources() {
586 return $this->sources
;
590 * Get the URL to the load.php endpoint for the given
591 * ResourceLoader source
594 * @param string $source
595 * @throws MWException On an invalid $source name
598 public function getLoadScript( $source ) {
599 if ( !isset( $this->sources
[$source] ) ) {
600 throw new MWException( "The $source source was never registered in ResourceLoader." );
602 return $this->sources
[$source];
607 * @param string $value
608 * @return string Hash
610 public static function makeHash( $value ) {
611 $hash = hash( 'fnv132', $value );
612 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
616 * Add an error to the 'errors' array and log it.
618 * @private For internal use by ResourceLoader and ResourceLoaderStartUpModule.
620 * @param Exception $e
622 * @param array $context
624 public function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
625 MWExceptionHandler
::logException( $e );
626 $this->logger
->warning(
628 $context +
[ 'exception' => $e ]
630 $this->errors
[] = self
::formatExceptionNoComment( $e );
634 * Helper method to get and combine versions of multiple modules.
637 * @param ResourceLoaderContext $context
638 * @param string[] $moduleNames List of known module names
639 * @return string Hash
641 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
642 if ( !$moduleNames ) {
645 $hashes = array_map( function ( $module ) use ( $context ) {
647 return $this->getModule( $module )->getVersionHash( $context );
648 } catch ( Exception
$e ) {
649 // If modules fail to compute a version, don't fail the request (T152266)
650 // and still compute versions of other modules.
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 * @return string Hash
676 public function makeVersionQuery( ResourceLoaderContext
$context ) {
677 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
678 // version hashes. There is no technical reason for this to be same, and for years the
679 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
680 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
681 // query parameter), then this method must continue to match the JS one.
683 foreach ( $context->getModules() as $name ) {
684 if ( !$this->getModule( $name ) ) {
685 // If a versioned request contains a missing module, the version is a mismatch
686 // as the client considered a module (and version) we don't have.
689 $moduleNames[] = $name;
691 return $this->getCombinedVersion( $context, $moduleNames );
695 * Output a response to a load request, including the content-type header.
697 * @param ResourceLoaderContext $context Context in which a response should be formed
699 public function respond( ResourceLoaderContext
$context ) {
700 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
701 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
702 // is used: ob_clean() will clear the GZIP header in that case and it won't come
703 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
704 // the whole thing in our own output buffer to be sure the active buffer
705 // doesn't use ob_gzhandler.
706 // See https://bugs.php.net/bug.php?id=36514
709 $this->measureResponseTime( RequestContext
::getMain()->getTiming() );
711 // Find out which modules are missing and instantiate the others
714 foreach ( $context->getModules() as $name ) {
715 $module = $this->getModule( $name );
717 // Do not allow private modules to be loaded from the web.
718 // This is a security issue, see T36907.
719 if ( $module->getGroup() === 'private' ) {
720 $this->logger
->debug( "Request for private module '$name' denied" );
721 $this->errors
[] = "Cannot show private module \"$name\"";
724 $modules[$name] = $module;
731 // Preload for getCombinedVersion() and for batch makeModuleResponse()
732 $this->preloadModuleInfo( array_keys( $modules ), $context );
733 } catch ( Exception
$e ) {
734 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
737 // Combine versions to propagate cache invalidation
740 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
741 } catch ( Exception
$e ) {
742 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
745 // See RFC 2616 § 3.11 Entity Tags
746 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
747 $etag = 'W/"' . $versionHash . '"';
749 // Try the client-side cache first
750 if ( $this->tryRespondNotModified( $context, $etag ) ) {
751 return; // output handled (buffers cleared)
754 // Use file cache if enabled and available...
755 if ( $this->config
->get( 'UseFileCache' ) ) {
756 $fileCache = ResourceFileCache
::newFromContext( $context );
757 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
758 return; // output handled
762 // Generate a response
763 $response = $this->makeModuleResponse( $context, $modules, $missing );
765 // Capture any PHP warnings from the output buffer and append them to the
766 // error list if we're in debug mode.
767 if ( $context->getDebug() ) {
768 $warnings = ob_get_contents();
769 if ( strlen( $warnings ) ) {
770 $this->errors
[] = $warnings;
774 // Save response to file cache unless there are errors
775 if ( isset( $fileCache ) && !$this->errors
&& $missing === [] ) {
776 // Cache single modules and images...and other requests if there are enough hits
777 if ( ResourceFileCache
::useFileCache( $context ) ) {
778 if ( $fileCache->isCacheWorthy() ) {
779 $fileCache->saveText( $response );
781 $fileCache->incrMissesRecent( $context->getRequest() );
786 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
, $this->extraHeaders
);
788 // Remove the output buffer and output the response
791 if ( $context->getImageObj() && $this->errors
) {
792 // We can't show both the error messages and the response when it's an image.
793 $response = implode( "\n\n", $this->errors
);
794 } elseif ( $this->errors
) {
795 $errorText = implode( "\n\n", $this->errors
);
796 $errorResponse = self
::makeComment( $errorText );
797 if ( $context->shouldIncludeScripts() ) {
798 $errorResponse .= 'if (window.console && console.error) {'
799 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
803 // Prepend error info to the response
804 $response = $errorResponse . $response;
811 protected function measureResponseTime( Timing
$timing ) {
812 DeferredUpdates
::addCallableUpdate( function () use ( $timing ) {
813 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
814 if ( $measure !== false ) {
815 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
816 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
822 * Send main response headers to the client.
824 * Deals with Content-Type, CORS (for stylesheets), and caching.
826 * @param ResourceLoaderContext $context
827 * @param string $etag ETag header value
828 * @param bool $errors Whether there are errors in the response
829 * @param string[] $extra Array of extra HTTP response headers
832 protected function sendResponseHeaders(
833 ResourceLoaderContext
$context, $etag, $errors, array $extra = []
835 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
836 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
837 // Use a short cache expiry so that updates propagate to clients quickly, if:
838 // - No version specified (shared resources, e.g. stylesheets)
839 // - There were errors (recover quickly)
840 // - Version mismatch (T117587, T47877)
841 if ( is_null( $context->getVersion() )
843 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
845 $maxage = $rlMaxage['unversioned']['client'];
846 $smaxage = $rlMaxage['unversioned']['server'];
847 // If a version was specified we can use a longer expiry time since changing
848 // version numbers causes cache misses
850 $maxage = $rlMaxage['versioned']['client'];
851 $smaxage = $rlMaxage['versioned']['server'];
853 if ( $context->getImageObj() ) {
854 // Output different headers if we're outputting textual errors.
856 header( 'Content-Type: text/plain; charset=utf-8' );
858 $context->getImageObj()->sendResponseHeaders( $context );
860 } elseif ( $context->getOnly() === 'styles' ) {
861 header( 'Content-Type: text/css; charset=utf-8' );
862 header( 'Access-Control-Allow-Origin: *' );
864 header( 'Content-Type: text/javascript; charset=utf-8' );
866 // See RFC 2616 § 14.19 ETag
867 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
868 header( 'ETag: ' . $etag );
869 if ( $context->getDebug() ) {
870 // Do not cache debug responses
871 header( 'Cache-Control: private, no-cache, must-revalidate' );
872 header( 'Pragma: no-cache' );
874 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
875 $exp = min( $maxage, $smaxage );
876 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
878 foreach ( $extra as $header ) {
884 * Respond with HTTP 304 Not Modified if appropiate.
886 * If there's an If-None-Match header, respond with a 304 appropriately
887 * and clear out the output buffer. If the client cache is too old then do nothing.
889 * @param ResourceLoaderContext $context
890 * @param string $etag ETag header value
891 * @return bool True if HTTP 304 was sent and output handled
893 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
894 // See RFC 2616 § 14.26 If-None-Match
895 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
896 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
897 // Never send 304s in debug mode
898 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
899 // There's another bug in ob_gzhandler (see also the comment at
900 // the top of this function) that causes it to gzip even empty
901 // responses, meaning it's impossible to produce a truly empty
902 // response (because the gzip header is always there). This is
903 // a problem because 304 responses have to be completely empty
904 // per the HTTP spec, and Firefox behaves buggily when they're not.
905 // See also https://bugs.php.net/bug.php?id=51579
906 // To work around this, we tear down all output buffering before
908 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
910 HttpStatus
::header( 304 );
912 $this->sendResponseHeaders( $context, $etag, false );
919 * Send out code for a response from file cache if possible.
921 * @param ResourceFileCache $fileCache Cache object for this request URL
922 * @param ResourceLoaderContext $context Context in which to generate a response
923 * @param string $etag ETag header value
924 * @return bool If this found a cache file and handled the response
926 protected function tryRespondFromFileCache(
927 ResourceFileCache
$fileCache,
928 ResourceLoaderContext
$context,
931 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
932 // Buffer output to catch warnings.
934 // Get the maximum age the cache can be
935 $maxage = is_null( $context->getVersion() )
936 ?
$rlMaxage['unversioned']['server']
937 : $rlMaxage['versioned']['server'];
938 // Minimum timestamp the cache file must have
939 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
941 try { // RL always hits the DB on file cache miss...
942 wfGetDB( DB_REPLICA
);
943 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
944 $good = $fileCache->isCacheGood(); // cache existence check
948 $ts = $fileCache->cacheTimestamp();
949 // Send content type and cache headers
950 $this->sendResponseHeaders( $context, $etag, false );
951 $response = $fileCache->fetchText();
952 // Capture any PHP warnings from the output buffer and append them to the
953 // response in a comment if we're in debug mode.
954 if ( $context->getDebug() ) {
955 $warnings = ob_get_contents();
956 if ( strlen( $warnings ) ) {
957 $response = self
::makeComment( $warnings ) . $response;
960 // Remove the output buffer and output the response
962 echo $response . "\n/* Cached {$ts} */";
963 return true; // cache hit
968 return false; // cache miss
972 * Generate a CSS or JS comment block.
974 * Only use this for public data, not error message details.
976 * @param string $text
979 public static function makeComment( $text ) {
980 $encText = str_replace( '*/', '* /', $text );
981 return "/*\n$encText\n*/\n";
985 * Handle exception display.
987 * @param Exception $e Exception to be shown to the user
988 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
990 public static function formatException( $e ) {
991 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
995 * Handle exception display.
998 * @param Exception $e Exception to be shown to the user
999 * @return string Sanitized text that can be returned to the user
1001 protected static function formatExceptionNoComment( $e ) {
1002 global $wgShowExceptionDetails;
1004 if ( !$wgShowExceptionDetails ) {
1005 return MWExceptionHandler
::getPublicLogMessage( $e );
1008 return MWExceptionHandler
::getLogMessage( $e ) .
1010 MWExceptionHandler
::getRedactedTraceAsString( $e );
1014 * Generate code for a response.
1016 * Calling this method also populates the `errors` and `headers` members,
1017 * later used by respond().
1019 * @param ResourceLoaderContext $context Context in which to generate a response
1020 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1021 * @param string[] $missing List of requested module names that are unregistered (optional)
1022 * @return string Response data
1024 public function makeModuleResponse( ResourceLoaderContext
$context,
1025 array $modules, array $missing = []
1030 if ( $modules === [] && $missing === [] ) {
1032 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1033 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1034 no modules were requested. Max made me put this here. */
1038 $image = $context->getImageObj();
1040 $data = $image->getImageData( $context );
1041 if ( $data === false ) {
1043 $this->errors
[] = 'Image generation failed';
1048 foreach ( $missing as $name ) {
1049 $states[$name] = 'missing';
1055 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1057 foreach ( $modules as $name => $module ) {
1059 $content = $module->getModuleContent( $context );
1060 $implementKey = $name . '@' . $module->getVersionHash( $context );
1063 if ( isset( $content['headers'] ) ) {
1064 $this->extraHeaders
= array_merge( $this->extraHeaders
, $content['headers'] );
1068 switch ( $context->getOnly() ) {
1070 $scripts = $content['scripts'];
1071 if ( is_string( $scripts ) ) {
1072 // Load scripts raw...
1073 $strContent = $scripts;
1074 } elseif ( is_array( $scripts ) ) {
1075 // ...except when $scripts is an array of URLs or an associative array
1076 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1080 $styles = $content['styles'];
1081 // We no longer separate into media, they are all combined now with
1082 // custom media type groups into @media .. {} sections as part of the css string.
1083 // Module returns either an empty array or a numerical array with css strings.
1084 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1087 $scripts = $content['scripts'] ??
'';
1088 if ( is_string( $scripts ) ) {
1089 if ( $name === 'site' ||
$name === 'user' ) {
1090 // Legacy scripts that run in the global scope without a closure.
1091 // mw.loader.implement will use globalEval if scripts is a string.
1092 // Minify manually here, because general response minification is
1093 // not effective due it being a string literal, not a function.
1094 if ( !$context->getDebug() ) {
1095 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1098 $scripts = new XmlJsCode( $scripts );
1101 $strContent = self
::makeLoaderImplementScript(
1104 $content['styles'] ??
[],
1105 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1106 $content['templates'] ??
[]
1111 if ( !$context->getDebug() ) {
1112 $strContent = self
::filter( $filter, $strContent );
1114 // In debug mode, separate each response by a new line.
1115 // For example, between 'mw.loader.implement();' statements.
1116 $strContent = $this->ensureNewline( $strContent );
1119 if ( $context->getOnly() === 'scripts' ) {
1120 // Use a linebreak between module scripts (T162719)
1121 $out .= $this->ensureNewline( $strContent );
1123 $out .= $strContent;
1126 } catch ( Exception
$e ) {
1127 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1129 // Respond to client with error-state instead of module implementation
1130 $states[$name] = 'error';
1131 unset( $modules[$name] );
1133 $isRaw |
= $module->isRaw();
1136 // Update module states
1137 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1138 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1139 // Set the state of modules loaded as only scripts to ready as
1140 // they don't have an mw.loader.implement wrapper that sets the state
1141 foreach ( $modules as $name => $module ) {
1142 $states[$name] = 'ready';
1146 // Set the state of modules we didn't respond to with mw.loader.implement
1147 if ( count( $states ) ) {
1148 $stateScript = self
::makeLoaderStateScript( $states );
1149 if ( !$context->getDebug() ) {
1150 $stateScript = self
::filter( 'minify-js', $stateScript );
1152 // Use a linebreak between module script and state script (T162719)
1153 $out = $this->ensureNewline( $out ) . $stateScript;
1155 } elseif ( $states ) {
1156 $this->errors
[] = 'Problematic modules: '
1157 . self
::encodeJsonForScript( $states );
1164 * Ensure the string is either empty or ends in a line break
1165 * @param string $str
1168 private function ensureNewline( $str ) {
1169 $end = substr( $str, -1 );
1170 if ( $end === false ||
$end === '' ||
$end === "\n" ) {
1177 * Get names of modules that use a certain message.
1179 * @param string $messageKey
1180 * @return array List of module names
1182 public function getModulesByMessage( $messageKey ) {
1184 foreach ( $this->getModuleNames() as $moduleName ) {
1185 $module = $this->getModule( $moduleName );
1186 if ( in_array( $messageKey, $module->getMessages() ) ) {
1187 $moduleNames[] = $moduleName;
1190 return $moduleNames;
1194 * Return JS code that calls mw.loader.implement with given module properties.
1196 * @param string $name Module name or implement key (format "`[name]@[version]`")
1197 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1198 * list of URLs to JavaScript files, string of JavaScript for `$.globalEval`, or array with
1199 * 'files' and 'main' properties (see ResourceLoaderModule::getScript())
1200 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1201 * to CSS files keyed by media type
1202 * @param mixed $messages List of messages associated with this module. May either be an
1203 * associative array mapping message key to value, or a JSON-encoded message blob containing
1204 * the same data, wrapped in an XmlJsCode object.
1205 * @param array $templates Keys are name of templates and values are the source of
1207 * @throws MWException
1208 * @return string JavaScript code
1210 protected static function makeLoaderImplementScript(
1211 $name, $scripts, $styles, $messages, $templates
1213 if ( $scripts instanceof XmlJsCode
) {
1214 if ( $scripts->value
=== '' ) {
1216 } elseif ( self
::inDebugMode() ) {
1217 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1219 $scripts = new XmlJsCode( 'function($,jQuery,require,module){' . $scripts->value
. '}' );
1221 } elseif ( is_array( $scripts ) && isset( $scripts['files'] ) ) {
1222 $files = $scripts['files'];
1223 foreach ( $files as $path => &$file ) {
1224 // $file is changed (by reference) from a descriptor array to the content of the file
1225 // All of these essentially do $file = $file['content'];, some just have wrapping around it
1226 if ( $file['type'] === 'script' ) {
1227 // Multi-file modules only get two parameters ($ and jQuery are being phased out)
1228 if ( self
::inDebugMode() ) {
1229 $file = new XmlJsCode( "function ( require, module ) {\n{$file['content']}\n}" );
1231 $file = new XmlJsCode( 'function(require,module){' . $file['content'] . '}' );
1234 $file = $file['content'];
1237 $scripts = XmlJsCode
::encodeObject( [
1238 'main' => $scripts['main'],
1239 'files' => XmlJsCode
::encodeObject( $files, self
::inDebugMode() )
1240 ], self
::inDebugMode() );
1241 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1242 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1245 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1246 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1247 // of "{}". Force them to objects.
1255 self
::trimArray( $module );
1257 return Xml
::encodeJsCall( 'mw.loader.implement', $module, self
::inDebugMode() );
1261 * Returns JS code which, when called, will register a given list of messages.
1263 * @param mixed $messages Either an associative array mapping message key to value, or a
1264 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1265 * @return string JavaScript code
1267 public static function makeMessageSetScript( $messages ) {
1268 return Xml
::encodeJsCall(
1270 [ (object)$messages ],
1276 * Combines an associative array mapping media type to CSS into a
1277 * single stylesheet with "@media" blocks.
1279 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1282 public static function makeCombinedStyles( array $stylePairs ) {
1284 foreach ( $stylePairs as $media => $styles ) {
1285 // ResourceLoaderFileModule::getStyle can return the styles
1286 // as a string or an array of strings. This is to allow separation in
1288 $styles = (array)$styles;
1289 foreach ( $styles as $style ) {
1290 $style = trim( $style );
1291 // Don't output an empty "@media print { }" block (T42498)
1292 if ( $style !== '' ) {
1293 // Transform the media type based on request params and config
1294 // The way that this relies on $wgRequest to propagate request params is slightly evil
1295 $media = OutputPage
::transformCssMedia( $media );
1297 if ( $media === '' ||
$media == 'all' ) {
1299 } elseif ( is_string( $media ) ) {
1300 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1310 * Wrapper around json_encode that avoids needless escapes,
1311 * and pretty-prints in debug mode.
1315 * @param bool|string|array $data
1316 * @return string JSON
1318 public static function encodeJsonForScript( $data ) {
1319 // Keep output as small as possible by disabling needless escape modes
1320 // that PHP uses by default.
1321 // However, while most module scripts are only served on HTTP responses
1322 // for JavaScript, some modules can also be embedded in the HTML as inline
1323 // scripts. This, and the fact that we sometimes need to export strings
1324 // containing user-generated content and labels that may genuinely contain
1325 // a sequences like "</script>", we need to encode either '/' or '<'.
1326 // By default PHP escapes '/'. Let's escape '<' instead which is less common
1327 // and allows URLs to mostly remain readable.
1328 $jsonFlags = JSON_UNESCAPED_SLASHES |
1329 JSON_UNESCAPED_UNICODE |
1332 if ( self
::inDebugMode() ) {
1333 $jsonFlags |
= JSON_PRETTY_PRINT
;
1335 return json_encode( $data, $jsonFlags );
1339 * Returns a JS call to mw.loader.state, which sets the state of one
1340 * ore more modules to a given value. Has two calling conventions:
1342 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1343 * Set the state of a single module called $name to $state
1345 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1346 * Set the state of modules with the given names to the given states
1348 * @param array|string $states
1349 * @param string|null $state
1350 * @return string JavaScript code
1352 public static function makeLoaderStateScript( $states, $state = null ) {
1353 if ( !is_array( $states ) ) {
1354 $states = [ $states => $state ];
1356 return Xml
::encodeJsCall(
1363 private static function isEmptyObject( stdClass
$obj ) {
1364 foreach ( $obj as $key => $value ) {
1371 * Remove empty values from the end of an array.
1373 * Values considered empty:
1377 * - new XmlJsCode( '{}' )
1378 * - new stdClass() // (object) []
1380 * @param array $array
1382 private static function trimArray( array &$array ) {
1383 $i = count( $array );
1385 if ( $array[$i] === null
1386 ||
$array[$i] === []
1387 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1388 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1390 unset( $array[$i] );
1398 * Returns JS code which calls mw.loader.register with the given
1404 * ResourceLoader::makeLoaderRegisterScript( [
1405 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1406 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1413 * @param array $modules Array of module registration arrays, each containing
1414 * - string: module name
1415 * - string: module version
1416 * - array|null: List of dependencies (optional)
1417 * - string|null: Module group (optional)
1418 * - string|null: Name of foreign module source, or 'local' (optional)
1419 * - string|null: Script body of a skip function (optional)
1420 * @return string JavaScript code
1422 public static function makeLoaderRegisterScript( array $modules ) {
1423 // Optimisation: Transform dependency names into indexes when possible
1424 // to produce smaller output. They are expanded by mw.loader.register on
1425 // the other end using resolveIndexedDependencies().
1427 foreach ( $modules as $i => &$module ) {
1428 // Build module name index
1429 $index[$module[0]] = $i;
1431 foreach ( $modules as &$module ) {
1432 if ( isset( $module[2] ) ) {
1433 foreach ( $module[2] as &$dependency ) {
1434 if ( isset( $index[$dependency] ) ) {
1435 // Replace module name in dependency list with index
1436 $dependency = $index[$dependency];
1442 array_walk( $modules, [ self
::class, 'trimArray' ] );
1444 return Xml
::encodeJsCall(
1445 'mw.loader.register',
1452 * Returns JS code which calls mw.loader.addSource() with the given
1453 * parameters. Has two calling conventions:
1455 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1456 * Register a single source
1458 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1459 * Register sources with the given IDs and properties.
1461 * @param string|array $sources Source ID
1462 * @param string|null $loadUrl load.php url
1463 * @return string JavaScript code
1465 public static function makeLoaderSourcesScript( $sources, $loadUrl = null ) {
1466 if ( !is_array( $sources ) ) {
1467 $sources = [ $sources => $loadUrl ];
1469 return Xml
::encodeJsCall(
1470 'mw.loader.addSource',
1477 * Wraps JavaScript code to run after the startup module.
1479 * @param string $script JavaScript code
1480 * @return string JavaScript code
1482 public static function makeLoaderConditionalScript( $script ) {
1483 // Adds a function to lazy-created RLQ
1484 return '(RLQ=window.RLQ||[]).push(function(){' .
1485 trim( $script ) . '});';
1489 * Wraps JavaScript code to run after a required module.
1492 * @param string|string[] $modules Module name(s)
1493 * @param string $script JavaScript code
1494 * @return string JavaScript code
1496 public static function makeInlineCodeWithModule( $modules, $script ) {
1497 // Adds an array to lazy-created RLQ
1498 return '(RLQ=window.RLQ||[]).push(['
1499 . self
::encodeJsonForScript( $modules ) . ','
1500 . 'function(){' . trim( $script ) . '}'
1505 * Returns an HTML script tag that runs given JS code after startup and base modules.
1507 * The code will be wrapped in a closure, and it will be executed by ResourceLoader's
1508 * startup module if the client has adequate support for MediaWiki JavaScript code.
1510 * @param string $script JavaScript code
1511 * @param string|null $nonce [optional] Content-Security-Policy nonce
1512 * (from OutputPage::getCSPNonce)
1513 * @return string|WrappedString HTML
1515 public static function makeInlineScript( $script, $nonce = null ) {
1516 $js = self
::makeLoaderConditionalScript( $script );
1518 if ( $nonce === null ) {
1519 wfWarn( __METHOD__
. " did not get nonce. Will break CSP" );
1520 } elseif ( $nonce !== false ) {
1521 // If it was false, CSP is disabled, so no nonce attribute.
1522 // Nonce should be only base64 characters, so should be safe,
1523 // but better to be safely escaped than sorry.
1524 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1527 return new WrappedString(
1528 Html
::inlineScript( $js, $nonce ),
1529 "<script$escNonce>(RLQ=window.RLQ||[]).push(function(){",
1535 * Returns JS code which will set the MediaWiki configuration array to
1538 * @param array $configuration List of configuration values keyed by variable name
1539 * @return string JavaScript code
1542 public static function makeConfigSetScript( array $configuration ) {
1543 $js = Xml
::encodeJsCall(
1548 if ( $js === false ) {
1550 'JSON serialization of config data failed. ' .
1551 'This usually means the config data is not valid UTF-8.'
1553 MWExceptionHandler
::logException( $e );
1554 $js = Xml
::encodeJsCall( 'mw.log.error', [ $e->__toString() ] );
1560 * Convert an array of module names to a packed query string.
1562 * For example, `[ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]`
1563 * becomes `'foo.bar,baz|bar.baz,quux'`.
1565 * This process is reversed by ResourceLoader::expandModuleNames().
1566 * See also mw.loader#buildModulesString() which is a port of this, used
1567 * on the client-side.
1569 * @param array $modules List of module names (strings)
1570 * @return string Packed query string
1572 public static function makePackedModulesString( $modules ) {
1573 $moduleMap = []; // [ prefix => [ suffixes ] ]
1574 foreach ( $modules as $module ) {
1575 $pos = strrpos( $module, '.' );
1576 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1577 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1578 $moduleMap[$prefix][] = $suffix;
1582 foreach ( $moduleMap as $prefix => $suffixes ) {
1583 $p = $prefix === '' ?
'' : $prefix . '.';
1584 $arr[] = $p . implode( ',', $suffixes );
1586 return implode( '|', $arr );
1590 * Expand a string of the form `jquery.foo,bar|jquery.ui.baz,quux` to
1591 * an array of module names like `[ 'jquery.foo', 'jquery.bar',
1592 * 'jquery.ui.baz', 'jquery.ui.quux' ]`.
1594 * This process is reversed by ResourceLoader::makePackedModulesString().
1597 * @param string $modules Packed module name list
1598 * @return array Array of module names
1600 public static function expandModuleNames( $modules ) {
1602 $exploded = explode( '|', $modules );
1603 foreach ( $exploded as $group ) {
1604 if ( strpos( $group, ',' ) === false ) {
1605 // This is not a set of modules in foo.bar,baz notation
1606 // but a single module
1609 // This is a set of modules in foo.bar,baz notation
1610 $pos = strrpos( $group, '.' );
1611 if ( $pos === false ) {
1612 // Prefixless modules, i.e. without dots
1613 $retval = array_merge( $retval, explode( ',', $group ) );
1615 // We have a prefix and a bunch of suffixes
1616 $prefix = substr( $group, 0, $pos ); // 'foo'
1617 $suffixes = explode( ',', substr( $group, $pos +
1 ) ); // [ 'bar', 'baz' ]
1618 foreach ( $suffixes as $suffix ) {
1619 $retval[] = "$prefix.$suffix";
1628 * Determine whether debug mode was requested
1629 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1632 public static function inDebugMode() {
1633 if ( self
::$debugMode === null ) {
1634 global $wgRequest, $wgResourceLoaderDebug;
1635 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1636 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1639 return self
::$debugMode;
1643 * Reset static members used for caching.
1645 * Global state and $wgRequest are evil, but we're using it right
1646 * now and sometimes we need to be able to force ResourceLoader to
1647 * re-evaluate the context because it has changed (e.g. in the test suite).
1649 * @internal For use by unit tests
1650 * @codeCoverageIgnore
1652 public static function clearCache() {
1653 self
::$debugMode = null;
1657 * Build a load.php URL
1660 * @param string $source Name of the ResourceLoader source
1661 * @param ResourceLoaderContext $context
1662 * @param array $extraQuery
1663 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1665 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1668 $query = self
::createLoaderQuery( $context, $extraQuery );
1669 $script = $this->getLoadScript( $source );
1671 return wfAppendQuery( $script, $query );
1675 * Helper for createLoaderURL()
1678 * @see makeLoaderQuery
1679 * @param ResourceLoaderContext $context
1680 * @param array $extraQuery
1683 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1684 return self
::makeLoaderQuery(
1685 $context->getModules(),
1686 $context->getLanguage(),
1687 $context->getSkin(),
1688 $context->getUser(),
1689 $context->getVersion(),
1690 $context->getDebug(),
1691 $context->getOnly(),
1692 $context->getRequest()->getBool( 'printable' ),
1693 $context->getRequest()->getBool( 'handheld' ),
1699 * Build a query array (array representation of query string) for load.php. Helper
1700 * function for createLoaderURL().
1702 * @param array $modules
1703 * @param string $lang
1704 * @param string $skin
1705 * @param string|null $user
1706 * @param string|null $version
1707 * @param bool $debug
1708 * @param string|null $only
1709 * @param bool $printable
1710 * @param bool $handheld
1711 * @param array $extraQuery
1715 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1716 $version = null, $debug = false, $only = null, $printable = false,
1717 $handheld = false, $extraQuery = []
1720 'modules' => self
::makePackedModulesString( $modules ),
1724 if ( $debug === true ) {
1725 $query['debug'] = 'true';
1727 if ( $user !== null ) {
1728 $query['user'] = $user;
1730 if ( $version !== null ) {
1731 $query['version'] = $version;
1733 if ( $only !== null ) {
1734 $query['only'] = $only;
1737 $query['printable'] = 1;
1740 $query['handheld'] = 1;
1742 $query +
= $extraQuery;
1744 // Make queries uniform in order
1750 * Check a module name for validity.
1752 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1753 * at most 255 bytes.
1755 * @param string $moduleName Module name to check
1756 * @return bool Whether $moduleName is a valid module name
1758 public static function isValidModuleName( $moduleName ) {
1759 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1763 * Returns LESS compiler set up for use with MediaWiki
1766 * @param array $vars Associative array of variables that should be used
1767 * for compilation. Since 1.32, this method no longer automatically includes
1768 * global LESS vars from ResourceLoader::getLessVars (T191937).
1769 * @throws MWException
1770 * @return Less_Parser
1772 public function getLessCompiler( $vars = [] ) {
1774 // When called from the installer, it is possible that a required PHP extension
1775 // is missing (at least for now; see T49564). If this is the case, throw an
1776 // exception (caught by the installer) to prevent a fatal error later on.
1777 if ( !class_exists( 'Less_Parser' ) ) {
1778 throw new MWException( 'MediaWiki requires the less.php parser' );
1781 $parser = new Less_Parser
;
1782 $parser->ModifyVars( $vars );
1783 $parser->SetImportDirs( [
1784 "$IP/resources/src/mediawiki.less/" => '',
1786 $parser->SetOption( 'relativeUrls', false );
1792 * Get global LESS variables.
1795 * @deprecated since 1.32 Use ResourceLoderModule::getLessVars() instead.
1796 * @return array Map of variable names to string CSS values.
1798 public function getLessVars() {