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 static $lessVars = null;
47 * Module name/ResourceLoaderModule object pairs
50 protected $modules = array();
53 * Associative array mapping module name to info associative array
56 protected $moduleInfos = array();
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 = array();
69 * E.g. array( 'source-id' => 'http://.../load.php' )
72 protected $sources = array();
75 * Errors accumulated during current respond() call.
78 protected $errors = array();
81 * @var MessageBlobStore
86 * @var LoggerInterface
91 * Load information stored in the database about modules.
93 * This method grabs modules dependencies from the database and updates modules
96 * This is not inside the module code because it is much faster to
97 * request all of the information at once than it is to have each module
98 * requests its own information. This sacrifice of modularity yields a substantial
99 * performance improvement.
101 * @param array $modules List of module names to preload information for
102 * @param ResourceLoaderContext $context Context to load the information within
104 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
105 if ( !count( $modules ) ) {
106 // Or else Database*::select() will explode, plus it's cheaper!
109 $dbr = wfGetDB( DB_SLAVE
);
110 $skin = $context->getSkin();
111 $lang = $context->getLanguage();
113 // Get file dependency information
114 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
115 'md_module' => $modules,
120 // Set modules' dependencies
121 $modulesWithDeps = array();
122 foreach ( $res as $row ) {
123 $module = $this->getModule( $row->md_module
);
125 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
126 $modulesWithDeps[] = $row->md_module
;
130 // Register the absence of a dependency row too
131 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
132 $module = $this->getModule( $name );
134 $this->getModule( $name )->setFileDependencies( $skin, array() );
138 // Get message blob mtimes. Only do this for modules with messages
139 $modulesWithMessages = array();
140 foreach ( $modules as $name ) {
141 $module = $this->getModule( $name );
142 if ( $module && count( $module->getMessages() ) ) {
143 $modulesWithMessages[] = $name;
146 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
147 if ( count( $modulesWithMessages ) ) {
148 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
149 'mr_resource' => $modulesWithMessages,
153 foreach ( $res as $row ) {
154 $module = $this->getModule( $row->mr_resource
);
156 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
157 unset( $modulesWithoutMessages[$row->mr_resource
] );
161 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
162 $module = $this->getModule( $name );
164 $module->setMsgBlobMtime( $lang, 1 );
170 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
172 * Available filters are:
174 * - minify-js \see JavaScriptMinifier::minify
175 * - minify-css \see CSSMin::minify
177 * If $data is empty, only contains whitespace or the filter was unknown,
178 * $data is returned unmodified.
180 * @param string $filter Name of filter to run
181 * @param string $data Text to filter, such as JavaScript or CSS text
182 * @param array $options For back-compat, can also be the boolean value for "cacheReport". Keys:
183 * - (bool) cache: Whether to allow caching this data. Default: true.
184 * - (bool) cacheReport: Whether to include the "cache key" report comment. Default: false.
185 * @return string Filtered data, or a comment containing an error message
187 public function filter( $filter, $data, $options = array() ) {
189 if ( is_bool( $options ) ) {
190 $options = array( 'cacheReport' => $options );
193 $options +
= array( 'cache' => true, 'cacheReport' => false );
194 $stats = RequestContext
::getMain()->getStats();
196 // Don't filter empty content
197 if ( trim( $data ) === '' ) {
201 if ( !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
202 $this->logger
->warning( 'Invalid filter {filter}', array(
208 if ( !$options['cache'] ) {
209 $result = self
::applyFilter( $filter, $data, $this->config
);
211 $key = wfGlobalCacheKey(
215 self
::$filterCacheVersion, md5( $data )
217 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL
: CACHE_ANYTHING
);
218 $cacheEntry = $cache->get( $key );
219 if ( is_string( $cacheEntry ) ) {
220 $stats->increment( "resourceloader_cache.$filter.hit" );
225 $statStart = microtime( true );
226 $result = self
::applyFilter( $filter, $data, $this->config
);
227 $statTiming = microtime( true ) - $statStart;
228 $stats->increment( "resourceloader_cache.$filter.miss" );
229 $stats->timing( "resourceloader_cache.$filter.timing", 1000 * $statTiming );
230 if ( $options['cacheReport'] ) {
231 $result .= "\n/* cache key: $key */";
233 // Set a TTL since HHVM's APC doesn't have any limitation or eviction logic.
234 $cache->set( $key, $result, 24 * 3600 );
235 } catch ( Exception
$e ) {
236 MWExceptionHandler
::logException( $e );
237 $this->logger
->warning( 'Minification failed: {exception}', array(
240 $this->errors
[] = self
::formatExceptionNoComment( $e );
247 private static function applyFilter( $filter, $data, Config
$config ) {
250 return JavaScriptMinifier
::minify( $data,
251 $config->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
252 $config->get( 'ResourceLoaderMinifierMaxLineLength' )
255 return CSSMin
::minify( $data );
264 * Register core modules and runs registration hooks.
265 * @param Config|null $config
267 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
271 $logger = new NullLogger();
273 $this->setLogger( $logger );
276 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
277 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
279 $this->config
= $config;
281 // Add 'local' source first
282 $this->addSource( 'local', wfScript( 'load' ) );
285 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
287 // Register core modules
288 $this->register( include "$IP/resources/Resources.php" );
289 $this->register( include "$IP/resources/ResourcesOOUI.php" );
290 // Register extension modules
291 $this->register( $config->get( 'ResourceModules' ) );
292 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
294 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
295 $this->registerTestModules();
298 $this->setMessageBlobStore( new MessageBlobStore() );
304 public function getConfig() {
305 return $this->config
;
308 public function setLogger( LoggerInterface
$logger ) {
309 $this->logger
= $logger;
314 * @return MessageBlobStore
316 public function getMessageBlobStore() {
317 return $this->blobStore
;
322 * @param MessageBlobStore $blobStore
324 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
325 $this->blobStore
= $blobStore;
329 * Register a module with the ResourceLoader system.
331 * @param mixed $name Name of module as a string or List of name/object pairs as an array
332 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
333 * this may also be a ResourceLoaderModule object. Optional when using
334 * multiple-registration calling style.
335 * @throws MWException If a duplicate module registration is attempted
336 * @throws MWException If a module name contains illegal characters (pipes or commas)
337 * @throws MWException If something other than a ResourceLoaderModule is being registered
338 * @return bool False if there were any errors, in which case one or more modules were
341 public function register( $name, $info = null ) {
343 // Allow multiple modules to be registered in one call
344 $registrations = is_array( $name ) ?
$name : array( $name => $info );
345 foreach ( $registrations as $name => $info ) {
346 // Disallow duplicate registrations
347 if ( isset( $this->moduleInfos
[$name] ) ) {
348 // A module has already been registered by this name
349 throw new MWException(
350 'ResourceLoader duplicate registration error. ' .
351 'Another module has already been registered as ' . $name
355 // Check $name for validity
356 if ( !self
::isValidModuleName( $name ) ) {
357 throw new MWException( "ResourceLoader module name '$name' is invalid, "
358 . "see ResourceLoader::isValidModuleName()" );
362 if ( $info instanceof ResourceLoaderModule
) {
363 $this->moduleInfos
[$name] = array( 'object' => $info );
364 $info->setName( $name );
365 $this->modules
[$name] = $info;
366 } elseif ( is_array( $info ) ) {
367 // New calling convention
368 $this->moduleInfos
[$name] = $info;
370 throw new MWException(
371 'ResourceLoader module info type error for module \'' . $name .
372 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
376 // Last-minute changes
378 // Apply custom skin-defined styles to existing modules.
379 if ( $this->isFileModule( $name ) ) {
380 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
381 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
382 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
386 // If $name is preceded with a '+', the defined style files will be added to 'default'
387 // skinStyles, otherwise 'default' will be ignored as it normally would be.
388 if ( isset( $skinStyles[$name] ) ) {
389 $paths = (array)$skinStyles[$name];
390 $styleFiles = array();
391 } elseif ( isset( $skinStyles['+' . $name] ) ) {
392 $paths = (array)$skinStyles['+' . $name];
393 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
394 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
400 // Add new file paths, remapping them to refer to our directories and not use settings
401 // from the module we're modifying, which come from the base definition.
402 list( $localBasePath, $remoteBasePath ) =
403 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
405 foreach ( $paths as $path ) {
406 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
409 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
418 public function registerTestModules() {
421 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
422 throw new MWException( 'Attempt to register JavaScript test modules '
423 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
424 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
427 // Get core test suites
428 $testModules = array();
429 $testModules['qunit'] = array();
430 // Get other test suites (e.g. from extensions)
431 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
433 // Add the testrunner (which configures QUnit) to the dependencies.
434 // Since it must be ready before any of the test suites are executed.
435 foreach ( $testModules['qunit'] as &$module ) {
436 // Make sure all test modules are top-loading so that when QUnit starts
437 // on document-ready, it will run once and finish. If some tests arrive
438 // later (possibly after QUnit has already finished) they will be ignored.
439 $module['position'] = 'top';
440 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
443 $testModules['qunit'] =
444 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
446 foreach ( $testModules as $id => $names ) {
447 // Register test modules
448 $this->register( $testModules[$id] );
450 // Keep track of their names so that they can be loaded together
451 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
457 * Add a foreign source of modules.
459 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
460 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
461 * backwards-compatibility.
462 * @throws MWException
464 public function addSource( $id, $loadUrl = null ) {
465 // Allow multiple sources to be registered in one call
466 if ( is_array( $id ) ) {
467 foreach ( $id as $key => $value ) {
468 $this->addSource( $key, $value );
473 // Disallow duplicates
474 if ( isset( $this->sources
[$id] ) ) {
475 throw new MWException(
476 'ResourceLoader duplicate source addition error. ' .
477 'Another source has already been registered as ' . $id
481 // Pre 1.24 backwards-compatibility
482 if ( is_array( $loadUrl ) ) {
483 if ( !isset( $loadUrl['loadScript'] ) ) {
484 throw new MWException(
485 __METHOD__
. ' was passed an array with no "loadScript" key.'
489 $loadUrl = $loadUrl['loadScript'];
492 $this->sources
[$id] = $loadUrl;
496 * Get a list of module names.
498 * @return array List of module names
500 public function getModuleNames() {
501 return array_keys( $this->moduleInfos
);
505 * Get a list of test module names for one (or all) frameworks.
507 * If the given framework id is unknkown, or if the in-object variable is not an array,
508 * then it will return an empty array.
510 * @param string $framework Get only the test module names for one
511 * particular framework (optional)
514 public function getTestModuleNames( $framework = 'all' ) {
515 /** @todo api siteinfo prop testmodulenames modulenames */
516 if ( $framework == 'all' ) {
517 return $this->testModuleNames
;
518 } elseif ( isset( $this->testModuleNames
[$framework] )
519 && is_array( $this->testModuleNames
[$framework] )
521 return $this->testModuleNames
[$framework];
528 * Check whether a ResourceLoader module is registered
531 * @param string $name
534 public function isModuleRegistered( $name ) {
535 return isset( $this->moduleInfos
[$name] );
539 * Get the ResourceLoaderModule object for a given module name.
541 * If an array of module parameters exists but a ResourceLoaderModule object has not
542 * yet been instantiated, this method will instantiate and cache that object such that
543 * subsequent calls simply return the same object.
545 * @param string $name Module name
546 * @return ResourceLoaderModule|null If module has been registered, return a
547 * ResourceLoaderModule instance. Otherwise, return null.
549 public function getModule( $name ) {
550 if ( !isset( $this->modules
[$name] ) ) {
551 if ( !isset( $this->moduleInfos
[$name] ) ) {
555 // Construct the requested object
556 $info = $this->moduleInfos
[$name];
557 /** @var ResourceLoaderModule $object */
558 if ( isset( $info['object'] ) ) {
559 // Object given in info array
560 $object = $info['object'];
562 if ( !isset( $info['class'] ) ) {
563 $class = 'ResourceLoaderFileModule';
565 $class = $info['class'];
567 /** @var ResourceLoaderModule $object */
568 $object = new $class( $info );
569 $object->setConfig( $this->getConfig() );
571 $object->setName( $name );
572 $this->modules
[$name] = $object;
575 return $this->modules
[$name];
579 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
581 * @param string $name Module name
584 protected function isFileModule( $name ) {
585 if ( !isset( $this->moduleInfos
[$name] ) ) {
588 $info = $this->moduleInfos
[$name];
589 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
596 * Get the list of sources.
598 * @return array Like array( id => load.php url, .. )
600 public function getSources() {
601 return $this->sources
;
605 * Get the URL to the load.php endpoint for the given
606 * ResourceLoader source
609 * @param string $source
610 * @throws MWException On an invalid $source name
613 public function getLoadScript( $source ) {
614 if ( !isset( $this->sources
[$source] ) ) {
615 throw new MWException( "The $source source was never registered in ResourceLoader." );
617 return $this->sources
[$source];
622 * @param string $value
623 * @return string Hash
625 public static function makeHash( $value ) {
626 // Use base64 to output more entropy in a more compact string (default hex is only base16).
627 // The first 8 chars of a base64 encoded digest represent the same binary as
628 // the first 12 chars of a hex encoded digest.
629 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
633 * Helper method to get and combine versions of multiple modules.
636 * @param ResourceLoaderContext $context
637 * @param array $modules List of ResourceLoaderModule objects
638 * @return string Hash
640 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
644 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
645 // http://php.net/functions.anonymous
647 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
648 return $rl->getModule( $module )->getVersionHash( $context );
650 return self
::makeHash( implode( $hashes ) );
654 * Output a response to a load request, including the content-type header.
656 * @param ResourceLoaderContext $context Context in which a response should be formed
658 public function respond( ResourceLoaderContext
$context ) {
659 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
660 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
661 // is used: ob_clean() will clear the GZIP header in that case and it won't come
662 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
663 // the whole thing in our own output buffer to be sure the active buffer
664 // doesn't use ob_gzhandler.
665 // See http://bugs.php.net/bug.php?id=36514
668 // Find out which modules are missing and instantiate the others
671 foreach ( $context->getModules() as $name ) {
672 $module = $this->getModule( $name );
674 // Do not allow private modules to be loaded from the web.
675 // This is a security issue, see bug 34907.
676 if ( $module->getGroup() === 'private' ) {
677 $this->logger
->debug( "Request for private module '$name' denied" );
678 $this->errors
[] = "Cannot show private module \"$name\"";
681 $modules[$name] = $module;
688 // Preload for getCombinedVersion()
689 $this->preloadModuleInfo( array_keys( $modules ), $context );
690 } catch ( Exception
$e ) {
691 MWExceptionHandler
::logException( $e );
692 $this->logger
->warning( 'Preloading module info failed: {exception}', array(
695 $this->errors
[] = self
::formatExceptionNoComment( $e );
698 // Combine versions to propagate cache invalidation
701 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
702 } catch ( Exception
$e ) {
703 MWExceptionHandler
::logException( $e );
704 $this->logger
->warning( 'Calculating version hash failed: {exception}', array(
707 $this->errors
[] = self
::formatExceptionNoComment( $e );
710 // See RFC 2616 § 3.11 Entity Tags
711 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
712 $etag = 'W/"' . $versionHash . '"';
714 // Try the client-side cache first
715 if ( $this->tryRespondNotModified( $context, $etag ) ) {
716 return; // output handled (buffers cleared)
719 // Use file cache if enabled and available...
720 if ( $this->config
->get( 'UseFileCache' ) ) {
721 $fileCache = ResourceFileCache
::newFromContext( $context );
722 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
723 return; // output handled
727 // Generate a response
728 $response = $this->makeModuleResponse( $context, $modules, $missing );
730 // Capture any PHP warnings from the output buffer and append them to the
731 // error list if we're in debug mode.
732 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
733 $this->errors
[] = $warnings;
736 // Save response to file cache unless there are errors
737 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
738 // Cache single modules and images...and other requests if there are enough hits
739 if ( ResourceFileCache
::useFileCache( $context ) ) {
740 if ( $fileCache->isCacheWorthy() ) {
741 $fileCache->saveText( $response );
743 $fileCache->incrMissesRecent( $context->getRequest() );
748 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
750 // Remove the output buffer and output the response
753 if ( $context->getImageObj() && $this->errors
) {
754 // We can't show both the error messages and the response when it's an image.
755 $response = implode( "\n\n", $this->errors
);
756 } elseif ( $this->errors
) {
757 $errorText = implode( "\n\n", $this->errors
);
758 $errorResponse = self
::makeComment( $errorText );
759 if ( $context->shouldIncludeScripts() ) {
760 $errorResponse .= 'if (window.console && console.error) {'
761 . Xml
::encodeJsCall( 'console.error', array( $errorText ) )
765 // Prepend error info to the response
766 $response = $errorResponse . $response;
769 $this->errors
= array();
775 * Send main response headers to the client.
777 * Deals with Content-Type, CORS (for stylesheets), and caching.
779 * @param ResourceLoaderContext $context
780 * @param string $etag ETag header value
781 * @param bool $errors Whether there are errors in the response
784 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
785 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
786 // If a version wasn't specified we need a shorter expiry time for updates
787 // to propagate to clients quickly
788 // If there were errors, we also need a shorter expiry time so we can recover quickly
789 if ( is_null( $context->getVersion() ) ||
$errors ) {
790 $maxage = $rlMaxage['unversioned']['client'];
791 $smaxage = $rlMaxage['unversioned']['server'];
792 // If a version was specified we can use a longer expiry time since changing
793 // version numbers causes cache misses
795 $maxage = $rlMaxage['versioned']['client'];
796 $smaxage = $rlMaxage['versioned']['server'];
798 if ( $context->getImageObj() ) {
799 // Output different headers if we're outputting textual errors.
801 header( 'Content-Type: text/plain; charset=utf-8' );
803 $context->getImageObj()->sendResponseHeaders( $context );
805 } elseif ( $context->getOnly() === 'styles' ) {
806 header( 'Content-Type: text/css; charset=utf-8' );
807 header( 'Access-Control-Allow-Origin: *' );
809 header( 'Content-Type: text/javascript; charset=utf-8' );
811 // See RFC 2616 § 14.19 ETag
812 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
813 header( 'ETag: ' . $etag );
814 if ( $context->getDebug() ) {
815 // Do not cache debug responses
816 header( 'Cache-Control: private, no-cache, must-revalidate' );
817 header( 'Pragma: no-cache' );
819 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
820 $exp = min( $maxage, $smaxage );
821 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
824 // Send the current time expressed as fractional seconds since epoch,
825 // with microsecond precision. This helps distinguish hits from misses
827 header( 'MediaWiki-Timestamp: ' . microtime( true ) );
831 * Respond with HTTP 304 Not Modified if appropiate.
833 * If there's an If-None-Match header, respond with a 304 appropriately
834 * and clear out the output buffer. If the client cache is too old then do nothing.
836 * @param ResourceLoaderContext $context
837 * @param string $etag ETag header value
838 * @return bool True if HTTP 304 was sent and output handled
840 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
841 // See RFC 2616 § 14.26 If-None-Match
842 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
843 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
844 // Never send 304s in debug mode
845 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
846 // There's another bug in ob_gzhandler (see also the comment at
847 // the top of this function) that causes it to gzip even empty
848 // responses, meaning it's impossible to produce a truly empty
849 // response (because the gzip header is always there). This is
850 // a problem because 304 responses have to be completely empty
851 // per the HTTP spec, and Firefox behaves buggily when they're not.
852 // See also http://bugs.php.net/bug.php?id=51579
853 // To work around this, we tear down all output buffering before
855 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
857 HttpStatus
::header( 304 );
859 $this->sendResponseHeaders( $context, $etag, false );
866 * Send out code for a response from file cache if possible.
868 * @param ResourceFileCache $fileCache Cache object for this request URL
869 * @param ResourceLoaderContext $context Context in which to generate a response
870 * @param string $etag ETag header value
871 * @return bool If this found a cache file and handled the response
873 protected function tryRespondFromFileCache(
874 ResourceFileCache
$fileCache,
875 ResourceLoaderContext
$context,
878 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
879 // Buffer output to catch warnings.
881 // Get the maximum age the cache can be
882 $maxage = is_null( $context->getVersion() )
883 ?
$rlMaxage['unversioned']['server']
884 : $rlMaxage['versioned']['server'];
885 // Minimum timestamp the cache file must have
886 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
888 try { // RL always hits the DB on file cache miss...
890 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
891 $good = $fileCache->isCacheGood(); // cache existence check
895 $ts = $fileCache->cacheTimestamp();
896 // Send content type and cache headers
897 $this->sendResponseHeaders( $context, $etag, false );
898 $response = $fileCache->fetchText();
899 // Capture any PHP warnings from the output buffer and append them to the
900 // response in a comment if we're in debug mode.
901 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
902 $response = self
::makeComment( $warnings ) . $response;
904 // Remove the output buffer and output the response
906 echo $response . "\n/* Cached {$ts} */";
907 return true; // cache hit
912 return false; // cache miss
916 * Generate a CSS or JS comment block.
918 * Only use this for public data, not error message details.
920 * @param string $text
923 public static function makeComment( $text ) {
924 $encText = str_replace( '*/', '* /', $text );
925 return "/*\n$encText\n*/\n";
929 * Handle exception display.
931 * @param Exception $e Exception to be shown to the user
932 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
934 public static function formatException( $e ) {
935 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
939 * Handle exception display.
942 * @param Exception $e Exception to be shown to the user
943 * @return string Sanitized text that can be returned to the user
945 protected static function formatExceptionNoComment( $e ) {
946 global $wgShowExceptionDetails;
948 if ( !$wgShowExceptionDetails ) {
949 return MWExceptionHandler
::getPublicLogMessage( $e );
952 return MWExceptionHandler
::getLogMessage( $e );
956 * Generate code for a response.
958 * @param ResourceLoaderContext $context Context in which to generate a response
959 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
960 * @param string[] $missing List of requested module names that are unregistered (optional)
961 * @return string Response data
963 public function makeModuleResponse( ResourceLoaderContext
$context,
964 array $modules, array $missing = array()
969 if ( !count( $modules ) && !count( $missing ) ) {
971 /* This file is the Web entry point for MediaWiki's ResourceLoader:
972 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
973 no modules were requested. Max made me put this here. */
977 $image = $context->getImageObj();
979 $data = $image->getImageData( $context );
980 if ( $data === false ) {
982 $this->errors
[] = 'Image generation failed';
988 if ( $context->shouldIncludeMessages() ) {
990 $this->blobStore
->get( $this, $modules, $context->getLanguage() );
991 } catch ( Exception
$e ) {
992 MWExceptionHandler
::logException( $e );
993 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
996 $this->errors
[] = self
::formatExceptionNoComment( $e );
1000 foreach ( $missing as $name ) {
1001 $states[$name] = 'missing';
1006 foreach ( $modules as $name => $module ) {
1008 $content = $module->getModuleContent( $context );
1011 switch ( $context->getOnly() ) {
1013 $scripts = $content['scripts'];
1014 if ( is_string( $scripts ) ) {
1015 // Load scripts raw...
1017 } elseif ( is_array( $scripts ) ) {
1018 // ...except when $scripts is an array of URLs
1019 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array(), array() );
1023 $styles = $content['styles'];
1024 // We no longer seperate into media, they are all combined now with
1025 // custom media type groups into @media .. {} sections as part of the css string.
1026 // Module returns either an empty array or a numerical array with css strings.
1027 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1030 $out .= self
::makeLoaderImplementScript(
1032 isset( $content['scripts'] ) ?
$content['scripts'] : '',
1033 isset( $content['styles'] ) ?
$content['styles'] : array(),
1034 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : array(),
1035 isset( $content['templates'] ) ?
$content['templates'] : array()
1039 } catch ( Exception
$e ) {
1040 MWExceptionHandler
::logException( $e );
1041 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1044 $this->errors
[] = self
::formatExceptionNoComment( $e );
1046 // Respond to client with error-state instead of module implementation
1047 $states[$name] = 'error';
1048 unset( $modules[$name] );
1050 $isRaw |
= $module->isRaw();
1053 // Update module states
1054 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1055 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1056 // Set the state of modules loaded as only scripts to ready as
1057 // they don't have an mw.loader.implement wrapper that sets the state
1058 foreach ( $modules as $name => $module ) {
1059 $states[$name] = 'ready';
1063 // Set the state of modules we didn't respond to with mw.loader.implement
1064 if ( count( $states ) ) {
1065 $out .= self
::makeLoaderStateScript( $states );
1068 if ( count( $states ) ) {
1069 $this->errors
[] = 'Problematic modules: ' .
1070 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1074 $enableFilterCache = true;
1075 if ( count( $modules ) === 1 && reset( $modules ) instanceof ResourceLoaderUserTokensModule
) {
1076 // If we're building the embedded user.tokens, don't cache (T84960)
1077 $enableFilterCache = false;
1080 if ( !$context->getDebug() ) {
1081 if ( $context->getOnly() === 'styles' ) {
1082 $out = $this->filter( 'minify-css', $out );
1084 $out = $this->filter( 'minify-js', $out, array(
1085 'cache' => $enableFilterCache
1093 /* Static Methods */
1096 * Return JS code that calls mw.loader.implement with given module properties.
1098 * @param string $name Module name
1099 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1100 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1101 * to CSS files keyed by media type
1102 * @param mixed $messages List of messages associated with this module. May either be an
1103 * associative array mapping message key to value, or a JSON-encoded message blob containing
1104 * the same data, wrapped in an XmlJsCode object.
1105 * @param array $templates Keys are name of templates and values are the source of
1107 * @throws MWException
1110 public static function makeLoaderImplementScript(
1111 $name, $scripts, $styles, $messages, $templates
1113 if ( is_string( $scripts ) ) {
1114 // Site and user module are a legacy scripts that run in the global scope (no closure).
1115 // Transportation as string instructs mw.loader.implement to use globalEval.
1116 if ( $name === 'site' ||
$name === 'user' ) {
1117 // Minify manually because the general makeModuleResponse() minification won't be
1118 // effective here due to the script being a string instead of a function. (T107377)
1119 if ( !ResourceLoader
::inDebugMode() ) {
1120 $scripts = self
::applyFilter( 'minify-js', $scripts,
1121 ConfigFactory
::getDefaultInstance()->makeConfig( 'main' ) );
1124 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1126 } elseif ( !is_array( $scripts ) ) {
1127 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1129 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1130 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1131 // of "{}". Force them to objects.
1139 self
::trimArray( $module );
1141 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1145 * Returns JS code which, when called, will register a given list of messages.
1147 * @param mixed $messages Either an associative array mapping message key to value, or a
1148 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1151 public static function makeMessageSetScript( $messages ) {
1152 return Xml
::encodeJsCall(
1154 array( (object)$messages ),
1155 ResourceLoader
::inDebugMode()
1160 * Combines an associative array mapping media type to CSS into a
1161 * single stylesheet with "@media" blocks.
1163 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1166 public static function makeCombinedStyles( array $stylePairs ) {
1168 foreach ( $stylePairs as $media => $styles ) {
1169 // ResourceLoaderFileModule::getStyle can return the styles
1170 // as a string or an array of strings. This is to allow separation in
1172 $styles = (array)$styles;
1173 foreach ( $styles as $style ) {
1174 $style = trim( $style );
1175 // Don't output an empty "@media print { }" block (bug 40498)
1176 if ( $style !== '' ) {
1177 // Transform the media type based on request params and config
1178 // The way that this relies on $wgRequest to propagate request params is slightly evil
1179 $media = OutputPage
::transformCssMedia( $media );
1181 if ( $media === '' ||
$media == 'all' ) {
1183 } elseif ( is_string( $media ) ) {
1184 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1194 * Returns a JS call to mw.loader.state, which sets the state of a
1195 * module or modules to a given value. Has two calling conventions:
1197 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1198 * Set the state of a single module called $name to $state
1200 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1201 * Set the state of modules with the given names to the given states
1203 * @param string $name
1204 * @param string $state
1207 public static function makeLoaderStateScript( $name, $state = null ) {
1208 if ( is_array( $name ) ) {
1209 return Xml
::encodeJsCall(
1212 ResourceLoader
::inDebugMode()
1215 return Xml
::encodeJsCall(
1217 array( $name, $state ),
1218 ResourceLoader
::inDebugMode()
1224 * Returns JS code which calls the script given by $script. The script will
1225 * be called with local variables name, version, dependencies and group,
1226 * which will have values corresponding to $name, $version, $dependencies
1227 * and $group as supplied.
1229 * @param string $name Module name
1230 * @param string $version Module version hash
1231 * @param array $dependencies List of module names on which this module depends
1232 * @param string $group Group which the module is in.
1233 * @param string $source Source of the module, or 'local' if not foreign.
1234 * @param string $script JavaScript code
1237 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1238 $group, $source, $script
1240 $script = str_replace( "\n", "\n\t", trim( $script ) );
1241 return Xml
::encodeJsCall(
1242 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1243 array( $name, $version, $dependencies, $group, $source ),
1244 ResourceLoader
::inDebugMode()
1248 private static function isEmptyObject( stdClass
$obj ) {
1249 foreach ( $obj as $key => $value ) {
1256 * Remove empty values from the end of an array.
1258 * Values considered empty:
1262 * - new XmlJsCode( '{}' )
1263 * - new stdClass() // (object) array()
1265 * @param Array $array
1267 private static function trimArray( Array &$array ) {
1268 $i = count( $array );
1270 if ( $array[$i] === null
1271 ||
$array[$i] === array()
1272 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1273 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1275 unset( $array[$i] );
1283 * Returns JS code which calls mw.loader.register with the given
1284 * parameters. Has three calling conventions:
1286 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1287 * $dependencies, $group, $source, $skip
1289 * Register a single module.
1291 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1292 * Register modules with the given names.
1294 * - ResourceLoader::makeLoaderRegisterScript( array(
1295 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1296 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1299 * Registers modules with the given names and parameters.
1301 * @param string $name Module name
1302 * @param string $version Module version hash
1303 * @param array $dependencies List of module names on which this module depends
1304 * @param string $group Group which the module is in
1305 * @param string $source Source of the module, or 'local' if not foreign
1306 * @param string $skip Script body of the skip function
1309 public static function makeLoaderRegisterScript( $name, $version = null,
1310 $dependencies = null, $group = null, $source = null, $skip = null
1312 if ( is_array( $name ) ) {
1313 // Build module name index
1315 foreach ( $name as $i => &$module ) {
1316 $index[$module[0]] = $i;
1319 // Transform dependency names into indexes when possible, they will be resolved by
1320 // mw.loader.register on the other end
1321 foreach ( $name as &$module ) {
1322 if ( isset( $module[2] ) ) {
1323 foreach ( $module[2] as &$dependency ) {
1324 if ( isset( $index[$dependency] ) ) {
1325 $dependency = $index[$dependency];
1331 array_walk( $name, array( 'self', 'trimArray' ) );
1333 return Xml
::encodeJsCall(
1334 'mw.loader.register',
1336 ResourceLoader
::inDebugMode()
1339 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1340 self
::trimArray( $registration );
1341 return Xml
::encodeJsCall(
1342 'mw.loader.register',
1344 ResourceLoader
::inDebugMode()
1350 * Returns JS code which calls mw.loader.addSource() with the given
1351 * parameters. Has two calling conventions:
1353 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1354 * Register a single source
1356 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1357 * Register sources with the given IDs and properties.
1359 * @param string $id Source ID
1360 * @param array $properties Source properties (see addSource())
1363 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1364 if ( is_array( $id ) ) {
1365 return Xml
::encodeJsCall(
1366 'mw.loader.addSource',
1368 ResourceLoader
::inDebugMode()
1371 return Xml
::encodeJsCall(
1372 'mw.loader.addSource',
1373 array( $id, $properties ),
1374 ResourceLoader
::inDebugMode()
1380 * Returns JS code which runs given JS code if the client-side framework is
1383 * @deprecated since 1.25; use makeInlineScript instead
1384 * @param string $script JavaScript code
1387 public static function makeLoaderConditionalScript( $script ) {
1388 return "window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n" .
1389 trim( $script ) . "\n} );";
1393 * Construct an inline script tag with given JS code.
1395 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1396 * only if the client has adequate support for MediaWiki JavaScript code.
1398 * @param string $script JavaScript code
1399 * @return WrappedString HTML
1401 public static function makeInlineScript( $script ) {
1402 $js = self
::makeLoaderConditionalScript( $script );
1403 return new WrappedString(
1404 Html
::inlineScript( $js ),
1405 "<script>window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n",
1411 * Returns JS code which will set the MediaWiki configuration array to
1414 * @param array $configuration List of configuration values keyed by variable name
1417 public static function makeConfigSetScript( array $configuration ) {
1418 if ( ResourceLoader
::inDebugMode() ) {
1419 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ), true );
1422 $config = RequestContext
::getMain()->getConfig();
1423 $js = Xml
::encodeJsCall( 'mw.config.set', array( $configuration ), false );
1424 return self
::applyFilter( 'minify-js', $js, $config );
1428 * Convert an array of module names to a packed query string.
1430 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1431 * becomes 'foo.bar,baz|bar.baz,quux'
1432 * @param array $modules List of module names (strings)
1433 * @return string Packed query string
1435 public static function makePackedModulesString( $modules ) {
1436 $groups = array(); // array( prefix => array( suffixes ) )
1437 foreach ( $modules as $module ) {
1438 $pos = strrpos( $module, '.' );
1439 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1440 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1441 $groups[$prefix][] = $suffix;
1445 foreach ( $groups as $prefix => $suffixes ) {
1446 $p = $prefix === '' ?
'' : $prefix . '.';
1447 $arr[] = $p . implode( ',', $suffixes );
1449 $str = implode( '|', $arr );
1454 * Determine whether debug mode was requested
1455 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1458 public static function inDebugMode() {
1459 if ( self
::$debugMode === null ) {
1460 global $wgRequest, $wgResourceLoaderDebug;
1461 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1462 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1465 return self
::$debugMode;
1469 * Reset static members used for caching.
1471 * Global state and $wgRequest are evil, but we're using it right
1472 * now and sometimes we need to be able to force ResourceLoader to
1473 * re-evaluate the context because it has changed (e.g. in the test suite).
1475 public static function clearCache() {
1476 self
::$debugMode = null;
1480 * Build a load.php URL
1483 * @param string $source Name of the ResourceLoader source
1484 * @param ResourceLoaderContext $context
1485 * @param array $extraQuery
1486 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1488 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1489 $extraQuery = array()
1491 $query = self
::createLoaderQuery( $context, $extraQuery );
1492 $script = $this->getLoadScript( $source );
1494 return wfAppendQuery( $script, $query );
1498 * Build a load.php URL
1499 * @deprecated since 1.24 Use createLoaderURL() instead
1500 * @param array $modules Array of module names (strings)
1501 * @param string $lang Language code
1502 * @param string $skin Skin name
1503 * @param string|null $user User name. If null, the &user= parameter is omitted
1504 * @param string|null $version Versioning timestamp
1505 * @param bool $debug Whether the request should be in debug mode
1506 * @param string|null $only &only= parameter
1507 * @param bool $printable Printable mode
1508 * @param bool $handheld Handheld mode
1509 * @param array $extraQuery Extra query parameters to add
1510 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1512 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1513 $version = null, $debug = false, $only = null, $printable = false,
1514 $handheld = false, $extraQuery = array()
1516 global $wgLoadScript;
1518 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1519 $only, $printable, $handheld, $extraQuery
1522 return wfAppendQuery( $wgLoadScript, $query );
1526 * Helper for createLoaderURL()
1529 * @see makeLoaderQuery
1530 * @param ResourceLoaderContext $context
1531 * @param array $extraQuery
1534 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1535 return self
::makeLoaderQuery(
1536 $context->getModules(),
1537 $context->getLanguage(),
1538 $context->getSkin(),
1539 $context->getUser(),
1540 $context->getVersion(),
1541 $context->getDebug(),
1542 $context->getOnly(),
1543 $context->getRequest()->getBool( 'printable' ),
1544 $context->getRequest()->getBool( 'handheld' ),
1550 * Build a query array (array representation of query string) for load.php. Helper
1551 * function for makeLoaderURL().
1553 * @param array $modules
1554 * @param string $lang
1555 * @param string $skin
1556 * @param string $user
1557 * @param string $version
1558 * @param bool $debug
1559 * @param string $only
1560 * @param bool $printable
1561 * @param bool $handheld
1562 * @param array $extraQuery
1566 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1567 $version = null, $debug = false, $only = null, $printable = false,
1568 $handheld = false, $extraQuery = array()
1571 'modules' => self
::makePackedModulesString( $modules ),
1574 'debug' => $debug ?
'true' : 'false',
1576 if ( $user !== null ) {
1577 $query['user'] = $user;
1579 if ( $version !== null ) {
1580 $query['version'] = $version;
1582 if ( $only !== null ) {
1583 $query['only'] = $only;
1586 $query['printable'] = 1;
1589 $query['handheld'] = 1;
1591 $query +
= $extraQuery;
1593 // Make queries uniform in order
1599 * Check a module name for validity.
1601 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1602 * at most 255 bytes.
1604 * @param string $moduleName Module name to check
1605 * @return bool Whether $moduleName is a valid module name
1607 public static function isValidModuleName( $moduleName ) {
1608 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1612 * Returns LESS compiler set up for use with MediaWiki
1615 * @since 1.26 added $extraVars parameter
1616 * @param Config $config
1617 * @param array $extraVars Associative array of extra (i.e., other than the
1618 * globally-configured ones) that should be used for compilation.
1619 * @throws MWException
1620 * @return Less_Parser
1622 public static function getLessCompiler( Config
$config, $extraVars = array() ) {
1623 // When called from the installer, it is possible that a required PHP extension
1624 // is missing (at least for now; see bug 47564). If this is the case, throw an
1625 // exception (caught by the installer) to prevent a fatal error later on.
1626 if ( !class_exists( 'Less_Parser' ) ) {
1627 throw new MWException( 'MediaWiki requires the less.php parser' );
1630 $parser = new Less_Parser
;
1631 $parser->ModifyVars( array_merge( self
::getLessVars( $config ), $extraVars ) );
1632 $parser->SetImportDirs( array_fill_keys( $config->get( 'ResourceLoaderLESSImportPaths' ), '' ) );
1633 $parser->SetOption( 'relativeUrls', false );
1634 $parser->SetCacheDir( $config->get( 'CacheDirectory' ) ?
: wfTempDir() );
1640 * Get global LESS variables.
1642 * @param Config $config
1644 * @return array Map of variable names to string CSS values.
1646 public static function getLessVars( Config
$config ) {
1647 if ( !self
::$lessVars ) {
1648 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1649 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1650 self
::$lessVars = $lessVars;
1652 return self
::$lessVars;