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 protected static $filterCacheVersion = 7;
43 protected static $debugMode = null;
46 private $lessVars = null;
49 * Module name/ResourceLoaderModule object pairs
52 protected $modules = [];
55 * Associative array mapping module name to info associative array
58 protected $moduleInfos = [];
60 /** @var Config $config */
64 * Associative array mapping framework ids to a list of names of test suite modules
65 * like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... ], ... ]
68 protected $testModuleNames = [];
71 * E.g. [ 'source-id' => 'http://.../load.php' ]
74 protected $sources = [];
77 * Errors accumulated during current respond() call.
80 protected $errors = [];
83 * List of extra HTTP response headers provided by loaded modules.
85 * Populated by makeModuleResponse().
89 protected $extraHeaders = [];
92 * @var MessageBlobStore
97 * @var LoggerInterface
101 /** @var string JavaScript / CSS pragma to disable minification. **/
102 const FILTER_NOMIN
= '/*@nomin*/';
105 * Load information stored in the database about modules.
107 * This method grabs modules dependencies from the database and updates modules
110 * This is not inside the module code because it is much faster to
111 * request all of the information at once than it is to have each module
112 * requests its own information. This sacrifice of modularity yields a substantial
113 * performance improvement.
115 * @param array $moduleNames List of module names to preload information for
116 * @param ResourceLoaderContext $context Context to load the information within
118 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext
$context ) {
119 if ( !$moduleNames ) {
120 // Or else Database*::select() will explode, plus it's cheaper!
123 $dbr = wfGetDB( DB_REPLICA
);
124 $skin = $context->getSkin();
125 $lang = $context->getLanguage();
127 // Batched version of ResourceLoaderModule::getFileDependencies
128 $vary = "$skin|$lang";
129 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
130 'md_module' => $moduleNames,
135 // Prime in-object cache for file dependencies
136 $modulesWithDeps = [];
137 foreach ( $res as $row ) {
138 $module = $this->getModule( $row->md_module
);
140 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
141 FormatJson
::decode( $row->md_deps
, true )
143 $modulesWithDeps[] = $row->md_module
;
146 // Register the absence of a dependency row too
147 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
148 $module = $this->getModule( $name );
150 $this->getModule( $name )->setFileDependencies( $context, [] );
154 // Batched version of ResourceLoaderWikiModule::getTitleInfo
155 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $moduleNames );
157 // Prime in-object cache for message blobs for modules with messages
159 foreach ( $moduleNames as $name ) {
160 $module = $this->getModule( $name );
161 if ( $module && $module->getMessages() ) {
162 $modules[$name] = $module;
165 $store = $this->getMessageBlobStore();
166 $blobs = $store->getBlobs( $modules, $lang );
167 foreach ( $blobs as $name => $blob ) {
168 $modules[$name]->setMessageBlob( $blob, $lang );
173 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
175 * Available filters are:
177 * - minify-js \see JavaScriptMinifier::minify
178 * - minify-css \see CSSMin::minify
180 * If $data is empty, only contains whitespace or the filter was unknown,
181 * $data is returned unmodified.
183 * @param string $filter Name of filter to run
184 * @param string $data Text to filter, such as JavaScript or CSS text
185 * @param array $options Keys:
186 * - (bool) cache: Whether to allow caching this data. Default: true.
187 * @return string Filtered data, or a comment containing an error message
189 public static function filter( $filter, $data, array $options = [] ) {
190 if ( strpos( $data, self
::FILTER_NOMIN
) !== false ) {
194 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
195 return self
::applyFilter( $filter, $data );
198 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
199 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
201 $key = $cache->makeGlobalKey(
205 self
::$filterCacheVersion, md5( $data )
208 $result = $cache->get( $key );
209 if ( $result === false ) {
210 $stats->increment( "resourceloader_cache.$filter.miss" );
211 $result = self
::applyFilter( $filter, $data );
212 $cache->set( $key, $result, 24 * 3600 );
214 $stats->increment( "resourceloader_cache.$filter.hit" );
216 if ( $result === null ) {
224 private static function applyFilter( $filter, $data ) {
225 $data = trim( $data );
228 $data = ( $filter === 'minify-css' )
229 ? CSSMin
::minify( $data )
230 : JavaScriptMinifier
::minify( $data );
231 } catch ( Exception
$e ) {
232 MWExceptionHandler
::logException( $e );
240 * Register core modules and runs registration hooks.
241 * @param Config|null $config [optional]
242 * @param LoggerInterface|null $logger [optional]
244 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
247 $this->logger
= $logger ?
: new NullLogger();
250 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
251 $config = MediaWikiServices
::getInstance()->getMainConfig();
253 $this->config
= $config;
255 // Add 'local' source first
256 $this->addSource( 'local', $config->get( 'LoadScript' ) );
259 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
261 // Register core modules
262 $this->register( include "$IP/resources/Resources.php" );
263 // Register extension modules
264 $this->register( $config->get( 'ResourceModules' ) );
266 // Avoid PHP 7.1 warning from passing $this by reference
268 Hooks
::run( 'ResourceLoaderRegisterModules', [ &$rl ] );
270 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
271 $this->registerTestModules();
274 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
280 public function getConfig() {
281 return $this->config
;
286 * @param LoggerInterface $logger
288 public function setLogger( LoggerInterface
$logger ) {
289 $this->logger
= $logger;
294 * @return LoggerInterface
296 public function getLogger() {
297 return $this->logger
;
302 * @return MessageBlobStore
304 public function getMessageBlobStore() {
305 return $this->blobStore
;
310 * @param MessageBlobStore $blobStore
312 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
313 $this->blobStore
= $blobStore;
317 * Register a module with the ResourceLoader system.
319 * @param mixed $name Name of module as a string or List of name/object pairs as an array
320 * @param array|null $info Module info array. For backwards compatibility with 1.17alpha,
321 * this may also be a ResourceLoaderModule object. Optional when using
322 * multiple-registration calling style.
323 * @throws MWException If a duplicate module registration is attempted
324 * @throws MWException If a module name contains illegal characters (pipes or commas)
325 * @throws MWException If something other than a ResourceLoaderModule is being registered
326 * @return bool False if there were any errors, in which case one or more modules were
329 public function register( $name, $info = null ) {
330 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
332 // Allow multiple modules to be registered in one call
333 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
334 foreach ( $registrations as $name => $info ) {
335 // Warn on duplicate registrations
336 if ( isset( $this->moduleInfos
[$name] ) ) {
337 // A module has already been registered by this name
338 $this->logger
->warning(
339 'ResourceLoader duplicate registration warning. ' .
340 'Another module has already been registered as ' . $name
344 // Check $name for validity
345 if ( !self
::isValidModuleName( $name ) ) {
346 throw new MWException( "ResourceLoader module name '$name' is invalid, "
347 . "see ResourceLoader::isValidModuleName()" );
351 if ( $info instanceof ResourceLoaderModule
) {
352 $this->moduleInfos
[$name] = [ 'object' => $info ];
353 $info->setName( $name );
354 $this->modules
[$name] = $info;
355 } elseif ( is_array( $info ) ) {
356 // New calling convention
357 $this->moduleInfos
[$name] = $info;
359 throw new MWException(
360 'ResourceLoader module info type error for module \'' . $name .
361 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
365 // Last-minute changes
367 // Apply custom skin-defined styles to existing modules.
368 if ( $this->isFileModule( $name ) ) {
369 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
370 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
371 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
375 // If $name is preceded with a '+', the defined style files will be added to 'default'
376 // skinStyles, otherwise 'default' will be ignored as it normally would be.
377 if ( isset( $skinStyles[$name] ) ) {
378 $paths = (array)$skinStyles[$name];
380 } elseif ( isset( $skinStyles['+' . $name] ) ) {
381 $paths = (array)$skinStyles['+' . $name];
382 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
383 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
389 // Add new file paths, remapping them to refer to our directories and not use settings
390 // from the module we're modifying, which come from the base definition.
391 list( $localBasePath, $remoteBasePath ) =
392 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
394 foreach ( $paths as $path ) {
395 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
398 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
404 public function registerTestModules() {
407 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
408 throw new MWException( 'Attempt to register JavaScript test modules '
409 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
410 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
413 // Get core test suites
415 $testModules['qunit'] = [];
416 // Get other test suites (e.g. from extensions)
417 // Avoid PHP 7.1 warning from passing $this by reference
419 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
421 // Add the testrunner (which configures QUnit) to the dependencies.
422 // Since it must be ready before any of the test suites are executed.
423 foreach ( $testModules['qunit'] as &$module ) {
424 // Make sure all test modules are top-loading so that when QUnit starts
425 // on document-ready, it will run once and finish. If some tests arrive
426 // later (possibly after QUnit has already finished) they will be ignored.
427 $module['position'] = 'top';
428 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
431 $testModules['qunit'] =
432 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
434 foreach ( $testModules as $id => $names ) {
435 // Register test modules
436 $this->register( $testModules[$id] );
438 // Keep track of their names so that they can be loaded together
439 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
444 * Add a foreign source of modules.
446 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
448 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
449 * @param string|array|null $loadUrl load.php url (string), or array with loadUrl key for
450 * backwards-compatibility.
451 * @throws MWException
453 public function addSource( $id, $loadUrl = null ) {
454 // Allow multiple sources to be registered in one call
455 if ( is_array( $id ) ) {
456 foreach ( $id as $key => $value ) {
457 $this->addSource( $key, $value );
462 // Disallow duplicates
463 if ( isset( $this->sources
[$id] ) ) {
464 throw new MWException(
465 'ResourceLoader duplicate source addition error. ' .
466 'Another source has already been registered as ' . $id
470 // Pre 1.24 backwards-compatibility
471 if ( is_array( $loadUrl ) ) {
472 if ( !isset( $loadUrl['loadScript'] ) ) {
473 throw new MWException(
474 __METHOD__
. ' was passed an array with no "loadScript" key.'
478 $loadUrl = $loadUrl['loadScript'];
481 $this->sources
[$id] = $loadUrl;
485 * Get a list of module names.
487 * @return array List of module names
489 public function getModuleNames() {
490 return array_keys( $this->moduleInfos
);
494 * Get a list of test module names for one (or all) frameworks.
496 * If the given framework id is unknkown, or if the in-object variable is not an array,
497 * then it will return an empty array.
499 * @param string $framework Get only the test module names for one
500 * particular framework (optional)
503 public function getTestModuleNames( $framework = 'all' ) {
504 /** @todo api siteinfo prop testmodulenames modulenames */
505 if ( $framework == 'all' ) {
506 return $this->testModuleNames
;
507 } elseif ( isset( $this->testModuleNames
[$framework] )
508 && is_array( $this->testModuleNames
[$framework] )
510 return $this->testModuleNames
[$framework];
517 * Check whether a ResourceLoader module is registered
520 * @param string $name
523 public function isModuleRegistered( $name ) {
524 return isset( $this->moduleInfos
[$name] );
528 * Get the ResourceLoaderModule object for a given module name.
530 * If an array of module parameters exists but a ResourceLoaderModule object has not
531 * yet been instantiated, this method will instantiate and cache that object such that
532 * subsequent calls simply return the same object.
534 * @param string $name Module name
535 * @return ResourceLoaderModule|null If module has been registered, return a
536 * ResourceLoaderModule instance. Otherwise, return null.
538 public function getModule( $name ) {
539 if ( !isset( $this->modules
[$name] ) ) {
540 if ( !isset( $this->moduleInfos
[$name] ) ) {
544 // Construct the requested object
545 $info = $this->moduleInfos
[$name];
546 /** @var ResourceLoaderModule $object */
547 if ( isset( $info['object'] ) ) {
548 // Object given in info array
549 $object = $info['object'];
550 } elseif ( isset( $info['factory'] ) ) {
551 $object = call_user_func( $info['factory'], $info );
552 $object->setConfig( $this->getConfig() );
553 $object->setLogger( $this->logger
);
555 if ( !isset( $info['class'] ) ) {
556 $class = ResourceLoaderFileModule
::class;
558 $class = $info['class'];
560 /** @var ResourceLoaderModule $object */
561 $object = new $class( $info );
562 $object->setConfig( $this->getConfig() );
563 $object->setLogger( $this->logger
);
565 $object->setName( $name );
566 $this->modules
[$name] = $object;
569 return $this->modules
[$name];
573 * Whether the module is a ResourceLoaderFileModule (including subclasses).
575 * @param string $name Module name
578 protected function isFileModule( $name ) {
579 if ( !isset( $this->moduleInfos
[$name] ) ) {
582 $info = $this->moduleInfos
[$name];
583 if ( isset( $info['object'] ) ) {
587 // The implied default for 'class' is ResourceLoaderFileModule
588 !isset( $info['class'] ) ||
590 $info['class'] === ResourceLoaderFileModule
::class ||
591 is_subclass_of( $info['class'], ResourceLoaderFileModule
::class )
596 * Get the list of sources.
598 * @return array Like [ id => load.php url, ... ]
600 public function getSources() {
601 return $this->sources
;
605 * Get the URL to the load.php endpoint for the given
606 * ResourceLoader source
609 * @param string $source
610 * @throws MWException On an invalid $source name
613 public function getLoadScript( $source ) {
614 if ( !isset( $this->sources
[$source] ) ) {
615 throw new MWException( "The $source source was never registered in ResourceLoader." );
617 return $this->sources
[$source];
622 * @param string $value
623 * @return string Hash
625 public static function makeHash( $value ) {
626 $hash = hash( 'fnv132', $value );
627 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
631 * Add an error to the 'errors' array and log it.
633 * Should only be called from within respond().
636 * @param Exception $e
638 * @param array $context
640 protected function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
641 MWExceptionHandler
::logException( $e );
642 $this->logger
->warning(
644 $context +
[ 'exception' => $e ]
646 $this->errors
[] = self
::formatExceptionNoComment( $e );
650 * Helper method to get and combine versions of multiple modules.
653 * @param ResourceLoaderContext $context
654 * @param string[] $moduleNames List of known module names
655 * @return string Hash
657 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
658 if ( !$moduleNames ) {
661 $hashes = array_map( function ( $module ) use ( $context ) {
663 return $this->getModule( $module )->getVersionHash( $context );
664 } catch ( Exception
$e ) {
665 // If modules fail to compute a version, do still consider the versions
666 // of other modules - don't set an empty string E-Tag for the whole request.
667 // See also T152266 and StartupModule::getModuleRegistrations().
668 $this->outputErrorAndLog( $e,
669 'Calculating version for "{module}" failed: {exception}',
677 return self
::makeHash( implode( '', $hashes ) );
681 * Get the expected value of the 'version' query parameter.
683 * This is used by respond() to set a short Cache-Control header for requests with
684 * information newer than the current server has. This avoids pollution of edge caches.
685 * Typically during deployment. (T117587)
687 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
690 * @param ResourceLoaderContext $context
691 * @return string Hash
693 public function makeVersionQuery( ResourceLoaderContext
$context ) {
694 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
695 // version hashes. There is no technical reason for this to be same, and for years the
696 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
697 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
698 // query parameter), then this method must continue to match the JS one.
700 foreach ( $context->getModules() as $name ) {
701 if ( !$this->getModule( $name ) ) {
702 // If a versioned request contains a missing module, the version is a mismatch
703 // as the client considered a module (and version) we don't have.
706 $moduleNames[] = $name;
708 return $this->getCombinedVersion( $context, $moduleNames );
712 * Output a response to a load request, including the content-type header.
714 * @param ResourceLoaderContext $context Context in which a response should be formed
716 public function respond( ResourceLoaderContext
$context ) {
717 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
718 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
719 // is used: ob_clean() will clear the GZIP header in that case and it won't come
720 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
721 // the whole thing in our own output buffer to be sure the active buffer
722 // doesn't use ob_gzhandler.
723 // See https://bugs.php.net/bug.php?id=36514
726 $this->measureResponseTime( RequestContext
::getMain()->getTiming() );
728 // Find out which modules are missing and instantiate the others
731 foreach ( $context->getModules() as $name ) {
732 $module = $this->getModule( $name );
734 // Do not allow private modules to be loaded from the web.
735 // This is a security issue, see T36907.
736 if ( $module->getGroup() === 'private' ) {
737 $this->logger
->debug( "Request for private module '$name' denied" );
738 $this->errors
[] = "Cannot show private module \"$name\"";
741 $modules[$name] = $module;
748 // Preload for getCombinedVersion() and for batch makeModuleResponse()
749 $this->preloadModuleInfo( array_keys( $modules ), $context );
750 } catch ( Exception
$e ) {
751 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
754 // Combine versions to propagate cache invalidation
757 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
758 } catch ( Exception
$e ) {
759 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
762 // See RFC 2616 § 3.11 Entity Tags
763 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
764 $etag = 'W/"' . $versionHash . '"';
766 // Try the client-side cache first
767 if ( $this->tryRespondNotModified( $context, $etag ) ) {
768 return; // output handled (buffers cleared)
771 // Use file cache if enabled and available...
772 if ( $this->config
->get( 'UseFileCache' ) ) {
773 $fileCache = ResourceFileCache
::newFromContext( $context );
774 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
775 return; // output handled
779 // Generate a response
780 $response = $this->makeModuleResponse( $context, $modules, $missing );
782 // Capture any PHP warnings from the output buffer and append them to the
783 // error list if we're in debug mode.
784 if ( $context->getDebug() ) {
785 $warnings = ob_get_contents();
786 if ( strlen( $warnings ) ) {
787 $this->errors
[] = $warnings;
791 // Save response to file cache unless there are errors
792 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
793 // Cache single modules and images...and other requests if there are enough hits
794 if ( ResourceFileCache
::useFileCache( $context ) ) {
795 if ( $fileCache->isCacheWorthy() ) {
796 $fileCache->saveText( $response );
798 $fileCache->incrMissesRecent( $context->getRequest() );
803 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
, $this->extraHeaders
);
805 // Remove the output buffer and output the response
808 if ( $context->getImageObj() && $this->errors
) {
809 // We can't show both the error messages and the response when it's an image.
810 $response = implode( "\n\n", $this->errors
);
811 } elseif ( $this->errors
) {
812 $errorText = implode( "\n\n", $this->errors
);
813 $errorResponse = self
::makeComment( $errorText );
814 if ( $context->shouldIncludeScripts() ) {
815 $errorResponse .= 'if (window.console && console.error) {'
816 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
820 // Prepend error info to the response
821 $response = $errorResponse . $response;
828 protected function measureResponseTime( Timing
$timing ) {
829 DeferredUpdates
::addCallableUpdate( function () use ( $timing ) {
830 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
831 if ( $measure !== false ) {
832 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
833 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
839 * Send main response headers to the client.
841 * Deals with Content-Type, CORS (for stylesheets), and caching.
843 * @param ResourceLoaderContext $context
844 * @param string $etag ETag header value
845 * @param bool $errors Whether there are errors in the response
846 * @param string[] $extra Array of extra HTTP response headers
849 protected function sendResponseHeaders(
850 ResourceLoaderContext
$context, $etag, $errors, array $extra = []
852 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
853 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
854 // Use a short cache expiry so that updates propagate to clients quickly, if:
855 // - No version specified (shared resources, e.g. stylesheets)
856 // - There were errors (recover quickly)
857 // - Version mismatch (T117587, T47877)
858 if ( is_null( $context->getVersion() )
860 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
862 $maxage = $rlMaxage['unversioned']['client'];
863 $smaxage = $rlMaxage['unversioned']['server'];
864 // If a version was specified we can use a longer expiry time since changing
865 // version numbers causes cache misses
867 $maxage = $rlMaxage['versioned']['client'];
868 $smaxage = $rlMaxage['versioned']['server'];
870 if ( $context->getImageObj() ) {
871 // Output different headers if we're outputting textual errors.
873 header( 'Content-Type: text/plain; charset=utf-8' );
875 $context->getImageObj()->sendResponseHeaders( $context );
877 } elseif ( $context->getOnly() === 'styles' ) {
878 header( 'Content-Type: text/css; charset=utf-8' );
879 header( 'Access-Control-Allow-Origin: *' );
881 header( 'Content-Type: text/javascript; charset=utf-8' );
883 // See RFC 2616 § 14.19 ETag
884 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
885 header( 'ETag: ' . $etag );
886 if ( $context->getDebug() ) {
887 // Do not cache debug responses
888 header( 'Cache-Control: private, no-cache, must-revalidate' );
889 header( 'Pragma: no-cache' );
891 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
892 $exp = min( $maxage, $smaxage );
893 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
895 foreach ( $extra as $header ) {
901 * Respond with HTTP 304 Not Modified if appropiate.
903 * If there's an If-None-Match header, respond with a 304 appropriately
904 * and clear out the output buffer. If the client cache is too old then do nothing.
906 * @param ResourceLoaderContext $context
907 * @param string $etag ETag header value
908 * @return bool True if HTTP 304 was sent and output handled
910 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
911 // See RFC 2616 § 14.26 If-None-Match
912 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
913 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
914 // Never send 304s in debug mode
915 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
916 // There's another bug in ob_gzhandler (see also the comment at
917 // the top of this function) that causes it to gzip even empty
918 // responses, meaning it's impossible to produce a truly empty
919 // response (because the gzip header is always there). This is
920 // a problem because 304 responses have to be completely empty
921 // per the HTTP spec, and Firefox behaves buggily when they're not.
922 // See also https://bugs.php.net/bug.php?id=51579
923 // To work around this, we tear down all output buffering before
925 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
927 HttpStatus
::header( 304 );
929 $this->sendResponseHeaders( $context, $etag, false );
936 * Send out code for a response from file cache if possible.
938 * @param ResourceFileCache $fileCache Cache object for this request URL
939 * @param ResourceLoaderContext $context Context in which to generate a response
940 * @param string $etag ETag header value
941 * @return bool If this found a cache file and handled the response
943 protected function tryRespondFromFileCache(
944 ResourceFileCache
$fileCache,
945 ResourceLoaderContext
$context,
948 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
949 // Buffer output to catch warnings.
951 // Get the maximum age the cache can be
952 $maxage = is_null( $context->getVersion() )
953 ?
$rlMaxage['unversioned']['server']
954 : $rlMaxage['versioned']['server'];
955 // Minimum timestamp the cache file must have
956 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
958 try { // RL always hits the DB on file cache miss...
959 wfGetDB( DB_REPLICA
);
960 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
961 $good = $fileCache->isCacheGood(); // cache existence check
965 $ts = $fileCache->cacheTimestamp();
966 // Send content type and cache headers
967 $this->sendResponseHeaders( $context, $etag, false );
968 $response = $fileCache->fetchText();
969 // Capture any PHP warnings from the output buffer and append them to the
970 // response in a comment if we're in debug mode.
971 if ( $context->getDebug() ) {
972 $warnings = ob_get_contents();
973 if ( strlen( $warnings ) ) {
974 $response = self
::makeComment( $warnings ) . $response;
977 // Remove the output buffer and output the response
979 echo $response . "\n/* Cached {$ts} */";
980 return true; // cache hit
985 return false; // cache miss
989 * Generate a CSS or JS comment block.
991 * Only use this for public data, not error message details.
993 * @param string $text
996 public static function makeComment( $text ) {
997 $encText = str_replace( '*/', '* /', $text );
998 return "/*\n$encText\n*/\n";
1002 * Handle exception display.
1004 * @param Exception $e Exception to be shown to the user
1005 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
1007 public static function formatException( $e ) {
1008 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
1012 * Handle exception display.
1015 * @param Exception $e Exception to be shown to the user
1016 * @return string Sanitized text that can be returned to the user
1018 protected static function formatExceptionNoComment( $e ) {
1019 global $wgShowExceptionDetails;
1021 if ( !$wgShowExceptionDetails ) {
1022 return MWExceptionHandler
::getPublicLogMessage( $e );
1025 return MWExceptionHandler
::getLogMessage( $e ) .
1027 MWExceptionHandler
::getRedactedTraceAsString( $e );
1031 * Generate code for a response.
1033 * Calling this method also populates the `errors` and `headers` members,
1034 * later used by respond().
1036 * @param ResourceLoaderContext $context Context in which to generate a response
1037 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1038 * @param string[] $missing List of requested module names that are unregistered (optional)
1039 * @return string Response data
1041 public function makeModuleResponse( ResourceLoaderContext
$context,
1042 array $modules, array $missing = []
1047 if ( !count( $modules ) && !count( $missing ) ) {
1049 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1050 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1051 no modules were requested. Max made me put this here. */
1055 $image = $context->getImageObj();
1057 $data = $image->getImageData( $context );
1058 if ( $data === false ) {
1060 $this->errors
[] = 'Image generation failed';
1065 foreach ( $missing as $name ) {
1066 $states[$name] = 'missing';
1072 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1074 foreach ( $modules as $name => $module ) {
1076 $content = $module->getModuleContent( $context );
1077 $implementKey = $name . '@' . $module->getVersionHash( $context );
1080 if ( isset( $content['headers'] ) ) {
1081 $this->extraHeaders
= array_merge( $this->extraHeaders
, $content['headers'] );
1085 switch ( $context->getOnly() ) {
1087 $scripts = $content['scripts'];
1088 if ( is_string( $scripts ) ) {
1089 // Load scripts raw...
1090 $strContent = $scripts;
1091 } elseif ( is_array( $scripts ) ) {
1092 // ...except when $scripts is an array of URLs
1093 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1097 $styles = $content['styles'];
1098 // We no longer seperate into media, they are all combined now with
1099 // custom media type groups into @media .. {} sections as part of the css string.
1100 // Module returns either an empty array or a numerical array with css strings.
1101 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1104 $scripts = $content['scripts'] ??
'';
1105 if ( is_string( $scripts ) ) {
1106 if ( $name === 'site' ||
$name === 'user' ) {
1107 // Legacy scripts that run in the global scope without a closure.
1108 // mw.loader.implement will use globalEval if scripts is a string.
1109 // Minify manually here, because general response minification is
1110 // not effective due it being a string literal, not a function.
1111 if ( !self
::inDebugMode() ) {
1112 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1115 $scripts = new XmlJsCode( $scripts );
1118 $strContent = self
::makeLoaderImplementScript(
1121 $content['styles'] ??
[],
1122 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1123 $content['templates'] ??
[]
1128 if ( !$context->getDebug() ) {
1129 $strContent = self
::filter( $filter, $strContent );
1132 if ( $context->getOnly() === 'scripts' ) {
1133 // Use a linebreak between module scripts (T162719)
1134 $out .= $this->ensureNewline( $strContent );
1136 $out .= $strContent;
1139 } catch ( Exception
$e ) {
1140 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1142 // Respond to client with error-state instead of module implementation
1143 $states[$name] = 'error';
1144 unset( $modules[$name] );
1146 $isRaw |
= $module->isRaw();
1149 // Update module states
1150 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1151 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1152 // Set the state of modules loaded as only scripts to ready as
1153 // they don't have an mw.loader.implement wrapper that sets the state
1154 foreach ( $modules as $name => $module ) {
1155 $states[$name] = 'ready';
1159 // Set the state of modules we didn't respond to with mw.loader.implement
1160 if ( count( $states ) ) {
1161 $stateScript = self
::makeLoaderStateScript( $states );
1162 if ( !$context->getDebug() ) {
1163 $stateScript = self
::filter( 'minify-js', $stateScript );
1165 // Use a linebreak between module script and state script (T162719)
1166 $out = $this->ensureNewline( $out ) . $stateScript;
1169 if ( count( $states ) ) {
1170 $this->errors
[] = 'Problematic modules: ' .
1171 FormatJson
::encode( $states, self
::inDebugMode() );
1179 * Ensure the string is either empty or ends in a line break
1180 * @param string $str
1183 private function ensureNewline( $str ) {
1184 $end = substr( $str, -1 );
1185 if ( $end === false ||
$end === "\n" ) {
1192 * Get names of modules that use a certain message.
1194 * @param string $messageKey
1195 * @return array List of module names
1197 public function getModulesByMessage( $messageKey ) {
1199 foreach ( $this->getModuleNames() as $moduleName ) {
1200 $module = $this->getModule( $moduleName );
1201 if ( in_array( $messageKey, $module->getMessages() ) ) {
1202 $moduleNames[] = $moduleName;
1205 return $moduleNames;
1209 * Return JS code that calls mw.loader.implement with given module properties.
1211 * @param string $name Module name or implement key (format "`[name]@[version]`")
1212 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1213 * list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
1214 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1215 * to CSS files keyed by media type
1216 * @param mixed $messages List of messages associated with this module. May either be an
1217 * associative array mapping message key to value, or a JSON-encoded message blob containing
1218 * the same data, wrapped in an XmlJsCode object.
1219 * @param array $templates Keys are name of templates and values are the source of
1221 * @throws MWException
1222 * @return string JavaScript code
1224 protected static function makeLoaderImplementScript(
1225 $name, $scripts, $styles, $messages, $templates
1227 if ( $scripts instanceof XmlJsCode
) {
1228 if ( self
::inDebugMode() ) {
1229 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1231 $scripts = new XmlJsCode( 'function($,jQuery,require,module){'. $scripts->value
. '}' );
1233 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1234 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1236 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1237 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1238 // of "{}". Force them to objects.
1246 self
::trimArray( $module );
1248 return Xml
::encodeJsCall( 'mw.loader.implement', $module, self
::inDebugMode() );
1252 * Returns JS code which, when called, will register a given list of messages.
1254 * @param mixed $messages Either an associative array mapping message key to value, or a
1255 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1256 * @return string JavaScript code
1258 public static function makeMessageSetScript( $messages ) {
1259 return Xml
::encodeJsCall(
1261 [ (object)$messages ],
1267 * Combines an associative array mapping media type to CSS into a
1268 * single stylesheet with "@media" blocks.
1270 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1273 public static function makeCombinedStyles( array $stylePairs ) {
1275 foreach ( $stylePairs as $media => $styles ) {
1276 // ResourceLoaderFileModule::getStyle can return the styles
1277 // as a string or an array of strings. This is to allow separation in
1279 $styles = (array)$styles;
1280 foreach ( $styles as $style ) {
1281 $style = trim( $style );
1282 // Don't output an empty "@media print { }" block (T42498)
1283 if ( $style !== '' ) {
1284 // Transform the media type based on request params and config
1285 // The way that this relies on $wgRequest to propagate request params is slightly evil
1286 $media = OutputPage
::transformCssMedia( $media );
1288 if ( $media === '' ||
$media == 'all' ) {
1290 } elseif ( is_string( $media ) ) {
1291 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1301 * Returns a JS call to mw.loader.state, which sets the state of a
1302 * module or modules to a given value. Has two calling conventions:
1304 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1305 * Set the state of a single module called $name to $state
1307 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1308 * Set the state of modules with the given names to the given states
1310 * @param string $name
1311 * @param string|null $state
1312 * @return string JavaScript code
1314 public static function makeLoaderStateScript( $name, $state = null ) {
1315 if ( is_array( $name ) ) {
1316 return Xml
::encodeJsCall(
1322 return Xml
::encodeJsCall(
1331 * Returns JS code which calls the script given by $script. The script will
1332 * be called with local variables name, version, dependencies and group,
1333 * which will have values corresponding to $name, $version, $dependencies
1334 * and $group as supplied.
1336 * @param string $name Module name
1337 * @param string $version Module version hash
1338 * @param array $dependencies List of module names on which this module depends
1339 * @param string $group Group which the module is in.
1340 * @param string $source Source of the module, or 'local' if not foreign.
1341 * @param string $script JavaScript code
1342 * @return string JavaScript code
1344 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1345 $group, $source, $script
1347 $script = str_replace( "\n", "\n\t", trim( $script ) );
1348 return Xml
::encodeJsCall(
1349 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1350 [ $name, $version, $dependencies, $group, $source ],
1355 private static function isEmptyObject( stdClass
$obj ) {
1356 foreach ( $obj as $key => $value ) {
1363 * Remove empty values from the end of an array.
1365 * Values considered empty:
1369 * - new XmlJsCode( '{}' )
1370 * - new stdClass() // (object) []
1372 * @param Array $array
1374 private static function trimArray( array &$array ) {
1375 $i = count( $array );
1377 if ( $array[$i] === null
1378 ||
$array[$i] === []
1379 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1380 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1382 unset( $array[$i] );
1390 * Returns JS code which calls mw.loader.register with the given
1391 * parameters. Has three calling conventions:
1393 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1394 * $dependencies, $group, $source, $skip
1396 * Register a single module.
1398 * - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
1399 * Register modules with the given names.
1401 * - ResourceLoader::makeLoaderRegisterScript( [
1402 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1403 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1406 * Registers modules with the given names and parameters.
1408 * @param string $name Module name
1409 * @param string|null $version Module version hash
1410 * @param array|null $dependencies List of module names on which this module depends
1411 * @param string|null $group Group which the module is in
1412 * @param string|null $source Source of the module, or 'local' if not foreign
1413 * @param string|null $skip Script body of the skip function
1414 * @return string JavaScript code
1416 public static function makeLoaderRegisterScript( $name, $version = null,
1417 $dependencies = null, $group = null, $source = null, $skip = null
1419 if ( is_array( $name ) ) {
1420 // Build module name index
1422 foreach ( $name as $i => &$module ) {
1423 $index[$module[0]] = $i;
1426 // Transform dependency names into indexes when possible, they will be resolved by
1427 // mw.loader.register on the other end
1428 foreach ( $name as &$module ) {
1429 if ( isset( $module[2] ) ) {
1430 foreach ( $module[2] as &$dependency ) {
1431 if ( isset( $index[$dependency] ) ) {
1432 $dependency = $index[$dependency];
1438 array_walk( $name, [ 'self', 'trimArray' ] );
1440 return Xml
::encodeJsCall(
1441 'mw.loader.register',
1446 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1447 self
::trimArray( $registration );
1448 return Xml
::encodeJsCall(
1449 'mw.loader.register',
1457 * Returns JS code which calls mw.loader.addSource() with the given
1458 * parameters. Has two calling conventions:
1460 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1461 * Register a single source
1463 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1464 * Register sources with the given IDs and properties.
1466 * @param string $id Source ID
1467 * @param string|null $loadUrl load.php url
1468 * @return string JavaScript code
1470 public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
1471 if ( is_array( $id ) ) {
1472 return Xml
::encodeJsCall(
1473 'mw.loader.addSource',
1478 return Xml
::encodeJsCall(
1479 'mw.loader.addSource',
1487 * Wraps JavaScript code to run after the startup module.
1489 * @param string $script JavaScript code
1490 * @return string JavaScript code
1492 public static function makeLoaderConditionalScript( $script ) {
1493 // Adds a function to lazy-created RLQ
1494 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1495 trim( $script ) . '});';
1499 * Wraps JavaScript code to run after a required module.
1502 * @param string|string[] $modules Module name(s)
1503 * @param string $script JavaScript code
1504 * @return string JavaScript code
1506 public static function makeInlineCodeWithModule( $modules, $script ) {
1507 // Adds an array to lazy-created RLQ
1508 return '(window.RLQ=window.RLQ||[]).push(['
1509 . json_encode( $modules ) . ','
1510 . 'function(){' . trim( $script ) . '}'
1515 * Returns an HTML script tag that runs given JS code after startup and base modules.
1517 * The code will be wrapped in a closure, and it will be executed by ResourceLoader's
1518 * startup module if the client has adequate support for MediaWiki JavaScript code.
1520 * @param string $script JavaScript code
1521 * @param string|null $nonce [optional] Content-Security-Policy nonce
1522 * (from OutputPage::getCSPNonce)
1523 * @return string|WrappedString HTML
1525 public static function makeInlineScript( $script, $nonce = null ) {
1526 $js = self
::makeLoaderConditionalScript( $script );
1528 if ( $nonce === null ) {
1529 wfWarn( __METHOD__
. " did not get nonce. Will break CSP" );
1530 } elseif ( $nonce !== false ) {
1531 // If it was false, CSP is disabled, so no nonce attribute.
1532 // Nonce should be only base64 characters, so should be safe,
1533 // but better to be safely escaped than sorry.
1534 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1537 return new WrappedString(
1538 Html
::inlineScript( $js, $nonce ),
1539 "<script$escNonce>(window.RLQ=window.RLQ||[]).push(function(){",
1545 * Returns JS code which will set the MediaWiki configuration array to
1548 * @param array $configuration List of configuration values keyed by variable name
1549 * @return string JavaScript code
1551 public static function makeConfigSetScript( array $configuration ) {
1552 return Xml
::encodeJsCall(
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 ResourceLoaderContext::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 * Determine whether debug mode was requested
1591 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1594 public static function inDebugMode() {
1595 if ( self
::$debugMode === null ) {
1596 global $wgRequest, $wgResourceLoaderDebug;
1597 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1598 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1601 return self
::$debugMode;
1605 * Reset static members used for caching.
1607 * Global state and $wgRequest are evil, but we're using it right
1608 * now and sometimes we need to be able to force ResourceLoader to
1609 * re-evaluate the context because it has changed (e.g. in the test suite).
1611 public static function clearCache() {
1612 self
::$debugMode = null;
1616 * Build a load.php URL
1619 * @param string $source Name of the ResourceLoader source
1620 * @param ResourceLoaderContext $context
1621 * @param array $extraQuery
1622 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1624 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1627 $query = self
::createLoaderQuery( $context, $extraQuery );
1628 $script = $this->getLoadScript( $source );
1630 return wfAppendQuery( $script, $query );
1634 * Helper for createLoaderURL()
1637 * @see makeLoaderQuery
1638 * @param ResourceLoaderContext $context
1639 * @param array $extraQuery
1642 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1643 return self
::makeLoaderQuery(
1644 $context->getModules(),
1645 $context->getLanguage(),
1646 $context->getSkin(),
1647 $context->getUser(),
1648 $context->getVersion(),
1649 $context->getDebug(),
1650 $context->getOnly(),
1651 $context->getRequest()->getBool( 'printable' ),
1652 $context->getRequest()->getBool( 'handheld' ),
1658 * Build a query array (array representation of query string) for load.php. Helper
1659 * function for createLoaderURL().
1661 * @param array $modules
1662 * @param string $lang
1663 * @param string $skin
1664 * @param string|null $user
1665 * @param string|null $version
1666 * @param bool $debug
1667 * @param string|null $only
1668 * @param bool $printable
1669 * @param bool $handheld
1670 * @param array $extraQuery
1674 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1675 $version = null, $debug = false, $only = null, $printable = false,
1676 $handheld = false, $extraQuery = []
1679 'modules' => self
::makePackedModulesString( $modules ),
1682 'debug' => $debug ?
'true' : 'false',
1684 if ( $user !== null ) {
1685 $query['user'] = $user;
1687 if ( $version !== null ) {
1688 $query['version'] = $version;
1690 if ( $only !== null ) {
1691 $query['only'] = $only;
1694 $query['printable'] = 1;
1697 $query['handheld'] = 1;
1699 $query +
= $extraQuery;
1701 // Make queries uniform in order
1707 * Check a module name for validity.
1709 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1710 * at most 255 bytes.
1712 * @param string $moduleName Module name to check
1713 * @return bool Whether $moduleName is a valid module name
1715 public static function isValidModuleName( $moduleName ) {
1716 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1720 * Returns LESS compiler set up for use with MediaWiki
1723 * @param array $vars Associative array of variables that should be used
1724 * for compilation. Since 1.32, this method no longer automatically includes
1725 * global LESS vars from ResourceLoader::getLessVars (T191937).
1726 * @throws MWException
1727 * @return Less_Parser
1729 public function getLessCompiler( $vars = [] ) {
1731 // When called from the installer, it is possible that a required PHP extension
1732 // is missing (at least for now; see T49564). If this is the case, throw an
1733 // exception (caught by the installer) to prevent a fatal error later on.
1734 if ( !class_exists( 'Less_Parser' ) ) {
1735 throw new MWException( 'MediaWiki requires the less.php parser' );
1738 $parser = new Less_Parser
;
1739 $parser->ModifyVars( $vars );
1740 $parser->SetImportDirs( [
1741 "$IP/resources/src/mediawiki.less/" => '',
1743 $parser->SetOption( 'relativeUrls', false );
1749 * Get global LESS variables.
1752 * @return array Map of variable names to string CSS values.
1754 public function getLessVars() {
1755 if ( $this->lessVars
=== null ) {
1756 $this->lessVars
= $this->config
->get( 'ResourceLoaderLESSVars' );
1758 return $this->lessVars
;