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 * List of module names that contain QUnit test suites
64 protected $testSuiteModuleNames = [];
67 * E.g. [ 'source-id' => 'http://.../load.php' ]
70 protected $sources = [];
73 * Errors accumulated during current respond() call.
76 protected $errors = [];
79 * List of extra HTTP response headers provided by loaded modules.
81 * Populated by makeModuleResponse().
85 protected $extraHeaders = [];
88 * @var MessageBlobStore
93 * @var LoggerInterface
97 /** @var string JavaScript / CSS pragma to disable minification. **/
98 const FILTER_NOMIN
= '/*@nomin*/';
101 * Load information stored in the database about modules.
103 * This method grabs modules dependencies from the database and updates modules
106 * This is not inside the module code because it is much faster to
107 * request all of the information at once than it is to have each module
108 * requests its own information. This sacrifice of modularity yields a substantial
109 * performance improvement.
111 * @param array $moduleNames List of module names to preload information for
112 * @param ResourceLoaderContext $context Context to load the information within
114 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext
$context ) {
115 if ( !$moduleNames ) {
116 // Or else Database*::select() will explode, plus it's cheaper!
119 $dbr = wfGetDB( DB_REPLICA
);
120 $lang = $context->getLanguage();
122 // Batched version of ResourceLoaderModule::getFileDependencies
123 $vary = ResourceLoaderModule
::getVary( $context );
124 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
125 'md_module' => $moduleNames,
130 // Prime in-object cache for file dependencies
131 $modulesWithDeps = [];
132 foreach ( $res as $row ) {
133 $module = $this->getModule( $row->md_module
);
135 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
136 json_decode( $row->md_deps
, true )
138 $modulesWithDeps[] = $row->md_module
;
141 // Register the absence of a dependency row too
142 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
143 $module = $this->getModule( $name );
145 $this->getModule( $name )->setFileDependencies( $context, [] );
149 // Batched version of ResourceLoaderWikiModule::getTitleInfo
150 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $moduleNames );
152 // Prime in-object cache for message blobs for modules with messages
154 foreach ( $moduleNames as $name ) {
155 $module = $this->getModule( $name );
156 if ( $module && $module->getMessages() ) {
157 $modules[$name] = $module;
160 $store = $this->getMessageBlobStore();
161 $blobs = $store->getBlobs( $modules, $lang );
162 foreach ( $blobs as $name => $blob ) {
163 $modules[$name]->setMessageBlob( $blob, $lang );
168 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
170 * Available filters are:
172 * - minify-js \see JavaScriptMinifier::minify
173 * - minify-css \see CSSMin::minify
175 * If $data is empty, only contains whitespace or the filter was unknown,
176 * $data is returned unmodified.
178 * @param string $filter Name of filter to run
179 * @param string $data Text to filter, such as JavaScript or CSS text
180 * @param array $options Keys:
181 * - (bool) cache: Whether to allow caching this data. Default: true.
182 * @return string Filtered data, or a comment containing an error message
184 public static function filter( $filter, $data, array $options = [] ) {
185 if ( strpos( $data, self
::FILTER_NOMIN
) !== false ) {
189 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
190 return self
::applyFilter( $filter, $data );
193 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
194 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
196 $key = $cache->makeGlobalKey(
197 'resourceloader-filter',
203 $result = $cache->get( $key );
204 if ( $result === false ) {
205 $stats->increment( "resourceloader_cache.$filter.miss" );
206 $result = self
::applyFilter( $filter, $data );
207 $cache->set( $key, $result, 24 * 3600 );
209 $stats->increment( "resourceloader_cache.$filter.hit" );
211 if ( $result === null ) {
219 private static function applyFilter( $filter, $data ) {
220 $data = trim( $data );
223 $data = ( $filter === 'minify-css' )
224 ? CSSMin
::minify( $data )
225 : JavaScriptMinifier
::minify( $data );
226 } catch ( Exception
$e ) {
227 MWExceptionHandler
::logException( $e );
235 * Register core modules and runs registration hooks.
236 * @param Config|null $config
237 * @param LoggerInterface|null $logger [optional]
239 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
240 $this->logger
= $logger ?
: new NullLogger();
243 wfDeprecated( __METHOD__
. ' without a Config instance', '1.34' );
244 $config = MediaWikiServices
::getInstance()->getMainConfig();
246 $this->config
= $config;
248 // Add 'local' source first
249 $this->addSource( 'local', $config->get( 'LoadScript' ) );
251 // Special module that always exists
252 $this->register( 'startup', [ 'class' => ResourceLoaderStartUpModule
::class ] );
254 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
260 public function getConfig() {
261 return $this->config
;
266 * @param LoggerInterface $logger
268 public function setLogger( LoggerInterface
$logger ) {
269 $this->logger
= $logger;
274 * @return LoggerInterface
276 public function getLogger() {
277 return $this->logger
;
282 * @return MessageBlobStore
284 public function getMessageBlobStore() {
285 return $this->blobStore
;
290 * @param MessageBlobStore $blobStore
292 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
293 $this->blobStore
= $blobStore;
297 * Register a module with the ResourceLoader system.
299 * @param string|array[] $name Module name as a string or, array of module info arrays
301 * @param array|null $info Module info array. When using the first parameter to register
302 * multiple modules at once, this parameter is optional.
303 * @throws MWException If a duplicate module registration is attempted
304 * @throws MWException If a module name contains illegal characters (pipes or commas)
305 * @throws InvalidArgumentException If the module info is not an array
307 public function register( $name, $info = null ) {
308 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
310 // Allow multiple modules to be registered in one call
311 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
312 foreach ( $registrations as $name => $info ) {
313 // Warn on duplicate registrations
314 if ( isset( $this->moduleInfos
[$name] ) ) {
315 // A module has already been registered by this name
316 $this->logger
->warning(
317 'ResourceLoader duplicate registration warning. ' .
318 'Another module has already been registered as ' . $name
323 if ( !self
::isValidModuleName( $name ) ) {
324 throw new MWException( "ResourceLoader module name '$name' is invalid, "
325 . "see ResourceLoader::isValidModuleName()" );
327 if ( !is_array( $info ) ) {
328 throw new InvalidArgumentException(
329 'Invalid module info for "' . $name . '": expected array, got ' . gettype( $info )
334 $this->moduleInfos
[$name] = $info;
336 // Last-minute changes
337 // Apply custom skin-defined styles to existing modules.
338 if ( $this->isFileModule( $name ) ) {
339 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
340 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
341 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
345 // If $name is preceded with a '+', the defined style files will be added to 'default'
346 // skinStyles, otherwise 'default' will be ignored as it normally would be.
347 if ( isset( $skinStyles[$name] ) ) {
348 $paths = (array)$skinStyles[$name];
350 } elseif ( isset( $skinStyles['+' . $name] ) ) {
351 $paths = (array)$skinStyles['+' . $name];
352 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
353 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
359 // Add new file paths, remapping them to refer to our directories and not use settings
360 // from the module we're modifying, which come from the base definition.
361 list( $localBasePath, $remoteBasePath ) =
362 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
364 foreach ( $paths as $path ) {
365 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
368 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
375 * @internal For use by ServiceWiring only
376 * @codeCoverageIgnore
378 public function registerTestModules() {
381 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
382 throw new MWException( 'Attempt to register JavaScript test modules '
383 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
384 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
387 // This has a 'qunit' key for compat with the below hook.
388 $testModulesMeta = [ 'qunit' => [] ];
390 // Get test suites from extensions
391 // Avoid PHP 7.1 warning from passing $this by reference
393 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModulesMeta, &$rl ] );
394 $extRegistry = ExtensionRegistry
::getInstance();
395 // In case of conflict, the deprecated hook has precedence.
396 $testModules = $testModulesMeta['qunit'] +
$extRegistry->getAttribute( 'QUnitTestModules' );
398 $testSuiteModuleNames = [];
399 foreach ( $testModules as $name => &$module ) {
400 // Turn any single-module dependency into an array
401 if ( isset( $module['dependencies'] ) && is_string( $module['dependencies'] ) ) {
402 $module['dependencies'] = [ $module['dependencies'] ];
405 // Ensure the testrunner loads before any test suites
406 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
408 // Keep track of the test suites to load on SpecialJavaScriptTest
409 $testSuiteModuleNames[] = $name;
412 // Core test suites (their names have further precedence).
413 $testModules = ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules;
414 $testSuiteModuleNames[] = 'test.mediawiki.qunit.suites';
416 $this->register( $testModules );
417 $this->testSuiteModuleNames
= $testSuiteModuleNames;
421 * Add a foreign source of modules.
423 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
425 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
426 * @param string|array|null $loadUrl load.php url (string), or array with loadUrl key for
427 * backwards-compatibility.
428 * @throws MWException
430 public function addSource( $id, $loadUrl = null ) {
431 // Allow multiple sources to be registered in one call
432 if ( is_array( $id ) ) {
433 foreach ( $id as $key => $value ) {
434 $this->addSource( $key, $value );
439 // Disallow duplicates
440 if ( isset( $this->sources
[$id] ) ) {
441 throw new MWException(
442 'ResourceLoader duplicate source addition error. ' .
443 'Another source has already been registered as ' . $id
447 // Pre 1.24 backwards-compatibility
448 if ( is_array( $loadUrl ) ) {
449 if ( !isset( $loadUrl['loadScript'] ) ) {
450 throw new MWException(
451 __METHOD__
. ' was passed an array with no "loadScript" key.'
455 $loadUrl = $loadUrl['loadScript'];
458 $this->sources
[$id] = $loadUrl;
462 * Get a list of module names.
464 * @return array List of module names
466 public function getModuleNames() {
467 return array_keys( $this->moduleInfos
);
471 * Get a list of module names with QUnit test suites.
473 * @internal For use by SpecialJavaScriptTest only
475 * @codeCoverageIgnore
477 public function getTestSuiteModuleNames() {
478 return $this->testSuiteModuleNames
;
482 * Check whether a ResourceLoader module is registered
485 * @param string $name
488 public function isModuleRegistered( $name ) {
489 return isset( $this->moduleInfos
[$name] );
493 * Get the ResourceLoaderModule object for a given module name.
495 * If an array of module parameters exists but a ResourceLoaderModule object has not
496 * yet been instantiated, this method will instantiate and cache that object such that
497 * subsequent calls simply return the same object.
499 * @param string $name Module name
500 * @return ResourceLoaderModule|null If module has been registered, return a
501 * ResourceLoaderModule instance. Otherwise, return null.
503 public function getModule( $name ) {
504 if ( !isset( $this->modules
[$name] ) ) {
505 if ( !isset( $this->moduleInfos
[$name] ) ) {
509 // Construct the requested module object
510 $info = $this->moduleInfos
[$name];
511 if ( isset( $info['factory'] ) ) {
512 /** @var ResourceLoaderModule $object */
513 $object = call_user_func( $info['factory'], $info );
515 $class = $info['class'] ?? ResourceLoaderFileModule
::class;
516 /** @var ResourceLoaderModule $object */
517 $object = new $class( $info );
519 $object->setConfig( $this->getConfig() );
520 $object->setLogger( $this->logger
);
521 $object->setName( $name );
522 $this->modules
[$name] = $object;
525 return $this->modules
[$name];
529 * Whether the module is a ResourceLoaderFileModule (including subclasses).
531 * @param string $name Module name
534 protected function isFileModule( $name ) {
535 if ( !isset( $this->moduleInfos
[$name] ) ) {
538 $info = $this->moduleInfos
[$name];
539 return !isset( $info['factory'] ) && (
540 // The implied default for 'class' is ResourceLoaderFileModule
541 !isset( $info['class'] ) ||
543 $info['class'] === ResourceLoaderFileModule
::class ||
544 is_subclass_of( $info['class'], ResourceLoaderFileModule
::class )
549 * Get the list of sources.
551 * @return array Like [ id => load.php url, ... ]
553 public function getSources() {
554 return $this->sources
;
558 * Get the URL to the load.php endpoint for the given
559 * ResourceLoader source
562 * @param string $source
563 * @throws MWException On an invalid $source name
566 public function getLoadScript( $source ) {
567 if ( !isset( $this->sources
[$source] ) ) {
568 throw new MWException( "The $source source was never registered in ResourceLoader." );
570 return $this->sources
[$source];
575 * @param string $value
576 * @return string Hash
578 public static function makeHash( $value ) {
579 $hash = hash( 'fnv132', $value );
580 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
584 * Add an error to the 'errors' array and log it.
586 * @private For internal use by ResourceLoader and ResourceLoaderStartUpModule.
588 * @param Exception $e
590 * @param array $context
592 public function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
593 MWExceptionHandler
::logException( $e );
594 $this->logger
->warning(
596 $context +
[ 'exception' => $e ]
598 $this->errors
[] = self
::formatExceptionNoComment( $e );
602 * Helper method to get and combine versions of multiple modules.
605 * @param ResourceLoaderContext $context
606 * @param string[] $moduleNames List of known module names
607 * @return string Hash
609 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
610 if ( !$moduleNames ) {
613 $hashes = array_map( function ( $module ) use ( $context ) {
615 return $this->getModule( $module )->getVersionHash( $context );
616 } catch ( Exception
$e ) {
617 // If modules fail to compute a version, don't fail the request (T152266)
618 // and still compute versions of other modules.
619 $this->outputErrorAndLog( $e,
620 'Calculating version for "{module}" failed: {exception}',
628 return self
::makeHash( implode( '', $hashes ) );
632 * Get the expected value of the 'version' query parameter.
634 * This is used by respond() to set a short Cache-Control header for requests with
635 * information newer than the current server has. This avoids pollution of edge caches.
636 * Typically during deployment. (T117587)
638 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
641 * @param ResourceLoaderContext $context
642 * @return string Hash
644 public function makeVersionQuery( ResourceLoaderContext
$context ) {
645 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
646 // version hashes. There is no technical reason for this to be same, and for years the
647 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
648 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
649 // query parameter), then this method must continue to match the JS one.
651 foreach ( $context->getModules() as $name ) {
652 if ( !$this->getModule( $name ) ) {
653 // If a versioned request contains a missing module, the version is a mismatch
654 // as the client considered a module (and version) we don't have.
657 $moduleNames[] = $name;
659 return $this->getCombinedVersion( $context, $moduleNames );
663 * Output a response to a load request, including the content-type header.
665 * @param ResourceLoaderContext $context Context in which a response should be formed
667 public function respond( ResourceLoaderContext
$context ) {
668 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
669 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
670 // is used: ob_clean() will clear the GZIP header in that case and it won't come
671 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
672 // the whole thing in our own output buffer to be sure the active buffer
673 // doesn't use ob_gzhandler.
674 // See https://bugs.php.net/bug.php?id=36514
677 $this->measureResponseTime( RequestContext
::getMain()->getTiming() );
679 // Find out which modules are missing and instantiate the others
682 foreach ( $context->getModules() as $name ) {
683 $module = $this->getModule( $name );
685 // Do not allow private modules to be loaded from the web.
686 // This is a security issue, see T36907.
687 if ( $module->getGroup() === 'private' ) {
688 $this->logger
->debug( "Request for private module '$name' denied" );
689 $this->errors
[] = "Cannot show private module \"$name\"";
692 $modules[$name] = $module;
699 // Preload for getCombinedVersion() and for batch makeModuleResponse()
700 $this->preloadModuleInfo( array_keys( $modules ), $context );
701 } catch ( Exception
$e ) {
702 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
705 // Combine versions to propagate cache invalidation
708 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
709 } catch ( Exception
$e ) {
710 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
713 // See RFC 2616 § 3.11 Entity Tags
714 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
715 $etag = 'W/"' . $versionHash . '"';
717 // Try the client-side cache first
718 if ( $this->tryRespondNotModified( $context, $etag ) ) {
719 return; // output handled (buffers cleared)
722 // Use file cache if enabled and available...
723 if ( $this->config
->get( 'UseFileCache' ) ) {
724 $fileCache = ResourceFileCache
::newFromContext( $context );
725 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
726 return; // output handled
730 // Generate a response
731 $response = $this->makeModuleResponse( $context, $modules, $missing );
733 // Capture any PHP warnings from the output buffer and append them to the
734 // error list if we're in debug mode.
735 if ( $context->getDebug() ) {
736 $warnings = ob_get_contents();
737 if ( strlen( $warnings ) ) {
738 $this->errors
[] = $warnings;
742 // Save response to file cache unless there are errors
743 if ( isset( $fileCache ) && !$this->errors
&& $missing === [] ) {
744 // Cache single modules and images...and other requests if there are enough hits
745 if ( ResourceFileCache
::useFileCache( $context ) ) {
746 if ( $fileCache->isCacheWorthy() ) {
747 $fileCache->saveText( $response );
749 $fileCache->incrMissesRecent( $context->getRequest() );
754 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
, $this->extraHeaders
);
756 // Remove the output buffer and output the response
759 if ( $context->getImageObj() && $this->errors
) {
760 // We can't show both the error messages and the response when it's an image.
761 $response = implode( "\n\n", $this->errors
);
762 } elseif ( $this->errors
) {
763 $errorText = implode( "\n\n", $this->errors
);
764 $errorResponse = self
::makeComment( $errorText );
765 if ( $context->shouldIncludeScripts() ) {
766 $errorResponse .= 'if (window.console && console.error) {'
767 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
771 // Prepend error info to the response
772 $response = $errorResponse . $response;
779 protected function measureResponseTime( Timing
$timing ) {
780 DeferredUpdates
::addCallableUpdate( function () use ( $timing ) {
781 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
782 if ( $measure !== false ) {
783 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
784 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
790 * Send main response headers to the client.
792 * Deals with Content-Type, CORS (for stylesheets), and caching.
794 * @param ResourceLoaderContext $context
795 * @param string $etag ETag header value
796 * @param bool $errors Whether there are errors in the response
797 * @param string[] $extra Array of extra HTTP response headers
800 protected function sendResponseHeaders(
801 ResourceLoaderContext
$context, $etag, $errors, array $extra = []
803 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
804 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
805 // Use a short cache expiry so that updates propagate to clients quickly, if:
806 // - No version specified (shared resources, e.g. stylesheets)
807 // - There were errors (recover quickly)
808 // - Version mismatch (T117587, T47877)
809 if ( is_null( $context->getVersion() )
811 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
813 $maxage = $rlMaxage['unversioned']['client'];
814 $smaxage = $rlMaxage['unversioned']['server'];
815 // If a version was specified we can use a longer expiry time since changing
816 // version numbers causes cache misses
818 $maxage = $rlMaxage['versioned']['client'];
819 $smaxage = $rlMaxage['versioned']['server'];
821 if ( $context->getImageObj() ) {
822 // Output different headers if we're outputting textual errors.
824 header( 'Content-Type: text/plain; charset=utf-8' );
826 $context->getImageObj()->sendResponseHeaders( $context );
828 } elseif ( $context->getOnly() === 'styles' ) {
829 header( 'Content-Type: text/css; charset=utf-8' );
830 header( 'Access-Control-Allow-Origin: *' );
832 header( 'Content-Type: text/javascript; charset=utf-8' );
834 // See RFC 2616 § 14.19 ETag
835 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
836 header( 'ETag: ' . $etag );
837 if ( $context->getDebug() ) {
838 // Do not cache debug responses
839 header( 'Cache-Control: private, no-cache, must-revalidate' );
840 header( 'Pragma: no-cache' );
842 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
843 $exp = min( $maxage, $smaxage );
844 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
846 foreach ( $extra as $header ) {
852 * Respond with HTTP 304 Not Modified if appropiate.
854 * If there's an If-None-Match header, respond with a 304 appropriately
855 * and clear out the output buffer. If the client cache is too old then do nothing.
857 * @param ResourceLoaderContext $context
858 * @param string $etag ETag header value
859 * @return bool True if HTTP 304 was sent and output handled
861 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
862 // See RFC 2616 § 14.26 If-None-Match
863 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
864 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
865 // Never send 304s in debug mode
866 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
867 // There's another bug in ob_gzhandler (see also the comment at
868 // the top of this function) that causes it to gzip even empty
869 // responses, meaning it's impossible to produce a truly empty
870 // response (because the gzip header is always there). This is
871 // a problem because 304 responses have to be completely empty
872 // per the HTTP spec, and Firefox behaves buggily when they're not.
873 // See also https://bugs.php.net/bug.php?id=51579
874 // To work around this, we tear down all output buffering before
876 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
878 HttpStatus
::header( 304 );
880 $this->sendResponseHeaders( $context, $etag, false );
887 * Send out code for a response from file cache if possible.
889 * @param ResourceFileCache $fileCache Cache object for this request URL
890 * @param ResourceLoaderContext $context Context in which to generate a response
891 * @param string $etag ETag header value
892 * @return bool If this found a cache file and handled the response
894 protected function tryRespondFromFileCache(
895 ResourceFileCache
$fileCache,
896 ResourceLoaderContext
$context,
899 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
900 // Buffer output to catch warnings.
902 // Get the maximum age the cache can be
903 $maxage = is_null( $context->getVersion() )
904 ?
$rlMaxage['unversioned']['server']
905 : $rlMaxage['versioned']['server'];
906 // Minimum timestamp the cache file must have
907 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
909 try { // RL always hits the DB on file cache miss...
910 wfGetDB( DB_REPLICA
);
911 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
912 $good = $fileCache->isCacheGood(); // cache existence check
916 $ts = $fileCache->cacheTimestamp();
917 // Send content type and cache headers
918 $this->sendResponseHeaders( $context, $etag, false );
919 $response = $fileCache->fetchText();
920 // Capture any PHP warnings from the output buffer and append them to the
921 // response in a comment if we're in debug mode.
922 if ( $context->getDebug() ) {
923 $warnings = ob_get_contents();
924 if ( strlen( $warnings ) ) {
925 $response = self
::makeComment( $warnings ) . $response;
928 // Remove the output buffer and output the response
930 echo $response . "\n/* Cached {$ts} */";
931 return true; // cache hit
936 return false; // cache miss
940 * Generate a CSS or JS comment block.
942 * Only use this for public data, not error message details.
944 * @param string $text
947 public static function makeComment( $text ) {
948 $encText = str_replace( '*/', '* /', $text );
949 return "/*\n$encText\n*/\n";
953 * Handle exception display.
955 * @param Exception $e Exception to be shown to the user
956 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
958 public static function formatException( $e ) {
959 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
963 * Handle exception display.
966 * @param Exception $e Exception to be shown to the user
967 * @return string Sanitized text that can be returned to the user
969 protected static function formatExceptionNoComment( $e ) {
970 global $wgShowExceptionDetails;
972 if ( !$wgShowExceptionDetails ) {
973 return MWExceptionHandler
::getPublicLogMessage( $e );
976 return MWExceptionHandler
::getLogMessage( $e ) .
978 MWExceptionHandler
::getRedactedTraceAsString( $e );
982 * Generate code for a response.
984 * Calling this method also populates the `errors` and `headers` members,
985 * later used by respond().
987 * @param ResourceLoaderContext $context Context in which to generate a response
988 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
989 * @param string[] $missing List of requested module names that are unregistered (optional)
990 * @return string Response data
992 public function makeModuleResponse( ResourceLoaderContext
$context,
993 array $modules, array $missing = []
998 if ( $modules === [] && $missing === [] ) {
1000 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1001 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1002 no modules were requested. Max made me put this here. */
1006 $image = $context->getImageObj();
1008 $data = $image->getImageData( $context );
1009 if ( $data === false ) {
1011 $this->errors
[] = 'Image generation failed';
1016 foreach ( $missing as $name ) {
1017 $states[$name] = 'missing';
1020 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1022 foreach ( $modules as $name => $module ) {
1024 $content = $module->getModuleContent( $context );
1025 $implementKey = $name . '@' . $module->getVersionHash( $context );
1028 if ( isset( $content['headers'] ) ) {
1029 $this->extraHeaders
= array_merge( $this->extraHeaders
, $content['headers'] );
1033 switch ( $context->getOnly() ) {
1035 $scripts = $content['scripts'];
1036 if ( is_string( $scripts ) ) {
1037 // Load scripts raw...
1038 $strContent = $scripts;
1039 } elseif ( is_array( $scripts ) ) {
1040 // ...except when $scripts is an array of URLs or an associative array
1041 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1045 $styles = $content['styles'];
1046 // We no longer separate into media, they are all combined now with
1047 // custom media type groups into @media .. {} sections as part of the css string.
1048 // Module returns either an empty array or a numerical array with css strings.
1049 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1052 $scripts = $content['scripts'] ??
'';
1053 if ( is_string( $scripts ) ) {
1054 if ( $name === 'site' ||
$name === 'user' ) {
1055 // Legacy scripts that run in the global scope without a closure.
1056 // mw.loader.implement will use globalEval if scripts is a string.
1057 // Minify manually here, because general response minification is
1058 // not effective due it being a string literal, not a function.
1059 if ( !$context->getDebug() ) {
1060 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1063 $scripts = new XmlJsCode( $scripts );
1066 $strContent = self
::makeLoaderImplementScript(
1069 $content['styles'] ??
[],
1070 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1071 $content['templates'] ??
[]
1076 if ( !$context->getDebug() ) {
1077 $strContent = self
::filter( $filter, $strContent );
1079 // In debug mode, separate each response by a new line.
1080 // For example, between 'mw.loader.implement();' statements.
1081 $strContent = $this->ensureNewline( $strContent );
1084 if ( $context->getOnly() === 'scripts' ) {
1085 // Use a linebreak between module scripts (T162719)
1086 $out .= $this->ensureNewline( $strContent );
1088 $out .= $strContent;
1091 } catch ( Exception
$e ) {
1092 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1094 // Respond to client with error-state instead of module implementation
1095 $states[$name] = 'error';
1096 unset( $modules[$name] );
1100 // Update module states
1101 if ( $context->shouldIncludeScripts() && !$context->getRaw() ) {
1102 if ( $modules && $context->getOnly() === 'scripts' ) {
1103 // Set the state of modules loaded as only scripts to ready as
1104 // they don't have an mw.loader.implement wrapper that sets the state
1105 foreach ( $modules as $name => $module ) {
1106 $states[$name] = 'ready';
1110 // Set the state of modules we didn't respond to with mw.loader.implement
1112 $stateScript = self
::makeLoaderStateScript( $states );
1113 if ( !$context->getDebug() ) {
1114 $stateScript = self
::filter( 'minify-js', $stateScript );
1116 // Use a linebreak between module script and state script (T162719)
1117 $out = $this->ensureNewline( $out ) . $stateScript;
1119 } elseif ( $states ) {
1120 $this->errors
[] = 'Problematic modules: '
1121 . self
::encodeJsonForScript( $states );
1128 * Ensure the string is either empty or ends in a line break
1129 * @param string $str
1132 private function ensureNewline( $str ) {
1133 $end = substr( $str, -1 );
1134 if ( $end === false ||
$end === '' ||
$end === "\n" ) {
1141 * Get names of modules that use a certain message.
1143 * @param string $messageKey
1144 * @return array List of module names
1146 public function getModulesByMessage( $messageKey ) {
1148 foreach ( $this->getModuleNames() as $moduleName ) {
1149 $module = $this->getModule( $moduleName );
1150 if ( in_array( $messageKey, $module->getMessages() ) ) {
1151 $moduleNames[] = $moduleName;
1154 return $moduleNames;
1158 * Return JS code that calls mw.loader.implement with given module properties.
1160 * @param string $name Module name or implement key (format "`[name]@[version]`")
1161 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1162 * list of URLs to JavaScript files, string of JavaScript for `$.globalEval`, or array with
1163 * 'files' and 'main' properties (see ResourceLoaderModule::getScript())
1164 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1165 * to CSS files keyed by media type
1166 * @param mixed $messages List of messages associated with this module. May either be an
1167 * associative array mapping message key to value, or a JSON-encoded message blob containing
1168 * the same data, wrapped in an XmlJsCode object.
1169 * @param array $templates Keys are name of templates and values are the source of
1171 * @throws MWException
1172 * @return string JavaScript code
1174 protected static function makeLoaderImplementScript(
1175 $name, $scripts, $styles, $messages, $templates
1177 if ( $scripts instanceof XmlJsCode
) {
1178 if ( $scripts->value
=== '' ) {
1180 } elseif ( self
::inDebugMode() ) {
1181 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1183 $scripts = new XmlJsCode( 'function($,jQuery,require,module){' . $scripts->value
. '}' );
1185 } elseif ( is_array( $scripts ) && isset( $scripts['files'] ) ) {
1186 $files = $scripts['files'];
1187 foreach ( $files as $path => &$file ) {
1188 // $file is changed (by reference) from a descriptor array to the content of the file
1189 // All of these essentially do $file = $file['content'];, some just have wrapping around it
1190 if ( $file['type'] === 'script' ) {
1191 // Multi-file modules only get two parameters ($ and jQuery are being phased out)
1192 if ( self
::inDebugMode() ) {
1193 $file = new XmlJsCode( "function ( require, module ) {\n{$file['content']}\n}" );
1195 $file = new XmlJsCode( 'function(require,module){' . $file['content'] . '}' );
1198 $file = $file['content'];
1201 $scripts = XmlJsCode
::encodeObject( [
1202 'main' => $scripts['main'],
1203 'files' => XmlJsCode
::encodeObject( $files, self
::inDebugMode() )
1204 ], self
::inDebugMode() );
1205 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1206 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1209 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1210 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1211 // of "{}". Force them to objects.
1219 self
::trimArray( $module );
1221 return Xml
::encodeJsCall( 'mw.loader.implement', $module, self
::inDebugMode() );
1225 * Returns JS code which, when called, will register a given list of messages.
1227 * @param mixed $messages Either an associative array mapping message key to value, or a
1228 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1229 * @return string JavaScript code
1231 public static function makeMessageSetScript( $messages ) {
1232 return 'mw.messages.set('
1233 . self
::encodeJsonForScript( (object)$messages )
1238 * Combines an associative array mapping media type to CSS into a
1239 * single stylesheet with "@media" blocks.
1241 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1244 public static function makeCombinedStyles( array $stylePairs ) {
1246 foreach ( $stylePairs as $media => $styles ) {
1247 // ResourceLoaderFileModule::getStyle can return the styles
1248 // as a string or an array of strings. This is to allow separation in
1250 $styles = (array)$styles;
1251 foreach ( $styles as $style ) {
1252 $style = trim( $style );
1253 // Don't output an empty "@media print { }" block (T42498)
1254 if ( $style !== '' ) {
1255 // Transform the media type based on request params and config
1256 // The way that this relies on $wgRequest to propagate request params is slightly evil
1257 $media = OutputPage
::transformCssMedia( $media );
1259 if ( $media === '' ||
$media == 'all' ) {
1261 } elseif ( is_string( $media ) ) {
1262 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1272 * Wrapper around json_encode that avoids needless escapes,
1273 * and pretty-prints in debug mode.
1277 * @param bool|string|array $data
1278 * @return string JSON
1280 public static function encodeJsonForScript( $data ) {
1281 // Keep output as small as possible by disabling needless escape modes
1282 // that PHP uses by default.
1283 // However, while most module scripts are only served on HTTP responses
1284 // for JavaScript, some modules can also be embedded in the HTML as inline
1285 // scripts. This, and the fact that we sometimes need to export strings
1286 // containing user-generated content and labels that may genuinely contain
1287 // a sequences like "</script>", we need to encode either '/' or '<'.
1288 // By default PHP escapes '/'. Let's escape '<' instead which is less common
1289 // and allows URLs to mostly remain readable.
1290 $jsonFlags = JSON_UNESCAPED_SLASHES |
1291 JSON_UNESCAPED_UNICODE |
1294 if ( self
::inDebugMode() ) {
1295 $jsonFlags |
= JSON_PRETTY_PRINT
;
1297 return json_encode( $data, $jsonFlags );
1301 * Returns a JS call to mw.loader.state, which sets the state of one
1302 * ore more modules to a given value. Has two calling conventions:
1304 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1305 * Set the state of a single module called $name to $state
1307 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1308 * Set the state of modules with the given names to the given states
1310 * @param array|string $states
1311 * @param string|null $state
1312 * @return string JavaScript code
1314 public static function makeLoaderStateScript( $states, $state = null ) {
1315 if ( !is_array( $states ) ) {
1316 $states = [ $states => $state ];
1318 return 'mw.loader.state('
1319 . self
::encodeJsonForScript( $states )
1323 private static function isEmptyObject( stdClass
$obj ) {
1324 foreach ( $obj as $key => $value ) {
1331 * Remove empty values from the end of an array.
1333 * Values considered empty:
1337 * - new XmlJsCode( '{}' )
1338 * - new stdClass() // (object) []
1340 * @param array $array
1342 private static function trimArray( array &$array ) {
1343 $i = count( $array );
1345 if ( $array[$i] === null
1346 ||
$array[$i] === []
1347 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1348 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1350 unset( $array[$i] );
1358 * Returns JS code which calls mw.loader.register with the given
1364 * ResourceLoader::makeLoaderRegisterScript( [
1365 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1366 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1373 * @param array $modules Array of module registration arrays, each containing
1374 * - string: module name
1375 * - string: module version
1376 * - array|null: List of dependencies (optional)
1377 * - string|null: Module group (optional)
1378 * - string|null: Name of foreign module source, or 'local' (optional)
1379 * - string|null: Script body of a skip function (optional)
1380 * @return string JavaScript code
1382 public static function makeLoaderRegisterScript( array $modules ) {
1383 // Optimisation: Transform dependency names into indexes when possible
1384 // to produce smaller output. They are expanded by mw.loader.register on
1385 // the other end using resolveIndexedDependencies().
1387 foreach ( $modules as $i => &$module ) {
1388 // Build module name index
1389 $index[$module[0]] = $i;
1391 foreach ( $modules as &$module ) {
1392 if ( isset( $module[2] ) ) {
1393 foreach ( $module[2] as &$dependency ) {
1394 if ( isset( $index[$dependency] ) ) {
1395 // Replace module name in dependency list with index
1396 $dependency = $index[$dependency];
1402 array_walk( $modules, [ self
::class, 'trimArray' ] );
1404 return 'mw.loader.register('
1405 . self
::encodeJsonForScript( $modules )
1410 * Returns JS code which calls mw.loader.addSource() with the given
1411 * parameters. Has two calling conventions:
1413 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1414 * Register a single source
1416 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1417 * Register sources with the given IDs and properties.
1419 * @param string|array $sources Source ID
1420 * @param string|null $loadUrl load.php url
1421 * @return string JavaScript code
1423 public static function makeLoaderSourcesScript( $sources, $loadUrl = null ) {
1424 if ( !is_array( $sources ) ) {
1425 $sources = [ $sources => $loadUrl ];
1427 return 'mw.loader.addSource('
1428 . self
::encodeJsonForScript( $sources )
1433 * Wraps JavaScript code to run after the startup module.
1435 * @param string $script JavaScript code
1436 * @return string JavaScript code
1438 public static function makeLoaderConditionalScript( $script ) {
1439 // Adds a function to lazy-created RLQ
1440 return '(RLQ=window.RLQ||[]).push(function(){' .
1441 trim( $script ) . '});';
1445 * Wraps JavaScript code to run after a required module.
1448 * @param string|string[] $modules Module name(s)
1449 * @param string $script JavaScript code
1450 * @return string JavaScript code
1452 public static function makeInlineCodeWithModule( $modules, $script ) {
1453 // Adds an array to lazy-created RLQ
1454 return '(RLQ=window.RLQ||[]).push(['
1455 . self
::encodeJsonForScript( $modules ) . ','
1456 . 'function(){' . trim( $script ) . '}'
1461 * Returns an HTML script tag that runs given JS code after startup and base modules.
1463 * The code will be wrapped in a closure, and it will be executed by ResourceLoader's
1464 * startup module if the client has adequate support for MediaWiki JavaScript code.
1466 * @param string $script JavaScript code
1467 * @param string|null $nonce [optional] Content-Security-Policy nonce
1468 * (from OutputPage::getCSPNonce)
1469 * @return string|WrappedString HTML
1471 public static function makeInlineScript( $script, $nonce = null ) {
1472 $js = self
::makeLoaderConditionalScript( $script );
1474 if ( $nonce === null ) {
1475 wfWarn( __METHOD__
. " did not get nonce. Will break CSP" );
1476 } elseif ( $nonce !== false ) {
1477 // If it was false, CSP is disabled, so no nonce attribute.
1478 // Nonce should be only base64 characters, so should be safe,
1479 // but better to be safely escaped than sorry.
1480 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1483 return new WrappedString(
1484 Html
::inlineScript( $js, $nonce ),
1485 "<script$escNonce>(RLQ=window.RLQ||[]).push(function(){",
1491 * Returns JS code which will set the MediaWiki configuration array to
1494 * @param array $configuration List of configuration values keyed by variable name
1495 * @return string JavaScript code
1498 public static function makeConfigSetScript( array $configuration ) {
1499 $js = Xml
::encodeJsCall(
1504 if ( $js === false ) {
1506 'JSON serialization of config data failed. ' .
1507 'This usually means the config data is not valid UTF-8.'
1509 MWExceptionHandler
::logException( $e );
1510 $js = Xml
::encodeJsCall( 'mw.log.error', [ $e->__toString() ] );
1516 * Convert an array of module names to a packed query string.
1518 * For example, `[ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]`
1519 * becomes `'foo.bar,baz|bar.baz,quux'`.
1521 * This process is reversed by ResourceLoader::expandModuleNames().
1522 * See also mw.loader#buildModulesString() which is a port of this, used
1523 * on the client-side.
1525 * @param array $modules List of module names (strings)
1526 * @return string Packed query string
1528 public static function makePackedModulesString( $modules ) {
1529 $moduleMap = []; // [ prefix => [ suffixes ] ]
1530 foreach ( $modules as $module ) {
1531 $pos = strrpos( $module, '.' );
1532 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1533 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1534 $moduleMap[$prefix][] = $suffix;
1538 foreach ( $moduleMap as $prefix => $suffixes ) {
1539 $p = $prefix === '' ?
'' : $prefix . '.';
1540 $arr[] = $p . implode( ',', $suffixes );
1542 return implode( '|', $arr );
1546 * Expand a string of the form `jquery.foo,bar|jquery.ui.baz,quux` to
1547 * an array of module names like `[ 'jquery.foo', 'jquery.bar',
1548 * 'jquery.ui.baz', 'jquery.ui.quux' ]`.
1550 * This process is reversed by ResourceLoader::makePackedModulesString().
1553 * @param string $modules Packed module name list
1554 * @return array Array of module names
1556 public static function expandModuleNames( $modules ) {
1558 $exploded = explode( '|', $modules );
1559 foreach ( $exploded as $group ) {
1560 if ( strpos( $group, ',' ) === false ) {
1561 // This is not a set of modules in foo.bar,baz notation
1562 // but a single module
1565 // This is a set of modules in foo.bar,baz notation
1566 $pos = strrpos( $group, '.' );
1567 if ( $pos === false ) {
1568 // Prefixless modules, i.e. without dots
1569 $retval = array_merge( $retval, explode( ',', $group ) );
1571 // We have a prefix and a bunch of suffixes
1572 $prefix = substr( $group, 0, $pos ); // 'foo'
1573 $suffixes = explode( ',', substr( $group, $pos +
1 ) ); // [ 'bar', 'baz' ]
1574 foreach ( $suffixes as $suffix ) {
1575 $retval[] = "$prefix.$suffix";
1584 * Determine whether debug mode was requested
1585 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1588 public static function inDebugMode() {
1589 if ( self
::$debugMode === null ) {
1590 global $wgRequest, $wgResourceLoaderDebug;
1591 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1592 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1595 return self
::$debugMode;
1599 * Reset static members used for caching.
1601 * Global state and $wgRequest are evil, but we're using it right
1602 * now and sometimes we need to be able to force ResourceLoader to
1603 * re-evaluate the context because it has changed (e.g. in the test suite).
1605 * @internal For use by unit tests
1606 * @codeCoverageIgnore
1608 public static function clearCache() {
1609 self
::$debugMode = null;
1613 * Build a load.php URL
1616 * @param string $source Name of the ResourceLoader source
1617 * @param ResourceLoaderContext $context
1618 * @param array $extraQuery
1619 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1621 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1624 $query = self
::createLoaderQuery( $context, $extraQuery );
1625 $script = $this->getLoadScript( $source );
1627 return wfAppendQuery( $script, $query );
1631 * Helper for createLoaderURL()
1634 * @see makeLoaderQuery
1635 * @param ResourceLoaderContext $context
1636 * @param array $extraQuery
1639 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1640 return self
::makeLoaderQuery(
1641 $context->getModules(),
1642 $context->getLanguage(),
1643 $context->getSkin(),
1644 $context->getUser(),
1645 $context->getVersion(),
1646 $context->getDebug(),
1647 $context->getOnly(),
1648 $context->getRequest()->getBool( 'printable' ),
1649 $context->getRequest()->getBool( 'handheld' ),
1655 * Build a query array (array representation of query string) for load.php. Helper
1656 * function for createLoaderURL().
1658 * @param array $modules
1659 * @param string $lang
1660 * @param string $skin
1661 * @param string|null $user
1662 * @param string|null $version
1663 * @param bool $debug
1664 * @param string|null $only
1665 * @param bool $printable
1666 * @param bool $handheld
1667 * @param array $extraQuery
1670 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1671 $version = null, $debug = false, $only = null, $printable = false,
1672 $handheld = false, $extraQuery = []
1675 'modules' => self
::makePackedModulesString( $modules ),
1677 // Keep urls short by omitting query parameters that
1678 // match the defaults assumed by ResourceLoaderContext.
1679 // Note: This relies on the defaults either being insignificant or forever constant,
1680 // as otherwise cached urls could change in meaning when the defaults change.
1681 if ( $lang !== ResourceLoaderContext
::DEFAULT_LANG
) {
1682 $query['lang'] = $lang;
1684 if ( $skin !== ResourceLoaderContext
::DEFAULT_SKIN
) {
1685 $query['skin'] = $skin;
1687 if ( $debug === true ) {
1688 $query['debug'] = 'true';
1690 if ( $user !== null ) {
1691 $query['user'] = $user;
1693 if ( $version !== null ) {
1694 $query['version'] = $version;
1696 if ( $only !== null ) {
1697 $query['only'] = $only;
1700 $query['printable'] = 1;
1703 $query['handheld'] = 1;
1705 $query +
= $extraQuery;
1707 // Make queries uniform in order
1713 * Check a module name for validity.
1715 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1716 * at most 255 bytes.
1718 * @param string $moduleName Module name to check
1719 * @return bool Whether $moduleName is a valid module name
1721 public static function isValidModuleName( $moduleName ) {
1722 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1726 * Returns LESS compiler set up for use with MediaWiki
1729 * @param array $vars Associative array of variables that should be used
1730 * for compilation. Since 1.32, this method no longer automatically includes
1731 * global LESS vars from ResourceLoader::getLessVars (T191937).
1732 * @throws MWException
1733 * @return Less_Parser
1735 public function getLessCompiler( $vars = [] ) {
1737 // When called from the installer, it is possible that a required PHP extension
1738 // is missing (at least for now; see T49564). If this is the case, throw an
1739 // exception (caught by the installer) to prevent a fatal error later on.
1740 if ( !class_exists( 'Less_Parser' ) ) {
1741 throw new MWException( 'MediaWiki requires the less.php parser' );
1744 $parser = new Less_Parser
;
1745 $parser->ModifyVars( $vars );
1746 $parser->SetImportDirs( [
1747 "$IP/resources/src/mediawiki.less/" => '',
1749 $parser->SetOption( 'relativeUrls', false );
1755 * Get global LESS variables.
1758 * @deprecated since 1.32 Use ResourceLoderModule::getLessVars() instead.
1759 * @return array Map of variable names to string CSS values.
1761 public function getLessVars() {