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 = 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(
202 self
::$filterCacheVersion, md5( $data )
205 $result = $cache->get( $key );
206 if ( $result === false ) {
207 $stats->increment( "resourceloader_cache.$filter.miss" );
208 $result = self
::applyFilter( $filter, $data );
209 $cache->set( $key, $result, 24 * 3600 );
211 $stats->increment( "resourceloader_cache.$filter.hit" );
213 if ( $result === null ) {
221 private static function applyFilter( $filter, $data ) {
222 $data = trim( $data );
225 $data = ( $filter === 'minify-css' )
226 ? CSSMin
::minify( $data )
227 : JavaScriptMinifier
::minify( $data );
228 } catch ( Exception
$e ) {
229 MWExceptionHandler
::logException( $e );
237 * Register core modules and runs registration hooks.
238 * @param Config|null $config [optional]
239 * @param LoggerInterface|null $logger [optional]
241 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
244 $this->logger
= $logger ?
: new NullLogger();
247 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
248 $config = MediaWikiServices
::getInstance()->getMainConfig();
250 $this->config
= $config;
252 // Add 'local' source first
253 $this->addSource( 'local', $config->get( 'LoadScript' ) );
256 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
258 // Register core modules
259 $this->register( include "$IP/resources/Resources.php" );
260 // Register extension modules
261 $this->register( $config->get( 'ResourceModules' ) );
263 // Avoid PHP 7.1 warning from passing $this by reference
265 Hooks
::run( 'ResourceLoaderRegisterModules', [ &$rl ] );
267 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
268 $this->registerTestModules();
271 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
277 public function getConfig() {
278 return $this->config
;
283 * @param LoggerInterface $logger
285 public function setLogger( LoggerInterface
$logger ) {
286 $this->logger
= $logger;
291 * @return LoggerInterface
293 public function getLogger() {
294 return $this->logger
;
299 * @return MessageBlobStore
301 public function getMessageBlobStore() {
302 return $this->blobStore
;
307 * @param MessageBlobStore $blobStore
309 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
310 $this->blobStore
= $blobStore;
314 * Register a module with the ResourceLoader system.
316 * @param mixed $name Name of module as a string or List of name/object pairs as an array
317 * @param array|null $info Module info array. For backwards compatibility with 1.17alpha,
318 * this may also be a ResourceLoaderModule object. Optional when using
319 * multiple-registration calling style.
320 * @throws MWException If a duplicate module registration is attempted
321 * @throws MWException If a module name contains illegal characters (pipes or commas)
322 * @throws MWException If something other than a ResourceLoaderModule is being registered
323 * @return bool False if there were any errors, in which case one or more modules were
326 public function register( $name, $info = null ) {
327 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
329 // Allow multiple modules to be registered in one call
330 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
331 foreach ( $registrations as $name => $info ) {
332 // Warn on duplicate registrations
333 if ( isset( $this->moduleInfos
[$name] ) ) {
334 // A module has already been registered by this name
335 $this->logger
->warning(
336 'ResourceLoader duplicate registration warning. ' .
337 'Another module has already been registered as ' . $name
341 // Check $name for validity
342 if ( !self
::isValidModuleName( $name ) ) {
343 throw new MWException( "ResourceLoader module name '$name' is invalid, "
344 . "see ResourceLoader::isValidModuleName()" );
348 if ( $info instanceof ResourceLoaderModule
) {
349 $this->moduleInfos
[$name] = [ 'object' => $info ];
350 $info->setName( $name );
351 $this->modules
[$name] = $info;
352 } elseif ( is_array( $info ) ) {
353 // New calling convention
354 $this->moduleInfos
[$name] = $info;
356 throw new MWException(
357 'ResourceLoader module info type error for module \'' . $name .
358 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
362 // Last-minute changes
364 // Apply custom skin-defined styles to existing modules.
365 if ( $this->isFileModule( $name ) ) {
366 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
367 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
368 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
372 // If $name is preceded with a '+', the defined style files will be added to 'default'
373 // skinStyles, otherwise 'default' will be ignored as it normally would be.
374 if ( isset( $skinStyles[$name] ) ) {
375 $paths = (array)$skinStyles[$name];
377 } elseif ( isset( $skinStyles['+' . $name] ) ) {
378 $paths = (array)$skinStyles['+' . $name];
379 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
380 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
386 // Add new file paths, remapping them to refer to our directories and not use settings
387 // from the module we're modifying, which come from the base definition.
388 list( $localBasePath, $remoteBasePath ) =
389 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
391 foreach ( $paths as $path ) {
392 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
395 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
401 public function registerTestModules() {
404 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
405 throw new MWException( 'Attempt to register JavaScript test modules '
406 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
407 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
410 // Get core test suites
412 $testModules['qunit'] = [];
413 // Get other test suites (e.g. from extensions)
414 // Avoid PHP 7.1 warning from passing $this by reference
416 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
418 // Add the testrunner (which configures QUnit) to the dependencies.
419 // Since it must be ready before any of the test suites are executed.
420 foreach ( $testModules['qunit'] as &$module ) {
421 // Make sure all test modules are top-loading so that when QUnit starts
422 // on document-ready, it will run once and finish. If some tests arrive
423 // later (possibly after QUnit has already finished) they will be ignored.
424 $module['position'] = 'top';
425 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
428 $testModules['qunit'] =
429 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
431 foreach ( $testModules as $id => $names ) {
432 // Register test modules
433 $this->register( $testModules[$id] );
435 // Keep track of their names so that they can be loaded together
436 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
441 * Add a foreign source of modules.
443 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
445 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
446 * @param string|array|null $loadUrl load.php url (string), or array with loadUrl key for
447 * backwards-compatibility.
448 * @throws MWException
450 public function addSource( $id, $loadUrl = null ) {
451 // Allow multiple sources to be registered in one call
452 if ( is_array( $id ) ) {
453 foreach ( $id as $key => $value ) {
454 $this->addSource( $key, $value );
459 // Disallow duplicates
460 if ( isset( $this->sources
[$id] ) ) {
461 throw new MWException(
462 'ResourceLoader duplicate source addition error. ' .
463 'Another source has already been registered as ' . $id
467 // Pre 1.24 backwards-compatibility
468 if ( is_array( $loadUrl ) ) {
469 if ( !isset( $loadUrl['loadScript'] ) ) {
470 throw new MWException(
471 __METHOD__
. ' was passed an array with no "loadScript" key.'
475 $loadUrl = $loadUrl['loadScript'];
478 $this->sources
[$id] = $loadUrl;
482 * Get a list of module names.
484 * @return array List of module names
486 public function getModuleNames() {
487 return array_keys( $this->moduleInfos
);
491 * Get a list of test module names for one (or all) frameworks.
493 * If the given framework id is unknkown, or if the in-object variable is not an array,
494 * then it will return an empty array.
496 * @param string $framework Get only the test module names for one
497 * particular framework (optional)
500 public function getTestModuleNames( $framework = 'all' ) {
501 /** @todo api siteinfo prop testmodulenames modulenames */
502 if ( $framework == 'all' ) {
503 return $this->testModuleNames
;
504 } elseif ( isset( $this->testModuleNames
[$framework] )
505 && is_array( $this->testModuleNames
[$framework] )
507 return $this->testModuleNames
[$framework];
514 * Check whether a ResourceLoader module is registered
517 * @param string $name
520 public function isModuleRegistered( $name ) {
521 return isset( $this->moduleInfos
[$name] );
525 * Get the ResourceLoaderModule object for a given module name.
527 * If an array of module parameters exists but a ResourceLoaderModule object has not
528 * yet been instantiated, this method will instantiate and cache that object such that
529 * subsequent calls simply return the same object.
531 * @param string $name Module name
532 * @return ResourceLoaderModule|null If module has been registered, return a
533 * ResourceLoaderModule instance. Otherwise, return null.
535 public function getModule( $name ) {
536 if ( !isset( $this->modules
[$name] ) ) {
537 if ( !isset( $this->moduleInfos
[$name] ) ) {
541 // Construct the requested object
542 $info = $this->moduleInfos
[$name];
543 /** @var ResourceLoaderModule $object */
544 if ( isset( $info['object'] ) ) {
545 // Object given in info array
546 $object = $info['object'];
547 } elseif ( isset( $info['factory'] ) ) {
548 $object = call_user_func( $info['factory'], $info );
549 $object->setConfig( $this->getConfig() );
550 $object->setLogger( $this->logger
);
552 if ( !isset( $info['class'] ) ) {
553 $class = ResourceLoaderFileModule
::class;
555 $class = $info['class'];
557 /** @var ResourceLoaderModule $object */
558 $object = new $class( $info );
559 $object->setConfig( $this->getConfig() );
560 $object->setLogger( $this->logger
);
562 $object->setName( $name );
563 $this->modules
[$name] = $object;
566 return $this->modules
[$name];
570 * Whether the module is a ResourceLoaderFileModule (including subclasses).
572 * @param string $name Module name
575 protected function isFileModule( $name ) {
576 if ( !isset( $this->moduleInfos
[$name] ) ) {
579 $info = $this->moduleInfos
[$name];
580 if ( isset( $info['object'] ) ) {
584 // The implied default for 'class' is ResourceLoaderFileModule
585 !isset( $info['class'] ) ||
587 $info['class'] === ResourceLoaderFileModule
::class ||
588 is_subclass_of( $info['class'], ResourceLoaderFileModule
::class )
593 * Get the list of sources.
595 * @return array Like [ id => load.php url, ... ]
597 public function getSources() {
598 return $this->sources
;
602 * Get the URL to the load.php endpoint for the given
603 * ResourceLoader source
606 * @param string $source
607 * @throws MWException On an invalid $source name
610 public function getLoadScript( $source ) {
611 if ( !isset( $this->sources
[$source] ) ) {
612 throw new MWException( "The $source source was never registered in ResourceLoader." );
614 return $this->sources
[$source];
619 * @param string $value
620 * @return string Hash
622 public static function makeHash( $value ) {
623 $hash = hash( 'fnv132', $value );
624 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
628 * Add an error to the 'errors' array and log it.
630 * Should only be called from within respond().
633 * @param Exception $e
635 * @param array $context
637 protected function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
638 MWExceptionHandler
::logException( $e );
639 $this->logger
->warning(
641 $context +
[ 'exception' => $e ]
643 $this->errors
[] = self
::formatExceptionNoComment( $e );
647 * Helper method to get and combine versions of multiple modules.
650 * @param ResourceLoaderContext $context
651 * @param string[] $moduleNames List of known module names
652 * @return string Hash
654 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
655 if ( !$moduleNames ) {
658 $hashes = array_map( function ( $module ) use ( $context ) {
660 return $this->getModule( $module )->getVersionHash( $context );
661 } catch ( Exception
$e ) {
662 // If modules fail to compute a version, do still consider the versions
663 // of other modules - don't set an empty string E-Tag for the whole request.
664 // See also T152266 and StartupModule::getModuleRegistrations().
665 $this->outputErrorAndLog( $e,
666 'Calculating version for "{module}" failed: {exception}',
674 return self
::makeHash( implode( '', $hashes ) );
678 * Get the expected value of the 'version' query parameter.
680 * This is used by respond() to set a short Cache-Control header for requests with
681 * information newer than the current server has. This avoids pollution of edge caches.
682 * Typically during deployment. (T117587)
684 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
687 * @param ResourceLoaderContext $context
688 * @return string Hash
690 public function makeVersionQuery( ResourceLoaderContext
$context ) {
691 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
692 // version hashes. There is no technical reason for this to be same, and for years the
693 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
694 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
695 // query parameter), then this method must continue to match the JS one.
697 foreach ( $context->getModules() as $name ) {
698 if ( !$this->getModule( $name ) ) {
699 // If a versioned request contains a missing module, the version is a mismatch
700 // as the client considered a module (and version) we don't have.
703 $moduleNames[] = $name;
705 return $this->getCombinedVersion( $context, $moduleNames );
709 * Output a response to a load request, including the content-type header.
711 * @param ResourceLoaderContext $context Context in which a response should be formed
713 public function respond( ResourceLoaderContext
$context ) {
714 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
715 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
716 // is used: ob_clean() will clear the GZIP header in that case and it won't come
717 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
718 // the whole thing in our own output buffer to be sure the active buffer
719 // doesn't use ob_gzhandler.
720 // See https://bugs.php.net/bug.php?id=36514
723 $this->measureResponseTime( RequestContext
::getMain()->getTiming() );
725 // Find out which modules are missing and instantiate the others
728 foreach ( $context->getModules() as $name ) {
729 $module = $this->getModule( $name );
731 // Do not allow private modules to be loaded from the web.
732 // This is a security issue, see T36907.
733 if ( $module->getGroup() === 'private' ) {
734 $this->logger
->debug( "Request for private module '$name' denied" );
735 $this->errors
[] = "Cannot show private module \"$name\"";
738 $modules[$name] = $module;
745 // Preload for getCombinedVersion() and for batch makeModuleResponse()
746 $this->preloadModuleInfo( array_keys( $modules ), $context );
747 } catch ( Exception
$e ) {
748 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
751 // Combine versions to propagate cache invalidation
754 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
755 } catch ( Exception
$e ) {
756 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
759 // See RFC 2616 § 3.11 Entity Tags
760 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
761 $etag = 'W/"' . $versionHash . '"';
763 // Try the client-side cache first
764 if ( $this->tryRespondNotModified( $context, $etag ) ) {
765 return; // output handled (buffers cleared)
768 // Use file cache if enabled and available...
769 if ( $this->config
->get( 'UseFileCache' ) ) {
770 $fileCache = ResourceFileCache
::newFromContext( $context );
771 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
772 return; // output handled
776 // Generate a response
777 $response = $this->makeModuleResponse( $context, $modules, $missing );
779 // Capture any PHP warnings from the output buffer and append them to the
780 // error list if we're in debug mode.
781 if ( $context->getDebug() ) {
782 $warnings = ob_get_contents();
783 if ( strlen( $warnings ) ) {
784 $this->errors
[] = $warnings;
788 // Save response to file cache unless there are errors
789 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
790 // Cache single modules and images...and other requests if there are enough hits
791 if ( ResourceFileCache
::useFileCache( $context ) ) {
792 if ( $fileCache->isCacheWorthy() ) {
793 $fileCache->saveText( $response );
795 $fileCache->incrMissesRecent( $context->getRequest() );
800 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
, $this->extraHeaders
);
802 // Remove the output buffer and output the response
805 if ( $context->getImageObj() && $this->errors
) {
806 // We can't show both the error messages and the response when it's an image.
807 $response = implode( "\n\n", $this->errors
);
808 } elseif ( $this->errors
) {
809 $errorText = implode( "\n\n", $this->errors
);
810 $errorResponse = self
::makeComment( $errorText );
811 if ( $context->shouldIncludeScripts() ) {
812 $errorResponse .= 'if (window.console && console.error) {'
813 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
817 // Prepend error info to the response
818 $response = $errorResponse . $response;
825 protected function measureResponseTime( Timing
$timing ) {
826 DeferredUpdates
::addCallableUpdate( function () use ( $timing ) {
827 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
828 if ( $measure !== false ) {
829 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
830 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
836 * Send main response headers to the client.
838 * Deals with Content-Type, CORS (for stylesheets), and caching.
840 * @param ResourceLoaderContext $context
841 * @param string $etag ETag header value
842 * @param bool $errors Whether there are errors in the response
843 * @param string[] $extra Array of extra HTTP response headers
846 protected function sendResponseHeaders(
847 ResourceLoaderContext
$context, $etag, $errors, array $extra = []
849 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
850 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
851 // Use a short cache expiry so that updates propagate to clients quickly, if:
852 // - No version specified (shared resources, e.g. stylesheets)
853 // - There were errors (recover quickly)
854 // - Version mismatch (T117587, T47877)
855 if ( is_null( $context->getVersion() )
857 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
859 $maxage = $rlMaxage['unversioned']['client'];
860 $smaxage = $rlMaxage['unversioned']['server'];
861 // If a version was specified we can use a longer expiry time since changing
862 // version numbers causes cache misses
864 $maxage = $rlMaxage['versioned']['client'];
865 $smaxage = $rlMaxage['versioned']['server'];
867 if ( $context->getImageObj() ) {
868 // Output different headers if we're outputting textual errors.
870 header( 'Content-Type: text/plain; charset=utf-8' );
872 $context->getImageObj()->sendResponseHeaders( $context );
874 } elseif ( $context->getOnly() === 'styles' ) {
875 header( 'Content-Type: text/css; charset=utf-8' );
876 header( 'Access-Control-Allow-Origin: *' );
878 header( 'Content-Type: text/javascript; charset=utf-8' );
880 // See RFC 2616 § 14.19 ETag
881 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
882 header( 'ETag: ' . $etag );
883 if ( $context->getDebug() ) {
884 // Do not cache debug responses
885 header( 'Cache-Control: private, no-cache, must-revalidate' );
886 header( 'Pragma: no-cache' );
888 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
889 $exp = min( $maxage, $smaxage );
890 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
892 foreach ( $extra as $header ) {
898 * Respond with HTTP 304 Not Modified if appropiate.
900 * If there's an If-None-Match header, respond with a 304 appropriately
901 * and clear out the output buffer. If the client cache is too old then do nothing.
903 * @param ResourceLoaderContext $context
904 * @param string $etag ETag header value
905 * @return bool True if HTTP 304 was sent and output handled
907 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
908 // See RFC 2616 § 14.26 If-None-Match
909 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
910 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
911 // Never send 304s in debug mode
912 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
913 // There's another bug in ob_gzhandler (see also the comment at
914 // the top of this function) that causes it to gzip even empty
915 // responses, meaning it's impossible to produce a truly empty
916 // response (because the gzip header is always there). This is
917 // a problem because 304 responses have to be completely empty
918 // per the HTTP spec, and Firefox behaves buggily when they're not.
919 // See also https://bugs.php.net/bug.php?id=51579
920 // To work around this, we tear down all output buffering before
922 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
924 HttpStatus
::header( 304 );
926 $this->sendResponseHeaders( $context, $etag, false );
933 * Send out code for a response from file cache if possible.
935 * @param ResourceFileCache $fileCache Cache object for this request URL
936 * @param ResourceLoaderContext $context Context in which to generate a response
937 * @param string $etag ETag header value
938 * @return bool If this found a cache file and handled the response
940 protected function tryRespondFromFileCache(
941 ResourceFileCache
$fileCache,
942 ResourceLoaderContext
$context,
945 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
946 // Buffer output to catch warnings.
948 // Get the maximum age the cache can be
949 $maxage = is_null( $context->getVersion() )
950 ?
$rlMaxage['unversioned']['server']
951 : $rlMaxage['versioned']['server'];
952 // Minimum timestamp the cache file must have
953 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
955 try { // RL always hits the DB on file cache miss...
956 wfGetDB( DB_REPLICA
);
957 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
958 $good = $fileCache->isCacheGood(); // cache existence check
962 $ts = $fileCache->cacheTimestamp();
963 // Send content type and cache headers
964 $this->sendResponseHeaders( $context, $etag, false );
965 $response = $fileCache->fetchText();
966 // Capture any PHP warnings from the output buffer and append them to the
967 // response in a comment if we're in debug mode.
968 if ( $context->getDebug() ) {
969 $warnings = ob_get_contents();
970 if ( strlen( $warnings ) ) {
971 $response = self
::makeComment( $warnings ) . $response;
974 // Remove the output buffer and output the response
976 echo $response . "\n/* Cached {$ts} */";
977 return true; // cache hit
982 return false; // cache miss
986 * Generate a CSS or JS comment block.
988 * Only use this for public data, not error message details.
990 * @param string $text
993 public static function makeComment( $text ) {
994 $encText = str_replace( '*/', '* /', $text );
995 return "/*\n$encText\n*/\n";
999 * Handle exception display.
1001 * @param Exception $e Exception to be shown to the user
1002 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
1004 public static function formatException( $e ) {
1005 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
1009 * Handle exception display.
1012 * @param Exception $e Exception to be shown to the user
1013 * @return string Sanitized text that can be returned to the user
1015 protected static function formatExceptionNoComment( $e ) {
1016 global $wgShowExceptionDetails;
1018 if ( !$wgShowExceptionDetails ) {
1019 return MWExceptionHandler
::getPublicLogMessage( $e );
1022 return MWExceptionHandler
::getLogMessage( $e ) .
1024 MWExceptionHandler
::getRedactedTraceAsString( $e );
1028 * Generate code for a response.
1030 * Calling this method also populates the `errors` and `headers` members,
1031 * later used by respond().
1033 * @param ResourceLoaderContext $context Context in which to generate a response
1034 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1035 * @param string[] $missing List of requested module names that are unregistered (optional)
1036 * @return string Response data
1038 public function makeModuleResponse( ResourceLoaderContext
$context,
1039 array $modules, array $missing = []
1044 if ( !count( $modules ) && !count( $missing ) ) {
1046 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1047 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1048 no modules were requested. Max made me put this here. */
1052 $image = $context->getImageObj();
1054 $data = $image->getImageData( $context );
1055 if ( $data === false ) {
1057 $this->errors
[] = 'Image generation failed';
1062 foreach ( $missing as $name ) {
1063 $states[$name] = 'missing';
1069 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1071 foreach ( $modules as $name => $module ) {
1073 $content = $module->getModuleContent( $context );
1074 $implementKey = $name . '@' . $module->getVersionHash( $context );
1077 if ( isset( $content['headers'] ) ) {
1078 $this->extraHeaders
= array_merge( $this->extraHeaders
, $content['headers'] );
1082 switch ( $context->getOnly() ) {
1084 $scripts = $content['scripts'];
1085 if ( is_string( $scripts ) ) {
1086 // Load scripts raw...
1087 $strContent = $scripts;
1088 } elseif ( is_array( $scripts ) ) {
1089 // ...except when $scripts is an array of URLs
1090 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1094 $styles = $content['styles'];
1095 // We no longer separate into media, they are all combined now with
1096 // custom media type groups into @media .. {} sections as part of the css string.
1097 // Module returns either an empty array or a numerical array with css strings.
1098 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1101 $scripts = $content['scripts'] ??
'';
1102 if ( is_string( $scripts ) ) {
1103 if ( $name === 'site' ||
$name === 'user' ) {
1104 // Legacy scripts that run in the global scope without a closure.
1105 // mw.loader.implement will use globalEval if scripts is a string.
1106 // Minify manually here, because general response minification is
1107 // not effective due it being a string literal, not a function.
1108 if ( !self
::inDebugMode() ) {
1109 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1112 $scripts = new XmlJsCode( $scripts );
1115 $strContent = self
::makeLoaderImplementScript(
1118 $content['styles'] ??
[],
1119 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1120 $content['templates'] ??
[]
1125 if ( !$context->getDebug() ) {
1126 $strContent = self
::filter( $filter, $strContent );
1129 if ( $context->getOnly() === 'scripts' ) {
1130 // Use a linebreak between module scripts (T162719)
1131 $out .= $this->ensureNewline( $strContent );
1133 $out .= $strContent;
1136 } catch ( Exception
$e ) {
1137 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1139 // Respond to client with error-state instead of module implementation
1140 $states[$name] = 'error';
1141 unset( $modules[$name] );
1143 $isRaw |
= $module->isRaw();
1146 // Update module states
1147 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1148 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1149 // Set the state of modules loaded as only scripts to ready as
1150 // they don't have an mw.loader.implement wrapper that sets the state
1151 foreach ( $modules as $name => $module ) {
1152 $states[$name] = 'ready';
1156 // Set the state of modules we didn't respond to with mw.loader.implement
1157 if ( count( $states ) ) {
1158 $stateScript = self
::makeLoaderStateScript( $states );
1159 if ( !$context->getDebug() ) {
1160 $stateScript = self
::filter( 'minify-js', $stateScript );
1162 // Use a linebreak between module script and state script (T162719)
1163 $out = $this->ensureNewline( $out ) . $stateScript;
1167 // Keep default escaping of slashes (e.g. "</script>") for ResourceLoaderClientHtml.
1168 $this->errors
[] = 'Problematic modules: ' . json_encode( $states, JSON_PRETTY_PRINT
);
1176 * Ensure the string is either empty or ends in a line break
1177 * @param string $str
1180 private function ensureNewline( $str ) {
1181 $end = substr( $str, -1 );
1182 if ( $end === false ||
$end === "\n" ) {
1189 * Get names of modules that use a certain message.
1191 * @param string $messageKey
1192 * @return array List of module names
1194 public function getModulesByMessage( $messageKey ) {
1196 foreach ( $this->getModuleNames() as $moduleName ) {
1197 $module = $this->getModule( $moduleName );
1198 if ( in_array( $messageKey, $module->getMessages() ) ) {
1199 $moduleNames[] = $moduleName;
1202 return $moduleNames;
1206 * Return JS code that calls mw.loader.implement with given module properties.
1208 * @param string $name Module name or implement key (format "`[name]@[version]`")
1209 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1210 * list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
1211 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1212 * to CSS files keyed by media type
1213 * @param mixed $messages List of messages associated with this module. May either be an
1214 * associative array mapping message key to value, or a JSON-encoded message blob containing
1215 * the same data, wrapped in an XmlJsCode object.
1216 * @param array $templates Keys are name of templates and values are the source of
1218 * @throws MWException
1219 * @return string JavaScript code
1221 protected static function makeLoaderImplementScript(
1222 $name, $scripts, $styles, $messages, $templates
1224 if ( $scripts instanceof XmlJsCode
) {
1225 if ( self
::inDebugMode() ) {
1226 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1228 $scripts = new XmlJsCode( 'function($,jQuery,require,module){'. $scripts->value
. '}' );
1230 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1231 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1233 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1234 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1235 // of "{}". Force them to objects.
1243 self
::trimArray( $module );
1245 return Xml
::encodeJsCall( 'mw.loader.implement', $module, self
::inDebugMode() );
1249 * Returns JS code which, when called, will register a given list of messages.
1251 * @param mixed $messages Either an associative array mapping message key to value, or a
1252 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1253 * @return string JavaScript code
1255 public static function makeMessageSetScript( $messages ) {
1256 return Xml
::encodeJsCall(
1258 [ (object)$messages ],
1264 * Combines an associative array mapping media type to CSS into a
1265 * single stylesheet with "@media" blocks.
1267 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1270 public static function makeCombinedStyles( array $stylePairs ) {
1272 foreach ( $stylePairs as $media => $styles ) {
1273 // ResourceLoaderFileModule::getStyle can return the styles
1274 // as a string or an array of strings. This is to allow separation in
1276 $styles = (array)$styles;
1277 foreach ( $styles as $style ) {
1278 $style = trim( $style );
1279 // Don't output an empty "@media print { }" block (T42498)
1280 if ( $style !== '' ) {
1281 // Transform the media type based on request params and config
1282 // The way that this relies on $wgRequest to propagate request params is slightly evil
1283 $media = OutputPage
::transformCssMedia( $media );
1285 if ( $media === '' ||
$media == 'all' ) {
1287 } elseif ( is_string( $media ) ) {
1288 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1298 * Returns a JS call to mw.loader.state, which sets the state of one
1299 * ore more modules to a given value. Has two calling conventions:
1301 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1302 * Set the state of a single module called $name to $state
1304 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1305 * Set the state of modules with the given names to the given states
1307 * @param array|string $states
1308 * @param string|null $state
1309 * @return string JavaScript code
1311 public static function makeLoaderStateScript( $states, $state = null ) {
1312 if ( !is_array( $states ) ) {
1313 $states = [ $states => $state ];
1315 return Xml
::encodeJsCall(
1323 * Returns JS code which calls the script given by $script. The script will
1324 * be called with local variables name, version, dependencies and group,
1325 * which will have values corresponding to $name, $version, $dependencies
1326 * and $group as supplied.
1328 * @param string $name Module name
1329 * @param string $version Module version hash
1330 * @param array $dependencies List of module names on which this module depends
1331 * @param string $group Group which the module is in.
1332 * @param string $source Source of the module, or 'local' if not foreign.
1333 * @param string $script JavaScript code
1334 * @return string JavaScript code
1336 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1337 $group, $source, $script
1339 $script = str_replace( "\n", "\n\t", trim( $script ) );
1340 return Xml
::encodeJsCall(
1341 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1342 [ $name, $version, $dependencies, $group, $source ],
1347 private static function isEmptyObject( stdClass
$obj ) {
1348 foreach ( $obj as $key => $value ) {
1355 * Remove empty values from the end of an array.
1357 * Values considered empty:
1361 * - new XmlJsCode( '{}' )
1362 * - new stdClass() // (object) []
1364 * @param Array $array
1366 private static function trimArray( array &$array ) {
1367 $i = count( $array );
1369 if ( $array[$i] === null
1370 ||
$array[$i] === []
1371 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1372 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1374 unset( $array[$i] );
1382 * Returns JS code which calls mw.loader.register with the given
1383 * parameters. Has three calling conventions:
1385 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1386 * $dependencies, $group, $source, $skip
1388 * Register a single module.
1390 * - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
1391 * Register modules with the given names.
1393 * - ResourceLoader::makeLoaderRegisterScript( [
1394 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1395 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1398 * Registers modules with the given names and parameters.
1400 * @param string $name Module name
1401 * @param string|null $version Module version hash
1402 * @param array|null $dependencies List of module names on which this module depends
1403 * @param string|null $group Group which the module is in
1404 * @param string|null $source Source of the module, or 'local' if not foreign
1405 * @param string|null $skip Script body of the skip function
1406 * @return string JavaScript code
1408 public static function makeLoaderRegisterScript( $name, $version = null,
1409 $dependencies = null, $group = null, $source = null, $skip = null
1411 if ( is_array( $name ) ) {
1412 // Build module name index
1414 foreach ( $name as $i => &$module ) {
1415 $index[$module[0]] = $i;
1418 // Transform dependency names into indexes when possible, they will be resolved by
1419 // mw.loader.register on the other end
1420 foreach ( $name as &$module ) {
1421 if ( isset( $module[2] ) ) {
1422 foreach ( $module[2] as &$dependency ) {
1423 if ( isset( $index[$dependency] ) ) {
1424 $dependency = $index[$dependency];
1430 array_walk( $name, [ 'self', 'trimArray' ] );
1432 return Xml
::encodeJsCall(
1433 'mw.loader.register',
1438 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1439 self
::trimArray( $registration );
1440 return Xml
::encodeJsCall(
1441 'mw.loader.register',
1449 * Returns JS code which calls mw.loader.addSource() with the given
1450 * parameters. Has two calling conventions:
1452 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1453 * Register a single source
1455 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1456 * Register sources with the given IDs and properties.
1458 * @param string $id Source ID
1459 * @param string|null $loadUrl load.php url
1460 * @return string JavaScript code
1462 public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
1463 if ( is_array( $id ) ) {
1464 return Xml
::encodeJsCall(
1465 'mw.loader.addSource',
1470 return Xml
::encodeJsCall(
1471 'mw.loader.addSource',
1479 * Wraps JavaScript code to run after the startup module.
1481 * @param string $script JavaScript code
1482 * @return string JavaScript code
1484 public static function makeLoaderConditionalScript( $script ) {
1485 // Adds a function to lazy-created RLQ
1486 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1487 trim( $script ) . '});';
1491 * Wraps JavaScript code to run after a required module.
1494 * @param string|string[] $modules Module name(s)
1495 * @param string $script JavaScript code
1496 * @return string JavaScript code
1498 public static function makeInlineCodeWithModule( $modules, $script ) {
1499 // Adds an array to lazy-created RLQ
1500 return '(window.RLQ=window.RLQ||[]).push(['
1501 . json_encode( $modules ) . ','
1502 . 'function(){' . trim( $script ) . '}'
1507 * Returns an HTML script tag that runs given JS code after startup and base modules.
1509 * The code will be wrapped in a closure, and it will be executed by ResourceLoader's
1510 * startup module if the client has adequate support for MediaWiki JavaScript code.
1512 * @param string $script JavaScript code
1513 * @param string|null $nonce [optional] Content-Security-Policy nonce
1514 * (from OutputPage::getCSPNonce)
1515 * @return string|WrappedString HTML
1517 public static function makeInlineScript( $script, $nonce = null ) {
1518 $js = self
::makeLoaderConditionalScript( $script );
1520 if ( $nonce === null ) {
1521 wfWarn( __METHOD__
. " did not get nonce. Will break CSP" );
1522 } elseif ( $nonce !== false ) {
1523 // If it was false, CSP is disabled, so no nonce attribute.
1524 // Nonce should be only base64 characters, so should be safe,
1525 // but better to be safely escaped than sorry.
1526 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1529 return new WrappedString(
1530 Html
::inlineScript( $js, $nonce ),
1531 "<script$escNonce>(window.RLQ=window.RLQ||[]).push(function(){",
1537 * Returns JS code which will set the MediaWiki configuration array to
1540 * @param array $configuration List of configuration values keyed by variable name
1541 * @return string JavaScript code
1543 public static function makeConfigSetScript( array $configuration ) {
1544 return Xml
::encodeJsCall(
1552 * Convert an array of module names to a packed query string.
1554 * For example, `[ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]`
1555 * becomes `'foo.bar,baz|bar.baz,quux'`.
1557 * This process is reversed by ResourceLoaderContext::expandModuleNames().
1558 * See also mw.loader#buildModulesString() which is a port of this, used
1559 * on the client-side.
1561 * @param array $modules List of module names (strings)
1562 * @return string Packed query string
1564 public static function makePackedModulesString( $modules ) {
1565 $moduleMap = []; // [ prefix => [ suffixes ] ]
1566 foreach ( $modules as $module ) {
1567 $pos = strrpos( $module, '.' );
1568 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1569 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1570 $moduleMap[$prefix][] = $suffix;
1574 foreach ( $moduleMap as $prefix => $suffixes ) {
1575 $p = $prefix === '' ?
'' : $prefix . '.';
1576 $arr[] = $p . implode( ',', $suffixes );
1578 return implode( '|', $arr );
1582 * Determine whether debug mode was requested
1583 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1586 public static function inDebugMode() {
1587 if ( self
::$debugMode === null ) {
1588 global $wgRequest, $wgResourceLoaderDebug;
1589 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1590 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1593 return self
::$debugMode;
1597 * Reset static members used for caching.
1599 * Global state and $wgRequest are evil, but we're using it right
1600 * now and sometimes we need to be able to force ResourceLoader to
1601 * re-evaluate the context because it has changed (e.g. in the test suite).
1603 public static function clearCache() {
1604 self
::$debugMode = null;
1608 * Build a load.php URL
1611 * @param string $source Name of the ResourceLoader source
1612 * @param ResourceLoaderContext $context
1613 * @param array $extraQuery
1614 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1616 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1619 $query = self
::createLoaderQuery( $context, $extraQuery );
1620 $script = $this->getLoadScript( $source );
1622 return wfAppendQuery( $script, $query );
1626 * Helper for createLoaderURL()
1629 * @see makeLoaderQuery
1630 * @param ResourceLoaderContext $context
1631 * @param array $extraQuery
1634 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1635 return self
::makeLoaderQuery(
1636 $context->getModules(),
1637 $context->getLanguage(),
1638 $context->getSkin(),
1639 $context->getUser(),
1640 $context->getVersion(),
1641 $context->getDebug(),
1642 $context->getOnly(),
1643 $context->getRequest()->getBool( 'printable' ),
1644 $context->getRequest()->getBool( 'handheld' ),
1650 * Build a query array (array representation of query string) for load.php. Helper
1651 * function for createLoaderURL().
1653 * @param array $modules
1654 * @param string $lang
1655 * @param string $skin
1656 * @param string|null $user
1657 * @param string|null $version
1658 * @param bool $debug
1659 * @param string|null $only
1660 * @param bool $printable
1661 * @param bool $handheld
1662 * @param array $extraQuery
1666 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1667 $version = null, $debug = false, $only = null, $printable = false,
1668 $handheld = false, $extraQuery = []
1671 'modules' => self
::makePackedModulesString( $modules ),
1674 'debug' => $debug ?
'true' : 'false',
1676 if ( $user !== null ) {
1677 $query['user'] = $user;
1679 if ( $version !== null ) {
1680 $query['version'] = $version;
1682 if ( $only !== null ) {
1683 $query['only'] = $only;
1686 $query['printable'] = 1;
1689 $query['handheld'] = 1;
1691 $query +
= $extraQuery;
1693 // Make queries uniform in order
1699 * Check a module name for validity.
1701 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1702 * at most 255 bytes.
1704 * @param string $moduleName Module name to check
1705 * @return bool Whether $moduleName is a valid module name
1707 public static function isValidModuleName( $moduleName ) {
1708 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1712 * Returns LESS compiler set up for use with MediaWiki
1715 * @param array $vars Associative array of variables that should be used
1716 * for compilation. Since 1.32, this method no longer automatically includes
1717 * global LESS vars from ResourceLoader::getLessVars (T191937).
1718 * @throws MWException
1719 * @return Less_Parser
1721 public function getLessCompiler( $vars = [] ) {
1723 // When called from the installer, it is possible that a required PHP extension
1724 // is missing (at least for now; see T49564). If this is the case, throw an
1725 // exception (caught by the installer) to prevent a fatal error later on.
1726 if ( !class_exists( 'Less_Parser' ) ) {
1727 throw new MWException( 'MediaWiki requires the less.php parser' );
1730 $parser = new Less_Parser
;
1731 $parser->ModifyVars( $vars );
1732 $parser->SetImportDirs( [
1733 "$IP/resources/src/mediawiki.less/" => '',
1735 $parser->SetOption( 'relativeUrls', false );
1741 * Get global LESS variables.
1744 * @deprecated since 1.32 Use ResourceLoderModule::getLessVars() instead.
1745 * @return array Map of variable names to string CSS values.
1747 public function getLessVars() {