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 Psr\Log\LoggerAwareInterface
;
26 use Psr\Log\LoggerInterface
;
27 use Psr\Log\NullLogger
;
28 use WrappedString\WrappedString
;
31 * Dynamic JavaScript and CSS resource loading system.
33 * Most of the documentation is on the MediaWiki documentation wiki starting at:
34 * https://www.mediawiki.org/wiki/ResourceLoader
36 class ResourceLoader
implements LoggerAwareInterface
{
38 protected static $filterCacheVersion = 7;
41 protected static $debugMode = null;
44 private $lessVars = null;
47 * Module name/ResourceLoaderModule object pairs
50 protected $modules = [];
53 * Associative array mapping module name to info associative array
56 protected $moduleInfos = [];
58 /** @var Config $config */
62 * Associative array mapping framework ids to a list of names of test suite modules
63 * like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... ], ... ]
66 protected $testModuleNames = [];
69 * E.g. [ 'source-id' => 'http://.../load.php' ]
72 protected $sources = [];
75 * Errors accumulated during current respond() call.
78 protected $errors = [];
81 * @var MessageBlobStore
86 * @var LoggerInterface
90 /** @var string JavaScript / CSS pragma to disable minification. **/
91 const FILTER_NOMIN
= '/*@nomin*/';
94 * Load information stored in the database about modules.
96 * This method grabs modules dependencies from the database and updates modules
99 * This is not inside the module code because it is much faster to
100 * request all of the information at once than it is to have each module
101 * requests its own information. This sacrifice of modularity yields a substantial
102 * performance improvement.
104 * @param array $moduleNames List of module names to preload information for
105 * @param ResourceLoaderContext $context Context to load the information within
107 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext
$context ) {
108 if ( !$moduleNames ) {
109 // Or else Database*::select() will explode, plus it's cheaper!
112 $dbr = wfGetDB( DB_REPLICA
);
113 $skin = $context->getSkin();
114 $lang = $context->getLanguage();
116 // Batched version of ResourceLoaderModule::getFileDependencies
117 $vary = "$skin|$lang";
118 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
119 'md_module' => $moduleNames,
124 // Prime in-object cache for file dependencies
125 $modulesWithDeps = [];
126 foreach ( $res as $row ) {
127 $module = $this->getModule( $row->md_module
);
129 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
130 FormatJson
::decode( $row->md_deps
, true )
132 $modulesWithDeps[] = $row->md_module
;
135 // Register the absence of a dependency row too
136 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
137 $module = $this->getModule( $name );
139 $this->getModule( $name )->setFileDependencies( $context, [] );
143 // Batched version of ResourceLoaderWikiModule::getTitleInfo
144 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $moduleNames );
146 // Prime in-object cache for message blobs for modules with messages
148 foreach ( $moduleNames as $name ) {
149 $module = $this->getModule( $name );
150 if ( $module && $module->getMessages() ) {
151 $modules[$name] = $module;
154 $store = $this->getMessageBlobStore();
155 $blobs = $store->getBlobs( $modules, $lang );
156 foreach ( $blobs as $name => $blob ) {
157 $modules[$name]->setMessageBlob( $blob, $lang );
162 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
164 * Available filters are:
166 * - minify-js \see JavaScriptMinifier::minify
167 * - minify-css \see CSSMin::minify
169 * If $data is empty, only contains whitespace or the filter was unknown,
170 * $data is returned unmodified.
172 * @param string $filter Name of filter to run
173 * @param string $data Text to filter, such as JavaScript or CSS text
174 * @param array $options Keys:
175 * - (bool) cache: Whether to allow caching this data. Default: true.
176 * @return string Filtered data, or a comment containing an error message
178 public static function filter( $filter, $data, array $options = [] ) {
179 if ( strpos( $data, ResourceLoader
::FILTER_NOMIN
) !== false ) {
183 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
184 return self
::applyFilter( $filter, $data );
187 $stats = RequestContext
::getMain()->getStats();
188 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
190 $key = $cache->makeGlobalKey(
194 self
::$filterCacheVersion, md5( $data )
197 $result = $cache->get( $key );
198 if ( $result === false ) {
199 $stats->increment( "resourceloader_cache.$filter.miss" );
200 $result = self
::applyFilter( $filter, $data );
201 $cache->set( $key, $result, 24 * 3600 );
203 $stats->increment( "resourceloader_cache.$filter.hit" );
205 if ( $result === null ) {
213 private static function applyFilter( $filter, $data ) {
214 $data = trim( $data );
217 $data = ( $filter === 'minify-css' )
218 ? CSSMin
::minify( $data )
219 : JavaScriptMinifier
::minify( $data );
220 } catch ( Exception
$e ) {
221 MWExceptionHandler
::logException( $e );
231 * Register core modules and runs registration hooks.
232 * @param Config $config [optional]
233 * @param LoggerInterface $logger [optional]
235 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
238 $this->logger
= $logger ?
: new NullLogger();
241 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
242 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
244 $this->config
= $config;
246 // Add 'local' source first
247 $this->addSource( 'local', $config->get( 'LoadScript' ) );
250 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
252 // Register core modules
253 $this->register( include "$IP/resources/Resources.php" );
254 $this->register( include "$IP/resources/ResourcesOOUI.php" );
255 // Register extension modules
256 $this->register( $config->get( 'ResourceModules' ) );
257 Hooks
::run( 'ResourceLoaderRegisterModules', [ &$this ] );
259 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
260 $this->registerTestModules();
263 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
269 public function getConfig() {
270 return $this->config
;
275 * @param LoggerInterface $logger
277 public function setLogger( LoggerInterface
$logger ) {
278 $this->logger
= $logger;
283 * @return LoggerInterface
285 public function getLogger() {
286 return $this->logger
;
291 * @return MessageBlobStore
293 public function getMessageBlobStore() {
294 return $this->blobStore
;
299 * @param MessageBlobStore $blobStore
301 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
302 $this->blobStore
= $blobStore;
306 * Register a module with the ResourceLoader system.
308 * @param mixed $name Name of module as a string or List of name/object pairs as an array
309 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
310 * this may also be a ResourceLoaderModule object. Optional when using
311 * multiple-registration calling style.
312 * @throws MWException If a duplicate module registration is attempted
313 * @throws MWException If a module name contains illegal characters (pipes or commas)
314 * @throws MWException If something other than a ResourceLoaderModule is being registered
315 * @return bool False if there were any errors, in which case one or more modules were
318 public function register( $name, $info = null ) {
319 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
321 // Allow multiple modules to be registered in one call
322 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
323 foreach ( $registrations as $name => $info ) {
324 // Warn on duplicate registrations
325 if ( isset( $this->moduleInfos
[$name] ) ) {
326 // A module has already been registered by this name
327 $this->logger
->warning(
328 'ResourceLoader duplicate registration warning. ' .
329 'Another module has already been registered as ' . $name
333 // Check $name for validity
334 if ( !self
::isValidModuleName( $name ) ) {
335 throw new MWException( "ResourceLoader module name '$name' is invalid, "
336 . "see ResourceLoader::isValidModuleName()" );
340 if ( $info instanceof ResourceLoaderModule
) {
341 $this->moduleInfos
[$name] = [ 'object' => $info ];
342 $info->setName( $name );
343 $this->modules
[$name] = $info;
344 } elseif ( is_array( $info ) ) {
345 // New calling convention
346 $this->moduleInfos
[$name] = $info;
348 throw new MWException(
349 'ResourceLoader module info type error for module \'' . $name .
350 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
354 // Last-minute changes
356 // Apply custom skin-defined styles to existing modules.
357 if ( $this->isFileModule( $name ) ) {
358 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
359 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
360 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
364 // If $name is preceded with a '+', the defined style files will be added to 'default'
365 // skinStyles, otherwise 'default' will be ignored as it normally would be.
366 if ( isset( $skinStyles[$name] ) ) {
367 $paths = (array)$skinStyles[$name];
369 } elseif ( isset( $skinStyles['+' . $name] ) ) {
370 $paths = (array)$skinStyles['+' . $name];
371 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
372 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
378 // Add new file paths, remapping them to refer to our directories and not use settings
379 // from the module we're modifying, which come from the base definition.
380 list( $localBasePath, $remoteBasePath ) =
381 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
383 foreach ( $paths as $path ) {
384 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
387 $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] );
435 * Add a foreign source of modules.
437 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
439 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
440 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
441 * backwards-compatibility.
442 * @throws MWException
444 public function addSource( $id, $loadUrl = null ) {
445 // Allow multiple sources to be registered in one call
446 if ( is_array( $id ) ) {
447 foreach ( $id as $key => $value ) {
448 $this->addSource( $key, $value );
453 // Disallow duplicates
454 if ( isset( $this->sources
[$id] ) ) {
455 throw new MWException(
456 'ResourceLoader duplicate source addition error. ' .
457 'Another source has already been registered as ' . $id
461 // Pre 1.24 backwards-compatibility
462 if ( is_array( $loadUrl ) ) {
463 if ( !isset( $loadUrl['loadScript'] ) ) {
464 throw new MWException(
465 __METHOD__
. ' was passed an array with no "loadScript" key.'
469 $loadUrl = $loadUrl['loadScript'];
472 $this->sources
[$id] = $loadUrl;
476 * Get a list of module names.
478 * @return array List of module names
480 public function getModuleNames() {
481 return array_keys( $this->moduleInfos
);
485 * Get a list of test module names for one (or all) frameworks.
487 * If the given framework id is unknkown, or if the in-object variable is not an array,
488 * then it will return an empty array.
490 * @param string $framework Get only the test module names for one
491 * particular framework (optional)
494 public function getTestModuleNames( $framework = 'all' ) {
495 /** @todo api siteinfo prop testmodulenames modulenames */
496 if ( $framework == 'all' ) {
497 return $this->testModuleNames
;
498 } elseif ( isset( $this->testModuleNames
[$framework] )
499 && is_array( $this->testModuleNames
[$framework] )
501 return $this->testModuleNames
[$framework];
508 * Check whether a ResourceLoader module is registered
511 * @param string $name
514 public function isModuleRegistered( $name ) {
515 return isset( $this->moduleInfos
[$name] );
519 * Get the ResourceLoaderModule object for a given module name.
521 * If an array of module parameters exists but a ResourceLoaderModule object has not
522 * yet been instantiated, this method will instantiate and cache that object such that
523 * subsequent calls simply return the same object.
525 * @param string $name Module name
526 * @return ResourceLoaderModule|null If module has been registered, return a
527 * ResourceLoaderModule instance. Otherwise, return null.
529 public function getModule( $name ) {
530 if ( !isset( $this->modules
[$name] ) ) {
531 if ( !isset( $this->moduleInfos
[$name] ) ) {
535 // Construct the requested object
536 $info = $this->moduleInfos
[$name];
537 /** @var ResourceLoaderModule $object */
538 if ( isset( $info['object'] ) ) {
539 // Object given in info array
540 $object = $info['object'];
542 if ( !isset( $info['class'] ) ) {
543 $class = 'ResourceLoaderFileModule';
545 $class = $info['class'];
547 /** @var ResourceLoaderModule $object */
548 $object = new $class( $info );
549 $object->setConfig( $this->getConfig() );
550 $object->setLogger( $this->logger
);
552 $object->setName( $name );
553 $this->modules
[$name] = $object;
556 return $this->modules
[$name];
560 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
562 * @param string $name Module name
565 protected function isFileModule( $name ) {
566 if ( !isset( $this->moduleInfos
[$name] ) ) {
569 $info = $this->moduleInfos
[$name];
570 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
577 * Get the list of sources.
579 * @return array Like [ id => load.php url, ... ]
581 public function getSources() {
582 return $this->sources
;
586 * Get the URL to the load.php endpoint for the given
587 * ResourceLoader source
590 * @param string $source
591 * @throws MWException On an invalid $source name
594 public function getLoadScript( $source ) {
595 if ( !isset( $this->sources
[$source] ) ) {
596 throw new MWException( "The $source source was never registered in ResourceLoader." );
598 return $this->sources
[$source];
603 * @param string $value
604 * @return string Hash
606 public static function makeHash( $value ) {
607 $hash = hash( 'fnv132', $value );
608 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
612 * Helper method to get and combine versions of multiple modules.
615 * @param ResourceLoaderContext $context
616 * @param string[] $modules List of known module names
617 * @return string Hash
619 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
620 if ( !$moduleNames ) {
623 $hashes = array_map( function ( $module ) use ( $context ) {
624 return $this->getModule( $module )->getVersionHash( $context );
626 return self
::makeHash( implode( '', $hashes ) );
630 * Get the expected value of the 'version' query parameter.
632 * This is used by respond() to set a short Cache-Control header for requests with
633 * information newer than the current server has. This avoids pollution of edge caches.
634 * Typically during deployment. (T117587)
636 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
639 * @param ResourceLoaderContext $context
640 * @param string[] $modules List of module names
641 * @return string Hash
643 public function makeVersionQuery( ResourceLoaderContext
$context ) {
644 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
645 // version hashes. There is no technical reason for this to be same, and for years the
646 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
647 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
648 // query parameter), then this method must continue to match the JS one.
650 foreach ( $context->getModules() as $name ) {
651 if ( !$this->getModule( $name ) ) {
652 // If a versioned request contains a missing module, the version is a mismatch
653 // as the client considered a module (and version) we don't have.
656 $moduleNames[] = $name;
658 return $this->getCombinedVersion( $context, $moduleNames );
662 * Output a response to a load request, including the content-type header.
664 * @param ResourceLoaderContext $context Context in which a response should be formed
666 public function respond( ResourceLoaderContext
$context ) {
667 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
668 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
669 // is used: ob_clean() will clear the GZIP header in that case and it won't come
670 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
671 // the whole thing in our own output buffer to be sure the active buffer
672 // doesn't use ob_gzhandler.
673 // See http://bugs.php.net/bug.php?id=36514
676 // Find out which modules are missing and instantiate the others
679 foreach ( $context->getModules() as $name ) {
680 $module = $this->getModule( $name );
682 // Do not allow private modules to be loaded from the web.
683 // This is a security issue, see bug 34907.
684 if ( $module->getGroup() === 'private' ) {
685 $this->logger
->debug( "Request for private module '$name' denied" );
686 $this->errors
[] = "Cannot show private module \"$name\"";
689 $modules[$name] = $module;
696 // Preload for getCombinedVersion() and for batch makeModuleResponse()
697 $this->preloadModuleInfo( array_keys( $modules ), $context );
698 } catch ( Exception
$e ) {
699 MWExceptionHandler
::logException( $e );
700 $this->logger
->warning( 'Preloading module info failed: {exception}', [
703 $this->errors
[] = self
::formatExceptionNoComment( $e );
706 // Combine versions to propagate cache invalidation
709 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
710 } catch ( Exception
$e ) {
711 MWExceptionHandler
::logException( $e );
712 $this->logger
->warning( 'Calculating version hash failed: {exception}', [
715 $this->errors
[] = self
::formatExceptionNoComment( $e );
718 // See RFC 2616 § 3.11 Entity Tags
719 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
720 $etag = 'W/"' . $versionHash . '"';
722 // Try the client-side cache first
723 if ( $this->tryRespondNotModified( $context, $etag ) ) {
724 return; // output handled (buffers cleared)
727 // Use file cache if enabled and available...
728 if ( $this->config
->get( 'UseFileCache' ) ) {
729 $fileCache = ResourceFileCache
::newFromContext( $context );
730 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
731 return; // output handled
735 // Generate a response
736 $response = $this->makeModuleResponse( $context, $modules, $missing );
738 // Capture any PHP warnings from the output buffer and append them to the
739 // error list if we're in debug mode.
740 if ( $context->getDebug() ) {
741 $warnings = ob_get_contents();
742 if ( strlen( $warnings ) ) {
743 $this->errors
[] = $warnings;
747 // Save response to file cache unless there are errors
748 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
749 // Cache single modules and images...and other requests if there are enough hits
750 if ( ResourceFileCache
::useFileCache( $context ) ) {
751 if ( $fileCache->isCacheWorthy() ) {
752 $fileCache->saveText( $response );
754 $fileCache->incrMissesRecent( $context->getRequest() );
759 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
761 // Remove the output buffer and output the response
764 if ( $context->getImageObj() && $this->errors
) {
765 // We can't show both the error messages and the response when it's an image.
766 $response = implode( "\n\n", $this->errors
);
767 } elseif ( $this->errors
) {
768 $errorText = implode( "\n\n", $this->errors
);
769 $errorResponse = self
::makeComment( $errorText );
770 if ( $context->shouldIncludeScripts() ) {
771 $errorResponse .= 'if (window.console && console.error) {'
772 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
776 // Prepend error info to the response
777 $response = $errorResponse . $response;
786 * Send main response headers to the client.
788 * Deals with Content-Type, CORS (for stylesheets), and caching.
790 * @param ResourceLoaderContext $context
791 * @param string $etag ETag header value
792 * @param bool $errors Whether there are errors in the response
795 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
796 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
797 // Use a short cache expiry so that updates propagate to clients quickly, if:
798 // - No version specified (shared resources, e.g. stylesheets)
799 // - There were errors (recover quickly)
800 // - Version mismatch (T117587, T47877)
801 if ( is_null( $context->getVersion() )
803 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
805 $maxage = $rlMaxage['unversioned']['client'];
806 $smaxage = $rlMaxage['unversioned']['server'];
807 // If a version was specified we can use a longer expiry time since changing
808 // version numbers causes cache misses
810 $maxage = $rlMaxage['versioned']['client'];
811 $smaxage = $rlMaxage['versioned']['server'];
813 if ( $context->getImageObj() ) {
814 // Output different headers if we're outputting textual errors.
816 header( 'Content-Type: text/plain; charset=utf-8' );
818 $context->getImageObj()->sendResponseHeaders( $context );
820 } elseif ( $context->getOnly() === 'styles' ) {
821 header( 'Content-Type: text/css; charset=utf-8' );
822 header( 'Access-Control-Allow-Origin: *' );
824 header( 'Content-Type: text/javascript; charset=utf-8' );
826 // See RFC 2616 § 14.19 ETag
827 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
828 header( 'ETag: ' . $etag );
829 if ( $context->getDebug() ) {
830 // Do not cache debug responses
831 header( 'Cache-Control: private, no-cache, must-revalidate' );
832 header( 'Pragma: no-cache' );
834 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
835 $exp = min( $maxage, $smaxage );
836 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
841 * Respond with HTTP 304 Not Modified if appropiate.
843 * If there's an If-None-Match header, respond with a 304 appropriately
844 * and clear out the output buffer. If the client cache is too old then do nothing.
846 * @param ResourceLoaderContext $context
847 * @param string $etag ETag header value
848 * @return bool True if HTTP 304 was sent and output handled
850 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
851 // See RFC 2616 § 14.26 If-None-Match
852 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
853 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
854 // Never send 304s in debug mode
855 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
856 // There's another bug in ob_gzhandler (see also the comment at
857 // the top of this function) that causes it to gzip even empty
858 // responses, meaning it's impossible to produce a truly empty
859 // response (because the gzip header is always there). This is
860 // a problem because 304 responses have to be completely empty
861 // per the HTTP spec, and Firefox behaves buggily when they're not.
862 // See also http://bugs.php.net/bug.php?id=51579
863 // To work around this, we tear down all output buffering before
865 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
867 HttpStatus
::header( 304 );
869 $this->sendResponseHeaders( $context, $etag, false );
876 * Send out code for a response from file cache if possible.
878 * @param ResourceFileCache $fileCache Cache object for this request URL
879 * @param ResourceLoaderContext $context Context in which to generate a response
880 * @param string $etag ETag header value
881 * @return bool If this found a cache file and handled the response
883 protected function tryRespondFromFileCache(
884 ResourceFileCache
$fileCache,
885 ResourceLoaderContext
$context,
888 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
889 // Buffer output to catch warnings.
891 // Get the maximum age the cache can be
892 $maxage = is_null( $context->getVersion() )
893 ?
$rlMaxage['unversioned']['server']
894 : $rlMaxage['versioned']['server'];
895 // Minimum timestamp the cache file must have
896 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
898 try { // RL always hits the DB on file cache miss...
899 wfGetDB( DB_REPLICA
);
900 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
901 $good = $fileCache->isCacheGood(); // cache existence check
905 $ts = $fileCache->cacheTimestamp();
906 // Send content type and cache headers
907 $this->sendResponseHeaders( $context, $etag, false );
908 $response = $fileCache->fetchText();
909 // Capture any PHP warnings from the output buffer and append them to the
910 // response in a comment if we're in debug mode.
911 if ( $context->getDebug() ) {
912 $warnings = ob_get_contents();
913 if ( strlen( $warnings ) ) {
914 $response = self
::makeComment( $warnings ) . $response;
917 // Remove the output buffer and output the response
919 echo $response . "\n/* Cached {$ts} */";
920 return true; // cache hit
925 return false; // cache miss
929 * Generate a CSS or JS comment block.
931 * Only use this for public data, not error message details.
933 * @param string $text
936 public static function makeComment( $text ) {
937 $encText = str_replace( '*/', '* /', $text );
938 return "/*\n$encText\n*/\n";
942 * Handle exception display.
944 * @param Exception $e Exception to be shown to the user
945 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
947 public static function formatException( $e ) {
948 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
952 * Handle exception display.
955 * @param Exception $e Exception to be shown to the user
956 * @return string Sanitized text that can be returned to the user
958 protected static function formatExceptionNoComment( $e ) {
959 global $wgShowExceptionDetails;
961 if ( !$wgShowExceptionDetails ) {
962 return MWExceptionHandler
::getPublicLogMessage( $e );
965 return MWExceptionHandler
::getLogMessage( $e );
969 * Generate code for a response.
971 * @param ResourceLoaderContext $context Context in which to generate a response
972 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
973 * @param string[] $missing List of requested module names that are unregistered (optional)
974 * @return string Response data
976 public function makeModuleResponse( ResourceLoaderContext
$context,
977 array $modules, array $missing = []
982 if ( !count( $modules ) && !count( $missing ) ) {
984 /* This file is the Web entry point for MediaWiki's ResourceLoader:
985 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
986 no modules were requested. Max made me put this here. */
990 $image = $context->getImageObj();
992 $data = $image->getImageData( $context );
993 if ( $data === false ) {
995 $this->errors
[] = 'Image generation failed';
1000 foreach ( $missing as $name ) {
1001 $states[$name] = 'missing';
1007 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1009 foreach ( $modules as $name => $module ) {
1011 $content = $module->getModuleContent( $context );
1015 switch ( $context->getOnly() ) {
1017 $scripts = $content['scripts'];
1018 if ( is_string( $scripts ) ) {
1019 // Load scripts raw...
1020 $strContent = $scripts;
1021 } elseif ( is_array( $scripts ) ) {
1022 // ...except when $scripts is an array of URLs
1023 $strContent = self
::makeLoaderImplementScript( $name, $scripts, [], [], [] );
1027 $styles = $content['styles'];
1028 // We no longer seperate into media, they are all combined now with
1029 // custom media type groups into @media .. {} sections as part of the css string.
1030 // Module returns either an empty array or a numerical array with css strings.
1031 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1034 $scripts = isset( $content['scripts'] ) ?
$content['scripts'] : '';
1035 if ( is_string( $scripts ) ) {
1036 if ( $name === 'site' ||
$name === 'user' ) {
1037 // Legacy scripts that run in the global scope without a closure.
1038 // mw.loader.implement will use globalEval if scripts is a string.
1039 // Minify manually here, because general response minification is
1040 // not effective due it being a string literal, not a function.
1041 if ( !ResourceLoader
::inDebugMode() ) {
1042 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1045 $scripts = new XmlJsCode( $scripts );
1048 $strContent = self
::makeLoaderImplementScript(
1051 isset( $content['styles'] ) ?
$content['styles'] : [],
1052 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1053 isset( $content['templates'] ) ?
$content['templates'] : []
1058 if ( !$context->getDebug() ) {
1059 $strContent = self
::filter( $filter, $strContent );
1062 $out .= $strContent;
1064 } catch ( Exception
$e ) {
1065 MWExceptionHandler
::logException( $e );
1066 $this->logger
->warning( 'Generating module package failed: {exception}', [
1069 $this->errors
[] = self
::formatExceptionNoComment( $e );
1071 // Respond to client with error-state instead of module implementation
1072 $states[$name] = 'error';
1073 unset( $modules[$name] );
1075 $isRaw |
= $module->isRaw();
1078 // Update module states
1079 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1080 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1081 // Set the state of modules loaded as only scripts to ready as
1082 // they don't have an mw.loader.implement wrapper that sets the state
1083 foreach ( $modules as $name => $module ) {
1084 $states[$name] = 'ready';
1088 // Set the state of modules we didn't respond to with mw.loader.implement
1089 if ( count( $states ) ) {
1090 $stateScript = self
::makeLoaderStateScript( $states );
1091 if ( !$context->getDebug() ) {
1092 $stateScript = self
::filter( 'minify-js', $stateScript );
1094 $out .= $stateScript;
1097 if ( count( $states ) ) {
1098 $this->errors
[] = 'Problematic modules: ' .
1099 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1107 * Get names of modules that use a certain message.
1109 * @param string $messageKey
1110 * @return array List of module names
1112 public function getModulesByMessage( $messageKey ) {
1114 foreach ( $this->getModuleNames() as $moduleName ) {
1115 $module = $this->getModule( $moduleName );
1116 if ( in_array( $messageKey, $module->getMessages() ) ) {
1117 $moduleNames[] = $moduleName;
1120 return $moduleNames;
1123 /* Static Methods */
1126 * Return JS code that calls mw.loader.implement with given module properties.
1128 * @param string $name Module name
1129 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1130 * list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
1131 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1132 * to CSS files keyed by media type
1133 * @param mixed $messages List of messages associated with this module. May either be an
1134 * associative array mapping message key to value, or a JSON-encoded message blob containing
1135 * the same data, wrapped in an XmlJsCode object.
1136 * @param array $templates Keys are name of templates and values are the source of
1138 * @throws MWException
1141 protected static function makeLoaderImplementScript(
1142 $name, $scripts, $styles, $messages, $templates
1145 if ( $scripts instanceof XmlJsCode
) {
1146 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1147 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1148 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1150 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1151 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1152 // of "{}". Force them to objects.
1160 self
::trimArray( $module );
1162 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1166 * Returns JS code which, when called, will register a given list of messages.
1168 * @param mixed $messages Either an associative array mapping message key to value, or a
1169 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1172 public static function makeMessageSetScript( $messages ) {
1173 return Xml
::encodeJsCall(
1175 [ (object)$messages ],
1176 ResourceLoader
::inDebugMode()
1181 * Combines an associative array mapping media type to CSS into a
1182 * single stylesheet with "@media" blocks.
1184 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1187 public static function makeCombinedStyles( array $stylePairs ) {
1189 foreach ( $stylePairs as $media => $styles ) {
1190 // ResourceLoaderFileModule::getStyle can return the styles
1191 // as a string or an array of strings. This is to allow separation in
1193 $styles = (array)$styles;
1194 foreach ( $styles as $style ) {
1195 $style = trim( $style );
1196 // Don't output an empty "@media print { }" block (bug 40498)
1197 if ( $style !== '' ) {
1198 // Transform the media type based on request params and config
1199 // The way that this relies on $wgRequest to propagate request params is slightly evil
1200 $media = OutputPage
::transformCssMedia( $media );
1202 if ( $media === '' ||
$media == 'all' ) {
1204 } elseif ( is_string( $media ) ) {
1205 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1215 * Returns a JS call to mw.loader.state, which sets the state of a
1216 * module or modules to a given value. Has two calling conventions:
1218 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1219 * Set the state of a single module called $name to $state
1221 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1222 * Set the state of modules with the given names to the given states
1224 * @param string $name
1225 * @param string $state
1228 public static function makeLoaderStateScript( $name, $state = null ) {
1229 if ( is_array( $name ) ) {
1230 return Xml
::encodeJsCall(
1233 ResourceLoader
::inDebugMode()
1236 return Xml
::encodeJsCall(
1239 ResourceLoader
::inDebugMode()
1245 * Returns JS code which calls the script given by $script. The script will
1246 * be called with local variables name, version, dependencies and group,
1247 * which will have values corresponding to $name, $version, $dependencies
1248 * and $group as supplied.
1250 * @param string $name Module name
1251 * @param string $version Module version hash
1252 * @param array $dependencies List of module names on which this module depends
1253 * @param string $group Group which the module is in.
1254 * @param string $source Source of the module, or 'local' if not foreign.
1255 * @param string $script JavaScript code
1258 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1259 $group, $source, $script
1261 $script = str_replace( "\n", "\n\t", trim( $script ) );
1262 return Xml
::encodeJsCall(
1263 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1264 [ $name, $version, $dependencies, $group, $source ],
1265 ResourceLoader
::inDebugMode()
1269 private static function isEmptyObject( stdClass
$obj ) {
1270 foreach ( $obj as $key => $value ) {
1277 * Remove empty values from the end of an array.
1279 * Values considered empty:
1283 * - new XmlJsCode( '{}' )
1284 * - new stdClass() // (object) []
1286 * @param Array $array
1288 private static function trimArray( array &$array ) {
1289 $i = count( $array );
1291 if ( $array[$i] === null
1292 ||
$array[$i] === []
1293 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1294 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1296 unset( $array[$i] );
1304 * Returns JS code which calls mw.loader.register with the given
1305 * parameters. Has three calling conventions:
1307 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1308 * $dependencies, $group, $source, $skip
1310 * Register a single module.
1312 * - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
1313 * Register modules with the given names.
1315 * - ResourceLoader::makeLoaderRegisterScript( [
1316 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1317 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1320 * Registers modules with the given names and parameters.
1322 * @param string $name Module name
1323 * @param string $version Module version hash
1324 * @param array $dependencies List of module names on which this module depends
1325 * @param string $group Group which the module is in
1326 * @param string $source Source of the module, or 'local' if not foreign
1327 * @param string $skip Script body of the skip function
1330 public static function makeLoaderRegisterScript( $name, $version = null,
1331 $dependencies = null, $group = null, $source = null, $skip = null
1333 if ( is_array( $name ) ) {
1334 // Build module name index
1336 foreach ( $name as $i => &$module ) {
1337 $index[$module[0]] = $i;
1340 // Transform dependency names into indexes when possible, they will be resolved by
1341 // mw.loader.register on the other end
1342 foreach ( $name as &$module ) {
1343 if ( isset( $module[2] ) ) {
1344 foreach ( $module[2] as &$dependency ) {
1345 if ( isset( $index[$dependency] ) ) {
1346 $dependency = $index[$dependency];
1352 array_walk( $name, [ 'self', 'trimArray' ] );
1354 return Xml
::encodeJsCall(
1355 'mw.loader.register',
1357 ResourceLoader
::inDebugMode()
1360 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1361 self
::trimArray( $registration );
1362 return Xml
::encodeJsCall(
1363 'mw.loader.register',
1365 ResourceLoader
::inDebugMode()
1371 * Returns JS code which calls mw.loader.addSource() with the given
1372 * parameters. Has two calling conventions:
1374 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1375 * Register a single source
1377 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1378 * Register sources with the given IDs and properties.
1380 * @param string $id Source ID
1381 * @param string $loadUrl load.php url
1384 public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
1385 if ( is_array( $id ) ) {
1386 return Xml
::encodeJsCall(
1387 'mw.loader.addSource',
1389 ResourceLoader
::inDebugMode()
1392 return Xml
::encodeJsCall(
1393 'mw.loader.addSource',
1395 ResourceLoader
::inDebugMode()
1401 * Returns JS code which runs given JS code if the client-side framework is
1404 * @deprecated since 1.25; use makeInlineScript instead
1405 * @param string $script JavaScript code
1408 public static function makeLoaderConditionalScript( $script ) {
1409 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1410 trim( $script ) . '});';
1414 * Construct an inline script tag with given JS code.
1416 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1417 * only if the client has adequate support for MediaWiki JavaScript code.
1419 * @param string $script JavaScript code
1420 * @return WrappedString HTML
1422 public static function makeInlineScript( $script ) {
1423 $js = self
::makeLoaderConditionalScript( $script );
1424 return new WrappedString(
1425 Html
::inlineScript( $js ),
1426 '<script>(window.RLQ=window.RLQ||[]).push(function(){',
1432 * Returns JS code which will set the MediaWiki configuration array to
1435 * @param array $configuration List of configuration values keyed by variable name
1436 * @param bool $pretty Pretty-print with extra whitespace
1439 public static function makeConfigSetScript( array $configuration, $pretty = null ) {
1440 return Xml
::encodeJsCall(
1443 ( $pretty === null ) ? ResourceLoader
::inDebugMode() : $pretty
1448 * Convert an array of module names to a packed query string.
1450 * For example, [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]
1451 * becomes 'foo.bar,baz|bar.baz,quux'
1452 * @param array $modules List of module names (strings)
1453 * @return string Packed query string
1455 public static function makePackedModulesString( $modules ) {
1456 $groups = []; // [ prefix => [ suffixes ] ]
1457 foreach ( $modules as $module ) {
1458 $pos = strrpos( $module, '.' );
1459 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1460 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1461 $groups[$prefix][] = $suffix;
1465 foreach ( $groups as $prefix => $suffixes ) {
1466 $p = $prefix === '' ?
'' : $prefix . '.';
1467 $arr[] = $p . implode( ',', $suffixes );
1469 $str = implode( '|', $arr );
1474 * Determine whether debug mode was requested
1475 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1478 public static function inDebugMode() {
1479 if ( self
::$debugMode === null ) {
1480 global $wgRequest, $wgResourceLoaderDebug;
1481 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1482 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1485 return self
::$debugMode;
1489 * Reset static members used for caching.
1491 * Global state and $wgRequest are evil, but we're using it right
1492 * now and sometimes we need to be able to force ResourceLoader to
1493 * re-evaluate the context because it has changed (e.g. in the test suite).
1495 public static function clearCache() {
1496 self
::$debugMode = null;
1500 * Build a load.php URL
1503 * @param string $source Name of the ResourceLoader source
1504 * @param ResourceLoaderContext $context
1505 * @param array $extraQuery
1506 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1508 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1511 $query = self
::createLoaderQuery( $context, $extraQuery );
1512 $script = $this->getLoadScript( $source );
1514 return wfAppendQuery( $script, $query );
1518 * Helper for createLoaderURL()
1521 * @see makeLoaderQuery
1522 * @param ResourceLoaderContext $context
1523 * @param array $extraQuery
1526 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1527 return self
::makeLoaderQuery(
1528 $context->getModules(),
1529 $context->getLanguage(),
1530 $context->getSkin(),
1531 $context->getUser(),
1532 $context->getVersion(),
1533 $context->getDebug(),
1534 $context->getOnly(),
1535 $context->getRequest()->getBool( 'printable' ),
1536 $context->getRequest()->getBool( 'handheld' ),
1542 * Build a query array (array representation of query string) for load.php. Helper
1543 * function for createLoaderURL().
1545 * @param array $modules
1546 * @param string $lang
1547 * @param string $skin
1548 * @param string $user
1549 * @param string $version
1550 * @param bool $debug
1551 * @param string $only
1552 * @param bool $printable
1553 * @param bool $handheld
1554 * @param array $extraQuery
1558 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1559 $version = null, $debug = false, $only = null, $printable = false,
1560 $handheld = false, $extraQuery = []
1563 'modules' => self
::makePackedModulesString( $modules ),
1566 'debug' => $debug ?
'true' : 'false',
1568 if ( $user !== null ) {
1569 $query['user'] = $user;
1571 if ( $version !== null ) {
1572 $query['version'] = $version;
1574 if ( $only !== null ) {
1575 $query['only'] = $only;
1578 $query['printable'] = 1;
1581 $query['handheld'] = 1;
1583 $query +
= $extraQuery;
1585 // Make queries uniform in order
1591 * Check a module name for validity.
1593 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1594 * at most 255 bytes.
1596 * @param string $moduleName Module name to check
1597 * @return bool Whether $moduleName is a valid module name
1599 public static function isValidModuleName( $moduleName ) {
1600 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1604 * Returns LESS compiler set up for use with MediaWiki
1607 * @param array $extraVars Associative array of extra (i.e., other than the
1608 * globally-configured ones) that should be used for compilation.
1609 * @throws MWException
1610 * @return Less_Parser
1612 public function getLessCompiler( $extraVars = [] ) {
1613 // When called from the installer, it is possible that a required PHP extension
1614 // is missing (at least for now; see bug 47564). If this is the case, throw an
1615 // exception (caught by the installer) to prevent a fatal error later on.
1616 if ( !class_exists( 'Less_Parser' ) ) {
1617 throw new MWException( 'MediaWiki requires the less.php parser' );
1620 $parser = new Less_Parser
;
1621 $parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
1622 $parser->SetImportDirs(
1623 array_fill_keys( $this->config
->get( 'ResourceLoaderLESSImportPaths' ), '' )
1625 $parser->SetOption( 'relativeUrls', false );
1631 * Get global LESS variables.
1634 * @return array Map of variable names to string CSS values.
1636 public function getLessVars() {
1637 if ( !$this->lessVars
) {
1638 $lessVars = $this->config
->get( 'ResourceLoaderLESSVars' );
1639 Hooks
::run( 'ResourceLoaderGetLessVars', [ &$lessVars ] );
1640 $this->lessVars
= $lessVars;
1642 return $this->lessVars
;