3 * Base class for resource loading system.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Roan Kattouw
22 * @author Trevor Parscal
25 use MediaWiki\MediaWikiServices
;
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
28 use Psr\Log\NullLogger
;
29 use Wikimedia\Rdbms\DBConnectionError
;
30 use Wikimedia\WrappedString
;
33 * Dynamic JavaScript and CSS resource loading system.
35 * Most of the documentation is on the MediaWiki documentation wiki starting at:
36 * https://www.mediawiki.org/wiki/ResourceLoader
38 class ResourceLoader
implements LoggerAwareInterface
{
40 const CACHE_VERSION
= 8;
43 protected static $debugMode = null;
46 * Module name/ResourceLoaderModule object pairs
49 protected $modules = [];
52 * Associative array mapping module name to info associative array
55 protected $moduleInfos = [];
57 /** @var Config $config */
61 * Associative array mapping framework ids to a list of names of test suite modules
62 * like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... ], ... ]
65 protected $testModuleNames = [];
68 * E.g. [ 'source-id' => 'http://.../load.php' ]
71 protected $sources = [];
74 * Errors accumulated during current respond() call.
77 protected $errors = [];
80 * List of extra HTTP response headers provided by loaded modules.
82 * Populated by makeModuleResponse().
86 protected $extraHeaders = [];
89 * @var MessageBlobStore
94 * @var LoggerInterface
98 /** @var string JavaScript / CSS pragma to disable minification. **/
99 const FILTER_NOMIN
= '/*@nomin*/';
102 * Load information stored in the database about modules.
104 * This method grabs modules dependencies from the database and updates modules
107 * This is not inside the module code because it is much faster to
108 * request all of the information at once than it is to have each module
109 * requests its own information. This sacrifice of modularity yields a substantial
110 * performance improvement.
112 * @param array $moduleNames List of module names to preload information for
113 * @param ResourceLoaderContext $context Context to load the information within
115 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext
$context ) {
116 if ( !$moduleNames ) {
117 // Or else Database*::select() will explode, plus it's cheaper!
120 $dbr = wfGetDB( DB_REPLICA
);
121 $skin = $context->getSkin();
122 $lang = $context->getLanguage();
124 // Batched version of ResourceLoaderModule::getFileDependencies
125 $vary = "$skin|$lang";
126 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
127 'md_module' => $moduleNames,
132 // Prime in-object cache for file dependencies
133 $modulesWithDeps = [];
134 foreach ( $res as $row ) {
135 $module = $this->getModule( $row->md_module
);
137 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
138 json_decode( $row->md_deps
, true )
140 $modulesWithDeps[] = $row->md_module
;
143 // Register the absence of a dependency row too
144 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
145 $module = $this->getModule( $name );
147 $this->getModule( $name )->setFileDependencies( $context, [] );
151 // Batched version of ResourceLoaderWikiModule::getTitleInfo
152 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $moduleNames );
154 // Prime in-object cache for message blobs for modules with messages
156 foreach ( $moduleNames as $name ) {
157 $module = $this->getModule( $name );
158 if ( $module && $module->getMessages() ) {
159 $modules[$name] = $module;
162 $store = $this->getMessageBlobStore();
163 $blobs = $store->getBlobs( $modules, $lang );
164 foreach ( $blobs as $name => $blob ) {
165 $modules[$name]->setMessageBlob( $blob, $lang );
170 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
172 * Available filters are:
174 * - minify-js \see JavaScriptMinifier::minify
175 * - minify-css \see CSSMin::minify
177 * If $data is empty, only contains whitespace or the filter was unknown,
178 * $data is returned unmodified.
180 * @param string $filter Name of filter to run
181 * @param string $data Text to filter, such as JavaScript or CSS text
182 * @param array $options Keys:
183 * - (bool) cache: Whether to allow caching this data. Default: true.
184 * @return string Filtered data, or a comment containing an error message
186 public static function filter( $filter, $data, array $options = [] ) {
187 if ( strpos( $data, self
::FILTER_NOMIN
) !== false ) {
191 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
192 return self
::applyFilter( $filter, $data );
195 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
196 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
198 $key = $cache->makeGlobalKey(
206 $result = $cache->get( $key );
207 if ( $result === false ) {
208 $stats->increment( "resourceloader_cache.$filter.miss" );
209 $result = self
::applyFilter( $filter, $data );
210 $cache->set( $key, $result, 24 * 3600 );
212 $stats->increment( "resourceloader_cache.$filter.hit" );
214 if ( $result === null ) {
222 private static function applyFilter( $filter, $data ) {
223 $data = trim( $data );
226 $data = ( $filter === 'minify-css' )
227 ? CSSMin
::minify( $data )
228 : JavaScriptMinifier
::minify( $data );
229 } catch ( Exception
$e ) {
230 MWExceptionHandler
::logException( $e );
238 * Register core modules and runs registration hooks.
239 * @param Config|null $config [optional]
240 * @param LoggerInterface|null $logger [optional]
242 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
245 $this->logger
= $logger ?
: new NullLogger();
248 // TODO: Deprecate and remove.
249 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
250 $config = MediaWikiServices
::getInstance()->getMainConfig();
252 $this->config
= $config;
254 // Add 'local' source first
255 $this->addSource( 'local', $config->get( 'LoadScript' ) );
257 // Register core modules
258 $this->register( include "$IP/resources/Resources.php" );
259 // Register extension modules
260 $this->register( $config->get( 'ResourceModules' ) );
262 // Avoid PHP 7.1 warning from passing $this by reference
264 Hooks
::run( 'ResourceLoaderRegisterModules', [ &$rl ] );
266 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
267 $this->registerTestModules();
270 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
276 public function getConfig() {
277 return $this->config
;
282 * @param LoggerInterface $logger
284 public function setLogger( LoggerInterface
$logger ) {
285 $this->logger
= $logger;
290 * @return LoggerInterface
292 public function getLogger() {
293 return $this->logger
;
298 * @return MessageBlobStore
300 public function getMessageBlobStore() {
301 return $this->blobStore
;
306 * @param MessageBlobStore $blobStore
308 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
309 $this->blobStore
= $blobStore;
313 * Register a module with the ResourceLoader system.
315 * @param mixed $name Name of module as a string or List of name/object pairs as an array
316 * @param array|null $info Module info array. For backwards compatibility with 1.17alpha,
317 * this may also be a ResourceLoaderModule object. Optional when using
318 * multiple-registration calling style.
319 * @throws MWException If a duplicate module registration is attempted
320 * @throws MWException If a module name contains illegal characters (pipes or commas)
321 * @throws MWException If something other than a ResourceLoaderModule is being registered
323 public function register( $name, $info = null ) {
324 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
326 // Allow multiple modules to be registered in one call
327 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
328 foreach ( $registrations as $name => $info ) {
329 // Warn on duplicate registrations
330 if ( isset( $this->moduleInfos
[$name] ) ) {
331 // A module has already been registered by this name
332 $this->logger
->warning(
333 'ResourceLoader duplicate registration warning. ' .
334 'Another module has already been registered as ' . $name
338 // Check $name for validity
339 if ( !self
::isValidModuleName( $name ) ) {
340 throw new MWException( "ResourceLoader module name '$name' is invalid, "
341 . "see ResourceLoader::isValidModuleName()" );
345 if ( $info instanceof ResourceLoaderModule
) {
346 $this->moduleInfos
[$name] = [ 'object' => $info ];
347 $info->setName( $name );
348 $this->modules
[$name] = $info;
349 } elseif ( is_array( $info ) ) {
350 // New calling convention
351 $this->moduleInfos
[$name] = $info;
353 throw new MWException(
354 'ResourceLoader module info type error for module \'' . $name .
355 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
359 // Last-minute changes
361 // Apply custom skin-defined styles to existing modules.
362 if ( $this->isFileModule( $name ) ) {
363 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
364 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
365 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
369 // If $name is preceded with a '+', the defined style files will be added to 'default'
370 // skinStyles, otherwise 'default' will be ignored as it normally would be.
371 if ( isset( $skinStyles[$name] ) ) {
372 $paths = (array)$skinStyles[$name];
374 } elseif ( isset( $skinStyles['+' . $name] ) ) {
375 $paths = (array)$skinStyles['+' . $name];
376 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
377 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
383 // Add new file paths, remapping them to refer to our directories and not use settings
384 // from the module we're modifying, which come from the base definition.
385 list( $localBasePath, $remoteBasePath ) =
386 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
388 foreach ( $paths as $path ) {
389 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
392 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
398 public function registerTestModules() {
401 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
402 throw new MWException( 'Attempt to register JavaScript test modules '
403 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
404 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
411 // Get test suites from extensions
412 // Avoid PHP 7.1 warning from passing $this by reference
414 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
415 $extRegistry = ExtensionRegistry
::getInstance();
416 // In case of conflict, the deprecated hook has precedence.
417 $testModules['qunit'] +
= $extRegistry->getAttribute( 'QUnitTestModules' );
419 // Add the QUnit testrunner as implicit dependency to extension test suites.
420 foreach ( $testModules['qunit'] as &$module ) {
421 // Shuck any single-module dependency as an array
422 if ( isset( $module['dependencies'] ) && is_string( $module['dependencies'] ) ) {
423 $module['dependencies'] = [ $module['dependencies'] ];
426 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
429 // Get core test suites
430 $testModules['qunit'] =
431 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
433 foreach ( $testModules as $id => $names ) {
434 // Register test modules
435 $this->register( $testModules[$id] );
437 // Keep track of their names so that they can be loaded together
438 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
443 * Add a foreign source of modules.
445 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
447 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
448 * @param string|array|null $loadUrl load.php url (string), or array with loadUrl key for
449 * backwards-compatibility.
450 * @throws MWException
452 public function addSource( $id, $loadUrl = null ) {
453 // Allow multiple sources to be registered in one call
454 if ( is_array( $id ) ) {
455 foreach ( $id as $key => $value ) {
456 $this->addSource( $key, $value );
461 // Disallow duplicates
462 if ( isset( $this->sources
[$id] ) ) {
463 throw new MWException(
464 'ResourceLoader duplicate source addition error. ' .
465 'Another source has already been registered as ' . $id
469 // Pre 1.24 backwards-compatibility
470 if ( is_array( $loadUrl ) ) {
471 if ( !isset( $loadUrl['loadScript'] ) ) {
472 throw new MWException(
473 __METHOD__
. ' was passed an array with no "loadScript" key.'
477 $loadUrl = $loadUrl['loadScript'];
480 $this->sources
[$id] = $loadUrl;
484 * Get a list of module names.
486 * @return array List of module names
488 public function getModuleNames() {
489 return array_keys( $this->moduleInfos
);
493 * Get a list of test module names for one (or all) frameworks.
495 * If the given framework id is unknkown, or if the in-object variable is not an array,
496 * then it will return an empty array.
498 * @param string $framework Get only the test module names for one
499 * particular framework (optional)
502 public function getTestModuleNames( $framework = 'all' ) {
503 /** @todo api siteinfo prop testmodulenames modulenames */
504 if ( $framework == 'all' ) {
505 return $this->testModuleNames
;
506 } elseif ( isset( $this->testModuleNames
[$framework] )
507 && is_array( $this->testModuleNames
[$framework] )
509 return $this->testModuleNames
[$framework];
516 * Check whether a ResourceLoader module is registered
519 * @param string $name
522 public function isModuleRegistered( $name ) {
523 return isset( $this->moduleInfos
[$name] );
527 * Get the ResourceLoaderModule object for a given module name.
529 * If an array of module parameters exists but a ResourceLoaderModule object has not
530 * yet been instantiated, this method will instantiate and cache that object such that
531 * subsequent calls simply return the same object.
533 * @param string $name Module name
534 * @return ResourceLoaderModule|null If module has been registered, return a
535 * ResourceLoaderModule instance. Otherwise, return null.
537 public function getModule( $name ) {
538 if ( !isset( $this->modules
[$name] ) ) {
539 if ( !isset( $this->moduleInfos
[$name] ) ) {
543 // Construct the requested object
544 $info = $this->moduleInfos
[$name];
545 /** @var ResourceLoaderModule $object */
546 if ( isset( $info['object'] ) ) {
547 // Object given in info array
548 $object = $info['object'];
549 } elseif ( isset( $info['factory'] ) ) {
550 $object = call_user_func( $info['factory'], $info );
551 $object->setConfig( $this->getConfig() );
552 $object->setLogger( $this->logger
);
554 $class = $info['class'] ?? ResourceLoaderFileModule
::class;
555 /** @var ResourceLoaderModule $object */
556 $object = new $class( $info );
557 $object->setConfig( $this->getConfig() );
558 $object->setLogger( $this->logger
);
560 $object->setName( $name );
561 $this->modules
[$name] = $object;
564 return $this->modules
[$name];
568 * Whether the module is a ResourceLoaderFileModule (including subclasses).
570 * @param string $name Module name
573 protected function isFileModule( $name ) {
574 if ( !isset( $this->moduleInfos
[$name] ) ) {
577 $info = $this->moduleInfos
[$name];
578 if ( isset( $info['object'] ) ) {
582 // The implied default for 'class' is ResourceLoaderFileModule
583 !isset( $info['class'] ) ||
585 $info['class'] === ResourceLoaderFileModule
::class ||
586 is_subclass_of( $info['class'], ResourceLoaderFileModule
::class )
591 * Get the list of sources.
593 * @return array Like [ id => load.php url, ... ]
595 public function getSources() {
596 return $this->sources
;
600 * Get the URL to the load.php endpoint for the given
601 * ResourceLoader source
604 * @param string $source
605 * @throws MWException On an invalid $source name
608 public function getLoadScript( $source ) {
609 if ( !isset( $this->sources
[$source] ) ) {
610 throw new MWException( "The $source source was never registered in ResourceLoader." );
612 return $this->sources
[$source];
617 * @param string $value
618 * @return string Hash
620 public static function makeHash( $value ) {
621 $hash = hash( 'fnv132', $value );
622 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
626 * Add an error to the 'errors' array and log it.
628 * @private For internal use by ResourceLoader and ResourceLoaderStartUpModule.
630 * @param Exception $e
632 * @param array $context
634 public function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
635 MWExceptionHandler
::logException( $e );
636 $this->logger
->warning(
638 $context +
[ 'exception' => $e ]
640 $this->errors
[] = self
::formatExceptionNoComment( $e );
644 * Helper method to get and combine versions of multiple modules.
647 * @param ResourceLoaderContext $context
648 * @param string[] $moduleNames List of known module names
649 * @return string Hash
651 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
652 if ( !$moduleNames ) {
655 $hashes = array_map( function ( $module ) use ( $context ) {
657 return $this->getModule( $module )->getVersionHash( $context );
658 } catch ( Exception
$e ) {
659 // If modules fail to compute a version, don't fail the request (T152266)
660 // and still compute versions of other modules.
661 $this->outputErrorAndLog( $e,
662 'Calculating version for "{module}" failed: {exception}',
670 return self
::makeHash( implode( '', $hashes ) );
674 * Get the expected value of the 'version' query parameter.
676 * This is used by respond() to set a short Cache-Control header for requests with
677 * information newer than the current server has. This avoids pollution of edge caches.
678 * Typically during deployment. (T117587)
680 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
683 * @param ResourceLoaderContext $context
684 * @return string Hash
686 public function makeVersionQuery( ResourceLoaderContext
$context ) {
687 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
688 // version hashes. There is no technical reason for this to be same, and for years the
689 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
690 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
691 // query parameter), then this method must continue to match the JS one.
693 foreach ( $context->getModules() as $name ) {
694 if ( !$this->getModule( $name ) ) {
695 // If a versioned request contains a missing module, the version is a mismatch
696 // as the client considered a module (and version) we don't have.
699 $moduleNames[] = $name;
701 return $this->getCombinedVersion( $context, $moduleNames );
705 * Output a response to a load request, including the content-type header.
707 * @param ResourceLoaderContext $context Context in which a response should be formed
709 public function respond( ResourceLoaderContext
$context ) {
710 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
711 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
712 // is used: ob_clean() will clear the GZIP header in that case and it won't come
713 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
714 // the whole thing in our own output buffer to be sure the active buffer
715 // doesn't use ob_gzhandler.
716 // See https://bugs.php.net/bug.php?id=36514
719 $this->measureResponseTime( RequestContext
::getMain()->getTiming() );
721 // Find out which modules are missing and instantiate the others
724 foreach ( $context->getModules() as $name ) {
725 $module = $this->getModule( $name );
727 // Do not allow private modules to be loaded from the web.
728 // This is a security issue, see T36907.
729 if ( $module->getGroup() === 'private' ) {
730 $this->logger
->debug( "Request for private module '$name' denied" );
731 $this->errors
[] = "Cannot show private module \"$name\"";
734 $modules[$name] = $module;
741 // Preload for getCombinedVersion() and for batch makeModuleResponse()
742 $this->preloadModuleInfo( array_keys( $modules ), $context );
743 } catch ( Exception
$e ) {
744 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
747 // Combine versions to propagate cache invalidation
750 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
751 } catch ( Exception
$e ) {
752 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
755 // See RFC 2616 § 3.11 Entity Tags
756 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
757 $etag = 'W/"' . $versionHash . '"';
759 // Try the client-side cache first
760 if ( $this->tryRespondNotModified( $context, $etag ) ) {
761 return; // output handled (buffers cleared)
764 // Use file cache if enabled and available...
765 if ( $this->config
->get( 'UseFileCache' ) ) {
766 $fileCache = ResourceFileCache
::newFromContext( $context );
767 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
768 return; // output handled
772 // Generate a response
773 $response = $this->makeModuleResponse( $context, $modules, $missing );
775 // Capture any PHP warnings from the output buffer and append them to the
776 // error list if we're in debug mode.
777 if ( $context->getDebug() ) {
778 $warnings = ob_get_contents();
779 if ( strlen( $warnings ) ) {
780 $this->errors
[] = $warnings;
784 // Save response to file cache unless there are errors
785 if ( isset( $fileCache ) && !$this->errors
&& $missing === [] ) {
786 // Cache single modules and images...and other requests if there are enough hits
787 if ( ResourceFileCache
::useFileCache( $context ) ) {
788 if ( $fileCache->isCacheWorthy() ) {
789 $fileCache->saveText( $response );
791 $fileCache->incrMissesRecent( $context->getRequest() );
796 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
, $this->extraHeaders
);
798 // Remove the output buffer and output the response
801 if ( $context->getImageObj() && $this->errors
) {
802 // We can't show both the error messages and the response when it's an image.
803 $response = implode( "\n\n", $this->errors
);
804 } elseif ( $this->errors
) {
805 $errorText = implode( "\n\n", $this->errors
);
806 $errorResponse = self
::makeComment( $errorText );
807 if ( $context->shouldIncludeScripts() ) {
808 $errorResponse .= 'if (window.console && console.error) {'
809 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
813 // Prepend error info to the response
814 $response = $errorResponse . $response;
821 protected function measureResponseTime( Timing
$timing ) {
822 DeferredUpdates
::addCallableUpdate( function () use ( $timing ) {
823 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
824 if ( $measure !== false ) {
825 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
826 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
832 * Send main response headers to the client.
834 * Deals with Content-Type, CORS (for stylesheets), and caching.
836 * @param ResourceLoaderContext $context
837 * @param string $etag ETag header value
838 * @param bool $errors Whether there are errors in the response
839 * @param string[] $extra Array of extra HTTP response headers
842 protected function sendResponseHeaders(
843 ResourceLoaderContext
$context, $etag, $errors, array $extra = []
845 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
846 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
847 // Use a short cache expiry so that updates propagate to clients quickly, if:
848 // - No version specified (shared resources, e.g. stylesheets)
849 // - There were errors (recover quickly)
850 // - Version mismatch (T117587, T47877)
851 if ( is_null( $context->getVersion() )
853 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
855 $maxage = $rlMaxage['unversioned']['client'];
856 $smaxage = $rlMaxage['unversioned']['server'];
857 // If a version was specified we can use a longer expiry time since changing
858 // version numbers causes cache misses
860 $maxage = $rlMaxage['versioned']['client'];
861 $smaxage = $rlMaxage['versioned']['server'];
863 if ( $context->getImageObj() ) {
864 // Output different headers if we're outputting textual errors.
866 header( 'Content-Type: text/plain; charset=utf-8' );
868 $context->getImageObj()->sendResponseHeaders( $context );
870 } elseif ( $context->getOnly() === 'styles' ) {
871 header( 'Content-Type: text/css; charset=utf-8' );
872 header( 'Access-Control-Allow-Origin: *' );
874 header( 'Content-Type: text/javascript; charset=utf-8' );
876 // See RFC 2616 § 14.19 ETag
877 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
878 header( 'ETag: ' . $etag );
879 if ( $context->getDebug() ) {
880 // Do not cache debug responses
881 header( 'Cache-Control: private, no-cache, must-revalidate' );
882 header( 'Pragma: no-cache' );
884 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
885 $exp = min( $maxage, $smaxage );
886 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
888 foreach ( $extra as $header ) {
894 * Respond with HTTP 304 Not Modified if appropiate.
896 * If there's an If-None-Match header, respond with a 304 appropriately
897 * and clear out the output buffer. If the client cache is too old then do nothing.
899 * @param ResourceLoaderContext $context
900 * @param string $etag ETag header value
901 * @return bool True if HTTP 304 was sent and output handled
903 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
904 // See RFC 2616 § 14.26 If-None-Match
905 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
906 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
907 // Never send 304s in debug mode
908 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
909 // There's another bug in ob_gzhandler (see also the comment at
910 // the top of this function) that causes it to gzip even empty
911 // responses, meaning it's impossible to produce a truly empty
912 // response (because the gzip header is always there). This is
913 // a problem because 304 responses have to be completely empty
914 // per the HTTP spec, and Firefox behaves buggily when they're not.
915 // See also https://bugs.php.net/bug.php?id=51579
916 // To work around this, we tear down all output buffering before
918 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
920 HttpStatus
::header( 304 );
922 $this->sendResponseHeaders( $context, $etag, false );
929 * Send out code for a response from file cache if possible.
931 * @param ResourceFileCache $fileCache Cache object for this request URL
932 * @param ResourceLoaderContext $context Context in which to generate a response
933 * @param string $etag ETag header value
934 * @return bool If this found a cache file and handled the response
936 protected function tryRespondFromFileCache(
937 ResourceFileCache
$fileCache,
938 ResourceLoaderContext
$context,
941 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
942 // Buffer output to catch warnings.
944 // Get the maximum age the cache can be
945 $maxage = is_null( $context->getVersion() )
946 ?
$rlMaxage['unversioned']['server']
947 : $rlMaxage['versioned']['server'];
948 // Minimum timestamp the cache file must have
949 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
951 try { // RL always hits the DB on file cache miss...
952 wfGetDB( DB_REPLICA
);
953 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
954 $good = $fileCache->isCacheGood(); // cache existence check
958 $ts = $fileCache->cacheTimestamp();
959 // Send content type and cache headers
960 $this->sendResponseHeaders( $context, $etag, false );
961 $response = $fileCache->fetchText();
962 // Capture any PHP warnings from the output buffer and append them to the
963 // response in a comment if we're in debug mode.
964 if ( $context->getDebug() ) {
965 $warnings = ob_get_contents();
966 if ( strlen( $warnings ) ) {
967 $response = self
::makeComment( $warnings ) . $response;
970 // Remove the output buffer and output the response
972 echo $response . "\n/* Cached {$ts} */";
973 return true; // cache hit
978 return false; // cache miss
982 * Generate a CSS or JS comment block.
984 * Only use this for public data, not error message details.
986 * @param string $text
989 public static function makeComment( $text ) {
990 $encText = str_replace( '*/', '* /', $text );
991 return "/*\n$encText\n*/\n";
995 * Handle exception display.
997 * @param Exception $e Exception to be shown to the user
998 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
1000 public static function formatException( $e ) {
1001 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
1005 * Handle exception display.
1008 * @param Exception $e Exception to be shown to the user
1009 * @return string Sanitized text that can be returned to the user
1011 protected static function formatExceptionNoComment( $e ) {
1012 global $wgShowExceptionDetails;
1014 if ( !$wgShowExceptionDetails ) {
1015 return MWExceptionHandler
::getPublicLogMessage( $e );
1018 return MWExceptionHandler
::getLogMessage( $e ) .
1020 MWExceptionHandler
::getRedactedTraceAsString( $e );
1024 * Generate code for a response.
1026 * Calling this method also populates the `errors` and `headers` members,
1027 * later used by respond().
1029 * @param ResourceLoaderContext $context Context in which to generate a response
1030 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1031 * @param string[] $missing List of requested module names that are unregistered (optional)
1032 * @return string Response data
1034 public function makeModuleResponse( ResourceLoaderContext
$context,
1035 array $modules, array $missing = []
1040 if ( $modules === [] && $missing === [] ) {
1042 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1043 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1044 no modules were requested. Max made me put this here. */
1048 $image = $context->getImageObj();
1050 $data = $image->getImageData( $context );
1051 if ( $data === false ) {
1053 $this->errors
[] = 'Image generation failed';
1058 foreach ( $missing as $name ) {
1059 $states[$name] = 'missing';
1065 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1067 foreach ( $modules as $name => $module ) {
1069 $content = $module->getModuleContent( $context );
1070 $implementKey = $name . '@' . $module->getVersionHash( $context );
1073 if ( isset( $content['headers'] ) ) {
1074 $this->extraHeaders
= array_merge( $this->extraHeaders
, $content['headers'] );
1078 switch ( $context->getOnly() ) {
1080 $scripts = $content['scripts'];
1081 if ( is_string( $scripts ) ) {
1082 // Load scripts raw...
1083 $strContent = $scripts;
1084 } elseif ( is_array( $scripts ) ) {
1085 // ...except when $scripts is an array of URLs or an associative array
1086 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1090 $styles = $content['styles'];
1091 // We no longer separate into media, they are all combined now with
1092 // custom media type groups into @media .. {} sections as part of the css string.
1093 // Module returns either an empty array or a numerical array with css strings.
1094 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1097 $scripts = $content['scripts'] ??
'';
1098 if ( is_string( $scripts ) ) {
1099 if ( $name === 'site' ||
$name === 'user' ) {
1100 // Legacy scripts that run in the global scope without a closure.
1101 // mw.loader.implement will use globalEval if scripts is a string.
1102 // Minify manually here, because general response minification is
1103 // not effective due it being a string literal, not a function.
1104 if ( !$context->getDebug() ) {
1105 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1108 $scripts = new XmlJsCode( $scripts );
1111 $strContent = self
::makeLoaderImplementScript(
1114 $content['styles'] ??
[],
1115 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1116 $content['templates'] ??
[]
1121 if ( !$context->getDebug() ) {
1122 $strContent = self
::filter( $filter, $strContent );
1125 if ( $context->getOnly() === 'scripts' ) {
1126 // Use a linebreak between module scripts (T162719)
1127 $out .= $this->ensureNewline( $strContent );
1129 $out .= $strContent;
1132 } catch ( Exception
$e ) {
1133 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1135 // Respond to client with error-state instead of module implementation
1136 $states[$name] = 'error';
1137 unset( $modules[$name] );
1139 $isRaw |
= $module->isRaw();
1142 // Update module states
1143 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1144 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1145 // Set the state of modules loaded as only scripts to ready as
1146 // they don't have an mw.loader.implement wrapper that sets the state
1147 foreach ( $modules as $name => $module ) {
1148 $states[$name] = 'ready';
1152 // Set the state of modules we didn't respond to with mw.loader.implement
1153 if ( count( $states ) ) {
1154 $stateScript = self
::makeLoaderStateScript( $states );
1155 if ( !$context->getDebug() ) {
1156 $stateScript = self
::filter( 'minify-js', $stateScript );
1158 // Use a linebreak between module script and state script (T162719)
1159 $out = $this->ensureNewline( $out ) . $stateScript;
1161 } elseif ( $states ) {
1162 $this->errors
[] = 'Problematic modules: '
1163 . self
::encodeJsonForScript( $states );
1170 * Ensure the string is either empty or ends in a line break
1171 * @param string $str
1174 private function ensureNewline( $str ) {
1175 $end = substr( $str, -1 );
1176 if ( $end === false ||
$end === "\n" ) {
1183 * Get names of modules that use a certain message.
1185 * @param string $messageKey
1186 * @return array List of module names
1188 public function getModulesByMessage( $messageKey ) {
1190 foreach ( $this->getModuleNames() as $moduleName ) {
1191 $module = $this->getModule( $moduleName );
1192 if ( in_array( $messageKey, $module->getMessages() ) ) {
1193 $moduleNames[] = $moduleName;
1196 return $moduleNames;
1200 * Return JS code that calls mw.loader.implement with given module properties.
1202 * @param string $name Module name or implement key (format "`[name]@[version]`")
1203 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1204 * list of URLs to JavaScript files, string of JavaScript for `$.globalEval`, or array with
1205 * 'files' and 'main' properties (see ResourceLoaderModule::getScript())
1206 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1207 * to CSS files keyed by media type
1208 * @param mixed $messages List of messages associated with this module. May either be an
1209 * associative array mapping message key to value, or a JSON-encoded message blob containing
1210 * the same data, wrapped in an XmlJsCode object.
1211 * @param array $templates Keys are name of templates and values are the source of
1213 * @throws MWException
1214 * @return string JavaScript code
1216 protected static function makeLoaderImplementScript(
1217 $name, $scripts, $styles, $messages, $templates
1219 if ( $scripts instanceof XmlJsCode
) {
1220 if ( $scripts->value
=== '' ) {
1222 } elseif ( self
::inDebugMode() ) {
1223 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1225 $scripts = new XmlJsCode( 'function($,jQuery,require,module){' . $scripts->value
. '}' );
1227 } elseif ( is_array( $scripts ) && isset( $scripts['files'] ) ) {
1228 $files = $scripts['files'];
1229 foreach ( $files as $path => &$file ) {
1230 // $file is changed (by reference) from a descriptor array to the content of the file
1231 // All of these essentially do $file = $file['content'];, some just have wrapping around it
1232 if ( $file['type'] === 'script' ) {
1233 // Multi-file modules only get two parameters ($ and jQuery are being phased out)
1234 if ( self
::inDebugMode() ) {
1235 $file = new XmlJsCode( "function ( require, module ) {\n{$file['content']}\n}" );
1237 $file = new XmlJsCode( 'function(require,module){' . $file['content'] . '}' );
1240 $file = $file['content'];
1243 $scripts = XmlJsCode
::encodeObject( [
1244 'main' => $scripts['main'],
1245 'files' => XmlJsCode
::encodeObject( $files, self
::inDebugMode() )
1246 ], self
::inDebugMode() );
1247 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1248 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1251 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1252 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1253 // of "{}". Force them to objects.
1261 self
::trimArray( $module );
1263 return Xml
::encodeJsCall( 'mw.loader.implement', $module, self
::inDebugMode() );
1267 * Returns JS code which, when called, will register a given list of messages.
1269 * @param mixed $messages Either an associative array mapping message key to value, or a
1270 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1271 * @return string JavaScript code
1273 public static function makeMessageSetScript( $messages ) {
1274 return Xml
::encodeJsCall(
1276 [ (object)$messages ],
1282 * Combines an associative array mapping media type to CSS into a
1283 * single stylesheet with "@media" blocks.
1285 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1288 public static function makeCombinedStyles( array $stylePairs ) {
1290 foreach ( $stylePairs as $media => $styles ) {
1291 // ResourceLoaderFileModule::getStyle can return the styles
1292 // as a string or an array of strings. This is to allow separation in
1294 $styles = (array)$styles;
1295 foreach ( $styles as $style ) {
1296 $style = trim( $style );
1297 // Don't output an empty "@media print { }" block (T42498)
1298 if ( $style !== '' ) {
1299 // Transform the media type based on request params and config
1300 // The way that this relies on $wgRequest to propagate request params is slightly evil
1301 $media = OutputPage
::transformCssMedia( $media );
1303 if ( $media === '' ||
$media == 'all' ) {
1305 } elseif ( is_string( $media ) ) {
1306 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1316 * Wrapper around json_encode that avoids needless escapes,
1317 * and pretty-prints in debug mode.
1321 * @param bool|string|array $data
1322 * @return string JSON
1324 public static function encodeJsonForScript( $data ) {
1325 // Keep output as small as possible by disabling needless escape modes
1326 // that PHP uses by default.
1327 // However, while most module scripts are only served on HTTP responses
1328 // for JavaScript, some modules can also be embedded in the HTML as inline
1329 // scripts. This, and the fact that we sometimes need to export strings
1330 // containing user-generated content and labels that may genuinely contain
1331 // a sequences like "</script>", we need to encode either '/' or '<'.
1332 // By default PHP escapes '/'. Let's escape '<' instead which is less common
1333 // and allows URLs to mostly remain readable.
1334 $jsonFlags = JSON_UNESCAPED_SLASHES |
1335 JSON_UNESCAPED_UNICODE |
1338 if ( self
::inDebugMode() ) {
1339 $jsonFlags |
= JSON_PRETTY_PRINT
;
1341 return json_encode( $data, $jsonFlags );
1345 * Returns a JS call to mw.loader.state, which sets the state of one
1346 * ore more modules to a given value. Has two calling conventions:
1348 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1349 * Set the state of a single module called $name to $state
1351 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1352 * Set the state of modules with the given names to the given states
1354 * @param array|string $states
1355 * @param string|null $state
1356 * @return string JavaScript code
1358 public static function makeLoaderStateScript( $states, $state = null ) {
1359 if ( !is_array( $states ) ) {
1360 $states = [ $states => $state ];
1362 return Xml
::encodeJsCall(
1369 private static function isEmptyObject( stdClass
$obj ) {
1370 foreach ( $obj as $key => $value ) {
1377 * Remove empty values from the end of an array.
1379 * Values considered empty:
1383 * - new XmlJsCode( '{}' )
1384 * - new stdClass() // (object) []
1386 * @param array $array
1388 private static function trimArray( array &$array ) {
1389 $i = count( $array );
1391 if ( $array[$i] === null
1392 ||
$array[$i] === []
1393 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1394 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1396 unset( $array[$i] );
1404 * Returns JS code which calls mw.loader.register with the given
1410 * ResourceLoader::makeLoaderRegisterScript( [
1411 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1412 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1419 * @param array $modules Array of module registration arrays, each containing
1420 * - string: module name
1421 * - string: module version
1422 * - array|null: List of dependencies (optional)
1423 * - string|null: Module group (optional)
1424 * - string|null: Name of foreign module source, or 'local' (optional)
1425 * - string|null: Script body of a skip function (optional)
1426 * @return string JavaScript code
1428 public static function makeLoaderRegisterScript( array $modules ) {
1429 // Optimisation: Transform dependency names into indexes when possible
1430 // to produce smaller output. They are expanded by mw.loader.register on
1431 // the other end using resolveIndexedDependencies().
1433 foreach ( $modules as $i => &$module ) {
1434 // Build module name index
1435 $index[$module[0]] = $i;
1437 foreach ( $modules as &$module ) {
1438 if ( isset( $module[2] ) ) {
1439 foreach ( $module[2] as &$dependency ) {
1440 if ( isset( $index[$dependency] ) ) {
1441 // Replace module name in dependency list with index
1442 $dependency = $index[$dependency];
1448 array_walk( $modules, [ 'self', 'trimArray' ] );
1450 return Xml
::encodeJsCall(
1451 'mw.loader.register',
1458 * Returns JS code which calls mw.loader.addSource() with the given
1459 * parameters. Has two calling conventions:
1461 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1462 * Register a single source
1464 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1465 * Register sources with the given IDs and properties.
1467 * @param string|array $sources Source ID
1468 * @param string|null $loadUrl load.php url
1469 * @return string JavaScript code
1471 public static function makeLoaderSourcesScript( $sources, $loadUrl = null ) {
1472 if ( !is_array( $sources ) ) {
1473 $sources = [ $sources => $loadUrl ];
1475 return Xml
::encodeJsCall(
1476 'mw.loader.addSource',
1483 * Wraps JavaScript code to run after the startup module.
1485 * @param string $script JavaScript code
1486 * @return string JavaScript code
1488 public static function makeLoaderConditionalScript( $script ) {
1489 // Adds a function to lazy-created RLQ
1490 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1491 trim( $script ) . '});';
1495 * Wraps JavaScript code to run after a required module.
1498 * @param string|string[] $modules Module name(s)
1499 * @param string $script JavaScript code
1500 * @return string JavaScript code
1502 public static function makeInlineCodeWithModule( $modules, $script ) {
1503 // Adds an array to lazy-created RLQ
1504 return '(window.RLQ=window.RLQ||[]).push(['
1505 . self
::encodeJsonForScript( $modules ) . ','
1506 . 'function(){' . trim( $script ) . '}'
1511 * Returns an HTML script tag that runs given JS code after startup and base modules.
1513 * The code will be wrapped in a closure, and it will be executed by ResourceLoader's
1514 * startup module if the client has adequate support for MediaWiki JavaScript code.
1516 * @param string $script JavaScript code
1517 * @param string|null $nonce [optional] Content-Security-Policy nonce
1518 * (from OutputPage::getCSPNonce)
1519 * @return string|WrappedString HTML
1521 public static function makeInlineScript( $script, $nonce = null ) {
1522 $js = self
::makeLoaderConditionalScript( $script );
1524 if ( $nonce === null ) {
1525 wfWarn( __METHOD__
. " did not get nonce. Will break CSP" );
1526 } elseif ( $nonce !== false ) {
1527 // If it was false, CSP is disabled, so no nonce attribute.
1528 // Nonce should be only base64 characters, so should be safe,
1529 // but better to be safely escaped than sorry.
1530 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1533 return new WrappedString(
1534 Html
::inlineScript( $js, $nonce ),
1535 "<script$escNonce>(window.RLQ=window.RLQ||[]).push(function(){",
1541 * Returns JS code which will set the MediaWiki configuration array to
1544 * @param array $configuration List of configuration values keyed by variable name
1545 * @return string JavaScript code
1548 public static function makeConfigSetScript( array $configuration ) {
1549 $js = Xml
::encodeJsCall(
1554 if ( $js === false ) {
1556 'JSON serialization of config data failed. ' .
1557 'This usually means the config data is not valid UTF-8.'
1559 MWExceptionHandler
::logException( $e );
1560 $js = Xml
::encodeJsCall( 'mw.log.error', [ $e->__toString() ] );
1566 * Convert an array of module names to a packed query string.
1568 * For example, `[ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]`
1569 * becomes `'foo.bar,baz|bar.baz,quux'`.
1571 * This process is reversed by ResourceLoaderContext::expandModuleNames().
1572 * See also mw.loader#buildModulesString() which is a port of this, used
1573 * on the client-side.
1575 * @param array $modules List of module names (strings)
1576 * @return string Packed query string
1578 public static function makePackedModulesString( $modules ) {
1579 $moduleMap = []; // [ prefix => [ suffixes ] ]
1580 foreach ( $modules as $module ) {
1581 $pos = strrpos( $module, '.' );
1582 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1583 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1584 $moduleMap[$prefix][] = $suffix;
1588 foreach ( $moduleMap as $prefix => $suffixes ) {
1589 $p = $prefix === '' ?
'' : $prefix . '.';
1590 $arr[] = $p . implode( ',', $suffixes );
1592 return implode( '|', $arr );
1596 * Determine whether debug mode was requested
1597 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1600 public static function inDebugMode() {
1601 if ( self
::$debugMode === null ) {
1602 global $wgRequest, $wgResourceLoaderDebug;
1603 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1604 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1607 return self
::$debugMode;
1611 * Reset static members used for caching.
1613 * Global state and $wgRequest are evil, but we're using it right
1614 * now and sometimes we need to be able to force ResourceLoader to
1615 * re-evaluate the context because it has changed (e.g. in the test suite).
1617 * @internal For use by unit tests
1618 * @codeCoverageIgnore
1620 public static function clearCache() {
1621 self
::$debugMode = null;
1625 * Build a load.php URL
1628 * @param string $source Name of the ResourceLoader source
1629 * @param ResourceLoaderContext $context
1630 * @param array $extraQuery
1631 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1633 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1636 $query = self
::createLoaderQuery( $context, $extraQuery );
1637 $script = $this->getLoadScript( $source );
1639 return wfAppendQuery( $script, $query );
1643 * Helper for createLoaderURL()
1646 * @see makeLoaderQuery
1647 * @param ResourceLoaderContext $context
1648 * @param array $extraQuery
1651 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1652 return self
::makeLoaderQuery(
1653 $context->getModules(),
1654 $context->getLanguage(),
1655 $context->getSkin(),
1656 $context->getUser(),
1657 $context->getVersion(),
1658 $context->getDebug(),
1659 $context->getOnly(),
1660 $context->getRequest()->getBool( 'printable' ),
1661 $context->getRequest()->getBool( 'handheld' ),
1667 * Build a query array (array representation of query string) for load.php. Helper
1668 * function for createLoaderURL().
1670 * @param array $modules
1671 * @param string $lang
1672 * @param string $skin
1673 * @param string|null $user
1674 * @param string|null $version
1675 * @param bool $debug
1676 * @param string|null $only
1677 * @param bool $printable
1678 * @param bool $handheld
1679 * @param array $extraQuery
1683 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1684 $version = null, $debug = false, $only = null, $printable = false,
1685 $handheld = false, $extraQuery = []
1688 'modules' => self
::makePackedModulesString( $modules ),
1692 if ( $debug === true ) {
1693 $query['debug'] = 'true';
1695 if ( $user !== null ) {
1696 $query['user'] = $user;
1698 if ( $version !== null ) {
1699 $query['version'] = $version;
1701 if ( $only !== null ) {
1702 $query['only'] = $only;
1705 $query['printable'] = 1;
1708 $query['handheld'] = 1;
1710 $query +
= $extraQuery;
1712 // Make queries uniform in order
1718 * Check a module name for validity.
1720 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1721 * at most 255 bytes.
1723 * @param string $moduleName Module name to check
1724 * @return bool Whether $moduleName is a valid module name
1726 public static function isValidModuleName( $moduleName ) {
1727 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1731 * Returns LESS compiler set up for use with MediaWiki
1734 * @param array $vars Associative array of variables that should be used
1735 * for compilation. Since 1.32, this method no longer automatically includes
1736 * global LESS vars from ResourceLoader::getLessVars (T191937).
1737 * @throws MWException
1738 * @return Less_Parser
1740 public function getLessCompiler( $vars = [] ) {
1742 // When called from the installer, it is possible that a required PHP extension
1743 // is missing (at least for now; see T49564). If this is the case, throw an
1744 // exception (caught by the installer) to prevent a fatal error later on.
1745 if ( !class_exists( 'Less_Parser' ) ) {
1746 throw new MWException( 'MediaWiki requires the less.php parser' );
1749 $parser = new Less_Parser
;
1750 $parser->ModifyVars( $vars );
1751 $parser->SetImportDirs( [
1752 "$IP/resources/src/mediawiki.less/" => '',
1754 $parser->SetOption( 'relativeUrls', false );
1760 * Get global LESS variables.
1763 * @deprecated since 1.32 Use ResourceLoderModule::getLessVars() instead.
1764 * @return array Map of variable names to string CSS values.
1766 public function getLessVars() {