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 WrappedString\WrappedString
;
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
{
39 protected static $filterCacheVersion = 7;
42 protected static $debugMode = null;
45 private $lessVars = null;
48 * Module name/ResourceLoaderModule object pairs
51 protected $modules = [];
54 * Associative array mapping module name to info associative array
57 protected $moduleInfos = [];
59 /** @var Config $config */
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', ... ], ... ]
67 protected $testModuleNames = [];
70 * E.g. [ 'source-id' => 'http://.../load.php' ]
73 protected $sources = [];
76 * Errors accumulated during current respond() call.
79 protected $errors = [];
82 * @var MessageBlobStore
87 * @var LoggerInterface
91 /** @var string JavaScript / CSS pragma to disable minification. **/
92 const FILTER_NOMIN
= '/*@nomin*/';
95 * Load information stored in the database about modules.
97 * This method grabs modules dependencies from the database and updates modules
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!
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,
125 // Prime in-object cache for file dependencies
126 $modulesWithDeps = [];
127 foreach ( $res as $row ) {
128 $module = $this->getModule( $row->md_module
);
130 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
131 FormatJson
::decode( $row->md_deps
, true )
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 );
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
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 ) {
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(
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 );
204 $stats->increment( "resourceloader_cache.$filter.hit" );
206 if ( $result === null ) {
214 private static function applyFilter( $filter, $data ) {
215 $data = trim( $data );
218 $data = ( $filter === 'minify-css' )
219 ? CSSMin
::minify( $data )
220 : JavaScriptMinifier
::minify( $data );
221 } catch ( Exception
$e ) {
222 MWExceptionHandler
::logException( $e );
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 ) {
239 $this->logger
= $logger ?
: new NullLogger();
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' ) );
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
) );
270 public function getConfig() {
271 return $this->config
;
276 * @param LoggerInterface $logger
278 public function setLogger( LoggerInterface
$logger ) {
279 $this->logger
= $logger;
284 * @return LoggerInterface
286 public function getLogger() {
287 return $this->logger
;
292 * @return MessageBlobStore
294 public function getMessageBlobStore() {
295 return $this->blobStore
;
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
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()" );
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;
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] ) ) {
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];
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'] :
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;
396 public function registerTestModules() {
399 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
400 throw new MWException( 'Attempt to register JavaScript test modules '
401 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
402 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
405 // Get core test suites
407 $testModules['qunit'] = [];
408 // Get other test suites (e.g. from extensions)
409 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$this ] );
411 // Add the testrunner (which configures QUnit) to the dependencies.
412 // Since it must be ready before any of the test suites are executed.
413 foreach ( $testModules['qunit'] as &$module ) {
414 // Make sure all test modules are top-loading so that when QUnit starts
415 // on document-ready, it will run once and finish. If some tests arrive
416 // later (possibly after QUnit has already finished) they will be ignored.
417 $module['position'] = 'top';
418 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
421 $testModules['qunit'] =
422 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
424 foreach ( $testModules as $id => $names ) {
425 // Register test modules
426 $this->register( $testModules[$id] );
428 // Keep track of their names so that they can be loaded together
429 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
434 * Add a foreign source of modules.
436 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
438 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
439 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
440 * backwards-compatibility.
441 * @throws MWException
443 public function addSource( $id, $loadUrl = null ) {
444 // Allow multiple sources to be registered in one call
445 if ( is_array( $id ) ) {
446 foreach ( $id as $key => $value ) {
447 $this->addSource( $key, $value );
452 // Disallow duplicates
453 if ( isset( $this->sources
[$id] ) ) {
454 throw new MWException(
455 'ResourceLoader duplicate source addition error. ' .
456 'Another source has already been registered as ' . $id
460 // Pre 1.24 backwards-compatibility
461 if ( is_array( $loadUrl ) ) {
462 if ( !isset( $loadUrl['loadScript'] ) ) {
463 throw new MWException(
464 __METHOD__
. ' was passed an array with no "loadScript" key.'
468 $loadUrl = $loadUrl['loadScript'];
471 $this->sources
[$id] = $loadUrl;
475 * Get a list of module names.
477 * @return array List of module names
479 public function getModuleNames() {
480 return array_keys( $this->moduleInfos
);
484 * Get a list of test module names for one (or all) frameworks.
486 * If the given framework id is unknkown, or if the in-object variable is not an array,
487 * then it will return an empty array.
489 * @param string $framework Get only the test module names for one
490 * particular framework (optional)
493 public function getTestModuleNames( $framework = 'all' ) {
494 /** @todo api siteinfo prop testmodulenames modulenames */
495 if ( $framework == 'all' ) {
496 return $this->testModuleNames
;
497 } elseif ( isset( $this->testModuleNames
[$framework] )
498 && is_array( $this->testModuleNames
[$framework] )
500 return $this->testModuleNames
[$framework];
507 * Check whether a ResourceLoader module is registered
510 * @param string $name
513 public function isModuleRegistered( $name ) {
514 return isset( $this->moduleInfos
[$name] );
518 * Get the ResourceLoaderModule object for a given module name.
520 * If an array of module parameters exists but a ResourceLoaderModule object has not
521 * yet been instantiated, this method will instantiate and cache that object such that
522 * subsequent calls simply return the same object.
524 * @param string $name Module name
525 * @return ResourceLoaderModule|null If module has been registered, return a
526 * ResourceLoaderModule instance. Otherwise, return null.
528 public function getModule( $name ) {
529 if ( !isset( $this->modules
[$name] ) ) {
530 if ( !isset( $this->moduleInfos
[$name] ) ) {
534 // Construct the requested object
535 $info = $this->moduleInfos
[$name];
536 /** @var ResourceLoaderModule $object */
537 if ( isset( $info['object'] ) ) {
538 // Object given in info array
539 $object = $info['object'];
541 if ( !isset( $info['class'] ) ) {
542 $class = 'ResourceLoaderFileModule';
544 $class = $info['class'];
546 /** @var ResourceLoaderModule $object */
547 $object = new $class( $info );
548 $object->setConfig( $this->getConfig() );
549 $object->setLogger( $this->logger
);
551 $object->setName( $name );
552 $this->modules
[$name] = $object;
555 return $this->modules
[$name];
559 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
561 * @param string $name Module name
564 protected function isFileModule( $name ) {
565 if ( !isset( $this->moduleInfos
[$name] ) ) {
568 $info = $this->moduleInfos
[$name];
569 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
576 * Get the list of sources.
578 * @return array Like [ id => load.php url, ... ]
580 public function getSources() {
581 return $this->sources
;
585 * Get the URL to the load.php endpoint for the given
586 * ResourceLoader source
589 * @param string $source
590 * @throws MWException On an invalid $source name
593 public function getLoadScript( $source ) {
594 if ( !isset( $this->sources
[$source] ) ) {
595 throw new MWException( "The $source source was never registered in ResourceLoader." );
597 return $this->sources
[$source];
602 * @param string $value
603 * @return string Hash
605 public static function makeHash( $value ) {
606 $hash = hash( 'fnv132', $value );
607 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
611 * Helper method to get and combine versions of multiple modules.
614 * @param ResourceLoaderContext $context
615 * @param string[] $modules List of known module names
616 * @return string Hash
618 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
619 if ( !$moduleNames ) {
622 $hashes = array_map( function ( $module ) use ( $context ) {
623 return $this->getModule( $module )->getVersionHash( $context );
625 return self
::makeHash( implode( '', $hashes ) );
629 * Get the expected value of the 'version' query parameter.
631 * This is used by respond() to set a short Cache-Control header for requests with
632 * information newer than the current server has. This avoids pollution of edge caches.
633 * Typically during deployment. (T117587)
635 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
638 * @param ResourceLoaderContext $context
639 * @param string[] $modules List of module names
640 * @return string Hash
642 public function makeVersionQuery( ResourceLoaderContext
$context ) {
643 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
644 // version hashes. There is no technical reason for this to be same, and for years the
645 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
646 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
647 // query parameter), then this method must continue to match the JS one.
649 foreach ( $context->getModules() as $name ) {
650 if ( !$this->getModule( $name ) ) {
651 // If a versioned request contains a missing module, the version is a mismatch
652 // as the client considered a module (and version) we don't have.
655 $moduleNames[] = $name;
657 return $this->getCombinedVersion( $context, $moduleNames );
661 * Output a response to a load request, including the content-type header.
663 * @param ResourceLoaderContext $context Context in which a response should be formed
665 public function respond( ResourceLoaderContext
$context ) {
666 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
667 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
668 // is used: ob_clean() will clear the GZIP header in that case and it won't come
669 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
670 // the whole thing in our own output buffer to be sure the active buffer
671 // doesn't use ob_gzhandler.
672 // See https://bugs.php.net/bug.php?id=36514
675 // Find out which modules are missing and instantiate the others
678 foreach ( $context->getModules() as $name ) {
679 $module = $this->getModule( $name );
681 // Do not allow private modules to be loaded from the web.
682 // This is a security issue, see bug 34907.
683 if ( $module->getGroup() === 'private' ) {
684 $this->logger
->debug( "Request for private module '$name' denied" );
685 $this->errors
[] = "Cannot show private module \"$name\"";
688 $modules[$name] = $module;
695 // Preload for getCombinedVersion() and for batch makeModuleResponse()
696 $this->preloadModuleInfo( array_keys( $modules ), $context );
697 } catch ( Exception
$e ) {
698 MWExceptionHandler
::logException( $e );
699 $this->logger
->warning( 'Preloading module info failed: {exception}', [
702 $this->errors
[] = self
::formatExceptionNoComment( $e );
705 // Combine versions to propagate cache invalidation
708 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
709 } catch ( Exception
$e ) {
710 MWExceptionHandler
::logException( $e );
711 $this->logger
->warning( 'Calculating version hash failed: {exception}', [
714 $this->errors
[] = self
::formatExceptionNoComment( $e );
717 // See RFC 2616 § 3.11 Entity Tags
718 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
719 $etag = 'W/"' . $versionHash . '"';
721 // Try the client-side cache first
722 if ( $this->tryRespondNotModified( $context, $etag ) ) {
723 return; // output handled (buffers cleared)
726 // Use file cache if enabled and available...
727 if ( $this->config
->get( 'UseFileCache' ) ) {
728 $fileCache = ResourceFileCache
::newFromContext( $context );
729 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
730 return; // output handled
734 // Generate a response
735 $response = $this->makeModuleResponse( $context, $modules, $missing );
737 // Capture any PHP warnings from the output buffer and append them to the
738 // error list if we're in debug mode.
739 if ( $context->getDebug() ) {
740 $warnings = ob_get_contents();
741 if ( strlen( $warnings ) ) {
742 $this->errors
[] = $warnings;
746 // Save response to file cache unless there are errors
747 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
748 // Cache single modules and images...and other requests if there are enough hits
749 if ( ResourceFileCache
::useFileCache( $context ) ) {
750 if ( $fileCache->isCacheWorthy() ) {
751 $fileCache->saveText( $response );
753 $fileCache->incrMissesRecent( $context->getRequest() );
758 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
760 // Remove the output buffer and output the response
763 if ( $context->getImageObj() && $this->errors
) {
764 // We can't show both the error messages and the response when it's an image.
765 $response = implode( "\n\n", $this->errors
);
766 } elseif ( $this->errors
) {
767 $errorText = implode( "\n\n", $this->errors
);
768 $errorResponse = self
::makeComment( $errorText );
769 if ( $context->shouldIncludeScripts() ) {
770 $errorResponse .= 'if (window.console && console.error) {'
771 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
775 // Prepend error info to the response
776 $response = $errorResponse . $response;
784 * Send main response headers to the client.
786 * Deals with Content-Type, CORS (for stylesheets), and caching.
788 * @param ResourceLoaderContext $context
789 * @param string $etag ETag header value
790 * @param bool $errors Whether there are errors in the response
793 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
794 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
795 // Use a short cache expiry so that updates propagate to clients quickly, if:
796 // - No version specified (shared resources, e.g. stylesheets)
797 // - There were errors (recover quickly)
798 // - Version mismatch (T117587, T47877)
799 if ( is_null( $context->getVersion() )
801 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
803 $maxage = $rlMaxage['unversioned']['client'];
804 $smaxage = $rlMaxage['unversioned']['server'];
805 // If a version was specified we can use a longer expiry time since changing
806 // version numbers causes cache misses
808 $maxage = $rlMaxage['versioned']['client'];
809 $smaxage = $rlMaxage['versioned']['server'];
811 if ( $context->getImageObj() ) {
812 // Output different headers if we're outputting textual errors.
814 header( 'Content-Type: text/plain; charset=utf-8' );
816 $context->getImageObj()->sendResponseHeaders( $context );
818 } elseif ( $context->getOnly() === 'styles' ) {
819 header( 'Content-Type: text/css; charset=utf-8' );
820 header( 'Access-Control-Allow-Origin: *' );
822 header( 'Content-Type: text/javascript; charset=utf-8' );
824 // See RFC 2616 § 14.19 ETag
825 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
826 header( 'ETag: ' . $etag );
827 if ( $context->getDebug() ) {
828 // Do not cache debug responses
829 header( 'Cache-Control: private, no-cache, must-revalidate' );
830 header( 'Pragma: no-cache' );
832 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
833 $exp = min( $maxage, $smaxage );
834 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
839 * Respond with HTTP 304 Not Modified if appropiate.
841 * If there's an If-None-Match header, respond with a 304 appropriately
842 * and clear out the output buffer. If the client cache is too old then do nothing.
844 * @param ResourceLoaderContext $context
845 * @param string $etag ETag header value
846 * @return bool True if HTTP 304 was sent and output handled
848 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
849 // See RFC 2616 § 14.26 If-None-Match
850 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
851 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
852 // Never send 304s in debug mode
853 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
854 // There's another bug in ob_gzhandler (see also the comment at
855 // the top of this function) that causes it to gzip even empty
856 // responses, meaning it's impossible to produce a truly empty
857 // response (because the gzip header is always there). This is
858 // a problem because 304 responses have to be completely empty
859 // per the HTTP spec, and Firefox behaves buggily when they're not.
860 // See also https://bugs.php.net/bug.php?id=51579
861 // To work around this, we tear down all output buffering before
863 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
865 HttpStatus
::header( 304 );
867 $this->sendResponseHeaders( $context, $etag, false );
874 * Send out code for a response from file cache if possible.
876 * @param ResourceFileCache $fileCache Cache object for this request URL
877 * @param ResourceLoaderContext $context Context in which to generate a response
878 * @param string $etag ETag header value
879 * @return bool If this found a cache file and handled the response
881 protected function tryRespondFromFileCache(
882 ResourceFileCache
$fileCache,
883 ResourceLoaderContext
$context,
886 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
887 // Buffer output to catch warnings.
889 // Get the maximum age the cache can be
890 $maxage = is_null( $context->getVersion() )
891 ?
$rlMaxage['unversioned']['server']
892 : $rlMaxage['versioned']['server'];
893 // Minimum timestamp the cache file must have
894 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
896 try { // RL always hits the DB on file cache miss...
897 wfGetDB( DB_REPLICA
);
898 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
899 $good = $fileCache->isCacheGood(); // cache existence check
903 $ts = $fileCache->cacheTimestamp();
904 // Send content type and cache headers
905 $this->sendResponseHeaders( $context, $etag, false );
906 $response = $fileCache->fetchText();
907 // Capture any PHP warnings from the output buffer and append them to the
908 // response in a comment if we're in debug mode.
909 if ( $context->getDebug() ) {
910 $warnings = ob_get_contents();
911 if ( strlen( $warnings ) ) {
912 $response = self
::makeComment( $warnings ) . $response;
915 // Remove the output buffer and output the response
917 echo $response . "\n/* Cached {$ts} */";
918 return true; // cache hit
923 return false; // cache miss
927 * Generate a CSS or JS comment block.
929 * Only use this for public data, not error message details.
931 * @param string $text
934 public static function makeComment( $text ) {
935 $encText = str_replace( '*/', '* /', $text );
936 return "/*\n$encText\n*/\n";
940 * Handle exception display.
942 * @param Exception $e Exception to be shown to the user
943 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
945 public static function formatException( $e ) {
946 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
950 * Handle exception display.
953 * @param Exception $e Exception to be shown to the user
954 * @return string Sanitized text that can be returned to the user
956 protected static function formatExceptionNoComment( $e ) {
957 global $wgShowExceptionDetails;
959 if ( !$wgShowExceptionDetails ) {
960 return MWExceptionHandler
::getPublicLogMessage( $e );
963 return MWExceptionHandler
::getLogMessage( $e );
967 * Generate code for a response.
969 * @param ResourceLoaderContext $context Context in which to generate a response
970 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
971 * @param string[] $missing List of requested module names that are unregistered (optional)
972 * @return string Response data
974 public function makeModuleResponse( ResourceLoaderContext
$context,
975 array $modules, array $missing = []
980 if ( !count( $modules ) && !count( $missing ) ) {
982 /* This file is the Web entry point for MediaWiki's ResourceLoader:
983 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
984 no modules were requested. Max made me put this here. */
988 $image = $context->getImageObj();
990 $data = $image->getImageData( $context );
991 if ( $data === false ) {
993 $this->errors
[] = 'Image generation failed';
998 foreach ( $missing as $name ) {
999 $states[$name] = 'missing';
1005 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1007 foreach ( $modules as $name => $module ) {
1009 $content = $module->getModuleContent( $context );
1010 $implementKey = $name . '@' . $module->getVersionHash( $context );
1014 switch ( $context->getOnly() ) {
1016 $scripts = $content['scripts'];
1017 if ( is_string( $scripts ) ) {
1018 // Load scripts raw...
1019 $strContent = $scripts;
1020 } elseif ( is_array( $scripts ) ) {
1021 // ...except when $scripts is an array of URLs
1022 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1026 $styles = $content['styles'];
1027 // We no longer seperate into media, they are all combined now with
1028 // custom media type groups into @media .. {} sections as part of the css string.
1029 // Module returns either an empty array or a numerical array with css strings.
1030 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1033 $scripts = isset( $content['scripts'] ) ?
$content['scripts'] : '';
1034 if ( is_string( $scripts ) ) {
1035 if ( $name === 'site' ||
$name === 'user' ) {
1036 // Legacy scripts that run in the global scope without a closure.
1037 // mw.loader.implement will use globalEval if scripts is a string.
1038 // Minify manually here, because general response minification is
1039 // not effective due it being a string literal, not a function.
1040 if ( !ResourceLoader
::inDebugMode() ) {
1041 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1044 $scripts = new XmlJsCode( $scripts );
1047 $strContent = self
::makeLoaderImplementScript(
1050 isset( $content['styles'] ) ?
$content['styles'] : [],
1051 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1052 isset( $content['templates'] ) ?
$content['templates'] : []
1057 if ( !$context->getDebug() ) {
1058 $strContent = self
::filter( $filter, $strContent );
1061 $out .= $strContent;
1063 } catch ( Exception
$e ) {
1064 MWExceptionHandler
::logException( $e );
1065 $this->logger
->warning( 'Generating module package failed: {exception}', [
1068 $this->errors
[] = self
::formatExceptionNoComment( $e );
1070 // Respond to client with error-state instead of module implementation
1071 $states[$name] = 'error';
1072 unset( $modules[$name] );
1074 $isRaw |
= $module->isRaw();
1077 // Update module states
1078 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1079 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1080 // Set the state of modules loaded as only scripts to ready as
1081 // they don't have an mw.loader.implement wrapper that sets the state
1082 foreach ( $modules as $name => $module ) {
1083 $states[$name] = 'ready';
1087 // Set the state of modules we didn't respond to with mw.loader.implement
1088 if ( count( $states ) ) {
1089 $stateScript = self
::makeLoaderStateScript( $states );
1090 if ( !$context->getDebug() ) {
1091 $stateScript = self
::filter( 'minify-js', $stateScript );
1093 $out .= $stateScript;
1096 if ( count( $states ) ) {
1097 $this->errors
[] = 'Problematic modules: ' .
1098 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1106 * Get names of modules that use a certain message.
1108 * @param string $messageKey
1109 * @return array List of module names
1111 public function getModulesByMessage( $messageKey ) {
1113 foreach ( $this->getModuleNames() as $moduleName ) {
1114 $module = $this->getModule( $moduleName );
1115 if ( in_array( $messageKey, $module->getMessages() ) ) {
1116 $moduleNames[] = $moduleName;
1119 return $moduleNames;
1122 /* Static Methods */
1125 * Return JS code that calls mw.loader.implement with given module properties.
1127 * @param string $name Module name or implement key (format "`[name]@[version]`")
1128 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1129 * list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
1130 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1131 * to CSS files keyed by media type
1132 * @param mixed $messages List of messages associated with this module. May either be an
1133 * associative array mapping message key to value, or a JSON-encoded message blob containing
1134 * the same data, wrapped in an XmlJsCode object.
1135 * @param array $templates Keys are name of templates and values are the source of
1137 * @throws MWException
1140 protected static function makeLoaderImplementScript(
1141 $name, $scripts, $styles, $messages, $templates
1143 if ( $scripts instanceof XmlJsCode
) {
1144 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1145 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1146 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1148 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1149 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1150 // of "{}". Force them to objects.
1158 self
::trimArray( $module );
1160 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1164 * Returns JS code which, when called, will register a given list of messages.
1166 * @param mixed $messages Either an associative array mapping message key to value, or a
1167 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1170 public static function makeMessageSetScript( $messages ) {
1171 return Xml
::encodeJsCall(
1173 [ (object)$messages ],
1174 ResourceLoader
::inDebugMode()
1179 * Combines an associative array mapping media type to CSS into a
1180 * single stylesheet with "@media" blocks.
1182 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1185 public static function makeCombinedStyles( array $stylePairs ) {
1187 foreach ( $stylePairs as $media => $styles ) {
1188 // ResourceLoaderFileModule::getStyle can return the styles
1189 // as a string or an array of strings. This is to allow separation in
1191 $styles = (array)$styles;
1192 foreach ( $styles as $style ) {
1193 $style = trim( $style );
1194 // Don't output an empty "@media print { }" block (bug 40498)
1195 if ( $style !== '' ) {
1196 // Transform the media type based on request params and config
1197 // The way that this relies on $wgRequest to propagate request params is slightly evil
1198 $media = OutputPage
::transformCssMedia( $media );
1200 if ( $media === '' ||
$media == 'all' ) {
1202 } elseif ( is_string( $media ) ) {
1203 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1213 * Returns a JS call to mw.loader.state, which sets the state of a
1214 * module or modules to a given value. Has two calling conventions:
1216 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1217 * Set the state of a single module called $name to $state
1219 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1220 * Set the state of modules with the given names to the given states
1222 * @param string $name
1223 * @param string $state
1226 public static function makeLoaderStateScript( $name, $state = null ) {
1227 if ( is_array( $name ) ) {
1228 return Xml
::encodeJsCall(
1231 ResourceLoader
::inDebugMode()
1234 return Xml
::encodeJsCall(
1237 ResourceLoader
::inDebugMode()
1243 * Returns JS code which calls the script given by $script. The script will
1244 * be called with local variables name, version, dependencies and group,
1245 * which will have values corresponding to $name, $version, $dependencies
1246 * and $group as supplied.
1248 * @param string $name Module name
1249 * @param string $version Module version hash
1250 * @param array $dependencies List of module names on which this module depends
1251 * @param string $group Group which the module is in.
1252 * @param string $source Source of the module, or 'local' if not foreign.
1253 * @param string $script JavaScript code
1256 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1257 $group, $source, $script
1259 $script = str_replace( "\n", "\n\t", trim( $script ) );
1260 return Xml
::encodeJsCall(
1261 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1262 [ $name, $version, $dependencies, $group, $source ],
1263 ResourceLoader
::inDebugMode()
1267 private static function isEmptyObject( stdClass
$obj ) {
1268 foreach ( $obj as $key => $value ) {
1275 * Remove empty values from the end of an array.
1277 * Values considered empty:
1281 * - new XmlJsCode( '{}' )
1282 * - new stdClass() // (object) []
1284 * @param Array $array
1286 private static function trimArray( array &$array ) {
1287 $i = count( $array );
1289 if ( $array[$i] === null
1290 ||
$array[$i] === []
1291 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1292 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1294 unset( $array[$i] );
1302 * Returns JS code which calls mw.loader.register with the given
1303 * parameters. Has three calling conventions:
1305 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1306 * $dependencies, $group, $source, $skip
1308 * Register a single module.
1310 * - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
1311 * Register modules with the given names.
1313 * - ResourceLoader::makeLoaderRegisterScript( [
1314 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1315 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1318 * Registers modules with the given names and parameters.
1320 * @param string $name Module name
1321 * @param string $version Module version hash
1322 * @param array $dependencies List of module names on which this module depends
1323 * @param string $group Group which the module is in
1324 * @param string $source Source of the module, or 'local' if not foreign
1325 * @param string $skip Script body of the skip function
1328 public static function makeLoaderRegisterScript( $name, $version = null,
1329 $dependencies = null, $group = null, $source = null, $skip = null
1331 if ( is_array( $name ) ) {
1332 // Build module name index
1334 foreach ( $name as $i => &$module ) {
1335 $index[$module[0]] = $i;
1338 // Transform dependency names into indexes when possible, they will be resolved by
1339 // mw.loader.register on the other end
1340 foreach ( $name as &$module ) {
1341 if ( isset( $module[2] ) ) {
1342 foreach ( $module[2] as &$dependency ) {
1343 if ( isset( $index[$dependency] ) ) {
1344 $dependency = $index[$dependency];
1350 array_walk( $name, [ 'self', 'trimArray' ] );
1352 return Xml
::encodeJsCall(
1353 'mw.loader.register',
1355 ResourceLoader
::inDebugMode()
1358 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1359 self
::trimArray( $registration );
1360 return Xml
::encodeJsCall(
1361 'mw.loader.register',
1363 ResourceLoader
::inDebugMode()
1369 * Returns JS code which calls mw.loader.addSource() with the given
1370 * parameters. Has two calling conventions:
1372 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1373 * Register a single source
1375 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1376 * Register sources with the given IDs and properties.
1378 * @param string $id Source ID
1379 * @param string $loadUrl load.php url
1382 public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
1383 if ( is_array( $id ) ) {
1384 return Xml
::encodeJsCall(
1385 'mw.loader.addSource',
1387 ResourceLoader
::inDebugMode()
1390 return Xml
::encodeJsCall(
1391 'mw.loader.addSource',
1393 ResourceLoader
::inDebugMode()
1399 * Returns JS code which runs given JS code if the client-side framework is
1402 * @deprecated since 1.25; use makeInlineScript instead
1403 * @param string $script JavaScript code
1406 public static function makeLoaderConditionalScript( $script ) {
1407 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1408 trim( $script ) . '});';
1412 * Construct an inline script tag with given JS code.
1414 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1415 * only if the client has adequate support for MediaWiki JavaScript code.
1417 * @param string $script JavaScript code
1418 * @return WrappedString HTML
1420 public static function makeInlineScript( $script ) {
1421 $js = self
::makeLoaderConditionalScript( $script );
1422 return new WrappedString(
1423 Html
::inlineScript( $js ),
1424 '<script>(window.RLQ=window.RLQ||[]).push(function(){',
1430 * Returns JS code which will set the MediaWiki configuration array to
1433 * @param array $configuration List of configuration values keyed by variable name
1436 public static function makeConfigSetScript( array $configuration ) {
1437 return Xml
::encodeJsCall(
1440 ResourceLoader
::inDebugMode()
1445 * Convert an array of module names to a packed query string.
1447 * For example, [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]
1448 * becomes 'foo.bar,baz|bar.baz,quux'
1449 * @param array $modules List of module names (strings)
1450 * @return string Packed query string
1452 public static function makePackedModulesString( $modules ) {
1453 $groups = []; // [ prefix => [ suffixes ] ]
1454 foreach ( $modules as $module ) {
1455 $pos = strrpos( $module, '.' );
1456 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1457 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1458 $groups[$prefix][] = $suffix;
1462 foreach ( $groups as $prefix => $suffixes ) {
1463 $p = $prefix === '' ?
'' : $prefix . '.';
1464 $arr[] = $p . implode( ',', $suffixes );
1466 $str = implode( '|', $arr );
1471 * Determine whether debug mode was requested
1472 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1475 public static function inDebugMode() {
1476 if ( self
::$debugMode === null ) {
1477 global $wgRequest, $wgResourceLoaderDebug;
1478 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1479 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1482 return self
::$debugMode;
1486 * Reset static members used for caching.
1488 * Global state and $wgRequest are evil, but we're using it right
1489 * now and sometimes we need to be able to force ResourceLoader to
1490 * re-evaluate the context because it has changed (e.g. in the test suite).
1492 public static function clearCache() {
1493 self
::$debugMode = null;
1497 * Build a load.php URL
1500 * @param string $source Name of the ResourceLoader source
1501 * @param ResourceLoaderContext $context
1502 * @param array $extraQuery
1503 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1505 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1508 $query = self
::createLoaderQuery( $context, $extraQuery );
1509 $script = $this->getLoadScript( $source );
1511 return wfAppendQuery( $script, $query );
1515 * Helper for createLoaderURL()
1518 * @see makeLoaderQuery
1519 * @param ResourceLoaderContext $context
1520 * @param array $extraQuery
1523 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1524 return self
::makeLoaderQuery(
1525 $context->getModules(),
1526 $context->getLanguage(),
1527 $context->getSkin(),
1528 $context->getUser(),
1529 $context->getVersion(),
1530 $context->getDebug(),
1531 $context->getOnly(),
1532 $context->getRequest()->getBool( 'printable' ),
1533 $context->getRequest()->getBool( 'handheld' ),
1539 * Build a query array (array representation of query string) for load.php. Helper
1540 * function for createLoaderURL().
1542 * @param array $modules
1543 * @param string $lang
1544 * @param string $skin
1545 * @param string $user
1546 * @param string $version
1547 * @param bool $debug
1548 * @param string $only
1549 * @param bool $printable
1550 * @param bool $handheld
1551 * @param array $extraQuery
1555 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1556 $version = null, $debug = false, $only = null, $printable = false,
1557 $handheld = false, $extraQuery = []
1560 'modules' => self
::makePackedModulesString( $modules ),
1563 'debug' => $debug ?
'true' : 'false',
1565 if ( $user !== null ) {
1566 $query['user'] = $user;
1568 if ( $version !== null ) {
1569 $query['version'] = $version;
1571 if ( $only !== null ) {
1572 $query['only'] = $only;
1575 $query['printable'] = 1;
1578 $query['handheld'] = 1;
1580 $query +
= $extraQuery;
1582 // Make queries uniform in order
1588 * Check a module name for validity.
1590 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1591 * at most 255 bytes.
1593 * @param string $moduleName Module name to check
1594 * @return bool Whether $moduleName is a valid module name
1596 public static function isValidModuleName( $moduleName ) {
1597 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1601 * Returns LESS compiler set up for use with MediaWiki
1604 * @param array $extraVars Associative array of extra (i.e., other than the
1605 * globally-configured ones) that should be used for compilation.
1606 * @throws MWException
1607 * @return Less_Parser
1609 public function getLessCompiler( $extraVars = [] ) {
1610 // When called from the installer, it is possible that a required PHP extension
1611 // is missing (at least for now; see bug 47564). If this is the case, throw an
1612 // exception (caught by the installer) to prevent a fatal error later on.
1613 if ( !class_exists( 'Less_Parser' ) ) {
1614 throw new MWException( 'MediaWiki requires the less.php parser' );
1617 $parser = new Less_Parser
;
1618 $parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
1619 $parser->SetImportDirs(
1620 array_fill_keys( $this->config
->get( 'ResourceLoaderLESSImportPaths' ), '' )
1622 $parser->SetOption( 'relativeUrls', false );
1628 * Get global LESS variables.
1631 * @return array Map of variable names to string CSS values.
1633 public function getLessVars() {
1634 if ( !$this->lessVars
) {
1635 $lessVars = $this->config
->get( 'ResourceLoaderLESSVars' );
1636 Hooks
::run( 'ResourceLoaderGetLessVars', [ &$lessVars ] );
1637 $this->lessVars
= $lessVars;
1639 return $this->lessVars
;