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 array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
66 protected $testModuleNames = [];
69 * E.g. array( '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_SLAVE
);
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 // Prime in-object cache for message blobs for modules with messages
145 foreach ( $moduleNames as $name ) {
146 $module = $this->getModule( $name );
147 if ( $module && $module->getMessages() ) {
148 $modules[$name] = $module;
151 $store = $this->getMessageBlobStore();
152 $blobs = $store->getBlobs( $modules, $lang );
153 foreach ( $blobs as $name => $blob ) {
154 $modules[$name]->setMessageBlob( $blob, $lang );
159 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
161 * Available filters are:
163 * - minify-js \see JavaScriptMinifier::minify
164 * - minify-css \see CSSMin::minify
166 * If $data is empty, only contains whitespace or the filter was unknown,
167 * $data is returned unmodified.
169 * @param string $filter Name of filter to run
170 * @param string $data Text to filter, such as JavaScript or CSS text
171 * @param array $options Keys:
172 * - (bool) cache: Whether to allow caching this data. Default: true.
173 * @return string Filtered data, or a comment containing an error message
175 public static function filter( $filter, $data, array $options = [] ) {
176 if ( strpos( $data, ResourceLoader
::FILTER_NOMIN
) !== false ) {
180 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
181 return self
::applyFilter( $filter, $data );
184 $stats = RequestContext
::getMain()->getStats();
185 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
187 $key = $cache->makeGlobalKey(
191 self
::$filterCacheVersion, md5( $data )
194 $result = $cache->get( $key );
195 if ( $result === false ) {
196 $stats->increment( "resourceloader_cache.$filter.miss" );
197 $result = self
::applyFilter( $filter, $data );
198 $cache->set( $key, $result, 24 * 3600 );
200 $stats->increment( "resourceloader_cache.$filter.hit" );
202 if ( $result === null ) {
210 private static function applyFilter( $filter, $data ) {
211 $data = trim( $data );
214 $data = ( $filter === 'minify-css' )
215 ? CSSMin
::minify( $data )
216 : JavaScriptMinifier
::minify( $data );
217 } catch ( Exception
$e ) {
218 MWExceptionHandler
::logException( $e );
228 * Register core modules and runs registration hooks.
229 * @param Config $config [optional]
230 * @param LoggerInterface $logger [optional]
232 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
235 $this->logger
= $logger ?
: new NullLogger();
238 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
239 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
241 $this->config
= $config;
243 // Add 'local' source first
244 $this->addSource( 'local', wfScript( 'load' ) );
247 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
249 // Register core modules
250 $this->register( include "$IP/resources/Resources.php" );
251 $this->register( include "$IP/resources/ResourcesOOUI.php" );
252 // Register extension modules
253 $this->register( $config->get( 'ResourceModules' ) );
254 Hooks
::run( 'ResourceLoaderRegisterModules', [ &$this ] );
256 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
257 $this->registerTestModules();
260 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
266 public function getConfig() {
267 return $this->config
;
272 * @param LoggerInterface $logger
274 public function setLogger( LoggerInterface
$logger ) {
275 $this->logger
= $logger;
280 * @return LoggerInterface
282 public function getLogger() {
283 return $this->logger
;
288 * @return MessageBlobStore
290 public function getMessageBlobStore() {
291 return $this->blobStore
;
296 * @param MessageBlobStore $blobStore
298 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
299 $this->blobStore
= $blobStore;
303 * Register a module with the ResourceLoader system.
305 * @param mixed $name Name of module as a string or List of name/object pairs as an array
306 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
307 * this may also be a ResourceLoaderModule object. Optional when using
308 * multiple-registration calling style.
309 * @throws MWException If a duplicate module registration is attempted
310 * @throws MWException If a module name contains illegal characters (pipes or commas)
311 * @throws MWException If something other than a ResourceLoaderModule is being registered
312 * @return bool False if there were any errors, in which case one or more modules were
315 public function register( $name, $info = null ) {
316 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
318 // Allow multiple modules to be registered in one call
319 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
320 foreach ( $registrations as $name => $info ) {
321 // Warn on duplicate registrations
322 if ( isset( $this->moduleInfos
[$name] ) ) {
323 // A module has already been registered by this name
324 $this->logger
->warning(
325 'ResourceLoader duplicate registration warning. ' .
326 'Another module has already been registered as ' . $name
330 // Check $name for validity
331 if ( !self
::isValidModuleName( $name ) ) {
332 throw new MWException( "ResourceLoader module name '$name' is invalid, "
333 . "see ResourceLoader::isValidModuleName()" );
337 if ( $info instanceof ResourceLoaderModule
) {
338 $this->moduleInfos
[$name] = [ 'object' => $info ];
339 $info->setName( $name );
340 $this->modules
[$name] = $info;
341 } elseif ( is_array( $info ) ) {
342 // New calling convention
343 $this->moduleInfos
[$name] = $info;
345 throw new MWException(
346 'ResourceLoader module info type error for module \'' . $name .
347 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
351 // Last-minute changes
353 // Apply custom skin-defined styles to existing modules.
354 if ( $this->isFileModule( $name ) ) {
355 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
356 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
357 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
361 // If $name is preceded with a '+', the defined style files will be added to 'default'
362 // skinStyles, otherwise 'default' will be ignored as it normally would be.
363 if ( isset( $skinStyles[$name] ) ) {
364 $paths = (array)$skinStyles[$name];
366 } elseif ( isset( $skinStyles['+' . $name] ) ) {
367 $paths = (array)$skinStyles['+' . $name];
368 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
369 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
375 // Add new file paths, remapping them to refer to our directories and not use settings
376 // from the module we're modifying, which come from the base definition.
377 list( $localBasePath, $remoteBasePath ) =
378 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
380 foreach ( $paths as $path ) {
381 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
384 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
393 public function registerTestModules() {
396 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
397 throw new MWException( 'Attempt to register JavaScript test modules '
398 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
399 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
402 // Get core test suites
404 $testModules['qunit'] = [];
405 // Get other test suites (e.g. from extensions)
406 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModules, &$this ] );
408 // Add the testrunner (which configures QUnit) to the dependencies.
409 // Since it must be ready before any of the test suites are executed.
410 foreach ( $testModules['qunit'] as &$module ) {
411 // Make sure all test modules are top-loading so that when QUnit starts
412 // on document-ready, it will run once and finish. If some tests arrive
413 // later (possibly after QUnit has already finished) they will be ignored.
414 $module['position'] = 'top';
415 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
418 $testModules['qunit'] =
419 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
421 foreach ( $testModules as $id => $names ) {
422 // Register test modules
423 $this->register( $testModules[$id] );
425 // Keep track of their names so that they can be loaded together
426 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
432 * Add a foreign source of modules.
434 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
436 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
437 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
438 * backwards-compatibility.
439 * @throws MWException
441 public function addSource( $id, $loadUrl = null ) {
442 // Allow multiple sources to be registered in one call
443 if ( is_array( $id ) ) {
444 foreach ( $id as $key => $value ) {
445 $this->addSource( $key, $value );
450 // Disallow duplicates
451 if ( isset( $this->sources
[$id] ) ) {
452 throw new MWException(
453 'ResourceLoader duplicate source addition error. ' .
454 'Another source has already been registered as ' . $id
458 // Pre 1.24 backwards-compatibility
459 if ( is_array( $loadUrl ) ) {
460 if ( !isset( $loadUrl['loadScript'] ) ) {
461 throw new MWException(
462 __METHOD__
. ' was passed an array with no "loadScript" key.'
466 $loadUrl = $loadUrl['loadScript'];
469 $this->sources
[$id] = $loadUrl;
473 * Get a list of module names.
475 * @return array List of module names
477 public function getModuleNames() {
478 return array_keys( $this->moduleInfos
);
482 * Get a list of test module names for one (or all) frameworks.
484 * If the given framework id is unknkown, or if the in-object variable is not an array,
485 * then it will return an empty array.
487 * @param string $framework Get only the test module names for one
488 * particular framework (optional)
491 public function getTestModuleNames( $framework = 'all' ) {
492 /** @todo api siteinfo prop testmodulenames modulenames */
493 if ( $framework == 'all' ) {
494 return $this->testModuleNames
;
495 } elseif ( isset( $this->testModuleNames
[$framework] )
496 && is_array( $this->testModuleNames
[$framework] )
498 return $this->testModuleNames
[$framework];
505 * Check whether a ResourceLoader module is registered
508 * @param string $name
511 public function isModuleRegistered( $name ) {
512 return isset( $this->moduleInfos
[$name] );
516 * Get the ResourceLoaderModule object for a given module name.
518 * If an array of module parameters exists but a ResourceLoaderModule object has not
519 * yet been instantiated, this method will instantiate and cache that object such that
520 * subsequent calls simply return the same object.
522 * @param string $name Module name
523 * @return ResourceLoaderModule|null If module has been registered, return a
524 * ResourceLoaderModule instance. Otherwise, return null.
526 public function getModule( $name ) {
527 if ( !isset( $this->modules
[$name] ) ) {
528 if ( !isset( $this->moduleInfos
[$name] ) ) {
532 // Construct the requested object
533 $info = $this->moduleInfos
[$name];
534 /** @var ResourceLoaderModule $object */
535 if ( isset( $info['object'] ) ) {
536 // Object given in info array
537 $object = $info['object'];
539 if ( !isset( $info['class'] ) ) {
540 $class = 'ResourceLoaderFileModule';
542 $class = $info['class'];
544 /** @var ResourceLoaderModule $object */
545 $object = new $class( $info );
546 $object->setConfig( $this->getConfig() );
547 $object->setLogger( $this->logger
);
549 $object->setName( $name );
550 $this->modules
[$name] = $object;
553 return $this->modules
[$name];
557 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
559 * @param string $name Module name
562 protected function isFileModule( $name ) {
563 if ( !isset( $this->moduleInfos
[$name] ) ) {
566 $info = $this->moduleInfos
[$name];
567 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
574 * Get the list of sources.
576 * @return array Like array( id => load.php url, .. )
578 public function getSources() {
579 return $this->sources
;
583 * Get the URL to the load.php endpoint for the given
584 * ResourceLoader source
587 * @param string $source
588 * @throws MWException On an invalid $source name
591 public function getLoadScript( $source ) {
592 if ( !isset( $this->sources
[$source] ) ) {
593 throw new MWException( "The $source source was never registered in ResourceLoader." );
595 return $this->sources
[$source];
600 * @param string $value
601 * @return string Hash
603 public static function makeHash( $value ) {
604 $hash = hash( 'fnv132', $value );
605 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
609 * Helper method to get and combine versions of multiple modules.
612 * @param ResourceLoaderContext $context
613 * @param array $modules List of ResourceLoaderModule objects
614 * @return string Hash
616 public function getCombinedVersion( ResourceLoaderContext
$context, array $modules ) {
620 $hashes = array_map( function ( $module ) use ( $context ) {
621 return $this->getModule( $module )->getVersionHash( $context );
623 return self
::makeHash( implode( $hashes ) );
627 * Output a response to a load request, including the content-type header.
629 * @param ResourceLoaderContext $context Context in which a response should be formed
631 public function respond( ResourceLoaderContext
$context ) {
632 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
633 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
634 // is used: ob_clean() will clear the GZIP header in that case and it won't come
635 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
636 // the whole thing in our own output buffer to be sure the active buffer
637 // doesn't use ob_gzhandler.
638 // See http://bugs.php.net/bug.php?id=36514
641 // Find out which modules are missing and instantiate the others
644 foreach ( $context->getModules() as $name ) {
645 $module = $this->getModule( $name );
647 // Do not allow private modules to be loaded from the web.
648 // This is a security issue, see bug 34907.
649 if ( $module->getGroup() === 'private' ) {
650 $this->logger
->debug( "Request for private module '$name' denied" );
651 $this->errors
[] = "Cannot show private module \"$name\"";
654 $modules[$name] = $module;
661 // Preload for getCombinedVersion() and for batch makeModuleResponse()
662 $this->preloadModuleInfo( array_keys( $modules ), $context );
663 } catch ( Exception
$e ) {
664 MWExceptionHandler
::logException( $e );
665 $this->logger
->warning( 'Preloading module info failed: {exception}', [
668 $this->errors
[] = self
::formatExceptionNoComment( $e );
671 // Combine versions to propagate cache invalidation
674 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
675 } catch ( Exception
$e ) {
676 MWExceptionHandler
::logException( $e );
677 $this->logger
->warning( 'Calculating version hash failed: {exception}', [
680 $this->errors
[] = self
::formatExceptionNoComment( $e );
683 // See RFC 2616 § 3.11 Entity Tags
684 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
685 $etag = 'W/"' . $versionHash . '"';
687 // Try the client-side cache first
688 if ( $this->tryRespondNotModified( $context, $etag ) ) {
689 return; // output handled (buffers cleared)
692 // Use file cache if enabled and available...
693 if ( $this->config
->get( 'UseFileCache' ) ) {
694 $fileCache = ResourceFileCache
::newFromContext( $context );
695 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
696 return; // output handled
700 // Generate a response
701 $response = $this->makeModuleResponse( $context, $modules, $missing );
703 // Capture any PHP warnings from the output buffer and append them to the
704 // error list if we're in debug mode.
705 if ( $context->getDebug() ) {
706 $warnings = ob_get_contents();
707 if ( strlen( $warnings ) ) {
708 $this->errors
[] = $warnings;
712 // Save response to file cache unless there are errors
713 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
714 // Cache single modules and images...and other requests if there are enough hits
715 if ( ResourceFileCache
::useFileCache( $context ) ) {
716 if ( $fileCache->isCacheWorthy() ) {
717 $fileCache->saveText( $response );
719 $fileCache->incrMissesRecent( $context->getRequest() );
724 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
726 // Remove the output buffer and output the response
729 if ( $context->getImageObj() && $this->errors
) {
730 // We can't show both the error messages and the response when it's an image.
731 $response = implode( "\n\n", $this->errors
);
732 } elseif ( $this->errors
) {
733 $errorText = implode( "\n\n", $this->errors
);
734 $errorResponse = self
::makeComment( $errorText );
735 if ( $context->shouldIncludeScripts() ) {
736 $errorResponse .= 'if (window.console && console.error) {'
737 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
741 // Prepend error info to the response
742 $response = $errorResponse . $response;
751 * Send main response headers to the client.
753 * Deals with Content-Type, CORS (for stylesheets), and caching.
755 * @param ResourceLoaderContext $context
756 * @param string $etag ETag header value
757 * @param bool $errors Whether there are errors in the response
760 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
761 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
762 // If a version wasn't specified we need a shorter expiry time for updates
763 // to propagate to clients quickly
764 // If there were errors, we also need a shorter expiry time so we can recover quickly
765 if ( is_null( $context->getVersion() ) ||
$errors ) {
766 $maxage = $rlMaxage['unversioned']['client'];
767 $smaxage = $rlMaxage['unversioned']['server'];
768 // If a version was specified we can use a longer expiry time since changing
769 // version numbers causes cache misses
771 $maxage = $rlMaxage['versioned']['client'];
772 $smaxage = $rlMaxage['versioned']['server'];
774 if ( $context->getImageObj() ) {
775 // Output different headers if we're outputting textual errors.
777 header( 'Content-Type: text/plain; charset=utf-8' );
779 $context->getImageObj()->sendResponseHeaders( $context );
781 } elseif ( $context->getOnly() === 'styles' ) {
782 header( 'Content-Type: text/css; charset=utf-8' );
783 header( 'Access-Control-Allow-Origin: *' );
785 header( 'Content-Type: text/javascript; charset=utf-8' );
787 // See RFC 2616 § 14.19 ETag
788 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
789 header( 'ETag: ' . $etag );
790 if ( $context->getDebug() ) {
791 // Do not cache debug responses
792 header( 'Cache-Control: private, no-cache, must-revalidate' );
793 header( 'Pragma: no-cache' );
795 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
796 $exp = min( $maxage, $smaxage );
797 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
802 * Respond with HTTP 304 Not Modified if appropiate.
804 * If there's an If-None-Match header, respond with a 304 appropriately
805 * and clear out the output buffer. If the client cache is too old then do nothing.
807 * @param ResourceLoaderContext $context
808 * @param string $etag ETag header value
809 * @return bool True if HTTP 304 was sent and output handled
811 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
812 // See RFC 2616 § 14.26 If-None-Match
813 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
814 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
815 // Never send 304s in debug mode
816 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
817 // There's another bug in ob_gzhandler (see also the comment at
818 // the top of this function) that causes it to gzip even empty
819 // responses, meaning it's impossible to produce a truly empty
820 // response (because the gzip header is always there). This is
821 // a problem because 304 responses have to be completely empty
822 // per the HTTP spec, and Firefox behaves buggily when they're not.
823 // See also http://bugs.php.net/bug.php?id=51579
824 // To work around this, we tear down all output buffering before
826 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
828 HttpStatus
::header( 304 );
830 $this->sendResponseHeaders( $context, $etag, false );
837 * Send out code for a response from file cache if possible.
839 * @param ResourceFileCache $fileCache Cache object for this request URL
840 * @param ResourceLoaderContext $context Context in which to generate a response
841 * @param string $etag ETag header value
842 * @return bool If this found a cache file and handled the response
844 protected function tryRespondFromFileCache(
845 ResourceFileCache
$fileCache,
846 ResourceLoaderContext
$context,
849 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
850 // Buffer output to catch warnings.
852 // Get the maximum age the cache can be
853 $maxage = is_null( $context->getVersion() )
854 ?
$rlMaxage['unversioned']['server']
855 : $rlMaxage['versioned']['server'];
856 // Minimum timestamp the cache file must have
857 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
859 try { // RL always hits the DB on file cache miss...
861 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
862 $good = $fileCache->isCacheGood(); // cache existence check
866 $ts = $fileCache->cacheTimestamp();
867 // Send content type and cache headers
868 $this->sendResponseHeaders( $context, $etag, false );
869 $response = $fileCache->fetchText();
870 // Capture any PHP warnings from the output buffer and append them to the
871 // response in a comment if we're in debug mode.
872 if ( $context->getDebug() ) {
873 $warnings = ob_get_contents();
874 if ( strlen( $warnings ) ) {
875 $response = self
::makeComment( $warnings ) . $response;
878 // Remove the output buffer and output the response
880 echo $response . "\n/* Cached {$ts} */";
881 return true; // cache hit
886 return false; // cache miss
890 * Generate a CSS or JS comment block.
892 * Only use this for public data, not error message details.
894 * @param string $text
897 public static function makeComment( $text ) {
898 $encText = str_replace( '*/', '* /', $text );
899 return "/*\n$encText\n*/\n";
903 * Handle exception display.
905 * @param Exception $e Exception to be shown to the user
906 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
908 public static function formatException( $e ) {
909 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
913 * Handle exception display.
916 * @param Exception $e Exception to be shown to the user
917 * @return string Sanitized text that can be returned to the user
919 protected static function formatExceptionNoComment( $e ) {
920 global $wgShowExceptionDetails;
922 if ( !$wgShowExceptionDetails ) {
923 return MWExceptionHandler
::getPublicLogMessage( $e );
926 return MWExceptionHandler
::getLogMessage( $e );
930 * Generate code for a response.
932 * @param ResourceLoaderContext $context Context in which to generate a response
933 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
934 * @param string[] $missing List of requested module names that are unregistered (optional)
935 * @return string Response data
937 public function makeModuleResponse( ResourceLoaderContext
$context,
938 array $modules, array $missing = []
943 if ( !count( $modules ) && !count( $missing ) ) {
945 /* This file is the Web entry point for MediaWiki's ResourceLoader:
946 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
947 no modules were requested. Max made me put this here. */
951 $image = $context->getImageObj();
953 $data = $image->getImageData( $context );
954 if ( $data === false ) {
956 $this->errors
[] = 'Image generation failed';
961 foreach ( $missing as $name ) {
962 $states[$name] = 'missing';
968 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
970 foreach ( $modules as $name => $module ) {
972 $content = $module->getModuleContent( $context );
976 switch ( $context->getOnly() ) {
978 $scripts = $content['scripts'];
979 if ( is_string( $scripts ) ) {
980 // Load scripts raw...
981 $strContent = $scripts;
982 } elseif ( is_array( $scripts ) ) {
983 // ...except when $scripts is an array of URLs
984 $strContent = self
::makeLoaderImplementScript( $name, $scripts, [], [], [] );
988 $styles = $content['styles'];
989 // We no longer seperate into media, they are all combined now with
990 // custom media type groups into @media .. {} sections as part of the css string.
991 // Module returns either an empty array or a numerical array with css strings.
992 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
995 $strContent = self
::makeLoaderImplementScript(
997 isset( $content['scripts'] ) ?
$content['scripts'] : '',
998 isset( $content['styles'] ) ?
$content['styles'] : [],
999 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1000 isset( $content['templates'] ) ?
$content['templates'] : []
1005 if ( !$context->getDebug() ) {
1006 $strContent = self
::filter( $filter, $strContent );
1009 $out .= $strContent;
1011 } catch ( Exception
$e ) {
1012 MWExceptionHandler
::logException( $e );
1013 $this->logger
->warning( 'Generating module package failed: {exception}', [
1016 $this->errors
[] = self
::formatExceptionNoComment( $e );
1018 // Respond to client with error-state instead of module implementation
1019 $states[$name] = 'error';
1020 unset( $modules[$name] );
1022 $isRaw |
= $module->isRaw();
1025 // Update module states
1026 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1027 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1028 // Set the state of modules loaded as only scripts to ready as
1029 // they don't have an mw.loader.implement wrapper that sets the state
1030 foreach ( $modules as $name => $module ) {
1031 $states[$name] = 'ready';
1035 // Set the state of modules we didn't respond to with mw.loader.implement
1036 if ( count( $states ) ) {
1037 $stateScript = self
::makeLoaderStateScript( $states );
1038 if ( !$context->getDebug() ) {
1039 $stateScript = self
::filter( 'minify-js', $stateScript );
1041 $out .= $stateScript;
1044 if ( count( $states ) ) {
1045 $this->errors
[] = 'Problematic modules: ' .
1046 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1054 * Get names of modules that use a certain message.
1056 * @param string $messageKey
1057 * @return array List of module names
1059 public function getModulesByMessage( $messageKey ) {
1061 foreach ( $this->getModuleNames() as $moduleName ) {
1062 $module = $this->getModule( $moduleName );
1063 if ( in_array( $messageKey, $module->getMessages() ) ) {
1064 $moduleNames[] = $moduleName;
1067 return $moduleNames;
1070 /* Static Methods */
1073 * Return JS code that calls mw.loader.implement with given module properties.
1075 * @param string $name Module name
1076 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1077 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1078 * to CSS files keyed by media type
1079 * @param mixed $messages List of messages associated with this module. May either be an
1080 * associative array mapping message key to value, or a JSON-encoded message blob containing
1081 * the same data, wrapped in an XmlJsCode object.
1082 * @param array $templates Keys are name of templates and values are the source of
1084 * @throws MWException
1087 public static function makeLoaderImplementScript(
1088 $name, $scripts, $styles, $messages, $templates
1090 if ( is_string( $scripts ) ) {
1091 // Site and user module are a legacy scripts that run in the global scope (no closure).
1092 // Transportation as string instructs mw.loader.implement to use globalEval.
1093 if ( $name === 'site' ||
$name === 'user' ) {
1094 // Minify manually because the general makeModuleResponse() minification won't be
1095 // effective here due to the script being a string instead of a function. (T107377)
1096 if ( !ResourceLoader
::inDebugMode() ) {
1097 $scripts = self
::filter( 'minify-js', $scripts );
1100 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts}\n}" );
1102 } elseif ( !is_array( $scripts ) ) {
1103 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1105 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1106 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1107 // of "{}". Force them to objects.
1115 self
::trimArray( $module );
1117 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1121 * Returns JS code which, when called, will register a given list of messages.
1123 * @param mixed $messages Either an associative array mapping message key to value, or a
1124 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1127 public static function makeMessageSetScript( $messages ) {
1128 return Xml
::encodeJsCall(
1130 [ (object)$messages ],
1131 ResourceLoader
::inDebugMode()
1136 * Combines an associative array mapping media type to CSS into a
1137 * single stylesheet with "@media" blocks.
1139 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1142 public static function makeCombinedStyles( array $stylePairs ) {
1144 foreach ( $stylePairs as $media => $styles ) {
1145 // ResourceLoaderFileModule::getStyle can return the styles
1146 // as a string or an array of strings. This is to allow separation in
1148 $styles = (array)$styles;
1149 foreach ( $styles as $style ) {
1150 $style = trim( $style );
1151 // Don't output an empty "@media print { }" block (bug 40498)
1152 if ( $style !== '' ) {
1153 // Transform the media type based on request params and config
1154 // The way that this relies on $wgRequest to propagate request params is slightly evil
1155 $media = OutputPage
::transformCssMedia( $media );
1157 if ( $media === '' ||
$media == 'all' ) {
1159 } elseif ( is_string( $media ) ) {
1160 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1170 * Returns a JS call to mw.loader.state, which sets the state of a
1171 * module or modules to a given value. Has two calling conventions:
1173 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1174 * Set the state of a single module called $name to $state
1176 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1177 * Set the state of modules with the given names to the given states
1179 * @param string $name
1180 * @param string $state
1183 public static function makeLoaderStateScript( $name, $state = null ) {
1184 if ( is_array( $name ) ) {
1185 return Xml
::encodeJsCall(
1188 ResourceLoader
::inDebugMode()
1191 return Xml
::encodeJsCall(
1194 ResourceLoader
::inDebugMode()
1200 * Returns JS code which calls the script given by $script. The script will
1201 * be called with local variables name, version, dependencies and group,
1202 * which will have values corresponding to $name, $version, $dependencies
1203 * and $group as supplied.
1205 * @param string $name Module name
1206 * @param string $version Module version hash
1207 * @param array $dependencies List of module names on which this module depends
1208 * @param string $group Group which the module is in.
1209 * @param string $source Source of the module, or 'local' if not foreign.
1210 * @param string $script JavaScript code
1213 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1214 $group, $source, $script
1216 $script = str_replace( "\n", "\n\t", trim( $script ) );
1217 return Xml
::encodeJsCall(
1218 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1219 [ $name, $version, $dependencies, $group, $source ],
1220 ResourceLoader
::inDebugMode()
1224 private static function isEmptyObject( stdClass
$obj ) {
1225 foreach ( $obj as $key => $value ) {
1232 * Remove empty values from the end of an array.
1234 * Values considered empty:
1238 * - new XmlJsCode( '{}' )
1239 * - new stdClass() // (object) array()
1241 * @param Array $array
1243 private static function trimArray( array &$array ) {
1244 $i = count( $array );
1246 if ( $array[$i] === null
1247 ||
$array[$i] === []
1248 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1249 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1251 unset( $array[$i] );
1259 * Returns JS code which calls mw.loader.register with the given
1260 * parameters. Has three calling conventions:
1262 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1263 * $dependencies, $group, $source, $skip
1265 * Register a single module.
1267 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1268 * Register modules with the given names.
1270 * - ResourceLoader::makeLoaderRegisterScript( array(
1271 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1272 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1275 * Registers modules with the given names and parameters.
1277 * @param string $name Module name
1278 * @param string $version Module version hash
1279 * @param array $dependencies List of module names on which this module depends
1280 * @param string $group Group which the module is in
1281 * @param string $source Source of the module, or 'local' if not foreign
1282 * @param string $skip Script body of the skip function
1285 public static function makeLoaderRegisterScript( $name, $version = null,
1286 $dependencies = null, $group = null, $source = null, $skip = null
1288 if ( is_array( $name ) ) {
1289 // Build module name index
1291 foreach ( $name as $i => &$module ) {
1292 $index[$module[0]] = $i;
1295 // Transform dependency names into indexes when possible, they will be resolved by
1296 // mw.loader.register on the other end
1297 foreach ( $name as &$module ) {
1298 if ( isset( $module[2] ) ) {
1299 foreach ( $module[2] as &$dependency ) {
1300 if ( isset( $index[$dependency] ) ) {
1301 $dependency = $index[$dependency];
1307 array_walk( $name, [ 'self', 'trimArray' ] );
1309 return Xml
::encodeJsCall(
1310 'mw.loader.register',
1312 ResourceLoader
::inDebugMode()
1315 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1316 self
::trimArray( $registration );
1317 return Xml
::encodeJsCall(
1318 'mw.loader.register',
1320 ResourceLoader
::inDebugMode()
1326 * Returns JS code which calls mw.loader.addSource() with the given
1327 * parameters. Has two calling conventions:
1329 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1330 * Register a single source
1332 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1333 * Register sources with the given IDs and properties.
1335 * @param string $id Source ID
1336 * @param array $properties Source properties (see addSource())
1339 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1340 if ( is_array( $id ) ) {
1341 return Xml
::encodeJsCall(
1342 'mw.loader.addSource',
1344 ResourceLoader
::inDebugMode()
1347 return Xml
::encodeJsCall(
1348 'mw.loader.addSource',
1349 [ $id, $properties ],
1350 ResourceLoader
::inDebugMode()
1356 * Returns JS code which runs given JS code if the client-side framework is
1359 * @deprecated since 1.25; use makeInlineScript instead
1360 * @param string $script JavaScript code
1363 public static function makeLoaderConditionalScript( $script ) {
1364 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1365 trim( $script ) . '});';
1369 * Construct an inline script tag with given JS code.
1371 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1372 * only if the client has adequate support for MediaWiki JavaScript code.
1374 * @param string $script JavaScript code
1375 * @return WrappedString HTML
1377 public static function makeInlineScript( $script ) {
1378 $js = self
::makeLoaderConditionalScript( $script );
1379 return new WrappedString(
1380 Html
::inlineScript( $js ),
1381 '<script>(window.RLQ=window.RLQ||[]).push(function(){',
1387 * Returns JS code which will set the MediaWiki configuration array to
1390 * @param array $configuration List of configuration values keyed by variable name
1393 public static function makeConfigSetScript( array $configuration ) {
1394 return Xml
::encodeJsCall(
1397 ResourceLoader
::inDebugMode()
1402 * Convert an array of module names to a packed query string.
1404 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1405 * becomes 'foo.bar,baz|bar.baz,quux'
1406 * @param array $modules List of module names (strings)
1407 * @return string Packed query string
1409 public static function makePackedModulesString( $modules ) {
1410 $groups = []; // array( prefix => array( suffixes ) )
1411 foreach ( $modules as $module ) {
1412 $pos = strrpos( $module, '.' );
1413 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1414 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1415 $groups[$prefix][] = $suffix;
1419 foreach ( $groups as $prefix => $suffixes ) {
1420 $p = $prefix === '' ?
'' : $prefix . '.';
1421 $arr[] = $p . implode( ',', $suffixes );
1423 $str = implode( '|', $arr );
1428 * Determine whether debug mode was requested
1429 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1432 public static function inDebugMode() {
1433 if ( self
::$debugMode === null ) {
1434 global $wgRequest, $wgResourceLoaderDebug;
1435 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1436 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1439 return self
::$debugMode;
1443 * Reset static members used for caching.
1445 * Global state and $wgRequest are evil, but we're using it right
1446 * now and sometimes we need to be able to force ResourceLoader to
1447 * re-evaluate the context because it has changed (e.g. in the test suite).
1449 public static function clearCache() {
1450 self
::$debugMode = null;
1454 * Build a load.php URL
1457 * @param string $source Name of the ResourceLoader source
1458 * @param ResourceLoaderContext $context
1459 * @param array $extraQuery
1460 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1462 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1465 $query = self
::createLoaderQuery( $context, $extraQuery );
1466 $script = $this->getLoadScript( $source );
1468 return wfAppendQuery( $script, $query );
1472 * Build a load.php URL
1473 * @deprecated since 1.24 Use createLoaderURL() instead
1474 * @param array $modules Array of module names (strings)
1475 * @param string $lang Language code
1476 * @param string $skin Skin name
1477 * @param string|null $user User name. If null, the &user= parameter is omitted
1478 * @param string|null $version Versioning timestamp
1479 * @param bool $debug Whether the request should be in debug mode
1480 * @param string|null $only &only= parameter
1481 * @param bool $printable Printable mode
1482 * @param bool $handheld Handheld mode
1483 * @param array $extraQuery Extra query parameters to add
1484 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1486 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1487 $version = null, $debug = false, $only = null, $printable = false,
1488 $handheld = false, $extraQuery = []
1490 global $wgLoadScript;
1492 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1493 $only, $printable, $handheld, $extraQuery
1496 return wfAppendQuery( $wgLoadScript, $query );
1500 * Helper for createLoaderURL()
1503 * @see makeLoaderQuery
1504 * @param ResourceLoaderContext $context
1505 * @param array $extraQuery
1508 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1509 return self
::makeLoaderQuery(
1510 $context->getModules(),
1511 $context->getLanguage(),
1512 $context->getSkin(),
1513 $context->getUser(),
1514 $context->getVersion(),
1515 $context->getDebug(),
1516 $context->getOnly(),
1517 $context->getRequest()->getBool( 'printable' ),
1518 $context->getRequest()->getBool( 'handheld' ),
1524 * Build a query array (array representation of query string) for load.php. Helper
1525 * function for makeLoaderURL().
1527 * @param array $modules
1528 * @param string $lang
1529 * @param string $skin
1530 * @param string $user
1531 * @param string $version
1532 * @param bool $debug
1533 * @param string $only
1534 * @param bool $printable
1535 * @param bool $handheld
1536 * @param array $extraQuery
1540 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1541 $version = null, $debug = false, $only = null, $printable = false,
1542 $handheld = false, $extraQuery = []
1545 'modules' => self
::makePackedModulesString( $modules ),
1548 'debug' => $debug ?
'true' : 'false',
1550 if ( $user !== null ) {
1551 $query['user'] = $user;
1553 if ( $version !== null ) {
1554 $query['version'] = $version;
1556 if ( $only !== null ) {
1557 $query['only'] = $only;
1560 $query['printable'] = 1;
1563 $query['handheld'] = 1;
1565 $query +
= $extraQuery;
1567 // Make queries uniform in order
1573 * Check a module name for validity.
1575 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1576 * at most 255 bytes.
1578 * @param string $moduleName Module name to check
1579 * @return bool Whether $moduleName is a valid module name
1581 public static function isValidModuleName( $moduleName ) {
1582 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1586 * Returns LESS compiler set up for use with MediaWiki
1589 * @param array $extraVars Associative array of extra (i.e., other than the
1590 * globally-configured ones) that should be used for compilation.
1591 * @throws MWException
1592 * @return Less_Parser
1594 public function getLessCompiler( $extraVars = [] ) {
1595 // When called from the installer, it is possible that a required PHP extension
1596 // is missing (at least for now; see bug 47564). If this is the case, throw an
1597 // exception (caught by the installer) to prevent a fatal error later on.
1598 if ( !class_exists( 'Less_Parser' ) ) {
1599 throw new MWException( 'MediaWiki requires the less.php parser' );
1602 $parser = new Less_Parser
;
1603 $parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
1604 $parser->SetImportDirs(
1605 array_fill_keys( $this->config
->get( 'ResourceLoaderLESSImportPaths' ), '' )
1607 $parser->SetOption( 'relativeUrls', false );
1608 $parser->SetCacheDir( $this->config
->get( 'CacheDirectory' ) ?
: wfTempDir() );
1614 * Get global LESS variables.
1617 * @return array Map of variable names to string CSS values.
1619 public function getLessVars() {
1620 if ( !$this->lessVars
) {
1621 $lessVars = $this->config
->get( 'ResourceLoaderLESSVars' );
1622 Hooks
::run( 'ResourceLoaderGetLessVars', [ &$lessVars ] );
1623 $this->lessVars
= $lessVars;
1625 return $this->lessVars
;