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 );
1012 $implementKey = $name . '@' . $module->getVersionHash( $context );
1016 switch ( $context->getOnly() ) {
1018 $scripts = $content['scripts'];
1019 if ( is_string( $scripts ) ) {
1020 // Load scripts raw...
1021 $strContent = $scripts;
1022 } elseif ( is_array( $scripts ) ) {
1023 // ...except when $scripts is an array of URLs
1024 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1028 $styles = $content['styles'];
1029 // We no longer seperate into media, they are all combined now with
1030 // custom media type groups into @media .. {} sections as part of the css string.
1031 // Module returns either an empty array or a numerical array with css strings.
1032 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1035 $scripts = isset( $content['scripts'] ) ?
$content['scripts'] : '';
1036 if ( is_string( $scripts ) ) {
1037 if ( $name === 'site' ||
$name === 'user' ) {
1038 // Legacy scripts that run in the global scope without a closure.
1039 // mw.loader.implement will use globalEval if scripts is a string.
1040 // Minify manually here, because general response minification is
1041 // not effective due it being a string literal, not a function.
1042 if ( !ResourceLoader
::inDebugMode() ) {
1043 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1046 $scripts = new XmlJsCode( $scripts );
1049 $strContent = self
::makeLoaderImplementScript(
1052 isset( $content['styles'] ) ?
$content['styles'] : [],
1053 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1054 isset( $content['templates'] ) ?
$content['templates'] : []
1059 if ( !$context->getDebug() ) {
1060 $strContent = self
::filter( $filter, $strContent );
1063 $out .= $strContent;
1065 } catch ( Exception
$e ) {
1066 MWExceptionHandler
::logException( $e );
1067 $this->logger
->warning( 'Generating module package failed: {exception}', [
1070 $this->errors
[] = self
::formatExceptionNoComment( $e );
1072 // Respond to client with error-state instead of module implementation
1073 $states[$name] = 'error';
1074 unset( $modules[$name] );
1076 $isRaw |
= $module->isRaw();
1079 // Update module states
1080 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1081 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1082 // Set the state of modules loaded as only scripts to ready as
1083 // they don't have an mw.loader.implement wrapper that sets the state
1084 foreach ( $modules as $name => $module ) {
1085 $states[$name] = 'ready';
1089 // Set the state of modules we didn't respond to with mw.loader.implement
1090 if ( count( $states ) ) {
1091 $stateScript = self
::makeLoaderStateScript( $states );
1092 if ( !$context->getDebug() ) {
1093 $stateScript = self
::filter( 'minify-js', $stateScript );
1095 $out .= $stateScript;
1098 if ( count( $states ) ) {
1099 $this->errors
[] = 'Problematic modules: ' .
1100 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1108 * Get names of modules that use a certain message.
1110 * @param string $messageKey
1111 * @return array List of module names
1113 public function getModulesByMessage( $messageKey ) {
1115 foreach ( $this->getModuleNames() as $moduleName ) {
1116 $module = $this->getModule( $moduleName );
1117 if ( in_array( $messageKey, $module->getMessages() ) ) {
1118 $moduleNames[] = $moduleName;
1121 return $moduleNames;
1124 /* Static Methods */
1127 * Return JS code that calls mw.loader.implement with given module properties.
1129 * @param string $name Module name or implement key (format "`[name]@[version]`")
1130 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1131 * list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
1132 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1133 * to CSS files keyed by media type
1134 * @param mixed $messages List of messages associated with this module. May either be an
1135 * associative array mapping message key to value, or a JSON-encoded message blob containing
1136 * the same data, wrapped in an XmlJsCode object.
1137 * @param array $templates Keys are name of templates and values are the source of
1139 * @throws MWException
1142 protected static function makeLoaderImplementScript(
1143 $name, $scripts, $styles, $messages, $templates
1146 if ( $scripts instanceof XmlJsCode
) {
1147 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1148 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1149 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1151 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1152 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1153 // of "{}". Force them to objects.
1161 self
::trimArray( $module );
1163 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1167 * Returns JS code which, when called, will register a given list of messages.
1169 * @param mixed $messages Either an associative array mapping message key to value, or a
1170 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1173 public static function makeMessageSetScript( $messages ) {
1174 return Xml
::encodeJsCall(
1176 [ (object)$messages ],
1177 ResourceLoader
::inDebugMode()
1182 * Combines an associative array mapping media type to CSS into a
1183 * single stylesheet with "@media" blocks.
1185 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1188 public static function makeCombinedStyles( array $stylePairs ) {
1190 foreach ( $stylePairs as $media => $styles ) {
1191 // ResourceLoaderFileModule::getStyle can return the styles
1192 // as a string or an array of strings. This is to allow separation in
1194 $styles = (array)$styles;
1195 foreach ( $styles as $style ) {
1196 $style = trim( $style );
1197 // Don't output an empty "@media print { }" block (bug 40498)
1198 if ( $style !== '' ) {
1199 // Transform the media type based on request params and config
1200 // The way that this relies on $wgRequest to propagate request params is slightly evil
1201 $media = OutputPage
::transformCssMedia( $media );
1203 if ( $media === '' ||
$media == 'all' ) {
1205 } elseif ( is_string( $media ) ) {
1206 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1216 * Returns a JS call to mw.loader.state, which sets the state of a
1217 * module or modules to a given value. Has two calling conventions:
1219 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1220 * Set the state of a single module called $name to $state
1222 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1223 * Set the state of modules with the given names to the given states
1225 * @param string $name
1226 * @param string $state
1229 public static function makeLoaderStateScript( $name, $state = null ) {
1230 if ( is_array( $name ) ) {
1231 return Xml
::encodeJsCall(
1234 ResourceLoader
::inDebugMode()
1237 return Xml
::encodeJsCall(
1240 ResourceLoader
::inDebugMode()
1246 * Returns JS code which calls the script given by $script. The script will
1247 * be called with local variables name, version, dependencies and group,
1248 * which will have values corresponding to $name, $version, $dependencies
1249 * and $group as supplied.
1251 * @param string $name Module name
1252 * @param string $version Module version hash
1253 * @param array $dependencies List of module names on which this module depends
1254 * @param string $group Group which the module is in.
1255 * @param string $source Source of the module, or 'local' if not foreign.
1256 * @param string $script JavaScript code
1259 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1260 $group, $source, $script
1262 $script = str_replace( "\n", "\n\t", trim( $script ) );
1263 return Xml
::encodeJsCall(
1264 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1265 [ $name, $version, $dependencies, $group, $source ],
1266 ResourceLoader
::inDebugMode()
1270 private static function isEmptyObject( stdClass
$obj ) {
1271 foreach ( $obj as $key => $value ) {
1278 * Remove empty values from the end of an array.
1280 * Values considered empty:
1284 * - new XmlJsCode( '{}' )
1285 * - new stdClass() // (object) []
1287 * @param Array $array
1289 private static function trimArray( array &$array ) {
1290 $i = count( $array );
1292 if ( $array[$i] === null
1293 ||
$array[$i] === []
1294 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1295 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1297 unset( $array[$i] );
1305 * Returns JS code which calls mw.loader.register with the given
1306 * parameters. Has three calling conventions:
1308 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1309 * $dependencies, $group, $source, $skip
1311 * Register a single module.
1313 * - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
1314 * Register modules with the given names.
1316 * - ResourceLoader::makeLoaderRegisterScript( [
1317 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1318 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1321 * Registers modules with the given names and parameters.
1323 * @param string $name Module name
1324 * @param string $version Module version hash
1325 * @param array $dependencies List of module names on which this module depends
1326 * @param string $group Group which the module is in
1327 * @param string $source Source of the module, or 'local' if not foreign
1328 * @param string $skip Script body of the skip function
1331 public static function makeLoaderRegisterScript( $name, $version = null,
1332 $dependencies = null, $group = null, $source = null, $skip = null
1334 if ( is_array( $name ) ) {
1335 // Build module name index
1337 foreach ( $name as $i => &$module ) {
1338 $index[$module[0]] = $i;
1341 // Transform dependency names into indexes when possible, they will be resolved by
1342 // mw.loader.register on the other end
1343 foreach ( $name as &$module ) {
1344 if ( isset( $module[2] ) ) {
1345 foreach ( $module[2] as &$dependency ) {
1346 if ( isset( $index[$dependency] ) ) {
1347 $dependency = $index[$dependency];
1353 array_walk( $name, [ 'self', 'trimArray' ] );
1355 return Xml
::encodeJsCall(
1356 'mw.loader.register',
1358 ResourceLoader
::inDebugMode()
1361 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1362 self
::trimArray( $registration );
1363 return Xml
::encodeJsCall(
1364 'mw.loader.register',
1366 ResourceLoader
::inDebugMode()
1372 * Returns JS code which calls mw.loader.addSource() with the given
1373 * parameters. Has two calling conventions:
1375 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1376 * Register a single source
1378 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1379 * Register sources with the given IDs and properties.
1381 * @param string $id Source ID
1382 * @param string $loadUrl load.php url
1385 public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
1386 if ( is_array( $id ) ) {
1387 return Xml
::encodeJsCall(
1388 'mw.loader.addSource',
1390 ResourceLoader
::inDebugMode()
1393 return Xml
::encodeJsCall(
1394 'mw.loader.addSource',
1396 ResourceLoader
::inDebugMode()
1402 * Returns JS code which runs given JS code if the client-side framework is
1405 * @deprecated since 1.25; use makeInlineScript instead
1406 * @param string $script JavaScript code
1409 public static function makeLoaderConditionalScript( $script ) {
1410 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1411 trim( $script ) . '});';
1415 * Construct an inline script tag with given JS code.
1417 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1418 * only if the client has adequate support for MediaWiki JavaScript code.
1420 * @param string $script JavaScript code
1421 * @return WrappedString HTML
1423 public static function makeInlineScript( $script ) {
1424 $js = self
::makeLoaderConditionalScript( $script );
1425 return new WrappedString(
1426 Html
::inlineScript( $js ),
1427 '<script>(window.RLQ=window.RLQ||[]).push(function(){',
1433 * Returns JS code which will set the MediaWiki configuration array to
1436 * @param array $configuration List of configuration values keyed by variable name
1437 * @param bool $pretty Pretty-print with extra whitespace
1440 public static function makeConfigSetScript( array $configuration, $pretty = null ) {
1441 return Xml
::encodeJsCall(
1444 ( $pretty === null ) ? ResourceLoader
::inDebugMode() : $pretty
1449 * Convert an array of module names to a packed query string.
1451 * For example, [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]
1452 * becomes 'foo.bar,baz|bar.baz,quux'
1453 * @param array $modules List of module names (strings)
1454 * @return string Packed query string
1456 public static function makePackedModulesString( $modules ) {
1457 $groups = []; // [ prefix => [ suffixes ] ]
1458 foreach ( $modules as $module ) {
1459 $pos = strrpos( $module, '.' );
1460 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1461 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1462 $groups[$prefix][] = $suffix;
1466 foreach ( $groups as $prefix => $suffixes ) {
1467 $p = $prefix === '' ?
'' : $prefix . '.';
1468 $arr[] = $p . implode( ',', $suffixes );
1470 $str = implode( '|', $arr );
1475 * Determine whether debug mode was requested
1476 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1479 public static function inDebugMode() {
1480 if ( self
::$debugMode === null ) {
1481 global $wgRequest, $wgResourceLoaderDebug;
1482 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1483 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1486 return self
::$debugMode;
1490 * Reset static members used for caching.
1492 * Global state and $wgRequest are evil, but we're using it right
1493 * now and sometimes we need to be able to force ResourceLoader to
1494 * re-evaluate the context because it has changed (e.g. in the test suite).
1496 public static function clearCache() {
1497 self
::$debugMode = null;
1501 * Build a load.php URL
1504 * @param string $source Name of the ResourceLoader source
1505 * @param ResourceLoaderContext $context
1506 * @param array $extraQuery
1507 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1509 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1512 $query = self
::createLoaderQuery( $context, $extraQuery );
1513 $script = $this->getLoadScript( $source );
1515 return wfAppendQuery( $script, $query );
1519 * Helper for createLoaderURL()
1522 * @see makeLoaderQuery
1523 * @param ResourceLoaderContext $context
1524 * @param array $extraQuery
1527 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1528 return self
::makeLoaderQuery(
1529 $context->getModules(),
1530 $context->getLanguage(),
1531 $context->getSkin(),
1532 $context->getUser(),
1533 $context->getVersion(),
1534 $context->getDebug(),
1535 $context->getOnly(),
1536 $context->getRequest()->getBool( 'printable' ),
1537 $context->getRequest()->getBool( 'handheld' ),
1543 * Build a query array (array representation of query string) for load.php. Helper
1544 * function for createLoaderURL().
1546 * @param array $modules
1547 * @param string $lang
1548 * @param string $skin
1549 * @param string $user
1550 * @param string $version
1551 * @param bool $debug
1552 * @param string $only
1553 * @param bool $printable
1554 * @param bool $handheld
1555 * @param array $extraQuery
1559 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1560 $version = null, $debug = false, $only = null, $printable = false,
1561 $handheld = false, $extraQuery = []
1564 'modules' => self
::makePackedModulesString( $modules ),
1567 'debug' => $debug ?
'true' : 'false',
1569 if ( $user !== null ) {
1570 $query['user'] = $user;
1572 if ( $version !== null ) {
1573 $query['version'] = $version;
1575 if ( $only !== null ) {
1576 $query['only'] = $only;
1579 $query['printable'] = 1;
1582 $query['handheld'] = 1;
1584 $query +
= $extraQuery;
1586 // Make queries uniform in order
1592 * Check a module name for validity.
1594 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1595 * at most 255 bytes.
1597 * @param string $moduleName Module name to check
1598 * @return bool Whether $moduleName is a valid module name
1600 public static function isValidModuleName( $moduleName ) {
1601 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1605 * Returns LESS compiler set up for use with MediaWiki
1608 * @param array $extraVars Associative array of extra (i.e., other than the
1609 * globally-configured ones) that should be used for compilation.
1610 * @throws MWException
1611 * @return Less_Parser
1613 public function getLessCompiler( $extraVars = [] ) {
1614 // When called from the installer, it is possible that a required PHP extension
1615 // is missing (at least for now; see bug 47564). If this is the case, throw an
1616 // exception (caught by the installer) to prevent a fatal error later on.
1617 if ( !class_exists( 'Less_Parser' ) ) {
1618 throw new MWException( 'MediaWiki requires the less.php parser' );
1621 $parser = new Less_Parser
;
1622 $parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
1623 $parser->SetImportDirs(
1624 array_fill_keys( $this->config
->get( 'ResourceLoaderLESSImportPaths' ), '' )
1626 $parser->SetOption( 'relativeUrls', false );
1632 * Get global LESS variables.
1635 * @return array Map of variable names to string CSS values.
1637 public function getLessVars() {
1638 if ( !$this->lessVars
) {
1639 $lessVars = $this->config
->get( 'ResourceLoaderLESSVars' );
1640 Hooks
::run( 'ResourceLoaderGetLessVars', [ &$lessVars ] );
1641 $this->lessVars
= $lessVars;
1643 return $this->lessVars
;