Special case opus mime detction
[mediawiki.git] / includes / resourceloader / ResourceLoader.php
blobf0b48d544f030ed3e473e42aa5f1552fef279c1f
1 <?php
2 /**
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
20 * @file
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 WrappedString\WrappedString;
31 /**
32 * Dynamic JavaScript and CSS resource loading system.
34 * Most of the documentation is on the MediaWiki documentation wiki starting at:
35 * https://www.mediawiki.org/wiki/ResourceLoader
37 class ResourceLoader implements LoggerAwareInterface {
38 /** @var int */
39 protected static $filterCacheVersion = 7;
41 /** @var bool */
42 protected static $debugMode = null;
44 /** @var array */
45 private $lessVars = null;
47 /**
48 * Module name/ResourceLoaderModule object pairs
49 * @var array
51 protected $modules = [];
53 /**
54 * Associative array mapping module name to info associative array
55 * @var array
57 protected $moduleInfos = [];
59 /** @var Config $config */
60 protected $config;
62 /**
63 * Associative array mapping framework ids to a list of names of test suite modules
64 * like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... ], ... ]
65 * @var array
67 protected $testModuleNames = [];
69 /**
70 * E.g. [ 'source-id' => 'http://.../load.php' ]
71 * @var array
73 protected $sources = [];
75 /**
76 * Errors accumulated during current respond() call.
77 * @var array
79 protected $errors = [];
81 /**
82 * @var MessageBlobStore
84 protected $blobStore;
86 /**
87 * @var LoggerInterface
89 private $logger;
91 /** @var string JavaScript / CSS pragma to disable minification. **/
92 const FILTER_NOMIN = '/*@nomin*/';
94 /**
95 * Load information stored in the database about modules.
97 * This method grabs modules dependencies from the database and updates modules
98 * objects.
100 * This is not inside the module code because it is much faster to
101 * request all of the information at once than it is to have each module
102 * requests its own information. This sacrifice of modularity yields a substantial
103 * performance improvement.
105 * @param array $moduleNames List of module names to preload information for
106 * @param ResourceLoaderContext $context Context to load the information within
108 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext $context ) {
109 if ( !$moduleNames ) {
110 // Or else Database*::select() will explode, plus it's cheaper!
111 return;
113 $dbr = wfGetDB( DB_REPLICA );
114 $skin = $context->getSkin();
115 $lang = $context->getLanguage();
117 // Batched version of ResourceLoaderModule::getFileDependencies
118 $vary = "$skin|$lang";
119 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
120 'md_module' => $moduleNames,
121 'md_skin' => $vary,
122 ], __METHOD__
125 // Prime in-object cache for file dependencies
126 $modulesWithDeps = [];
127 foreach ( $res as $row ) {
128 $module = $this->getModule( $row->md_module );
129 if ( $module ) {
130 $module->setFileDependencies( $context, ResourceLoaderModule::expandRelativePaths(
131 FormatJson::decode( $row->md_deps, true )
132 ) );
133 $modulesWithDeps[] = $row->md_module;
136 // Register the absence of a dependency row too
137 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
138 $module = $this->getModule( $name );
139 if ( $module ) {
140 $this->getModule( $name )->setFileDependencies( $context, [] );
144 // Batched version of ResourceLoaderWikiModule::getTitleInfo
145 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $moduleNames );
147 // Prime in-object cache for message blobs for modules with messages
148 $modules = [];
149 foreach ( $moduleNames as $name ) {
150 $module = $this->getModule( $name );
151 if ( $module && $module->getMessages() ) {
152 $modules[$name] = $module;
155 $store = $this->getMessageBlobStore();
156 $blobs = $store->getBlobs( $modules, $lang );
157 foreach ( $blobs as $name => $blob ) {
158 $modules[$name]->setMessageBlob( $blob, $lang );
163 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
165 * Available filters are:
167 * - minify-js \see JavaScriptMinifier::minify
168 * - minify-css \see CSSMin::minify
170 * If $data is empty, only contains whitespace or the filter was unknown,
171 * $data is returned unmodified.
173 * @param string $filter Name of filter to run
174 * @param string $data Text to filter, such as JavaScript or CSS text
175 * @param array $options Keys:
176 * - (bool) cache: Whether to allow caching this data. Default: true.
177 * @return string Filtered data, or a comment containing an error message
179 public static function filter( $filter, $data, array $options = [] ) {
180 if ( strpos( $data, ResourceLoader::FILTER_NOMIN ) !== false ) {
181 return $data;
184 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
185 return self::applyFilter( $filter, $data );
188 $stats = RequestContext::getMain()->getStats();
189 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
191 $key = $cache->makeGlobalKey(
192 'resourceloader',
193 'filter',
194 $filter,
195 self::$filterCacheVersion, md5( $data )
198 $result = $cache->get( $key );
199 if ( $result === false ) {
200 $stats->increment( "resourceloader_cache.$filter.miss" );
201 $result = self::applyFilter( $filter, $data );
202 $cache->set( $key, $result, 24 * 3600 );
203 } else {
204 $stats->increment( "resourceloader_cache.$filter.hit" );
206 if ( $result === null ) {
207 // Cached failure
208 $result = $data;
211 return $result;
214 private static function applyFilter( $filter, $data ) {
215 $data = trim( $data );
216 if ( $data ) {
217 try {
218 $data = ( $filter === 'minify-css' )
219 ? CSSMin::minify( $data )
220 : JavaScriptMinifier::minify( $data );
221 } catch ( Exception $e ) {
222 MWExceptionHandler::logException( $e );
223 return null;
226 return $data;
229 /* Methods */
232 * Register core modules and runs registration hooks.
233 * @param Config $config [optional]
234 * @param LoggerInterface $logger [optional]
236 public function __construct( Config $config = null, LoggerInterface $logger = null ) {
237 global $IP;
239 $this->logger = $logger ?: new NullLogger();
241 if ( !$config ) {
242 $this->logger->debug( __METHOD__ . ' was called without providing a Config instance' );
243 $config = MediaWikiServices::getInstance()->getMainConfig();
245 $this->config = $config;
247 // Add 'local' source first
248 $this->addSource( 'local', $config->get( 'LoadScript' ) );
250 // Add other sources
251 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
253 // Register core modules
254 $this->register( include "$IP/resources/Resources.php" );
255 $this->register( include "$IP/resources/ResourcesOOUI.php" );
256 // Register extension modules
257 $this->register( $config->get( 'ResourceModules' ) );
258 Hooks::run( 'ResourceLoaderRegisterModules', [ &$this ] );
260 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
261 $this->registerTestModules();
264 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger ) );
268 * @return Config
270 public function getConfig() {
271 return $this->config;
275 * @since 1.26
276 * @param LoggerInterface $logger
278 public function setLogger( LoggerInterface $logger ) {
279 $this->logger = $logger;
283 * @since 1.27
284 * @return LoggerInterface
286 public function getLogger() {
287 return $this->logger;
291 * @since 1.26
292 * @return MessageBlobStore
294 public function getMessageBlobStore() {
295 return $this->blobStore;
299 * @since 1.25
300 * @param MessageBlobStore $blobStore
302 public function setMessageBlobStore( MessageBlobStore $blobStore ) {
303 $this->blobStore = $blobStore;
307 * Register a module with the ResourceLoader system.
309 * @param mixed $name Name of module as a string or List of name/object pairs as an array
310 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
311 * this may also be a ResourceLoaderModule object. Optional when using
312 * multiple-registration calling style.
313 * @throws MWException If a duplicate module registration is attempted
314 * @throws MWException If a module name contains illegal characters (pipes or commas)
315 * @throws MWException If something other than a ResourceLoaderModule is being registered
316 * @return bool False if there were any errors, in which case one or more modules were
317 * not registered
319 public function register( $name, $info = null ) {
320 $moduleSkinStyles = $this->config->get( 'ResourceModuleSkinStyles' );
322 // Allow multiple modules to be registered in one call
323 $registrations = is_array( $name ) ? $name : [ $name => $info ];
324 foreach ( $registrations as $name => $info ) {
325 // Warn on duplicate registrations
326 if ( isset( $this->moduleInfos[$name] ) ) {
327 // A module has already been registered by this name
328 $this->logger->warning(
329 'ResourceLoader duplicate registration warning. ' .
330 'Another module has already been registered as ' . $name
334 // Check $name for validity
335 if ( !self::isValidModuleName( $name ) ) {
336 throw new MWException( "ResourceLoader module name '$name' is invalid, "
337 . "see ResourceLoader::isValidModuleName()" );
340 // Attach module
341 if ( $info instanceof ResourceLoaderModule ) {
342 $this->moduleInfos[$name] = [ 'object' => $info ];
343 $info->setName( $name );
344 $this->modules[$name] = $info;
345 } elseif ( is_array( $info ) ) {
346 // New calling convention
347 $this->moduleInfos[$name] = $info;
348 } else {
349 throw new MWException(
350 'ResourceLoader module info type error for module \'' . $name .
351 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
355 // Last-minute changes
357 // Apply custom skin-defined styles to existing modules.
358 if ( $this->isFileModule( $name ) ) {
359 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
360 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
361 if ( isset( $this->moduleInfos[$name]['skinStyles'][$skinName] ) ) {
362 continue;
365 // If $name is preceded with a '+', the defined style files will be added to 'default'
366 // skinStyles, otherwise 'default' will be ignored as it normally would be.
367 if ( isset( $skinStyles[$name] ) ) {
368 $paths = (array)$skinStyles[$name];
369 $styleFiles = [];
370 } elseif ( isset( $skinStyles['+' . $name] ) ) {
371 $paths = (array)$skinStyles['+' . $name];
372 $styleFiles = isset( $this->moduleInfos[$name]['skinStyles']['default'] ) ?
373 (array)$this->moduleInfos[$name]['skinStyles']['default'] :
375 } else {
376 continue;
379 // Add new file paths, remapping them to refer to our directories and not use settings
380 // from the module we're modifying, which come from the base definition.
381 list( $localBasePath, $remoteBasePath ) =
382 ResourceLoaderFileModule::extractBasePaths( $skinStyles );
384 foreach ( $paths as $path ) {
385 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
388 $this->moduleInfos[$name]['skinStyles'][$skinName] = $styleFiles;
394 public function registerTestModules() {
395 global $IP;
397 if ( $this->config->get( 'EnableJavaScriptTest' ) !== true ) {
398 throw new MWException( 'Attempt to register JavaScript test modules '
399 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
400 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
403 // Get core test suites
404 $testModules = [];
405 $testModules['qunit'] = [];
406 // Get other test suites (e.g. from extensions)
407 Hooks::run( 'ResourceLoaderTestModules', [ &$testModules, &$this ] );
409 // Add the testrunner (which configures QUnit) to the dependencies.
410 // Since it must be ready before any of the test suites are executed.
411 foreach ( $testModules['qunit'] as &$module ) {
412 // Make sure all test modules are top-loading so that when QUnit starts
413 // on document-ready, it will run once and finish. If some tests arrive
414 // later (possibly after QUnit has already finished) they will be ignored.
415 $module['position'] = 'top';
416 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
419 $testModules['qunit'] =
420 ( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules['qunit'];
422 foreach ( $testModules as $id => $names ) {
423 // Register test modules
424 $this->register( $testModules[$id] );
426 // Keep track of their names so that they can be loaded together
427 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
432 * Add a foreign source of modules.
434 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
436 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
437 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
438 * backwards-compatibility.
439 * @throws MWException
441 public function addSource( $id, $loadUrl = null ) {
442 // Allow multiple sources to be registered in one call
443 if ( is_array( $id ) ) {
444 foreach ( $id as $key => $value ) {
445 $this->addSource( $key, $value );
447 return;
450 // Disallow duplicates
451 if ( isset( $this->sources[$id] ) ) {
452 throw new MWException(
453 'ResourceLoader duplicate source addition error. ' .
454 'Another source has already been registered as ' . $id
458 // Pre 1.24 backwards-compatibility
459 if ( is_array( $loadUrl ) ) {
460 if ( !isset( $loadUrl['loadScript'] ) ) {
461 throw new MWException(
462 __METHOD__ . ' was passed an array with no "loadScript" key.'
466 $loadUrl = $loadUrl['loadScript'];
469 $this->sources[$id] = $loadUrl;
473 * Get a list of module names.
475 * @return array List of module names
477 public function getModuleNames() {
478 return array_keys( $this->moduleInfos );
482 * Get a list of test module names for one (or all) frameworks.
484 * If the given framework id is unknkown, or if the in-object variable is not an array,
485 * then it will return an empty array.
487 * @param string $framework Get only the test module names for one
488 * particular framework (optional)
489 * @return array
491 public function getTestModuleNames( $framework = 'all' ) {
492 /** @todo api siteinfo prop testmodulenames modulenames */
493 if ( $framework == 'all' ) {
494 return $this->testModuleNames;
495 } elseif ( isset( $this->testModuleNames[$framework] )
496 && is_array( $this->testModuleNames[$framework] )
498 return $this->testModuleNames[$framework];
499 } else {
500 return [];
505 * Check whether a ResourceLoader module is registered
507 * @since 1.25
508 * @param string $name
509 * @return bool
511 public function isModuleRegistered( $name ) {
512 return isset( $this->moduleInfos[$name] );
516 * Get the ResourceLoaderModule object for a given module name.
518 * If an array of module parameters exists but a ResourceLoaderModule object has not
519 * yet been instantiated, this method will instantiate and cache that object such that
520 * subsequent calls simply return the same object.
522 * @param string $name Module name
523 * @return ResourceLoaderModule|null If module has been registered, return a
524 * ResourceLoaderModule instance. Otherwise, return null.
526 public function getModule( $name ) {
527 if ( !isset( $this->modules[$name] ) ) {
528 if ( !isset( $this->moduleInfos[$name] ) ) {
529 // No such module
530 return null;
532 // Construct the requested object
533 $info = $this->moduleInfos[$name];
534 /** @var ResourceLoaderModule $object */
535 if ( isset( $info['object'] ) ) {
536 // Object given in info array
537 $object = $info['object'];
538 } else {
539 if ( !isset( $info['class'] ) ) {
540 $class = 'ResourceLoaderFileModule';
541 } else {
542 $class = $info['class'];
544 /** @var ResourceLoaderModule $object */
545 $object = new $class( $info );
546 $object->setConfig( $this->getConfig() );
547 $object->setLogger( $this->logger );
549 $object->setName( $name );
550 $this->modules[$name] = $object;
553 return $this->modules[$name];
557 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
559 * @param string $name Module name
560 * @return bool
562 protected function isFileModule( $name ) {
563 if ( !isset( $this->moduleInfos[$name] ) ) {
564 return false;
566 $info = $this->moduleInfos[$name];
567 if ( isset( $info['object'] ) || isset( $info['class'] ) ) {
568 return false;
570 return true;
574 * Get the list of sources.
576 * @return array Like [ id => load.php url, ... ]
578 public function getSources() {
579 return $this->sources;
583 * Get the URL to the load.php endpoint for the given
584 * ResourceLoader source
586 * @since 1.24
587 * @param string $source
588 * @throws MWException On an invalid $source name
589 * @return string
591 public function getLoadScript( $source ) {
592 if ( !isset( $this->sources[$source] ) ) {
593 throw new MWException( "The $source source was never registered in ResourceLoader." );
595 return $this->sources[$source];
599 * @since 1.26
600 * @param string $value
601 * @return string Hash
603 public static function makeHash( $value ) {
604 $hash = hash( 'fnv132', $value );
605 return Wikimedia\base_convert( $hash, 16, 36, 7 );
609 * Add an error to the 'errors' array and log it.
611 * Should only be called from within respond().
613 * @since 1.29
614 * @param Exception $e
615 * @param string $msg
616 * @param array $context
618 protected function outputErrorAndLog( Exception $e, $msg, array $context = [] ) {
619 MWExceptionHandler::logException( $e );
620 $this->logger->warning(
621 $msg,
622 $context + [ 'exception' => $e ]
624 $this->errors[] = self::formatExceptionNoComment( $e );
628 * Helper method to get and combine versions of multiple modules.
630 * @since 1.26
631 * @param ResourceLoaderContext $context
632 * @param string[] $modules List of known module names
633 * @return string Hash
635 public function getCombinedVersion( ResourceLoaderContext $context, array $moduleNames ) {
636 if ( !$moduleNames ) {
637 return '';
639 $hashes = array_map( function ( $module ) use ( $context ) {
640 try {
641 return $this->getModule( $module )->getVersionHash( $context );
642 } catch ( Exception $e ) {
643 // If modules fail to compute a version, do still consider the versions
644 // of other modules - don't set an empty string E-Tag for the whole request.
645 // See also T152266 and StartupModule::getModuleRegistrations().
646 $this->outputErrorAndLog( $e,
647 'Calculating version for "{module}" failed: {exception}',
649 'module' => $module,
652 return '';
654 }, $moduleNames );
655 return self::makeHash( implode( '', $hashes ) );
659 * Get the expected value of the 'version' query parameter.
661 * This is used by respond() to set a short Cache-Control header for requests with
662 * information newer than the current server has. This avoids pollution of edge caches.
663 * Typically during deployment. (T117587)
665 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
667 * @since 1.28
668 * @param ResourceLoaderContext $context
669 * @param string[] $modules List of module names
670 * @return string Hash
672 public function makeVersionQuery( ResourceLoaderContext $context ) {
673 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
674 // version hashes. There is no technical reason for this to be same, and for years the
675 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
676 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
677 // query parameter), then this method must continue to match the JS one.
678 $moduleNames = [];
679 foreach ( $context->getModules() as $name ) {
680 if ( !$this->getModule( $name ) ) {
681 // If a versioned request contains a missing module, the version is a mismatch
682 // as the client considered a module (and version) we don't have.
683 return '';
685 $moduleNames[] = $name;
687 return $this->getCombinedVersion( $context, $moduleNames );
691 * Output a response to a load request, including the content-type header.
693 * @param ResourceLoaderContext $context Context in which a response should be formed
695 public function respond( ResourceLoaderContext $context ) {
696 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
697 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
698 // is used: ob_clean() will clear the GZIP header in that case and it won't come
699 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
700 // the whole thing in our own output buffer to be sure the active buffer
701 // doesn't use ob_gzhandler.
702 // See https://bugs.php.net/bug.php?id=36514
703 ob_start();
705 // Find out which modules are missing and instantiate the others
706 $modules = [];
707 $missing = [];
708 foreach ( $context->getModules() as $name ) {
709 $module = $this->getModule( $name );
710 if ( $module ) {
711 // Do not allow private modules to be loaded from the web.
712 // This is a security issue, see bug 34907.
713 if ( $module->getGroup() === 'private' ) {
714 $this->logger->debug( "Request for private module '$name' denied" );
715 $this->errors[] = "Cannot show private module \"$name\"";
716 continue;
718 $modules[$name] = $module;
719 } else {
720 $missing[] = $name;
724 try {
725 // Preload for getCombinedVersion() and for batch makeModuleResponse()
726 $this->preloadModuleInfo( array_keys( $modules ), $context );
727 } catch ( Exception $e ) {
728 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
731 // Combine versions to propagate cache invalidation
732 $versionHash = '';
733 try {
734 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
735 } catch ( Exception $e ) {
736 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
739 // See RFC 2616 § 3.11 Entity Tags
740 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
741 $etag = 'W/"' . $versionHash . '"';
743 // Try the client-side cache first
744 if ( $this->tryRespondNotModified( $context, $etag ) ) {
745 return; // output handled (buffers cleared)
748 // Use file cache if enabled and available...
749 if ( $this->config->get( 'UseFileCache' ) ) {
750 $fileCache = ResourceFileCache::newFromContext( $context );
751 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
752 return; // output handled
756 // Generate a response
757 $response = $this->makeModuleResponse( $context, $modules, $missing );
759 // Capture any PHP warnings from the output buffer and append them to the
760 // error list if we're in debug mode.
761 if ( $context->getDebug() ) {
762 $warnings = ob_get_contents();
763 if ( strlen( $warnings ) ) {
764 $this->errors[] = $warnings;
768 // Save response to file cache unless there are errors
769 if ( isset( $fileCache ) && !$this->errors && !count( $missing ) ) {
770 // Cache single modules and images...and other requests if there are enough hits
771 if ( ResourceFileCache::useFileCache( $context ) ) {
772 if ( $fileCache->isCacheWorthy() ) {
773 $fileCache->saveText( $response );
774 } else {
775 $fileCache->incrMissesRecent( $context->getRequest() );
780 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors );
782 // Remove the output buffer and output the response
783 ob_end_clean();
785 if ( $context->getImageObj() && $this->errors ) {
786 // We can't show both the error messages and the response when it's an image.
787 $response = implode( "\n\n", $this->errors );
788 } elseif ( $this->errors ) {
789 $errorText = implode( "\n\n", $this->errors );
790 $errorResponse = self::makeComment( $errorText );
791 if ( $context->shouldIncludeScripts() ) {
792 $errorResponse .= 'if (window.console && console.error) {'
793 . Xml::encodeJsCall( 'console.error', [ $errorText ] )
794 . "}\n";
797 // Prepend error info to the response
798 $response = $errorResponse . $response;
801 $this->errors = [];
802 echo $response;
806 * Send main response headers to the client.
808 * Deals with Content-Type, CORS (for stylesheets), and caching.
810 * @param ResourceLoaderContext $context
811 * @param string $etag ETag header value
812 * @param bool $errors Whether there are errors in the response
813 * @return void
815 protected function sendResponseHeaders( ResourceLoaderContext $context, $etag, $errors ) {
816 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
817 // Use a short cache expiry so that updates propagate to clients quickly, if:
818 // - No version specified (shared resources, e.g. stylesheets)
819 // - There were errors (recover quickly)
820 // - Version mismatch (T117587, T47877)
821 if ( is_null( $context->getVersion() )
822 || $errors
823 || $context->getVersion() !== $this->makeVersionQuery( $context )
825 $maxage = $rlMaxage['unversioned']['client'];
826 $smaxage = $rlMaxage['unversioned']['server'];
827 // If a version was specified we can use a longer expiry time since changing
828 // version numbers causes cache misses
829 } else {
830 $maxage = $rlMaxage['versioned']['client'];
831 $smaxage = $rlMaxage['versioned']['server'];
833 if ( $context->getImageObj() ) {
834 // Output different headers if we're outputting textual errors.
835 if ( $errors ) {
836 header( 'Content-Type: text/plain; charset=utf-8' );
837 } else {
838 $context->getImageObj()->sendResponseHeaders( $context );
840 } elseif ( $context->getOnly() === 'styles' ) {
841 header( 'Content-Type: text/css; charset=utf-8' );
842 header( 'Access-Control-Allow-Origin: *' );
843 } else {
844 header( 'Content-Type: text/javascript; charset=utf-8' );
846 // See RFC 2616 § 14.19 ETag
847 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
848 header( 'ETag: ' . $etag );
849 if ( $context->getDebug() ) {
850 // Do not cache debug responses
851 header( 'Cache-Control: private, no-cache, must-revalidate' );
852 header( 'Pragma: no-cache' );
853 } else {
854 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
855 $exp = min( $maxage, $smaxage );
856 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
861 * Respond with HTTP 304 Not Modified if appropiate.
863 * If there's an If-None-Match header, respond with a 304 appropriately
864 * and clear out the output buffer. If the client cache is too old then do nothing.
866 * @param ResourceLoaderContext $context
867 * @param string $etag ETag header value
868 * @return bool True if HTTP 304 was sent and output handled
870 protected function tryRespondNotModified( ResourceLoaderContext $context, $etag ) {
871 // See RFC 2616 § 14.26 If-None-Match
872 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
873 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST );
874 // Never send 304s in debug mode
875 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
876 // There's another bug in ob_gzhandler (see also the comment at
877 // the top of this function) that causes it to gzip even empty
878 // responses, meaning it's impossible to produce a truly empty
879 // response (because the gzip header is always there). This is
880 // a problem because 304 responses have to be completely empty
881 // per the HTTP spec, and Firefox behaves buggily when they're not.
882 // See also https://bugs.php.net/bug.php?id=51579
883 // To work around this, we tear down all output buffering before
884 // sending the 304.
885 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
887 HttpStatus::header( 304 );
889 $this->sendResponseHeaders( $context, $etag, false );
890 return true;
892 return false;
896 * Send out code for a response from file cache if possible.
898 * @param ResourceFileCache $fileCache Cache object for this request URL
899 * @param ResourceLoaderContext $context Context in which to generate a response
900 * @param string $etag ETag header value
901 * @return bool If this found a cache file and handled the response
903 protected function tryRespondFromFileCache(
904 ResourceFileCache $fileCache,
905 ResourceLoaderContext $context,
906 $etag
908 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
909 // Buffer output to catch warnings.
910 ob_start();
911 // Get the maximum age the cache can be
912 $maxage = is_null( $context->getVersion() )
913 ? $rlMaxage['unversioned']['server']
914 : $rlMaxage['versioned']['server'];
915 // Minimum timestamp the cache file must have
916 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
917 if ( !$good ) {
918 try { // RL always hits the DB on file cache miss...
919 wfGetDB( DB_REPLICA );
920 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
921 $good = $fileCache->isCacheGood(); // cache existence check
924 if ( $good ) {
925 $ts = $fileCache->cacheTimestamp();
926 // Send content type and cache headers
927 $this->sendResponseHeaders( $context, $etag, false );
928 $response = $fileCache->fetchText();
929 // Capture any PHP warnings from the output buffer and append them to the
930 // response in a comment if we're in debug mode.
931 if ( $context->getDebug() ) {
932 $warnings = ob_get_contents();
933 if ( strlen( $warnings ) ) {
934 $response = self::makeComment( $warnings ) . $response;
937 // Remove the output buffer and output the response
938 ob_end_clean();
939 echo $response . "\n/* Cached {$ts} */";
940 return true; // cache hit
942 // Clear buffer
943 ob_end_clean();
945 return false; // cache miss
949 * Generate a CSS or JS comment block.
951 * Only use this for public data, not error message details.
953 * @param string $text
954 * @return string
956 public static function makeComment( $text ) {
957 $encText = str_replace( '*/', '* /', $text );
958 return "/*\n$encText\n*/\n";
962 * Handle exception display.
964 * @param Exception $e Exception to be shown to the user
965 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
967 public static function formatException( $e ) {
968 return self::makeComment( self::formatExceptionNoComment( $e ) );
972 * Handle exception display.
974 * @since 1.25
975 * @param Exception $e Exception to be shown to the user
976 * @return string Sanitized text that can be returned to the user
978 protected static function formatExceptionNoComment( $e ) {
979 global $wgShowExceptionDetails;
981 if ( !$wgShowExceptionDetails ) {
982 return MWExceptionHandler::getPublicLogMessage( $e );
985 return MWExceptionHandler::getLogMessage( $e ) .
986 "\nBacktrace:\n" .
987 MWExceptionHandler::getRedactedTraceAsString( $e );
991 * Generate code for a response.
993 * @param ResourceLoaderContext $context Context in which to generate a response
994 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
995 * @param string[] $missing List of requested module names that are unregistered (optional)
996 * @return string Response data
998 public function makeModuleResponse( ResourceLoaderContext $context,
999 array $modules, array $missing = []
1001 $out = '';
1002 $states = [];
1004 if ( !count( $modules ) && !count( $missing ) ) {
1005 return <<<MESSAGE
1006 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1007 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1008 no modules were requested. Max made me put this here. */
1009 MESSAGE;
1012 $image = $context->getImageObj();
1013 if ( $image ) {
1014 $data = $image->getImageData( $context );
1015 if ( $data === false ) {
1016 $data = '';
1017 $this->errors[] = 'Image generation failed';
1019 return $data;
1022 foreach ( $missing as $name ) {
1023 $states[$name] = 'missing';
1026 // Generate output
1027 $isRaw = false;
1029 $filter = $context->getOnly() === 'styles' ? 'minify-css' : 'minify-js';
1031 foreach ( $modules as $name => $module ) {
1032 try {
1033 $content = $module->getModuleContent( $context );
1034 $implementKey = $name . '@' . $module->getVersionHash( $context );
1035 $strContent = '';
1037 // Append output
1038 switch ( $context->getOnly() ) {
1039 case 'scripts':
1040 $scripts = $content['scripts'];
1041 if ( is_string( $scripts ) ) {
1042 // Load scripts raw...
1043 $strContent = $scripts;
1044 } elseif ( is_array( $scripts ) ) {
1045 // ...except when $scripts is an array of URLs
1046 $strContent = self::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1048 break;
1049 case 'styles':
1050 $styles = $content['styles'];
1051 // We no longer seperate into media, they are all combined now with
1052 // custom media type groups into @media .. {} sections as part of the css string.
1053 // Module returns either an empty array or a numerical array with css strings.
1054 $strContent = isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
1055 break;
1056 default:
1057 $scripts = isset( $content['scripts'] ) ? $content['scripts'] : '';
1058 if ( is_string( $scripts ) ) {
1059 if ( $name === 'site' || $name === 'user' ) {
1060 // Legacy scripts that run in the global scope without a closure.
1061 // mw.loader.implement will use globalEval if scripts is a string.
1062 // Minify manually here, because general response minification is
1063 // not effective due it being a string literal, not a function.
1064 if ( !ResourceLoader::inDebugMode() ) {
1065 $scripts = self::filter( 'minify-js', $scripts ); // T107377
1067 } else {
1068 $scripts = new XmlJsCode( $scripts );
1071 $strContent = self::makeLoaderImplementScript(
1072 $implementKey,
1073 $scripts,
1074 isset( $content['styles'] ) ? $content['styles'] : [],
1075 isset( $content['messagesBlob'] ) ? new XmlJsCode( $content['messagesBlob'] ) : [],
1076 isset( $content['templates'] ) ? $content['templates'] : []
1078 break;
1081 if ( !$context->getDebug() ) {
1082 $strContent = self::filter( $filter, $strContent );
1085 $out .= $strContent;
1087 } catch ( Exception $e ) {
1088 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1090 // Respond to client with error-state instead of module implementation
1091 $states[$name] = 'error';
1092 unset( $modules[$name] );
1094 $isRaw |= $module->isRaw();
1097 // Update module states
1098 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1099 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1100 // Set the state of modules loaded as only scripts to ready as
1101 // they don't have an mw.loader.implement wrapper that sets the state
1102 foreach ( $modules as $name => $module ) {
1103 $states[$name] = 'ready';
1107 // Set the state of modules we didn't respond to with mw.loader.implement
1108 if ( count( $states ) ) {
1109 $stateScript = self::makeLoaderStateScript( $states );
1110 if ( !$context->getDebug() ) {
1111 $stateScript = self::filter( 'minify-js', $stateScript );
1113 $out .= $stateScript;
1115 } else {
1116 if ( count( $states ) ) {
1117 $this->errors[] = 'Problematic modules: ' .
1118 FormatJson::encode( $states, ResourceLoader::inDebugMode() );
1122 return $out;
1126 * Get names of modules that use a certain message.
1128 * @param string $messageKey
1129 * @return array List of module names
1131 public function getModulesByMessage( $messageKey ) {
1132 $moduleNames = [];
1133 foreach ( $this->getModuleNames() as $moduleName ) {
1134 $module = $this->getModule( $moduleName );
1135 if ( in_array( $messageKey, $module->getMessages() ) ) {
1136 $moduleNames[] = $moduleName;
1139 return $moduleNames;
1142 /* Static Methods */
1145 * Return JS code that calls mw.loader.implement with given module properties.
1147 * @param string $name Module name or implement key (format "`[name]@[version]`")
1148 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1149 * list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
1150 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1151 * to CSS files keyed by media type
1152 * @param mixed $messages List of messages associated with this module. May either be an
1153 * associative array mapping message key to value, or a JSON-encoded message blob containing
1154 * the same data, wrapped in an XmlJsCode object.
1155 * @param array $templates Keys are name of templates and values are the source of
1156 * the template.
1157 * @throws MWException
1158 * @return string
1160 protected static function makeLoaderImplementScript(
1161 $name, $scripts, $styles, $messages, $templates
1163 if ( $scripts instanceof XmlJsCode ) {
1164 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1165 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1166 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1168 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1169 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1170 // of "{}". Force them to objects.
1171 $module = [
1172 $name,
1173 $scripts,
1174 (object)$styles,
1175 (object)$messages,
1176 (object)$templates,
1178 self::trimArray( $module );
1180 return Xml::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader::inDebugMode() );
1184 * Returns JS code which, when called, will register a given list of messages.
1186 * @param mixed $messages Either an associative array mapping message key to value, or a
1187 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1188 * @return string
1190 public static function makeMessageSetScript( $messages ) {
1191 return Xml::encodeJsCall(
1192 'mw.messages.set',
1193 [ (object)$messages ],
1194 ResourceLoader::inDebugMode()
1199 * Combines an associative array mapping media type to CSS into a
1200 * single stylesheet with "@media" blocks.
1202 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1203 * @return array
1205 public static function makeCombinedStyles( array $stylePairs ) {
1206 $out = [];
1207 foreach ( $stylePairs as $media => $styles ) {
1208 // ResourceLoaderFileModule::getStyle can return the styles
1209 // as a string or an array of strings. This is to allow separation in
1210 // the front-end.
1211 $styles = (array)$styles;
1212 foreach ( $styles as $style ) {
1213 $style = trim( $style );
1214 // Don't output an empty "@media print { }" block (bug 40498)
1215 if ( $style !== '' ) {
1216 // Transform the media type based on request params and config
1217 // The way that this relies on $wgRequest to propagate request params is slightly evil
1218 $media = OutputPage::transformCssMedia( $media );
1220 if ( $media === '' || $media == 'all' ) {
1221 $out[] = $style;
1222 } elseif ( is_string( $media ) ) {
1223 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1225 // else: skip
1229 return $out;
1233 * Returns a JS call to mw.loader.state, which sets the state of a
1234 * module or modules to a given value. Has two calling conventions:
1236 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1237 * Set the state of a single module called $name to $state
1239 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1240 * Set the state of modules with the given names to the given states
1242 * @param string $name
1243 * @param string $state
1244 * @return string
1246 public static function makeLoaderStateScript( $name, $state = null ) {
1247 if ( is_array( $name ) ) {
1248 return Xml::encodeJsCall(
1249 'mw.loader.state',
1250 [ $name ],
1251 ResourceLoader::inDebugMode()
1253 } else {
1254 return Xml::encodeJsCall(
1255 'mw.loader.state',
1256 [ $name, $state ],
1257 ResourceLoader::inDebugMode()
1263 * Returns JS code which calls the script given by $script. The script will
1264 * be called with local variables name, version, dependencies and group,
1265 * which will have values corresponding to $name, $version, $dependencies
1266 * and $group as supplied.
1268 * @param string $name Module name
1269 * @param string $version Module version hash
1270 * @param array $dependencies List of module names on which this module depends
1271 * @param string $group Group which the module is in.
1272 * @param string $source Source of the module, or 'local' if not foreign.
1273 * @param string $script JavaScript code
1274 * @return string
1276 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1277 $group, $source, $script
1279 $script = str_replace( "\n", "\n\t", trim( $script ) );
1280 return Xml::encodeJsCall(
1281 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1282 [ $name, $version, $dependencies, $group, $source ],
1283 ResourceLoader::inDebugMode()
1287 private static function isEmptyObject( stdClass $obj ) {
1288 foreach ( $obj as $key => $value ) {
1289 return false;
1291 return true;
1295 * Remove empty values from the end of an array.
1297 * Values considered empty:
1299 * - null
1300 * - []
1301 * - new XmlJsCode( '{}' )
1302 * - new stdClass() // (object) []
1304 * @param Array $array
1306 private static function trimArray( array &$array ) {
1307 $i = count( $array );
1308 while ( $i-- ) {
1309 if ( $array[$i] === null
1310 || $array[$i] === []
1311 || ( $array[$i] instanceof XmlJsCode && $array[$i]->value === '{}' )
1312 || ( $array[$i] instanceof stdClass && self::isEmptyObject( $array[$i] ) )
1314 unset( $array[$i] );
1315 } else {
1316 break;
1322 * Returns JS code which calls mw.loader.register with the given
1323 * parameters. Has three calling conventions:
1325 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1326 * $dependencies, $group, $source, $skip
1327 * ):
1328 * Register a single module.
1330 * - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
1331 * Register modules with the given names.
1333 * - ResourceLoader::makeLoaderRegisterScript( [
1334 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1335 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1336 * ...
1337 * ] ):
1338 * Registers modules with the given names and parameters.
1340 * @param string $name Module name
1341 * @param string $version Module version hash
1342 * @param array $dependencies List of module names on which this module depends
1343 * @param string $group Group which the module is in
1344 * @param string $source Source of the module, or 'local' if not foreign
1345 * @param string $skip Script body of the skip function
1346 * @return string
1348 public static function makeLoaderRegisterScript( $name, $version = null,
1349 $dependencies = null, $group = null, $source = null, $skip = null
1351 if ( is_array( $name ) ) {
1352 // Build module name index
1353 $index = [];
1354 foreach ( $name as $i => &$module ) {
1355 $index[$module[0]] = $i;
1358 // Transform dependency names into indexes when possible, they will be resolved by
1359 // mw.loader.register on the other end
1360 foreach ( $name as &$module ) {
1361 if ( isset( $module[2] ) ) {
1362 foreach ( $module[2] as &$dependency ) {
1363 if ( isset( $index[$dependency] ) ) {
1364 $dependency = $index[$dependency];
1370 array_walk( $name, [ 'self', 'trimArray' ] );
1372 return Xml::encodeJsCall(
1373 'mw.loader.register',
1374 [ $name ],
1375 ResourceLoader::inDebugMode()
1377 } else {
1378 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1379 self::trimArray( $registration );
1380 return Xml::encodeJsCall(
1381 'mw.loader.register',
1382 $registration,
1383 ResourceLoader::inDebugMode()
1389 * Returns JS code which calls mw.loader.addSource() with the given
1390 * parameters. Has two calling conventions:
1392 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1393 * Register a single source
1395 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1396 * Register sources with the given IDs and properties.
1398 * @param string $id Source ID
1399 * @param string $loadUrl load.php url
1400 * @return string
1402 public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
1403 if ( is_array( $id ) ) {
1404 return Xml::encodeJsCall(
1405 'mw.loader.addSource',
1406 [ $id ],
1407 ResourceLoader::inDebugMode()
1409 } else {
1410 return Xml::encodeJsCall(
1411 'mw.loader.addSource',
1412 [ $id, $loadUrl ],
1413 ResourceLoader::inDebugMode()
1419 * Returns JS code which runs given JS code if the client-side framework is
1420 * present.
1422 * @deprecated since 1.25; use makeInlineScript instead
1423 * @param string $script JavaScript code
1424 * @return string
1426 public static function makeLoaderConditionalScript( $script ) {
1427 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1428 trim( $script ) . '});';
1432 * Construct an inline script tag with given JS code.
1434 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1435 * only if the client has adequate support for MediaWiki JavaScript code.
1437 * @param string $script JavaScript code
1438 * @return WrappedString HTML
1440 public static function makeInlineScript( $script ) {
1441 $js = self::makeLoaderConditionalScript( $script );
1442 return new WrappedString(
1443 Html::inlineScript( $js ),
1444 '<script>(window.RLQ=window.RLQ||[]).push(function(){',
1445 '});</script>'
1450 * Returns JS code which will set the MediaWiki configuration array to
1451 * the given value.
1453 * @param array $configuration List of configuration values keyed by variable name
1454 * @return string
1456 public static function makeConfigSetScript( array $configuration ) {
1457 return Xml::encodeJsCall(
1458 'mw.config.set',
1459 [ $configuration ],
1460 ResourceLoader::inDebugMode()
1465 * Convert an array of module names to a packed query string.
1467 * For example, [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]
1468 * becomes 'foo.bar,baz|bar.baz,quux'
1469 * @param array $modules List of module names (strings)
1470 * @return string Packed query string
1472 public static function makePackedModulesString( $modules ) {
1473 $groups = []; // [ prefix => [ suffixes ] ]
1474 foreach ( $modules as $module ) {
1475 $pos = strrpos( $module, '.' );
1476 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1477 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1478 $groups[$prefix][] = $suffix;
1481 $arr = [];
1482 foreach ( $groups as $prefix => $suffixes ) {
1483 $p = $prefix === '' ? '' : $prefix . '.';
1484 $arr[] = $p . implode( ',', $suffixes );
1486 $str = implode( '|', $arr );
1487 return $str;
1491 * Determine whether debug mode was requested
1492 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1493 * @return bool
1495 public static function inDebugMode() {
1496 if ( self::$debugMode === null ) {
1497 global $wgRequest, $wgResourceLoaderDebug;
1498 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1499 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1502 return self::$debugMode;
1506 * Reset static members used for caching.
1508 * Global state and $wgRequest are evil, but we're using it right
1509 * now and sometimes we need to be able to force ResourceLoader to
1510 * re-evaluate the context because it has changed (e.g. in the test suite).
1512 public static function clearCache() {
1513 self::$debugMode = null;
1517 * Build a load.php URL
1519 * @since 1.24
1520 * @param string $source Name of the ResourceLoader source
1521 * @param ResourceLoaderContext $context
1522 * @param array $extraQuery
1523 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1525 public function createLoaderURL( $source, ResourceLoaderContext $context,
1526 $extraQuery = []
1528 $query = self::createLoaderQuery( $context, $extraQuery );
1529 $script = $this->getLoadScript( $source );
1531 return wfAppendQuery( $script, $query );
1535 * Helper for createLoaderURL()
1537 * @since 1.24
1538 * @see makeLoaderQuery
1539 * @param ResourceLoaderContext $context
1540 * @param array $extraQuery
1541 * @return array
1543 protected static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = [] ) {
1544 return self::makeLoaderQuery(
1545 $context->getModules(),
1546 $context->getLanguage(),
1547 $context->getSkin(),
1548 $context->getUser(),
1549 $context->getVersion(),
1550 $context->getDebug(),
1551 $context->getOnly(),
1552 $context->getRequest()->getBool( 'printable' ),
1553 $context->getRequest()->getBool( 'handheld' ),
1554 $extraQuery
1559 * Build a query array (array representation of query string) for load.php. Helper
1560 * function for createLoaderURL().
1562 * @param array $modules
1563 * @param string $lang
1564 * @param string $skin
1565 * @param string $user
1566 * @param string $version
1567 * @param bool $debug
1568 * @param string $only
1569 * @param bool $printable
1570 * @param bool $handheld
1571 * @param array $extraQuery
1573 * @return array
1575 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1576 $version = null, $debug = false, $only = null, $printable = false,
1577 $handheld = false, $extraQuery = []
1579 $query = [
1580 'modules' => self::makePackedModulesString( $modules ),
1581 'lang' => $lang,
1582 'skin' => $skin,
1583 'debug' => $debug ? 'true' : 'false',
1585 if ( $user !== null ) {
1586 $query['user'] = $user;
1588 if ( $version !== null ) {
1589 $query['version'] = $version;
1591 if ( $only !== null ) {
1592 $query['only'] = $only;
1594 if ( $printable ) {
1595 $query['printable'] = 1;
1597 if ( $handheld ) {
1598 $query['handheld'] = 1;
1600 $query += $extraQuery;
1602 // Make queries uniform in order
1603 ksort( $query );
1604 return $query;
1608 * Check a module name for validity.
1610 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1611 * at most 255 bytes.
1613 * @param string $moduleName Module name to check
1614 * @return bool Whether $moduleName is a valid module name
1616 public static function isValidModuleName( $moduleName ) {
1617 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1621 * Returns LESS compiler set up for use with MediaWiki
1623 * @since 1.27
1624 * @param array $extraVars Associative array of extra (i.e., other than the
1625 * globally-configured ones) that should be used for compilation.
1626 * @throws MWException
1627 * @return Less_Parser
1629 public function getLessCompiler( $extraVars = [] ) {
1630 // When called from the installer, it is possible that a required PHP extension
1631 // is missing (at least for now; see bug 47564). If this is the case, throw an
1632 // exception (caught by the installer) to prevent a fatal error later on.
1633 if ( !class_exists( 'Less_Parser' ) ) {
1634 throw new MWException( 'MediaWiki requires the less.php parser' );
1637 $parser = new Less_Parser;
1638 $parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
1639 $parser->SetImportDirs(
1640 array_fill_keys( $this->config->get( 'ResourceLoaderLESSImportPaths' ), '' )
1642 $parser->SetOption( 'relativeUrls', false );
1644 return $parser;
1648 * Get global LESS variables.
1650 * @since 1.27
1651 * @return array Map of variable names to string CSS values.
1653 public function getLessVars() {
1654 if ( !$this->lessVars ) {
1655 $lessVars = $this->config->get( 'ResourceLoaderLESSVars' );
1656 Hooks::run( 'ResourceLoaderGetLessVars', [ &$lessVars ] );
1657 $this->lessVars = $lessVars;
1659 return $this->lessVars;