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
26 * Dynamic JavaScript and CSS resource loading system.
28 * Most of the documentation is on the MediaWiki documentation wiki starting at:
29 * https://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader
{
33 protected static $filterCacheVersion = 7;
36 protected static $debugMode = null;
39 private static $lessVars = null;
42 * Module name/ResourceLoaderModule object pairs
45 protected $modules = array();
48 * Associative array mapping module name to info associative array
51 protected $moduleInfos = array();
53 /** @var Config $config */
57 * Associative array mapping framework ids to a list of names of test suite modules
58 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
61 protected $testModuleNames = array();
64 * E.g. array( 'source-id' => 'http://.../load.php' )
67 protected $sources = array();
70 * Errors accumulated during current respond() call.
73 protected $errors = array();
76 * @var MessageBlobStore
81 * Load information stored in the database about modules.
83 * This method grabs modules dependencies from the database and updates modules
86 * This is not inside the module code because it is much faster to
87 * request all of the information at once than it is to have each module
88 * requests its own information. This sacrifice of modularity yields a substantial
89 * performance improvement.
91 * @param array $modules List of module names to preload information for
92 * @param ResourceLoaderContext $context Context to load the information within
94 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
95 if ( !count( $modules ) ) {
96 // Or else Database*::select() will explode, plus it's cheaper!
99 $dbr = wfGetDB( DB_SLAVE
);
100 $skin = $context->getSkin();
101 $lang = $context->getLanguage();
103 // Get file dependency information
104 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
105 'md_module' => $modules,
110 // Set modules' dependencies
111 $modulesWithDeps = array();
112 foreach ( $res as $row ) {
113 $module = $this->getModule( $row->md_module
);
115 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
116 $modulesWithDeps[] = $row->md_module
;
120 // Register the absence of a dependency row too
121 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
122 $module = $this->getModule( $name );
124 $this->getModule( $name )->setFileDependencies( $skin, array() );
128 // Get message blob mtimes. Only do this for modules with messages
129 $modulesWithMessages = array();
130 foreach ( $modules as $name ) {
131 $module = $this->getModule( $name );
132 if ( $module && count( $module->getMessages() ) ) {
133 $modulesWithMessages[] = $name;
136 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
137 if ( count( $modulesWithMessages ) ) {
138 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
139 'mr_resource' => $modulesWithMessages,
143 foreach ( $res as $row ) {
144 $module = $this->getModule( $row->mr_resource
);
146 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
147 unset( $modulesWithoutMessages[$row->mr_resource
] );
151 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
152 $module = $this->getModule( $name );
154 $module->setMsgBlobMtime( $lang, 1 );
160 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
162 * Available filters are:
164 * - minify-js \see JavaScriptMinifier::minify
165 * - minify-css \see CSSMin::minify
167 * If $data is empty, only contains whitespace or the filter was unknown,
168 * $data is returned unmodified.
170 * @param string $filter Name of filter to run
171 * @param string $data Text to filter, such as JavaScript or CSS text
172 * @param array $options For back-compat, can also be the boolean value for "cacheReport". Keys:
173 * - (bool) cache: Whether to allow caching this data. Default: true.
174 * - (bool) cacheReport: Whether to include the "cache key" report comment. Default: true.
175 * @return string Filtered data, or a comment containing an error message
177 public function filter( $filter, $data, $options = array() ) {
179 if ( is_bool( $options ) ) {
180 $options = array( 'cacheReport' => $options );
183 $options +
= array( 'cache' => true, 'cacheReport' => true );
185 // Don't filter empty content
186 if ( trim( $data ) === '' ) {
190 if ( !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
191 wfDebugLog( 'resourceloader', __METHOD__
. ": Invalid filter: $filter" );
195 if ( !$options['cache'] ) {
196 $result = $this->applyFilter( $filter, $data );
198 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
199 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL
: CACHE_ANYTHING
);
200 $cacheEntry = $cache->get( $key );
201 if ( is_string( $cacheEntry ) ) {
202 wfIncrStats( "resourceloader_cache.$filter.hit" );
207 wfIncrStats( "resourceloader_cache.$filter.miss" );
208 $result = $this->applyFilter( $filter, $data );
209 if ( $options['cacheReport'] ) {
210 $result .= "\n/* cache key: $key */";
212 $cache->set( $key, $result );
213 } catch ( Exception
$e ) {
214 MWExceptionHandler
::logException( $e );
215 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
216 $this->errors
[] = self
::formatExceptionNoComment( $e );
223 private function applyFilter( $filter, $data ) {
226 return JavaScriptMinifier
::minify( $data,
227 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
228 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
231 return CSSMin
::minify( $data );
239 * Register core modules and runs registration hooks.
240 * @param Config|null $config
242 public function __construct( Config
$config = null ) {
245 if ( $config === null ) {
246 wfDebug( __METHOD__
. ' was called without providing a Config instance' );
247 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
250 $this->config
= $config;
252 // Add 'local' source first
253 $this->addSource( 'local', wfScript( 'load' ) );
256 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
258 // Register core modules
259 $this->register( include "$IP/resources/Resources.php" );
260 $this->register( include "$IP/resources/ResourcesOOUI.php" );
261 // Register extension modules
262 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
263 $this->register( $config->get( 'ResourceModules' ) );
265 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
266 $this->registerTestModules();
269 $this->setMessageBlobStore( new MessageBlobStore() );
275 public function getConfig() {
276 return $this->config
;
280 * @param MessageBlobStore $blobStore
283 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
284 $this->blobStore
= $blobStore;
288 * Register a module with the ResourceLoader system.
290 * @param mixed $name Name of module as a string or List of name/object pairs as an array
291 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
292 * this may also be a ResourceLoaderModule object. Optional when using
293 * multiple-registration calling style.
294 * @throws MWException If a duplicate module registration is attempted
295 * @throws MWException If a module name contains illegal characters (pipes or commas)
296 * @throws MWException If something other than a ResourceLoaderModule is being registered
297 * @return bool False if there were any errors, in which case one or more modules were
300 public function register( $name, $info = null ) {
302 // Allow multiple modules to be registered in one call
303 $registrations = is_array( $name ) ?
$name : array( $name => $info );
304 foreach ( $registrations as $name => $info ) {
305 // Disallow duplicate registrations
306 if ( isset( $this->moduleInfos
[$name] ) ) {
307 // A module has already been registered by this name
308 throw new MWException(
309 'ResourceLoader duplicate registration error. ' .
310 'Another module has already been registered as ' . $name
314 // Check $name for validity
315 if ( !self
::isValidModuleName( $name ) ) {
316 throw new MWException( "ResourceLoader module name '$name' is invalid, "
317 . "see ResourceLoader::isValidModuleName()" );
321 if ( $info instanceof ResourceLoaderModule
) {
322 $this->moduleInfos
[$name] = array( 'object' => $info );
323 $info->setName( $name );
324 $this->modules
[$name] = $info;
325 } elseif ( is_array( $info ) ) {
326 // New calling convention
327 $this->moduleInfos
[$name] = $info;
329 throw new MWException(
330 'ResourceLoader module info type error for module \'' . $name .
331 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
335 // Last-minute changes
337 // Apply custom skin-defined styles to existing modules.
338 if ( $this->isFileModule( $name ) ) {
339 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
340 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
341 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
345 // If $name is preceded with a '+', the defined style files will be added to 'default'
346 // skinStyles, otherwise 'default' will be ignored as it normally would be.
347 if ( isset( $skinStyles[$name] ) ) {
348 $paths = (array)$skinStyles[$name];
349 $styleFiles = array();
350 } elseif ( isset( $skinStyles['+' . $name] ) ) {
351 $paths = (array)$skinStyles['+' . $name];
352 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
353 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
359 // Add new file paths, remapping them to refer to our directories and not use settings
360 // from the module we're modifying, which come from the base definition.
361 list( $localBasePath, $remoteBasePath ) =
362 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
364 foreach ( $paths as $path ) {
365 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
368 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
377 public function registerTestModules() {
380 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
381 throw new MWException( 'Attempt to register JavaScript test modules '
382 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
383 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
386 // Get core test suites
387 $testModules = array();
388 $testModules['qunit'] = array();
389 // Get other test suites (e.g. from extensions)
390 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
392 // Add the testrunner (which configures QUnit) to the dependencies.
393 // Since it must be ready before any of the test suites are executed.
394 foreach ( $testModules['qunit'] as &$module ) {
395 // Make sure all test modules are top-loading so that when QUnit starts
396 // on document-ready, it will run once and finish. If some tests arrive
397 // later (possibly after QUnit has already finished) they will be ignored.
398 $module['position'] = 'top';
399 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
402 $testModules['qunit'] =
403 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
405 foreach ( $testModules as $id => $names ) {
406 // Register test modules
407 $this->register( $testModules[$id] );
409 // Keep track of their names so that they can be loaded together
410 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
416 * Add a foreign source of modules.
418 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
419 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
420 * backwards-compatibility.
421 * @throws MWException
423 public function addSource( $id, $loadUrl = null ) {
424 // Allow multiple sources to be registered in one call
425 if ( is_array( $id ) ) {
426 foreach ( $id as $key => $value ) {
427 $this->addSource( $key, $value );
432 // Disallow duplicates
433 if ( isset( $this->sources
[$id] ) ) {
434 throw new MWException(
435 'ResourceLoader duplicate source addition error. ' .
436 'Another source has already been registered as ' . $id
440 // Pre 1.24 backwards-compatibility
441 if ( is_array( $loadUrl ) ) {
442 if ( !isset( $loadUrl['loadScript'] ) ) {
443 throw new MWException(
444 __METHOD__
. ' was passed an array with no "loadScript" key.'
448 $loadUrl = $loadUrl['loadScript'];
451 $this->sources
[$id] = $loadUrl;
455 * Get a list of module names.
457 * @return array List of module names
459 public function getModuleNames() {
460 return array_keys( $this->moduleInfos
);
464 * Get a list of test module names for one (or all) frameworks.
466 * If the given framework id is unknkown, or if the in-object variable is not an array,
467 * then it will return an empty array.
469 * @param string $framework Get only the test module names for one
470 * particular framework (optional)
473 public function getTestModuleNames( $framework = 'all' ) {
474 /** @todo api siteinfo prop testmodulenames modulenames */
475 if ( $framework == 'all' ) {
476 return $this->testModuleNames
;
477 } elseif ( isset( $this->testModuleNames
[$framework] )
478 && is_array( $this->testModuleNames
[$framework] )
480 return $this->testModuleNames
[$framework];
487 * Check whether a ResourceLoader module is registered
490 * @param string $name
493 public function isModuleRegistered( $name ) {
494 return isset( $this->moduleInfos
[$name] );
498 * Get the ResourceLoaderModule object for a given module name.
500 * If an array of module parameters exists but a ResourceLoaderModule object has not
501 * yet been instantiated, this method will instantiate and cache that object such that
502 * subsequent calls simply return the same object.
504 * @param string $name Module name
505 * @return ResourceLoaderModule|null If module has been registered, return a
506 * ResourceLoaderModule instance. Otherwise, return null.
508 public function getModule( $name ) {
509 if ( !isset( $this->modules
[$name] ) ) {
510 if ( !isset( $this->moduleInfos
[$name] ) ) {
514 // Construct the requested object
515 $info = $this->moduleInfos
[$name];
516 /** @var ResourceLoaderModule $object */
517 if ( isset( $info['object'] ) ) {
518 // Object given in info array
519 $object = $info['object'];
521 if ( !isset( $info['class'] ) ) {
522 $class = 'ResourceLoaderFileModule';
524 $class = $info['class'];
526 /** @var ResourceLoaderModule $object */
527 $object = new $class( $info );
528 $object->setConfig( $this->getConfig() );
530 $object->setName( $name );
531 $this->modules
[$name] = $object;
534 return $this->modules
[$name];
538 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
540 * @param string $name Module name
543 protected function isFileModule( $name ) {
544 if ( !isset( $this->moduleInfos
[$name] ) ) {
547 $info = $this->moduleInfos
[$name];
548 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
555 * Get the list of sources.
557 * @return array Like array( id => load.php url, .. )
559 public function getSources() {
560 return $this->sources
;
564 * Get the URL to the load.php endpoint for the given
565 * ResourceLoader source
568 * @param string $source
569 * @throws MWException On an invalid $source name
572 public function getLoadScript( $source ) {
573 if ( !isset( $this->sources
[$source] ) ) {
574 throw new MWException( "The $source source was never registered in ResourceLoader." );
576 return $this->sources
[$source];
581 * @param string $value
582 * @return string Hash
584 public static function makeHash( $value ) {
585 // Use base64 to output more entropy in a more compact string (default hex is only base16).
586 // The first 8 chars of a base64 encoded digest represent the same binary as
587 // the first 12 chars of a hex encoded digest.
588 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
592 * Helper method to get and combine versions of multiple modules.
595 * @param ResourceLoaderContext $context
596 * @param array $modules List of ResourceLoaderModule objects
597 * @return string Hash
599 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
603 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
604 // http://php.net/functions.anonymous
606 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
607 return $rl->getModule( $module )->getVersionHash( $context );
609 return self
::makeHash( implode( $hashes ) );
613 * Output a response to a load request, including the content-type header.
615 * @param ResourceLoaderContext $context Context in which a response should be formed
617 public function respond( ResourceLoaderContext
$context ) {
618 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
619 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
620 // is used: ob_clean() will clear the GZIP header in that case and it won't come
621 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
622 // the whole thing in our own output buffer to be sure the active buffer
623 // doesn't use ob_gzhandler.
624 // See http://bugs.php.net/bug.php?id=36514
627 // Find out which modules are missing and instantiate the others
630 foreach ( $context->getModules() as $name ) {
631 $module = $this->getModule( $name );
633 // Do not allow private modules to be loaded from the web.
634 // This is a security issue, see bug 34907.
635 if ( $module->getGroup() === 'private' ) {
636 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
637 $this->errors
[] = "Cannot show private module \"$name\"";
640 $modules[$name] = $module;
647 // Preload for getCombinedVersion()
648 $this->preloadModuleInfo( array_keys( $modules ), $context );
649 } catch ( Exception
$e ) {
650 MWExceptionHandler
::logException( $e );
651 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
652 $this->errors
[] = self
::formatExceptionNoComment( $e );
655 // Combine versions to propagate cache invalidation
658 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
659 } catch ( Exception
$e ) {
660 MWExceptionHandler
::logException( $e );
661 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating version hash failed: $e" );
662 $this->errors
[] = self
::formatExceptionNoComment( $e );
665 // See RFC 2616 § 3.11 Entity Tags
666 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
667 $etag = 'W/"' . $versionHash . '"';
669 // Try the client-side cache first
670 if ( $this->tryRespondNotModified( $context, $etag ) ) {
671 return; // output handled (buffers cleared)
674 // Use file cache if enabled and available...
675 if ( $this->config
->get( 'UseFileCache' ) ) {
676 $fileCache = ResourceFileCache
::newFromContext( $context );
677 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
678 return; // output handled
682 // Generate a response
683 $response = $this->makeModuleResponse( $context, $modules, $missing );
685 // Capture any PHP warnings from the output buffer and append them to the
686 // error list if we're in debug mode.
687 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
688 $this->errors
[] = $warnings;
691 // Save response to file cache unless there are errors
692 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
693 // Cache single modules and images...and other requests if there are enough hits
694 if ( ResourceFileCache
::useFileCache( $context ) ) {
695 if ( $fileCache->isCacheWorthy() ) {
696 $fileCache->saveText( $response );
698 $fileCache->incrMissesRecent( $context->getRequest() );
703 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
705 // Remove the output buffer and output the response
708 if ( $context->getImageObj() && $this->errors
) {
709 // We can't show both the error messages and the response when it's an image.
711 foreach ( $this->errors
as $error ) {
712 $errorText .= $error . "\n";
714 $response = $errorText;
715 } elseif ( $this->errors
) {
716 // Prepend comments indicating errors
718 foreach ( $this->errors
as $error ) {
719 $errorText .= self
::makeComment( $error );
721 $response = $errorText . $response;
724 $this->errors
= array();
730 * Send main response headers to the client.
732 * Deals with Content-Type, CORS (for stylesheets), and caching.
734 * @param ResourceLoaderContext $context
735 * @param string $etag ETag header value
736 * @param bool $errors Whether there are errors in the response
739 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
740 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
741 // If a version wasn't specified we need a shorter expiry time for updates
742 // to propagate to clients quickly
743 // If there were errors, we also need a shorter expiry time so we can recover quickly
744 if ( is_null( $context->getVersion() ) ||
$errors ) {
745 $maxage = $rlMaxage['unversioned']['client'];
746 $smaxage = $rlMaxage['unversioned']['server'];
747 // If a version was specified we can use a longer expiry time since changing
748 // version numbers causes cache misses
750 $maxage = $rlMaxage['versioned']['client'];
751 $smaxage = $rlMaxage['versioned']['server'];
753 if ( $context->getImageObj() ) {
754 // Output different headers if we're outputting textual errors.
756 header( 'Content-Type: text/plain; charset=utf-8' );
758 $context->getImageObj()->sendResponseHeaders( $context );
760 } elseif ( $context->getOnly() === 'styles' ) {
761 header( 'Content-Type: text/css; charset=utf-8' );
762 header( 'Access-Control-Allow-Origin: *' );
764 header( 'Content-Type: text/javascript; charset=utf-8' );
766 // See RFC 2616 § 14.19 ETag
767 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
768 header( 'ETag: ' . $etag );
769 if ( $context->getDebug() ) {
770 // Do not cache debug responses
771 header( 'Cache-Control: private, no-cache, must-revalidate' );
772 header( 'Pragma: no-cache' );
774 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
775 $exp = min( $maxage, $smaxage );
776 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
781 * Respond with HTTP 304 Not Modified if appropiate.
783 * If there's an If-None-Match header, respond with a 304 appropriately
784 * and clear out the output buffer. If the client cache is too old then do nothing.
786 * @param ResourceLoaderContext $context
787 * @param string $etag ETag header value
788 * @return bool True if HTTP 304 was sent and output handled
790 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
791 // See RFC 2616 § 14.26 If-None-Match
792 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
793 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
794 // Never send 304s in debug mode
795 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
796 // There's another bug in ob_gzhandler (see also the comment at
797 // the top of this function) that causes it to gzip even empty
798 // responses, meaning it's impossible to produce a truly empty
799 // response (because the gzip header is always there). This is
800 // a problem because 304 responses have to be completely empty
801 // per the HTTP spec, and Firefox behaves buggily when they're not.
802 // See also http://bugs.php.net/bug.php?id=51579
803 // To work around this, we tear down all output buffering before
805 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
807 header( 'HTTP/1.0 304 Not Modified' );
808 header( 'Status: 304 Not Modified' );
810 $this->sendResponseHeaders( $context, $etag, false );
817 * Send out code for a response from file cache if possible.
819 * @param ResourceFileCache $fileCache Cache object for this request URL
820 * @param ResourceLoaderContext $context Context in which to generate a response
821 * @param string $etag ETag header value
822 * @return bool If this found a cache file and handled the response
824 protected function tryRespondFromFileCache(
825 ResourceFileCache
$fileCache,
826 ResourceLoaderContext
$context,
829 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
830 // Buffer output to catch warnings.
832 // Get the maximum age the cache can be
833 $maxage = is_null( $context->getVersion() )
834 ?
$rlMaxage['unversioned']['server']
835 : $rlMaxage['versioned']['server'];
836 // Minimum timestamp the cache file must have
837 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
839 try { // RL always hits the DB on file cache miss...
841 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
842 $good = $fileCache->isCacheGood(); // cache existence check
846 $ts = $fileCache->cacheTimestamp();
847 // Send content type and cache headers
848 $this->sendResponseHeaders( $context, $etag, false );
849 $response = $fileCache->fetchText();
850 // Capture any PHP warnings from the output buffer and append them to the
851 // response in a comment if we're in debug mode.
852 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
853 $response = self
::makeComment( $warnings ) . $response;
855 // Remove the output buffer and output the response
857 echo $response . "\n/* Cached {$ts} */";
858 return true; // cache hit
863 return false; // cache miss
867 * Generate a CSS or JS comment block.
869 * Only use this for public data, not error message details.
871 * @param string $text
874 public static function makeComment( $text ) {
875 $encText = str_replace( '*/', '* /', $text );
876 return "/*\n$encText\n*/\n";
880 * Handle exception display.
882 * @param Exception $e Exception to be shown to the user
883 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
885 public static function formatException( $e ) {
886 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
890 * Handle exception display.
893 * @param Exception $e Exception to be shown to the user
894 * @return string Sanitized text that can be returned to the user
896 protected static function formatExceptionNoComment( $e ) {
897 global $wgShowExceptionDetails;
899 if ( $wgShowExceptionDetails ) {
900 return $e->__toString();
902 return wfMessage( 'internalerror' )->text();
907 * Generate code for a response.
909 * @param ResourceLoaderContext $context Context in which to generate a response
910 * @param array $modules List of module objects keyed by module name
911 * @param array $missing List of requested module names that are unregistered (optional)
912 * @return string Response data
914 public function makeModuleResponse( ResourceLoaderContext
$context,
915 array $modules, array $missing = array()
920 if ( !count( $modules ) && !count( $missing ) ) {
922 /* This file is the Web entry point for MediaWiki's ResourceLoader:
923 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
924 no modules were requested. Max made me put this here. */
928 $image = $context->getImageObj();
930 $data = $image->getImageData( $context );
931 if ( $data === false ) {
933 $this->errors
[] = 'Image generation failed';
939 if ( $context->shouldIncludeMessages() ) {
941 $blobs = $this->blobStore
->get( $this, $modules, $context->getLanguage() );
942 } catch ( Exception
$e ) {
943 MWExceptionHandler
::logException( $e );
946 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
948 $this->errors
[] = self
::formatExceptionNoComment( $e );
954 foreach ( $missing as $name ) {
955 $states[$name] = 'missing';
960 foreach ( $modules as $name => $module ) {
962 * @var $module ResourceLoaderModule
967 if ( $context->shouldIncludeScripts() ) {
968 // If we are in debug mode, we'll want to return an array of URLs if possible
969 // However, we can't do this if the module doesn't support it
970 // We also can't do this if there is an only= parameter, because we have to give
971 // the module a way to return a load.php URL without causing an infinite loop
972 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
973 $scripts = $module->getScriptURLsForDebug( $context );
975 $scripts = $module->getScript( $context );
976 // rtrim() because there are usually a few line breaks
977 // after the last ';'. A new line at EOF, a new line
978 // added by ResourceLoaderFileModule::readScriptFiles, etc.
979 if ( is_string( $scripts )
980 && strlen( $scripts )
981 && substr( rtrim( $scripts ), -1 ) !== ';'
983 // Append semicolon to prevent weird bugs caused by files not
984 // terminating their statements right (bug 27054)
991 if ( $context->shouldIncludeStyles() ) {
992 // Don't create empty stylesheets like array( '' => '' ) for modules
993 // that don't *have* any stylesheets (bug 38024).
994 $stylePairs = $module->getStyles( $context );
995 if ( count( $stylePairs ) ) {
996 // If we are in debug mode without &only= set, we'll want to return an array of URLs
997 // See comment near shouldIncludeScripts() for more details
998 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
1000 'url' => $module->getStyleURLsForDebug( $context )
1003 // Minify CSS before embedding in mw.loader.implement call
1004 // (unless in debug mode)
1005 if ( !$context->getDebug() ) {
1006 foreach ( $stylePairs as $media => $style ) {
1007 // Can be either a string or an array of strings.
1008 if ( is_array( $style ) ) {
1009 $stylePairs[$media] = array();
1010 foreach ( $style as $cssText ) {
1011 if ( is_string( $cssText ) ) {
1012 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
1015 } elseif ( is_string( $style ) ) {
1016 $stylePairs[$media] = $this->filter( 'minify-css', $style );
1020 // Wrap styles into @media groups as needed and flatten into a numerical array
1022 'css' => self
::makeCombinedStyles( $stylePairs )
1029 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
1032 switch ( $context->getOnly() ) {
1034 if ( is_string( $scripts ) ) {
1035 // Load scripts raw...
1037 } elseif ( is_array( $scripts ) ) {
1038 // ...except when $scripts is an array of URLs
1039 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1043 // We no longer seperate into media, they are all combined now with
1044 // custom media type groups into @media .. {} sections as part of the css string.
1045 // Module returns either an empty array or a numerical array with css strings.
1046 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1049 $out .= self
::makeLoaderImplementScript(
1053 new XmlJsCode( $messagesBlob ),
1054 $module->getTemplates()
1058 } catch ( Exception
$e ) {
1059 MWExceptionHandler
::logException( $e );
1060 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
1061 $this->errors
[] = self
::formatExceptionNoComment( $e );
1063 // Respond to client with error-state instead of module implementation
1064 $states[$name] = 'error';
1065 unset( $modules[$name] );
1067 $isRaw |
= $module->isRaw();
1070 // Update module states
1071 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1072 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1073 // Set the state of modules loaded as only scripts to ready as
1074 // they don't have an mw.loader.implement wrapper that sets the state
1075 foreach ( $modules as $name => $module ) {
1076 $states[$name] = 'ready';
1080 // Set the state of modules we didn't respond to with mw.loader.implement
1081 if ( count( $states ) ) {
1082 $out .= self
::makeLoaderStateScript( $states );
1085 if ( count( $states ) ) {
1086 $this->errors
[] = 'Problematic modules: ' .
1087 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1091 $enableFilterCache = true;
1092 if ( count( $modules ) === 1 && reset( $modules ) instanceof ResourceLoaderUserTokensModule
) {
1093 // If we're building the embedded user.tokens, don't cache (T84960)
1094 $enableFilterCache = false;
1097 if ( !$context->getDebug() ) {
1098 if ( $context->getOnly() === 'styles' ) {
1099 $out = $this->filter( 'minify-css', $out );
1101 $out = $this->filter( 'minify-js', $out, array(
1102 'cache' => $enableFilterCache
1110 /* Static Methods */
1113 * Return JS code that calls mw.loader.implement with given module properties.
1115 * @param string $name Module name
1116 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1117 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1118 * to CSS files keyed by media type
1119 * @param mixed $messages List of messages associated with this module. May either be an
1120 * associative array mapping message key to value, or a JSON-encoded message blob containing
1121 * the same data, wrapped in an XmlJsCode object.
1122 * @param array $templates Keys are name of templates and values are the source of
1124 * @throws MWException
1127 public static function makeLoaderImplementScript(
1128 $name, $scripts, $styles, $messages, $templates
1130 if ( is_string( $scripts ) ) {
1131 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1132 } elseif ( !is_array( $scripts ) ) {
1133 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1135 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1136 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1137 // of "{}". Force them to objects.
1143 (object) $templates,
1145 self
::trimArray( $module );
1147 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1151 * Returns JS code which, when called, will register a given list of messages.
1153 * @param mixed $messages Either an associative array mapping message key to value, or a
1154 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1157 public static function makeMessageSetScript( $messages ) {
1158 return Xml
::encodeJsCall(
1160 array( (object)$messages ),
1161 ResourceLoader
::inDebugMode()
1166 * Combines an associative array mapping media type to CSS into a
1167 * single stylesheet with "@media" blocks.
1169 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1172 public static function makeCombinedStyles( array $stylePairs ) {
1174 foreach ( $stylePairs as $media => $styles ) {
1175 // ResourceLoaderFileModule::getStyle can return the styles
1176 // as a string or an array of strings. This is to allow separation in
1178 $styles = (array)$styles;
1179 foreach ( $styles as $style ) {
1180 $style = trim( $style );
1181 // Don't output an empty "@media print { }" block (bug 40498)
1182 if ( $style !== '' ) {
1183 // Transform the media type based on request params and config
1184 // The way that this relies on $wgRequest to propagate request params is slightly evil
1185 $media = OutputPage
::transformCssMedia( $media );
1187 if ( $media === '' ||
$media == 'all' ) {
1189 } elseif ( is_string( $media ) ) {
1190 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1200 * Returns a JS call to mw.loader.state, which sets the state of a
1201 * module or modules to a given value. Has two calling conventions:
1203 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1204 * Set the state of a single module called $name to $state
1206 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1207 * Set the state of modules with the given names to the given states
1209 * @param string $name
1210 * @param string $state
1213 public static function makeLoaderStateScript( $name, $state = null ) {
1214 if ( is_array( $name ) ) {
1215 return Xml
::encodeJsCall(
1218 ResourceLoader
::inDebugMode()
1221 return Xml
::encodeJsCall(
1223 array( $name, $state ),
1224 ResourceLoader
::inDebugMode()
1230 * Returns JS code which calls the script given by $script. The script will
1231 * be called with local variables name, version, dependencies and group,
1232 * which will have values corresponding to $name, $version, $dependencies
1233 * and $group as supplied.
1235 * @param string $name Module name
1236 * @param string $version Module version hash
1237 * @param array $dependencies List of module names on which this module depends
1238 * @param string $group Group which the module is in.
1239 * @param string $source Source of the module, or 'local' if not foreign.
1240 * @param string $script JavaScript code
1243 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1244 $group, $source, $script
1246 $script = str_replace( "\n", "\n\t", trim( $script ) );
1247 return Xml
::encodeJsCall(
1248 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1249 array( $name, $version, $dependencies, $group, $source ),
1250 ResourceLoader
::inDebugMode()
1254 private static function isEmptyObject( stdClass
$obj ) {
1255 foreach ( $obj as $key => &$value ) {
1262 * Remove empty values from the end of an array.
1264 * Values considered empty:
1268 * - new XmlJsCode( '{}' )
1269 * - new stdClass() // (object) array()
1271 * @param Array $array
1273 private static function trimArray( Array &$array ) {
1274 $i = count( $array );
1276 if ( $array[$i] === null
1277 ||
$array[$i] === array()
1278 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1279 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1281 unset( $array[$i] );
1289 * Returns JS code which calls mw.loader.register with the given
1290 * parameters. Has three calling conventions:
1292 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1293 * $dependencies, $group, $source, $skip
1295 * Register a single module.
1297 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1298 * Register modules with the given names.
1300 * - ResourceLoader::makeLoaderRegisterScript( array(
1301 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1302 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1305 * Registers modules with the given names and parameters.
1307 * @param string $name Module name
1308 * @param string $version Module version hash
1309 * @param array $dependencies List of module names on which this module depends
1310 * @param string $group Group which the module is in
1311 * @param string $source Source of the module, or 'local' if not foreign
1312 * @param string $skip Script body of the skip function
1315 public static function makeLoaderRegisterScript( $name, $version = null,
1316 $dependencies = null, $group = null, $source = null, $skip = null
1318 if ( is_array( $name ) ) {
1319 // Build module name index
1321 foreach ( $name as $i => &$module ) {
1322 $index[$module[0]] = $i;
1325 // Transform dependency names into indexes when possible, they will be resolved by
1326 // mw.loader.register on the other end
1327 foreach ( $name as &$module ) {
1328 if ( isset( $module[2] ) ) {
1329 foreach ( $module[2] as &$dependency ) {
1330 if ( isset( $index[$dependency] ) ) {
1331 $dependency = $index[$dependency];
1337 array_walk( $name, array( 'self', 'trimArray' ) );
1339 return Xml
::encodeJsCall(
1340 'mw.loader.register',
1342 ResourceLoader
::inDebugMode()
1345 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1346 self
::trimArray( $registration );
1347 return Xml
::encodeJsCall(
1348 'mw.loader.register',
1350 ResourceLoader
::inDebugMode()
1356 * Returns JS code which calls mw.loader.addSource() with the given
1357 * parameters. Has two calling conventions:
1359 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1360 * Register a single source
1362 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1363 * Register sources with the given IDs and properties.
1365 * @param string $id Source ID
1366 * @param array $properties Source properties (see addSource())
1369 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1370 if ( is_array( $id ) ) {
1371 return Xml
::encodeJsCall(
1372 'mw.loader.addSource',
1374 ResourceLoader
::inDebugMode()
1377 return Xml
::encodeJsCall(
1378 'mw.loader.addSource',
1379 array( $id, $properties ),
1380 ResourceLoader
::inDebugMode()
1386 * Returns JS code which runs given JS code if the client-side framework is
1389 * @deprecated since 1.25; use makeInlineScript instead
1390 * @param string $script JavaScript code
1393 public static function makeLoaderConditionalScript( $script ) {
1394 return "if(window.mw){\n" . trim( $script ) . "\n}";
1398 * Construct an inline script tag with given JS code.
1400 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1401 * only if the client has adequate support for MediaWiki JavaScript code.
1403 * @param string $script JavaScript code
1404 * @return string HTML
1406 public static function makeInlineScript( $script ) {
1407 $js = self
::makeLoaderConditionalScript( $script );
1408 return Html
::inlineScript( $js );
1412 * Returns JS code which will set the MediaWiki configuration array to
1415 * @param array $configuration List of configuration values keyed by variable name
1418 public static function makeConfigSetScript( array $configuration ) {
1419 return Xml
::encodeJsCall(
1421 array( $configuration ),
1422 ResourceLoader
::inDebugMode()
1427 * Convert an array of module names to a packed query string.
1429 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1430 * becomes 'foo.bar,baz|bar.baz,quux'
1431 * @param array $modules List of module names (strings)
1432 * @return string Packed query string
1434 public static function makePackedModulesString( $modules ) {
1435 $groups = array(); // array( prefix => array( suffixes ) )
1436 foreach ( $modules as $module ) {
1437 $pos = strrpos( $module, '.' );
1438 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1439 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1440 $groups[$prefix][] = $suffix;
1444 foreach ( $groups as $prefix => $suffixes ) {
1445 $p = $prefix === '' ?
'' : $prefix . '.';
1446 $arr[] = $p . implode( ',', $suffixes );
1448 $str = implode( '|', $arr );
1453 * Determine whether debug mode was requested
1454 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1457 public static function inDebugMode() {
1458 if ( self
::$debugMode === null ) {
1459 global $wgRequest, $wgResourceLoaderDebug;
1460 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1461 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1464 return self
::$debugMode;
1468 * Reset static members used for caching.
1470 * Global state and $wgRequest are evil, but we're using it right
1471 * now and sometimes we need to be able to force ResourceLoader to
1472 * re-evaluate the context because it has changed (e.g. in the test suite).
1474 public static function clearCache() {
1475 self
::$debugMode = null;
1479 * Build a load.php URL
1482 * @param string $source Name of the ResourceLoader source
1483 * @param ResourceLoaderContext $context
1484 * @param array $extraQuery
1485 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1487 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1488 $extraQuery = array()
1490 $query = self
::createLoaderQuery( $context, $extraQuery );
1491 $script = $this->getLoadScript( $source );
1493 // Prevent the IE6 extension check from being triggered (bug 28840)
1494 // by appending a character that's invalid in Windows extensions ('*')
1495 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1499 * Build a load.php URL
1500 * @deprecated since 1.24 Use createLoaderURL() instead
1501 * @param array $modules Array of module names (strings)
1502 * @param string $lang Language code
1503 * @param string $skin Skin name
1504 * @param string|null $user User name. If null, the &user= parameter is omitted
1505 * @param string|null $version Versioning timestamp
1506 * @param bool $debug Whether the request should be in debug mode
1507 * @param string|null $only &only= parameter
1508 * @param bool $printable Printable mode
1509 * @param bool $handheld Handheld mode
1510 * @param array $extraQuery Extra query parameters to add
1511 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1513 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1514 $version = null, $debug = false, $only = null, $printable = false,
1515 $handheld = false, $extraQuery = array()
1517 global $wgLoadScript;
1519 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1520 $only, $printable, $handheld, $extraQuery
1523 // Prevent the IE6 extension check from being triggered (bug 28840)
1524 // by appending a character that's invalid in Windows extensions ('*')
1525 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1529 * Helper for createLoaderURL()
1532 * @see makeLoaderQuery
1533 * @param ResourceLoaderContext $context
1534 * @param array $extraQuery
1537 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1538 return self
::makeLoaderQuery(
1539 $context->getModules(),
1540 $context->getLanguage(),
1541 $context->getSkin(),
1542 $context->getUser(),
1543 $context->getVersion(),
1544 $context->getDebug(),
1545 $context->getOnly(),
1546 $context->getRequest()->getBool( 'printable' ),
1547 $context->getRequest()->getBool( 'handheld' ),
1553 * Build a query array (array representation of query string) for load.php. Helper
1554 * function for makeLoaderURL().
1556 * @param array $modules
1557 * @param string $lang
1558 * @param string $skin
1559 * @param string $user
1560 * @param string $version
1561 * @param bool $debug
1562 * @param string $only
1563 * @param bool $printable
1564 * @param bool $handheld
1565 * @param array $extraQuery
1569 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1570 $version = null, $debug = false, $only = null, $printable = false,
1571 $handheld = false, $extraQuery = array()
1574 'modules' => self
::makePackedModulesString( $modules ),
1577 'debug' => $debug ?
'true' : 'false',
1579 if ( $user !== null ) {
1580 $query['user'] = $user;
1582 if ( $version !== null ) {
1583 $query['version'] = $version;
1585 if ( $only !== null ) {
1586 $query['only'] = $only;
1589 $query['printable'] = 1;
1592 $query['handheld'] = 1;
1594 $query +
= $extraQuery;
1596 // Make queries uniform in order
1602 * Check a module name for validity.
1604 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1605 * at most 255 bytes.
1607 * @param string $moduleName Module name to check
1608 * @return bool Whether $moduleName is a valid module name
1610 public static function isValidModuleName( $moduleName ) {
1611 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1615 * Returns LESS compiler set up for use with MediaWiki
1617 * @param Config $config
1618 * @throws MWException
1622 public static function getLessCompiler( Config
$config ) {
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( 'lessc' ) ) {
1627 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1629 if ( !function_exists( 'ctype_digit' ) ) {
1630 throw new MWException( 'lessc requires the Ctype extension' );
1633 $less = new lessc();
1634 $less->setPreserveComments( true );
1635 $less->setVariables( self
::getLessVars( $config ) );
1636 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1637 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1638 $less->registerFunction( $name, $func );
1644 * Get global LESS variables.
1646 * @param Config $config
1648 * @return array Map of variable names to string CSS values.
1650 public static function getLessVars( Config
$config ) {
1651 if ( !self
::$lessVars ) {
1652 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1653 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1654 // Sort by key to ensure consistent hashing for cache lookups.
1656 self
::$lessVars = $lessVars;
1658 return self
::$lessVars;