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
322 * @return bool False if there were any errors, in which case one or more modules were
325 public function register( $name, $info = null ) {
326 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
328 // Allow multiple modules to be registered in one call
329 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
330 foreach ( $registrations as $name => $info ) {
331 // Warn on duplicate registrations
332 if ( isset( $this->moduleInfos
[$name] ) ) {
333 // A module has already been registered by this name
334 $this->logger
->warning(
335 'ResourceLoader duplicate registration warning. ' .
336 'Another module has already been registered as ' . $name
340 // Check $name for validity
341 if ( !self
::isValidModuleName( $name ) ) {
342 throw new MWException( "ResourceLoader module name '$name' is invalid, "
343 . "see ResourceLoader::isValidModuleName()" );
347 if ( $info instanceof ResourceLoaderModule
) {
348 $this->moduleInfos
[$name] = [ 'object' => $info ];
349 $info->setName( $name );
350 $this->modules
[$name] = $info;
351 } elseif ( is_array( $info ) ) {
352 // New calling convention
353 $this->moduleInfos
[$name] = $info;
355 throw new MWException(
356 'ResourceLoader module info type error for module \'' . $name .
357 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
361 // Last-minute changes
363 // Apply custom skin-defined styles to existing modules.
364 if ( $this->isFileModule( $name ) ) {
365 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
366 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
367 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
371 // If $name is preceded with a '+', the defined style files will be added to 'default'
372 // skinStyles, otherwise 'default' will be ignored as it normally would be.
373 if ( isset( $skinStyles[$name] ) ) {
374 $paths = (array)$skinStyles[$name];
376 } elseif ( isset( $skinStyles['+' . $name] ) ) {
377 $paths = (array)$skinStyles['+' . $name];
378 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
379 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
385 // Add new file paths, remapping them to refer to our directories and not use settings
386 // from the module we're modifying, which come from the base definition.
387 list( $localBasePath, $remoteBasePath ) =
388 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
390 foreach ( $paths as $path ) {
391 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
394 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
400 public function registerTestModules() {
403 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
404 throw new MWException( 'Attempt to register JavaScript test modules '
405 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
406 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
413 // Get test suites from extensions
414 // Avoid PHP 7.1 warning from passing $this by reference
416 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
417 $extRegistry = ExtensionRegistry
::getInstance();
418 // In case of conflict, the deprecated hook has precedence.
419 $testModules['qunit'] +
= $extRegistry->getAttribute( 'QUnitTestModules' );
421 // Add the QUnit testrunner as implicit dependency to extension test suites.
422 foreach ( $testModules['qunit'] as &$module ) {
423 // Shuck any single-module dependency as an array
424 if ( isset( $module['dependencies'] ) && is_string( $module['dependencies'] ) ) {
425 $module['dependencies'] = [ $module['dependencies'] ];
428 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
431 // Get core test suites
432 $testModules['qunit'] =
433 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
435 foreach ( $testModules as $id => $names ) {
436 // Register test modules
437 $this->register( $testModules[$id] );
439 // Keep track of their names so that they can be loaded together
440 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
445 * Add a foreign source of modules.
447 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
449 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
450 * @param string|array|null $loadUrl load.php url (string), or array with loadUrl key for
451 * backwards-compatibility.
452 * @throws MWException
454 public function addSource( $id, $loadUrl = null ) {
455 // Allow multiple sources to be registered in one call
456 if ( is_array( $id ) ) {
457 foreach ( $id as $key => $value ) {
458 $this->addSource( $key, $value );
463 // Disallow duplicates
464 if ( isset( $this->sources
[$id] ) ) {
465 throw new MWException(
466 'ResourceLoader duplicate source addition error. ' .
467 'Another source has already been registered as ' . $id
471 // Pre 1.24 backwards-compatibility
472 if ( is_array( $loadUrl ) ) {
473 if ( !isset( $loadUrl['loadScript'] ) ) {
474 throw new MWException(
475 __METHOD__
. ' was passed an array with no "loadScript" key.'
479 $loadUrl = $loadUrl['loadScript'];
482 $this->sources
[$id] = $loadUrl;
486 * Get a list of module names.
488 * @return array List of module names
490 public function getModuleNames() {
491 return array_keys( $this->moduleInfos
);
495 * Get a list of test module names for one (or all) frameworks.
497 * If the given framework id is unknkown, or if the in-object variable is not an array,
498 * then it will return an empty array.
500 * @param string $framework Get only the test module names for one
501 * particular framework (optional)
504 public function getTestModuleNames( $framework = 'all' ) {
505 /** @todo api siteinfo prop testmodulenames modulenames */
506 if ( $framework == 'all' ) {
507 return $this->testModuleNames
;
508 } elseif ( isset( $this->testModuleNames
[$framework] )
509 && is_array( $this->testModuleNames
[$framework] )
511 return $this->testModuleNames
[$framework];
518 * Check whether a ResourceLoader module is registered
521 * @param string $name
524 public function isModuleRegistered( $name ) {
525 return isset( $this->moduleInfos
[$name] );
529 * Get the ResourceLoaderModule object for a given module name.
531 * If an array of module parameters exists but a ResourceLoaderModule object has not
532 * yet been instantiated, this method will instantiate and cache that object such that
533 * subsequent calls simply return the same object.
535 * @param string $name Module name
536 * @return ResourceLoaderModule|null If module has been registered, return a
537 * ResourceLoaderModule instance. Otherwise, return null.
539 public function getModule( $name ) {
540 if ( !isset( $this->modules
[$name] ) ) {
541 if ( !isset( $this->moduleInfos
[$name] ) ) {
545 // Construct the requested object
546 $info = $this->moduleInfos
[$name];
547 /** @var ResourceLoaderModule $object */
548 if ( isset( $info['object'] ) ) {
549 // Object given in info array
550 $object = $info['object'];
551 } elseif ( isset( $info['factory'] ) ) {
552 $object = call_user_func( $info['factory'], $info );
553 $object->setConfig( $this->getConfig() );
554 $object->setLogger( $this->logger
);
556 $class = $info['class'] ?? ResourceLoaderFileModule
::class;
557 /** @var ResourceLoaderModule $object */
558 $object = new $class( $info );
559 $object->setConfig( $this->getConfig() );
560 $object->setLogger( $this->logger
);
562 $object->setName( $name );
563 $this->modules
[$name] = $object;
566 return $this->modules
[$name];
570 * Whether the module is a ResourceLoaderFileModule (including subclasses).
572 * @param string $name Module name
575 protected function isFileModule( $name ) {
576 if ( !isset( $this->moduleInfos
[$name] ) ) {
579 $info = $this->moduleInfos
[$name];
580 if ( isset( $info['object'] ) ) {
584 // The implied default for 'class' is ResourceLoaderFileModule
585 !isset( $info['class'] ) ||
587 $info['class'] === ResourceLoaderFileModule
::class ||
588 is_subclass_of( $info['class'], ResourceLoaderFileModule
::class )
593 * Get the list of sources.
595 * @return array Like [ id => load.php url, ... ]
597 public function getSources() {
598 return $this->sources
;
602 * Get the URL to the load.php endpoint for the given
603 * ResourceLoader source
606 * @param string $source
607 * @throws MWException On an invalid $source name
610 public function getLoadScript( $source ) {
611 if ( !isset( $this->sources
[$source] ) ) {
612 throw new MWException( "The $source source was never registered in ResourceLoader." );
614 return $this->sources
[$source];
619 * @param string $value
620 * @return string Hash
622 public static function makeHash( $value ) {
623 $hash = hash( 'fnv132', $value );
624 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
628 * Add an error to the 'errors' array and log it.
630 * @private For internal use by ResourceLoader and ResourceLoaderStartUpModule.
632 * @param Exception $e
634 * @param array $context
636 public function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
637 MWExceptionHandler
::logException( $e );
638 $this->logger
->warning(
640 $context +
[ 'exception' => $e ]
642 $this->errors
[] = self
::formatExceptionNoComment( $e );
646 * Helper method to get and combine versions of multiple modules.
649 * @param ResourceLoaderContext $context
650 * @param string[] $moduleNames List of known module names
651 * @return string Hash
653 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
654 if ( !$moduleNames ) {
657 $hashes = array_map( function ( $module ) use ( $context ) {
659 return $this->getModule( $module )->getVersionHash( $context );
660 } catch ( Exception
$e ) {
661 // If modules fail to compute a version, don't fail the request (T152266)
662 // and still compute versions of other modules.
663 $this->outputErrorAndLog( $e,
664 'Calculating version for "{module}" failed: {exception}',
672 return self
::makeHash( implode( '', $hashes ) );
676 * Get the expected value of the 'version' query parameter.
678 * This is used by respond() to set a short Cache-Control header for requests with
679 * information newer than the current server has. This avoids pollution of edge caches.
680 * Typically during deployment. (T117587)
682 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
685 * @param ResourceLoaderContext $context
686 * @return string Hash
688 public function makeVersionQuery( ResourceLoaderContext
$context ) {
689 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
690 // version hashes. There is no technical reason for this to be same, and for years the
691 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
692 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
693 // query parameter), then this method must continue to match the JS one.
695 foreach ( $context->getModules() as $name ) {
696 if ( !$this->getModule( $name ) ) {
697 // If a versioned request contains a missing module, the version is a mismatch
698 // as the client considered a module (and version) we don't have.
701 $moduleNames[] = $name;
703 return $this->getCombinedVersion( $context, $moduleNames );
707 * Output a response to a load request, including the content-type header.
709 * @param ResourceLoaderContext $context Context in which a response should be formed
711 public function respond( ResourceLoaderContext
$context ) {
712 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
713 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
714 // is used: ob_clean() will clear the GZIP header in that case and it won't come
715 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
716 // the whole thing in our own output buffer to be sure the active buffer
717 // doesn't use ob_gzhandler.
718 // See https://bugs.php.net/bug.php?id=36514
721 $this->measureResponseTime( RequestContext
::getMain()->getTiming() );
723 // Find out which modules are missing and instantiate the others
726 foreach ( $context->getModules() as $name ) {
727 $module = $this->getModule( $name );
729 // Do not allow private modules to be loaded from the web.
730 // This is a security issue, see T36907.
731 if ( $module->getGroup() === 'private' ) {
732 $this->logger
->debug( "Request for private module '$name' denied" );
733 $this->errors
[] = "Cannot show private module \"$name\"";
736 $modules[$name] = $module;
743 // Preload for getCombinedVersion() and for batch makeModuleResponse()
744 $this->preloadModuleInfo( array_keys( $modules ), $context );
745 } catch ( Exception
$e ) {
746 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
749 // Combine versions to propagate cache invalidation
752 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
753 } catch ( Exception
$e ) {
754 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
757 // See RFC 2616 § 3.11 Entity Tags
758 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
759 $etag = 'W/"' . $versionHash . '"';
761 // Try the client-side cache first
762 if ( $this->tryRespondNotModified( $context, $etag ) ) {
763 return; // output handled (buffers cleared)
766 // Use file cache if enabled and available...
767 if ( $this->config
->get( 'UseFileCache' ) ) {
768 $fileCache = ResourceFileCache
::newFromContext( $context );
769 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
770 return; // output handled
774 // Generate a response
775 $response = $this->makeModuleResponse( $context, $modules, $missing );
777 // Capture any PHP warnings from the output buffer and append them to the
778 // error list if we're in debug mode.
779 if ( $context->getDebug() ) {
780 $warnings = ob_get_contents();
781 if ( strlen( $warnings ) ) {
782 $this->errors
[] = $warnings;
786 // Save response to file cache unless there are errors
787 if ( isset( $fileCache ) && !$this->errors
&& $missing === [] ) {
788 // Cache single modules and images...and other requests if there are enough hits
789 if ( ResourceFileCache
::useFileCache( $context ) ) {
790 if ( $fileCache->isCacheWorthy() ) {
791 $fileCache->saveText( $response );
793 $fileCache->incrMissesRecent( $context->getRequest() );
798 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
, $this->extraHeaders
);
800 // Remove the output buffer and output the response
803 if ( $context->getImageObj() && $this->errors
) {
804 // We can't show both the error messages and the response when it's an image.
805 $response = implode( "\n\n", $this->errors
);
806 } elseif ( $this->errors
) {
807 $errorText = implode( "\n\n", $this->errors
);
808 $errorResponse = self
::makeComment( $errorText );
809 if ( $context->shouldIncludeScripts() ) {
810 $errorResponse .= 'if (window.console && console.error) {'
811 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
815 // Prepend error info to the response
816 $response = $errorResponse . $response;
823 protected function measureResponseTime( Timing
$timing ) {
824 DeferredUpdates
::addCallableUpdate( function () use ( $timing ) {
825 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
826 if ( $measure !== false ) {
827 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
828 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
834 * Send main response headers to the client.
836 * Deals with Content-Type, CORS (for stylesheets), and caching.
838 * @param ResourceLoaderContext $context
839 * @param string $etag ETag header value
840 * @param bool $errors Whether there are errors in the response
841 * @param string[] $extra Array of extra HTTP response headers
844 protected function sendResponseHeaders(
845 ResourceLoaderContext
$context, $etag, $errors, array $extra = []
847 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
848 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
849 // Use a short cache expiry so that updates propagate to clients quickly, if:
850 // - No version specified (shared resources, e.g. stylesheets)
851 // - There were errors (recover quickly)
852 // - Version mismatch (T117587, T47877)
853 if ( is_null( $context->getVersion() )
855 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
857 $maxage = $rlMaxage['unversioned']['client'];
858 $smaxage = $rlMaxage['unversioned']['server'];
859 // If a version was specified we can use a longer expiry time since changing
860 // version numbers causes cache misses
862 $maxage = $rlMaxage['versioned']['client'];
863 $smaxage = $rlMaxage['versioned']['server'];
865 if ( $context->getImageObj() ) {
866 // Output different headers if we're outputting textual errors.
868 header( 'Content-Type: text/plain; charset=utf-8' );
870 $context->getImageObj()->sendResponseHeaders( $context );
872 } elseif ( $context->getOnly() === 'styles' ) {
873 header( 'Content-Type: text/css; charset=utf-8' );
874 header( 'Access-Control-Allow-Origin: *' );
876 header( 'Content-Type: text/javascript; charset=utf-8' );
878 // See RFC 2616 § 14.19 ETag
879 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
880 header( 'ETag: ' . $etag );
881 if ( $context->getDebug() ) {
882 // Do not cache debug responses
883 header( 'Cache-Control: private, no-cache, must-revalidate' );
884 header( 'Pragma: no-cache' );
886 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
887 $exp = min( $maxage, $smaxage );
888 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
890 foreach ( $extra as $header ) {
896 * Respond with HTTP 304 Not Modified if appropiate.
898 * If there's an If-None-Match header, respond with a 304 appropriately
899 * and clear out the output buffer. If the client cache is too old then do nothing.
901 * @param ResourceLoaderContext $context
902 * @param string $etag ETag header value
903 * @return bool True if HTTP 304 was sent and output handled
905 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
906 // See RFC 2616 § 14.26 If-None-Match
907 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
908 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
909 // Never send 304s in debug mode
910 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
911 // There's another bug in ob_gzhandler (see also the comment at
912 // the top of this function) that causes it to gzip even empty
913 // responses, meaning it's impossible to produce a truly empty
914 // response (because the gzip header is always there). This is
915 // a problem because 304 responses have to be completely empty
916 // per the HTTP spec, and Firefox behaves buggily when they're not.
917 // See also https://bugs.php.net/bug.php?id=51579
918 // To work around this, we tear down all output buffering before
920 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
922 HttpStatus
::header( 304 );
924 $this->sendResponseHeaders( $context, $etag, false );
931 * Send out code for a response from file cache if possible.
933 * @param ResourceFileCache $fileCache Cache object for this request URL
934 * @param ResourceLoaderContext $context Context in which to generate a response
935 * @param string $etag ETag header value
936 * @return bool If this found a cache file and handled the response
938 protected function tryRespondFromFileCache(
939 ResourceFileCache
$fileCache,
940 ResourceLoaderContext
$context,
943 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
944 // Buffer output to catch warnings.
946 // Get the maximum age the cache can be
947 $maxage = is_null( $context->getVersion() )
948 ?
$rlMaxage['unversioned']['server']
949 : $rlMaxage['versioned']['server'];
950 // Minimum timestamp the cache file must have
951 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
953 try { // RL always hits the DB on file cache miss...
954 wfGetDB( DB_REPLICA
);
955 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
956 $good = $fileCache->isCacheGood(); // cache existence check
960 $ts = $fileCache->cacheTimestamp();
961 // Send content type and cache headers
962 $this->sendResponseHeaders( $context, $etag, false );
963 $response = $fileCache->fetchText();
964 // Capture any PHP warnings from the output buffer and append them to the
965 // response in a comment if we're in debug mode.
966 if ( $context->getDebug() ) {
967 $warnings = ob_get_contents();
968 if ( strlen( $warnings ) ) {
969 $response = self
::makeComment( $warnings ) . $response;
972 // Remove the output buffer and output the response
974 echo $response . "\n/* Cached {$ts} */";
975 return true; // cache hit
980 return false; // cache miss
984 * Generate a CSS or JS comment block.
986 * Only use this for public data, not error message details.
988 * @param string $text
991 public static function makeComment( $text ) {
992 $encText = str_replace( '*/', '* /', $text );
993 return "/*\n$encText\n*/\n";
997 * Handle exception display.
999 * @param Exception $e Exception to be shown to the user
1000 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
1002 public static function formatException( $e ) {
1003 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
1007 * Handle exception display.
1010 * @param Exception $e Exception to be shown to the user
1011 * @return string Sanitized text that can be returned to the user
1013 protected static function formatExceptionNoComment( $e ) {
1014 global $wgShowExceptionDetails;
1016 if ( !$wgShowExceptionDetails ) {
1017 return MWExceptionHandler
::getPublicLogMessage( $e );
1020 return MWExceptionHandler
::getLogMessage( $e ) .
1022 MWExceptionHandler
::getRedactedTraceAsString( $e );
1026 * Generate code for a response.
1028 * Calling this method also populates the `errors` and `headers` members,
1029 * later used by respond().
1031 * @param ResourceLoaderContext $context Context in which to generate a response
1032 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1033 * @param string[] $missing List of requested module names that are unregistered (optional)
1034 * @return string Response data
1036 public function makeModuleResponse( ResourceLoaderContext
$context,
1037 array $modules, array $missing = []
1042 if ( $modules === [] && $missing === [] ) {
1044 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1045 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1046 no modules were requested. Max made me put this here. */
1050 $image = $context->getImageObj();
1052 $data = $image->getImageData( $context );
1053 if ( $data === false ) {
1055 $this->errors
[] = 'Image generation failed';
1060 foreach ( $missing as $name ) {
1061 $states[$name] = 'missing';
1067 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1069 foreach ( $modules as $name => $module ) {
1071 $content = $module->getModuleContent( $context );
1072 $implementKey = $name . '@' . $module->getVersionHash( $context );
1075 if ( isset( $content['headers'] ) ) {
1076 $this->extraHeaders
= array_merge( $this->extraHeaders
, $content['headers'] );
1080 switch ( $context->getOnly() ) {
1082 $scripts = $content['scripts'];
1083 if ( is_string( $scripts ) ) {
1084 // Load scripts raw...
1085 $strContent = $scripts;
1086 } elseif ( is_array( $scripts ) ) {
1087 // ...except when $scripts is an array of URLs or an associative array
1088 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1092 $styles = $content['styles'];
1093 // We no longer separate into media, they are all combined now with
1094 // custom media type groups into @media .. {} sections as part of the css string.
1095 // Module returns either an empty array or a numerical array with css strings.
1096 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1099 $scripts = $content['scripts'] ??
'';
1100 if ( is_string( $scripts ) ) {
1101 if ( $name === 'site' ||
$name === 'user' ) {
1102 // Legacy scripts that run in the global scope without a closure.
1103 // mw.loader.implement will use globalEval if scripts is a string.
1104 // Minify manually here, because general response minification is
1105 // not effective due it being a string literal, not a function.
1106 if ( !$context->getDebug() ) {
1107 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1110 $scripts = new XmlJsCode( $scripts );
1113 $strContent = self
::makeLoaderImplementScript(
1116 $content['styles'] ??
[],
1117 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1118 $content['templates'] ??
[]
1123 if ( !$context->getDebug() ) {
1124 $strContent = self
::filter( $filter, $strContent );
1127 if ( $context->getOnly() === 'scripts' ) {
1128 // Use a linebreak between module scripts (T162719)
1129 $out .= $this->ensureNewline( $strContent );
1131 $out .= $strContent;
1134 } catch ( Exception
$e ) {
1135 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1137 // Respond to client with error-state instead of module implementation
1138 $states[$name] = 'error';
1139 unset( $modules[$name] );
1141 $isRaw |
= $module->isRaw();
1144 // Update module states
1145 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1146 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1147 // Set the state of modules loaded as only scripts to ready as
1148 // they don't have an mw.loader.implement wrapper that sets the state
1149 foreach ( $modules as $name => $module ) {
1150 $states[$name] = 'ready';
1154 // Set the state of modules we didn't respond to with mw.loader.implement
1155 if ( count( $states ) ) {
1156 $stateScript = self
::makeLoaderStateScript( $states );
1157 if ( !$context->getDebug() ) {
1158 $stateScript = self
::filter( 'minify-js', $stateScript );
1160 // Use a linebreak between module script and state script (T162719)
1161 $out = $this->ensureNewline( $out ) . $stateScript;
1165 $this->errors
[] = 'Problematic modules: '
1166 . self
::encodeJsonForScript( $states );
1174 * Ensure the string is either empty or ends in a line break
1175 * @param string $str
1178 private function ensureNewline( $str ) {
1179 $end = substr( $str, -1 );
1180 if ( $end === false ||
$end === "\n" ) {
1187 * Get names of modules that use a certain message.
1189 * @param string $messageKey
1190 * @return array List of module names
1192 public function getModulesByMessage( $messageKey ) {
1194 foreach ( $this->getModuleNames() as $moduleName ) {
1195 $module = $this->getModule( $moduleName );
1196 if ( in_array( $messageKey, $module->getMessages() ) ) {
1197 $moduleNames[] = $moduleName;
1200 return $moduleNames;
1204 * Return JS code that calls mw.loader.implement with given module properties.
1206 * @param string $name Module name or implement key (format "`[name]@[version]`")
1207 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1208 * list of URLs to JavaScript files, string of JavaScript for `$.globalEval`, or array with
1209 * 'files' and 'main' properties (see ResourceLoaderModule::getScript())
1210 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1211 * to CSS files keyed by media type
1212 * @param mixed $messages List of messages associated with this module. May either be an
1213 * associative array mapping message key to value, or a JSON-encoded message blob containing
1214 * the same data, wrapped in an XmlJsCode object.
1215 * @param array $templates Keys are name of templates and values are the source of
1217 * @throws MWException
1218 * @return string JavaScript code
1220 protected static function makeLoaderImplementScript(
1221 $name, $scripts, $styles, $messages, $templates
1223 if ( $scripts instanceof XmlJsCode
) {
1224 if ( $scripts->value
=== '' ) {
1226 } elseif ( self
::inDebugMode() ) {
1227 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1229 $scripts = new XmlJsCode( 'function($,jQuery,require,module){' . $scripts->value
. '}' );
1231 } elseif ( is_array( $scripts ) && isset( $scripts['files'] ) ) {
1232 $files = $scripts['files'];
1233 foreach ( $files as $path => &$file ) {
1234 // $file is changed (by reference) from a descriptor array to the content of the file
1235 // All of these essentially do $file = $file['content'];, some just have wrapping around it
1236 if ( $file['type'] === 'script' ) {
1237 // Multi-file modules only get two parameters ($ and jQuery are being phased out)
1238 if ( self
::inDebugMode() ) {
1239 $file = new XmlJsCode( "function ( require, module ) {\n{$file['content']}\n}" );
1241 $file = new XmlJsCode( 'function(require,module){' . $file['content'] . '}' );
1244 $file = $file['content'];
1247 $scripts = XmlJsCode
::encodeObject( [
1248 'main' => $scripts['main'],
1249 'files' => XmlJsCode
::encodeObject( $files, self
::inDebugMode() )
1250 ], self
::inDebugMode() );
1251 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1252 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1255 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1256 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1257 // of "{}". Force them to objects.
1265 self
::trimArray( $module );
1267 return Xml
::encodeJsCall( 'mw.loader.implement', $module, self
::inDebugMode() );
1271 * Returns JS code which, when called, will register a given list of messages.
1273 * @param mixed $messages Either an associative array mapping message key to value, or a
1274 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1275 * @return string JavaScript code
1277 public static function makeMessageSetScript( $messages ) {
1278 return Xml
::encodeJsCall(
1280 [ (object)$messages ],
1286 * Combines an associative array mapping media type to CSS into a
1287 * single stylesheet with "@media" blocks.
1289 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1292 public static function makeCombinedStyles( array $stylePairs ) {
1294 foreach ( $stylePairs as $media => $styles ) {
1295 // ResourceLoaderFileModule::getStyle can return the styles
1296 // as a string or an array of strings. This is to allow separation in
1298 $styles = (array)$styles;
1299 foreach ( $styles as $style ) {
1300 $style = trim( $style );
1301 // Don't output an empty "@media print { }" block (T42498)
1302 if ( $style !== '' ) {
1303 // Transform the media type based on request params and config
1304 // The way that this relies on $wgRequest to propagate request params is slightly evil
1305 $media = OutputPage
::transformCssMedia( $media );
1307 if ( $media === '' ||
$media == 'all' ) {
1309 } elseif ( is_string( $media ) ) {
1310 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1320 * Wrapper around json_encode that avoids needless escapes,
1321 * and pretty-prints in debug mode.
1325 * @param bool|string|array $data
1326 * @return string JSON
1328 public static function encodeJsonForScript( $data ) {
1329 // Keep output as small as possible by disabling needless escape modes
1330 // that PHP uses by default.
1331 // However, while most module scripts are only served on HTTP responses
1332 // for JavaScript, some modules can also be embedded in the HTML as inline
1333 // scripts. This, and the fact that we sometimes need to export strings
1334 // containing user-generated content and labels that may genuinely contain
1335 // a sequences like "</script>", we need to encode either '/' or '<'.
1336 // By default PHP escapes '/'. Let's escape '<' instead which is less common
1337 // and allows URLs to mostly remain readable.
1338 $jsonFlags = JSON_UNESCAPED_SLASHES |
1339 JSON_UNESCAPED_UNICODE |
1342 if ( self
::inDebugMode() ) {
1343 $jsonFlags |
= JSON_PRETTY_PRINT
;
1345 return json_encode( $data, $jsonFlags );
1349 * Returns a JS call to mw.loader.state, which sets the state of one
1350 * ore more modules to a given value. Has two calling conventions:
1352 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1353 * Set the state of a single module called $name to $state
1355 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1356 * Set the state of modules with the given names to the given states
1358 * @param array|string $states
1359 * @param string|null $state
1360 * @return string JavaScript code
1362 public static function makeLoaderStateScript( $states, $state = null ) {
1363 if ( !is_array( $states ) ) {
1364 $states = [ $states => $state ];
1366 return Xml
::encodeJsCall(
1373 private static function isEmptyObject( stdClass
$obj ) {
1374 foreach ( $obj as $key => $value ) {
1381 * Remove empty values from the end of an array.
1383 * Values considered empty:
1387 * - new XmlJsCode( '{}' )
1388 * - new stdClass() // (object) []
1390 * @param array $array
1392 private static function trimArray( array &$array ) {
1393 $i = count( $array );
1395 if ( $array[$i] === null
1396 ||
$array[$i] === []
1397 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1398 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1400 unset( $array[$i] );
1408 * Returns JS code which calls mw.loader.register with the given
1414 * ResourceLoader::makeLoaderRegisterScript( [
1415 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1416 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1423 * @param array $modules Array of module registration arrays, each containing
1424 * - string: module name
1425 * - string: module version
1426 * - array|null: List of dependencies (optional)
1427 * - string|null: Module group (optional)
1428 * - string|null: Name of foreign module source, or 'local' (optional)
1429 * - string|null: Script body of a skip function (optional)
1430 * @return string JavaScript code
1432 public static function makeLoaderRegisterScript( array $modules ) {
1433 // Optimisation: Transform dependency names into indexes when possible
1434 // to produce smaller output. They are expanded by mw.loader.register on
1435 // the other end using resolveIndexedDependencies().
1437 foreach ( $modules as $i => &$module ) {
1438 // Build module name index
1439 $index[$module[0]] = $i;
1441 foreach ( $modules as &$module ) {
1442 if ( isset( $module[2] ) ) {
1443 foreach ( $module[2] as &$dependency ) {
1444 if ( isset( $index[$dependency] ) ) {
1445 // Replace module name in dependency list with index
1446 $dependency = $index[$dependency];
1452 array_walk( $modules, [ 'self', 'trimArray' ] );
1454 return Xml
::encodeJsCall(
1455 'mw.loader.register',
1462 * Returns JS code which calls mw.loader.addSource() with the given
1463 * parameters. Has two calling conventions:
1465 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1466 * Register a single source
1468 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1469 * Register sources with the given IDs and properties.
1471 * @param string|array $sources Source ID
1472 * @param string|null $loadUrl load.php url
1473 * @return string JavaScript code
1475 public static function makeLoaderSourcesScript( $sources, $loadUrl = null ) {
1476 if ( !is_array( $sources ) ) {
1477 $sources = [ $sources => $loadUrl ];
1479 return Xml
::encodeJsCall(
1480 'mw.loader.addSource',
1487 * Wraps JavaScript code to run after the startup module.
1489 * @param string $script JavaScript code
1490 * @return string JavaScript code
1492 public static function makeLoaderConditionalScript( $script ) {
1493 // Adds a function to lazy-created RLQ
1494 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1495 trim( $script ) . '});';
1499 * Wraps JavaScript code to run after a required module.
1502 * @param string|string[] $modules Module name(s)
1503 * @param string $script JavaScript code
1504 * @return string JavaScript code
1506 public static function makeInlineCodeWithModule( $modules, $script ) {
1507 // Adds an array to lazy-created RLQ
1508 return '(window.RLQ=window.RLQ||[]).push(['
1509 . self
::encodeJsonForScript( $modules ) . ','
1510 . 'function(){' . trim( $script ) . '}'
1515 * Returns an HTML script tag that runs given JS code after startup and base modules.
1517 * The code will be wrapped in a closure, and it will be executed by ResourceLoader's
1518 * startup module if the client has adequate support for MediaWiki JavaScript code.
1520 * @param string $script JavaScript code
1521 * @param string|null $nonce [optional] Content-Security-Policy nonce
1522 * (from OutputPage::getCSPNonce)
1523 * @return string|WrappedString HTML
1525 public static function makeInlineScript( $script, $nonce = null ) {
1526 $js = self
::makeLoaderConditionalScript( $script );
1528 if ( $nonce === null ) {
1529 wfWarn( __METHOD__
. " did not get nonce. Will break CSP" );
1530 } elseif ( $nonce !== false ) {
1531 // If it was false, CSP is disabled, so no nonce attribute.
1532 // Nonce should be only base64 characters, so should be safe,
1533 // but better to be safely escaped than sorry.
1534 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1537 return new WrappedString(
1538 Html
::inlineScript( $js, $nonce ),
1539 "<script$escNonce>(window.RLQ=window.RLQ||[]).push(function(){",
1545 * Returns JS code which will set the MediaWiki configuration array to
1548 * @param array $configuration List of configuration values keyed by variable name
1549 * @return string JavaScript code
1552 public static function makeConfigSetScript( array $configuration ) {
1553 $js = Xml
::encodeJsCall(
1558 if ( $js === false ) {
1560 'JSON serialization of config data failed. ' .
1561 'This usually means the config data is not valid UTF-8.'
1563 MWExceptionHandler
::logException( $e );
1564 $js = Xml
::encodeJsCall( 'mw.log.error', [ $e->__toString() ] );
1570 * Convert an array of module names to a packed query string.
1572 * For example, `[ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]`
1573 * becomes `'foo.bar,baz|bar.baz,quux'`.
1575 * This process is reversed by ResourceLoaderContext::expandModuleNames().
1576 * See also mw.loader#buildModulesString() which is a port of this, used
1577 * on the client-side.
1579 * @param array $modules List of module names (strings)
1580 * @return string Packed query string
1582 public static function makePackedModulesString( $modules ) {
1583 $moduleMap = []; // [ prefix => [ suffixes ] ]
1584 foreach ( $modules as $module ) {
1585 $pos = strrpos( $module, '.' );
1586 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1587 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1588 $moduleMap[$prefix][] = $suffix;
1592 foreach ( $moduleMap as $prefix => $suffixes ) {
1593 $p = $prefix === '' ?
'' : $prefix . '.';
1594 $arr[] = $p . implode( ',', $suffixes );
1596 return implode( '|', $arr );
1600 * Determine whether debug mode was requested
1601 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1604 public static function inDebugMode() {
1605 if ( self
::$debugMode === null ) {
1606 global $wgRequest, $wgResourceLoaderDebug;
1607 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1608 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1611 return self
::$debugMode;
1615 * Reset static members used for caching.
1617 * Global state and $wgRequest are evil, but we're using it right
1618 * now and sometimes we need to be able to force ResourceLoader to
1619 * re-evaluate the context because it has changed (e.g. in the test suite).
1621 * @internal For use by unit tests
1622 * @codeCoverageIgnore
1624 public static function clearCache() {
1625 self
::$debugMode = null;
1629 * Build a load.php URL
1632 * @param string $source Name of the ResourceLoader source
1633 * @param ResourceLoaderContext $context
1634 * @param array $extraQuery
1635 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1637 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1640 $query = self
::createLoaderQuery( $context, $extraQuery );
1641 $script = $this->getLoadScript( $source );
1643 return wfAppendQuery( $script, $query );
1647 * Helper for createLoaderURL()
1650 * @see makeLoaderQuery
1651 * @param ResourceLoaderContext $context
1652 * @param array $extraQuery
1655 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1656 return self
::makeLoaderQuery(
1657 $context->getModules(),
1658 $context->getLanguage(),
1659 $context->getSkin(),
1660 $context->getUser(),
1661 $context->getVersion(),
1662 $context->getDebug(),
1663 $context->getOnly(),
1664 $context->getRequest()->getBool( 'printable' ),
1665 $context->getRequest()->getBool( 'handheld' ),
1671 * Build a query array (array representation of query string) for load.php. Helper
1672 * function for createLoaderURL().
1674 * @param array $modules
1675 * @param string $lang
1676 * @param string $skin
1677 * @param string|null $user
1678 * @param string|null $version
1679 * @param bool $debug
1680 * @param string|null $only
1681 * @param bool $printable
1682 * @param bool $handheld
1683 * @param array $extraQuery
1687 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1688 $version = null, $debug = false, $only = null, $printable = false,
1689 $handheld = false, $extraQuery = []
1692 'modules' => self
::makePackedModulesString( $modules ),
1696 if ( $debug === true ) {
1697 $query['debug'] = 'true';
1699 if ( $user !== null ) {
1700 $query['user'] = $user;
1702 if ( $version !== null ) {
1703 $query['version'] = $version;
1705 if ( $only !== null ) {
1706 $query['only'] = $only;
1709 $query['printable'] = 1;
1712 $query['handheld'] = 1;
1714 $query +
= $extraQuery;
1716 // Make queries uniform in order
1722 * Check a module name for validity.
1724 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1725 * at most 255 bytes.
1727 * @param string $moduleName Module name to check
1728 * @return bool Whether $moduleName is a valid module name
1730 public static function isValidModuleName( $moduleName ) {
1731 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1735 * Returns LESS compiler set up for use with MediaWiki
1738 * @param array $vars Associative array of variables that should be used
1739 * for compilation. Since 1.32, this method no longer automatically includes
1740 * global LESS vars from ResourceLoader::getLessVars (T191937).
1741 * @throws MWException
1742 * @return Less_Parser
1744 public function getLessCompiler( $vars = [] ) {
1746 // When called from the installer, it is possible that a required PHP extension
1747 // is missing (at least for now; see T49564). If this is the case, throw an
1748 // exception (caught by the installer) to prevent a fatal error later on.
1749 if ( !class_exists( 'Less_Parser' ) ) {
1750 throw new MWException( 'MediaWiki requires the less.php parser' );
1753 $parser = new Less_Parser
;
1754 $parser->ModifyVars( $vars );
1755 $parser->SetImportDirs( [
1756 "$IP/resources/src/mediawiki.less/" => '',
1758 $parser->SetOption( 'relativeUrls', false );
1764 * Get global LESS variables.
1767 * @deprecated since 1.32 Use ResourceLoderModule::getLessVars() instead.
1768 * @return array Map of variable names to string CSS values.
1770 public function getLessVars() {