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 // Batched version of ResourceLoaderModule::getFileDependencies
114 $vary = "$skin|$lang";
115 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
116 'md_module' => $modules,
120 // Prime in-object cache values for each module
121 $modulesWithDeps = array();
122 foreach ( $res as $row ) {
123 $module = $this->getModule( $row->md_module
);
125 $module->setFileDependencies( $context, ResourceLoader
::expandRelativePaths(
126 FormatJson
::decode( $row->md_deps
, true )
128 $modulesWithDeps[] = $row->md_module
;
131 // Register the absence of a dependency row too
132 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
133 $module = $this->getModule( $name );
135 $this->getModule( $name )->setFileDependencies( $context, array() );
139 // Get message blob mtimes. Only do this for modules with messages
140 $modulesWithMessages = array();
141 foreach ( $modules as $name ) {
142 $module = $this->getModule( $name );
143 if ( $module && count( $module->getMessages() ) ) {
144 $modulesWithMessages[] = $name;
147 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
148 if ( count( $modulesWithMessages ) ) {
149 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
150 'mr_resource' => $modulesWithMessages,
154 foreach ( $res as $row ) {
155 $module = $this->getModule( $row->mr_resource
);
157 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
158 unset( $modulesWithoutMessages[$row->mr_resource
] );
162 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
163 $module = $this->getModule( $name );
165 $module->setMsgBlobMtime( $lang, 1 );
171 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
173 * Available filters are:
175 * - minify-js \see JavaScriptMinifier::minify
176 * - minify-css \see CSSMin::minify
178 * If $data is empty, only contains whitespace or the filter was unknown,
179 * $data is returned unmodified.
181 * @param string $filter Name of filter to run
182 * @param string $data Text to filter, such as JavaScript or CSS text
183 * @param array $options For back-compat, can also be the boolean value for "cacheReport". Keys:
184 * - (bool) cache: Whether to allow caching this data. Default: true.
185 * - (bool) cacheReport: Whether to include the "cache key" report comment. Default: false.
186 * @return string Filtered data, or a comment containing an error message
188 public function filter( $filter, $data, $options = array() ) {
190 if ( is_bool( $options ) ) {
191 $options = array( 'cacheReport' => $options );
194 $options +
= array( 'cache' => true, 'cacheReport' => false );
195 $stats = RequestContext
::getMain()->getStats();
197 // Don't filter empty content
198 if ( trim( $data ) === '' ) {
202 if ( !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
203 $this->logger
->warning( 'Invalid filter {filter}', array(
209 if ( !$options['cache'] ) {
210 $result = self
::applyFilter( $filter, $data, $this->config
);
212 $key = wfGlobalCacheKey(
216 self
::$filterCacheVersion, md5( $data )
218 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL
: CACHE_ANYTHING
);
219 $cacheEntry = $cache->get( $key );
220 if ( is_string( $cacheEntry ) ) {
221 $stats->increment( "resourceloader_cache.$filter.hit" );
226 $statStart = microtime( true );
227 $result = self
::applyFilter( $filter, $data, $this->config
);
228 $statTiming = microtime( true ) - $statStart;
229 $stats->increment( "resourceloader_cache.$filter.miss" );
230 $stats->timing( "resourceloader_cache.$filter.timing", 1000 * $statTiming );
231 if ( $options['cacheReport'] ) {
232 $result .= "\n/* cache key: $key */";
234 // Set a TTL since HHVM's APC doesn't have any limitation or eviction logic.
235 $cache->set( $key, $result, 24 * 3600 );
236 } catch ( Exception
$e ) {
237 MWExceptionHandler
::logException( $e );
238 $this->logger
->warning( 'Minification failed: {exception}', array(
241 $this->errors
[] = self
::formatExceptionNoComment( $e );
248 private static function applyFilter( $filter, $data, Config
$config ) {
251 return JavaScriptMinifier
::minify( $data );
253 return CSSMin
::minify( $data );
262 * Register core modules and runs registration hooks.
263 * @param Config|null $config
265 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
269 $logger = new NullLogger();
271 $this->setLogger( $logger );
274 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
275 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
277 $this->config
= $config;
279 // Add 'local' source first
280 $this->addSource( 'local', wfScript( 'load' ) );
283 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
285 // Register core modules
286 $this->register( include "$IP/resources/Resources.php" );
287 $this->register( include "$IP/resources/ResourcesOOUI.php" );
288 // Register extension modules
289 $this->register( $config->get( 'ResourceModules' ) );
290 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
292 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
293 $this->registerTestModules();
296 $this->setMessageBlobStore( new MessageBlobStore() );
302 public function getConfig() {
303 return $this->config
;
306 public function setLogger( LoggerInterface
$logger ) {
307 $this->logger
= $logger;
312 * @return MessageBlobStore
314 public function getMessageBlobStore() {
315 return $this->blobStore
;
320 * @param MessageBlobStore $blobStore
322 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
323 $this->blobStore
= $blobStore;
327 * Register a module with the ResourceLoader system.
329 * @param mixed $name Name of module as a string or List of name/object pairs as an array
330 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
331 * this may also be a ResourceLoaderModule object. Optional when using
332 * multiple-registration calling style.
333 * @throws MWException If a duplicate module registration is attempted
334 * @throws MWException If a module name contains illegal characters (pipes or commas)
335 * @throws MWException If something other than a ResourceLoaderModule is being registered
336 * @return bool False if there were any errors, in which case one or more modules were
339 public function register( $name, $info = null ) {
341 // Allow multiple modules to be registered in one call
342 $registrations = is_array( $name ) ?
$name : array( $name => $info );
343 foreach ( $registrations as $name => $info ) {
344 // Disallow duplicate registrations
345 if ( isset( $this->moduleInfos
[$name] ) ) {
346 // A module has already been registered by this name
347 throw new MWException(
348 'ResourceLoader duplicate registration error. ' .
349 'Another module has already been registered as ' . $name
353 // Check $name for validity
354 if ( !self
::isValidModuleName( $name ) ) {
355 throw new MWException( "ResourceLoader module name '$name' is invalid, "
356 . "see ResourceLoader::isValidModuleName()" );
360 if ( $info instanceof ResourceLoaderModule
) {
361 $this->moduleInfos
[$name] = array( 'object' => $info );
362 $info->setName( $name );
363 $this->modules
[$name] = $info;
364 } elseif ( is_array( $info ) ) {
365 // New calling convention
366 $this->moduleInfos
[$name] = $info;
368 throw new MWException(
369 'ResourceLoader module info type error for module \'' . $name .
370 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
374 // Last-minute changes
376 // Apply custom skin-defined styles to existing modules.
377 if ( $this->isFileModule( $name ) ) {
378 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
379 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
380 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
384 // If $name is preceded with a '+', the defined style files will be added to 'default'
385 // skinStyles, otherwise 'default' will be ignored as it normally would be.
386 if ( isset( $skinStyles[$name] ) ) {
387 $paths = (array)$skinStyles[$name];
388 $styleFiles = array();
389 } elseif ( isset( $skinStyles['+' . $name] ) ) {
390 $paths = (array)$skinStyles['+' . $name];
391 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
392 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
398 // Add new file paths, remapping them to refer to our directories and not use settings
399 // from the module we're modifying, which come from the base definition.
400 list( $localBasePath, $remoteBasePath ) =
401 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
403 foreach ( $paths as $path ) {
404 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
407 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
416 public function registerTestModules() {
419 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
420 throw new MWException( 'Attempt to register JavaScript test modules '
421 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
422 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
425 // Get core test suites
426 $testModules = array();
427 $testModules['qunit'] = array();
428 // Get other test suites (e.g. from extensions)
429 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
431 // Add the testrunner (which configures QUnit) to the dependencies.
432 // Since it must be ready before any of the test suites are executed.
433 foreach ( $testModules['qunit'] as &$module ) {
434 // Make sure all test modules are top-loading so that when QUnit starts
435 // on document-ready, it will run once and finish. If some tests arrive
436 // later (possibly after QUnit has already finished) they will be ignored.
437 $module['position'] = 'top';
438 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
441 $testModules['qunit'] =
442 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
444 foreach ( $testModules as $id => $names ) {
445 // Register test modules
446 $this->register( $testModules[$id] );
448 // Keep track of their names so that they can be loaded together
449 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
455 * Add a foreign source of modules.
457 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
458 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
459 * backwards-compatibility.
460 * @throws MWException
462 public function addSource( $id, $loadUrl = null ) {
463 // Allow multiple sources to be registered in one call
464 if ( is_array( $id ) ) {
465 foreach ( $id as $key => $value ) {
466 $this->addSource( $key, $value );
471 // Disallow duplicates
472 if ( isset( $this->sources
[$id] ) ) {
473 throw new MWException(
474 'ResourceLoader duplicate source addition error. ' .
475 'Another source has already been registered as ' . $id
479 // Pre 1.24 backwards-compatibility
480 if ( is_array( $loadUrl ) ) {
481 if ( !isset( $loadUrl['loadScript'] ) ) {
482 throw new MWException(
483 __METHOD__
. ' was passed an array with no "loadScript" key.'
487 $loadUrl = $loadUrl['loadScript'];
490 $this->sources
[$id] = $loadUrl;
494 * Get a list of module names.
496 * @return array List of module names
498 public function getModuleNames() {
499 return array_keys( $this->moduleInfos
);
503 * Get a list of test module names for one (or all) frameworks.
505 * If the given framework id is unknkown, or if the in-object variable is not an array,
506 * then it will return an empty array.
508 * @param string $framework Get only the test module names for one
509 * particular framework (optional)
512 public function getTestModuleNames( $framework = 'all' ) {
513 /** @todo api siteinfo prop testmodulenames modulenames */
514 if ( $framework == 'all' ) {
515 return $this->testModuleNames
;
516 } elseif ( isset( $this->testModuleNames
[$framework] )
517 && is_array( $this->testModuleNames
[$framework] )
519 return $this->testModuleNames
[$framework];
526 * Check whether a ResourceLoader module is registered
529 * @param string $name
532 public function isModuleRegistered( $name ) {
533 return isset( $this->moduleInfos
[$name] );
537 * Get the ResourceLoaderModule object for a given module name.
539 * If an array of module parameters exists but a ResourceLoaderModule object has not
540 * yet been instantiated, this method will instantiate and cache that object such that
541 * subsequent calls simply return the same object.
543 * @param string $name Module name
544 * @return ResourceLoaderModule|null If module has been registered, return a
545 * ResourceLoaderModule instance. Otherwise, return null.
547 public function getModule( $name ) {
548 if ( !isset( $this->modules
[$name] ) ) {
549 if ( !isset( $this->moduleInfos
[$name] ) ) {
553 // Construct the requested object
554 $info = $this->moduleInfos
[$name];
555 /** @var ResourceLoaderModule $object */
556 if ( isset( $info['object'] ) ) {
557 // Object given in info array
558 $object = $info['object'];
560 if ( !isset( $info['class'] ) ) {
561 $class = 'ResourceLoaderFileModule';
563 $class = $info['class'];
565 /** @var ResourceLoaderModule $object */
566 $object = new $class( $info );
567 $object->setConfig( $this->getConfig() );
569 $object->setName( $name );
570 $this->modules
[$name] = $object;
573 return $this->modules
[$name];
577 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
579 * @param string $name Module name
582 protected function isFileModule( $name ) {
583 if ( !isset( $this->moduleInfos
[$name] ) ) {
586 $info = $this->moduleInfos
[$name];
587 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
594 * Get the list of sources.
596 * @return array Like array( id => load.php url, .. )
598 public function getSources() {
599 return $this->sources
;
603 * Get the URL to the load.php endpoint for the given
604 * ResourceLoader source
607 * @param string $source
608 * @throws MWException On an invalid $source name
611 public function getLoadScript( $source ) {
612 if ( !isset( $this->sources
[$source] ) ) {
613 throw new MWException( "The $source source was never registered in ResourceLoader." );
615 return $this->sources
[$source];
620 * @param string $value
621 * @return string Hash
623 public static function makeHash( $value ) {
624 // Use base64 to output more entropy in a more compact string (default hex is only base16).
625 // The first 8 chars of a base64 encoded digest represent the same binary as
626 // the first 12 chars of a hex encoded digest.
627 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
631 * Helper method to get and combine versions of multiple modules.
634 * @param ResourceLoaderContext $context
635 * @param array $modules List of ResourceLoaderModule objects
636 * @return string Hash
638 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
642 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
643 // http://php.net/functions.anonymous
645 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
646 return $rl->getModule( $module )->getVersionHash( $context );
648 return self
::makeHash( implode( $hashes ) );
652 * Output a response to a load request, including the content-type header.
654 * @param ResourceLoaderContext $context Context in which a response should be formed
656 public function respond( ResourceLoaderContext
$context ) {
657 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
658 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
659 // is used: ob_clean() will clear the GZIP header in that case and it won't come
660 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
661 // the whole thing in our own output buffer to be sure the active buffer
662 // doesn't use ob_gzhandler.
663 // See http://bugs.php.net/bug.php?id=36514
666 // Find out which modules are missing and instantiate the others
669 foreach ( $context->getModules() as $name ) {
670 $module = $this->getModule( $name );
672 // Do not allow private modules to be loaded from the web.
673 // This is a security issue, see bug 34907.
674 if ( $module->getGroup() === 'private' ) {
675 $this->logger
->debug( "Request for private module '$name' denied" );
676 $this->errors
[] = "Cannot show private module \"$name\"";
679 $modules[$name] = $module;
686 // Preload for getCombinedVersion()
687 $this->preloadModuleInfo( array_keys( $modules ), $context );
688 } catch ( Exception
$e ) {
689 MWExceptionHandler
::logException( $e );
690 $this->logger
->warning( 'Preloading module info failed: {exception}', array(
693 $this->errors
[] = self
::formatExceptionNoComment( $e );
696 // Combine versions to propagate cache invalidation
699 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
700 } catch ( Exception
$e ) {
701 MWExceptionHandler
::logException( $e );
702 $this->logger
->warning( 'Calculating version hash failed: {exception}', array(
705 $this->errors
[] = self
::formatExceptionNoComment( $e );
708 // See RFC 2616 § 3.11 Entity Tags
709 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
710 $etag = 'W/"' . $versionHash . '"';
712 // Try the client-side cache first
713 if ( $this->tryRespondNotModified( $context, $etag ) ) {
714 return; // output handled (buffers cleared)
717 // Use file cache if enabled and available...
718 if ( $this->config
->get( 'UseFileCache' ) ) {
719 $fileCache = ResourceFileCache
::newFromContext( $context );
720 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
721 return; // output handled
725 // Generate a response
726 $response = $this->makeModuleResponse( $context, $modules, $missing );
728 // Capture any PHP warnings from the output buffer and append them to the
729 // error list if we're in debug mode.
730 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
731 $this->errors
[] = $warnings;
734 // Save response to file cache unless there are errors
735 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
736 // Cache single modules and images...and other requests if there are enough hits
737 if ( ResourceFileCache
::useFileCache( $context ) ) {
738 if ( $fileCache->isCacheWorthy() ) {
739 $fileCache->saveText( $response );
741 $fileCache->incrMissesRecent( $context->getRequest() );
746 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
748 // Remove the output buffer and output the response
751 if ( $context->getImageObj() && $this->errors
) {
752 // We can't show both the error messages and the response when it's an image.
753 $response = implode( "\n\n", $this->errors
);
754 } elseif ( $this->errors
) {
755 $errorText = implode( "\n\n", $this->errors
);
756 $errorResponse = self
::makeComment( $errorText );
757 if ( $context->shouldIncludeScripts() ) {
758 $errorResponse .= 'if (window.console && console.error) {'
759 . Xml
::encodeJsCall( 'console.error', array( $errorText ) )
763 // Prepend error info to the response
764 $response = $errorResponse . $response;
767 $this->errors
= array();
773 * Send main response headers to the client.
775 * Deals with Content-Type, CORS (for stylesheets), and caching.
777 * @param ResourceLoaderContext $context
778 * @param string $etag ETag header value
779 * @param bool $errors Whether there are errors in the response
782 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
783 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
784 // If a version wasn't specified we need a shorter expiry time for updates
785 // to propagate to clients quickly
786 // If there were errors, we also need a shorter expiry time so we can recover quickly
787 if ( is_null( $context->getVersion() ) ||
$errors ) {
788 $maxage = $rlMaxage['unversioned']['client'];
789 $smaxage = $rlMaxage['unversioned']['server'];
790 // If a version was specified we can use a longer expiry time since changing
791 // version numbers causes cache misses
793 $maxage = $rlMaxage['versioned']['client'];
794 $smaxage = $rlMaxage['versioned']['server'];
796 if ( $context->getImageObj() ) {
797 // Output different headers if we're outputting textual errors.
799 header( 'Content-Type: text/plain; charset=utf-8' );
801 $context->getImageObj()->sendResponseHeaders( $context );
803 } elseif ( $context->getOnly() === 'styles' ) {
804 header( 'Content-Type: text/css; charset=utf-8' );
805 header( 'Access-Control-Allow-Origin: *' );
807 header( 'Content-Type: text/javascript; charset=utf-8' );
809 // See RFC 2616 § 14.19 ETag
810 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
811 header( 'ETag: ' . $etag );
812 if ( $context->getDebug() ) {
813 // Do not cache debug responses
814 header( 'Cache-Control: private, no-cache, must-revalidate' );
815 header( 'Pragma: no-cache' );
817 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
818 $exp = min( $maxage, $smaxage );
819 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
822 // Send the current time expressed as fractional seconds since epoch,
823 // with microsecond precision. This helps distinguish hits from misses
825 header( 'MediaWiki-Timestamp: ' . microtime( true ) );
829 * Respond with HTTP 304 Not Modified if appropiate.
831 * If there's an If-None-Match header, respond with a 304 appropriately
832 * and clear out the output buffer. If the client cache is too old then do nothing.
834 * @param ResourceLoaderContext $context
835 * @param string $etag ETag header value
836 * @return bool True if HTTP 304 was sent and output handled
838 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
839 // See RFC 2616 § 14.26 If-None-Match
840 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
841 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
842 // Never send 304s in debug mode
843 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
844 // There's another bug in ob_gzhandler (see also the comment at
845 // the top of this function) that causes it to gzip even empty
846 // responses, meaning it's impossible to produce a truly empty
847 // response (because the gzip header is always there). This is
848 // a problem because 304 responses have to be completely empty
849 // per the HTTP spec, and Firefox behaves buggily when they're not.
850 // See also http://bugs.php.net/bug.php?id=51579
851 // To work around this, we tear down all output buffering before
853 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
855 HttpStatus
::header( 304 );
857 $this->sendResponseHeaders( $context, $etag, false );
864 * Send out code for a response from file cache if possible.
866 * @param ResourceFileCache $fileCache Cache object for this request URL
867 * @param ResourceLoaderContext $context Context in which to generate a response
868 * @param string $etag ETag header value
869 * @return bool If this found a cache file and handled the response
871 protected function tryRespondFromFileCache(
872 ResourceFileCache
$fileCache,
873 ResourceLoaderContext
$context,
876 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
877 // Buffer output to catch warnings.
879 // Get the maximum age the cache can be
880 $maxage = is_null( $context->getVersion() )
881 ?
$rlMaxage['unversioned']['server']
882 : $rlMaxage['versioned']['server'];
883 // Minimum timestamp the cache file must have
884 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
886 try { // RL always hits the DB on file cache miss...
888 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
889 $good = $fileCache->isCacheGood(); // cache existence check
893 $ts = $fileCache->cacheTimestamp();
894 // Send content type and cache headers
895 $this->sendResponseHeaders( $context, $etag, false );
896 $response = $fileCache->fetchText();
897 // Capture any PHP warnings from the output buffer and append them to the
898 // response in a comment if we're in debug mode.
899 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
900 $response = self
::makeComment( $warnings ) . $response;
902 // Remove the output buffer and output the response
904 echo $response . "\n/* Cached {$ts} */";
905 return true; // cache hit
910 return false; // cache miss
914 * Generate a CSS or JS comment block.
916 * Only use this for public data, not error message details.
918 * @param string $text
921 public static function makeComment( $text ) {
922 $encText = str_replace( '*/', '* /', $text );
923 return "/*\n$encText\n*/\n";
927 * Handle exception display.
929 * @param Exception $e Exception to be shown to the user
930 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
932 public static function formatException( $e ) {
933 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
937 * Handle exception display.
940 * @param Exception $e Exception to be shown to the user
941 * @return string Sanitized text that can be returned to the user
943 protected static function formatExceptionNoComment( $e ) {
944 global $wgShowExceptionDetails;
946 if ( !$wgShowExceptionDetails ) {
947 return MWExceptionHandler
::getPublicLogMessage( $e );
950 return MWExceptionHandler
::getLogMessage( $e );
954 * Generate code for a response.
956 * @param ResourceLoaderContext $context Context in which to generate a response
957 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
958 * @param string[] $missing List of requested module names that are unregistered (optional)
959 * @return string Response data
961 public function makeModuleResponse( ResourceLoaderContext
$context,
962 array $modules, array $missing = array()
967 if ( !count( $modules ) && !count( $missing ) ) {
969 /* This file is the Web entry point for MediaWiki's ResourceLoader:
970 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
971 no modules were requested. Max made me put this here. */
975 $image = $context->getImageObj();
977 $data = $image->getImageData( $context );
978 if ( $data === false ) {
980 $this->errors
[] = 'Image generation failed';
986 if ( $context->shouldIncludeMessages() ) {
988 $this->blobStore
->get( $this, $modules, $context->getLanguage() );
989 } catch ( Exception
$e ) {
990 MWExceptionHandler
::logException( $e );
991 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
994 $this->errors
[] = self
::formatExceptionNoComment( $e );
998 foreach ( $missing as $name ) {
999 $states[$name] = 'missing';
1005 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1007 foreach ( $modules as $name => $module ) {
1009 $content = $module->getModuleContent( $context );
1013 switch ( $context->getOnly() ) {
1015 $scripts = $content['scripts'];
1016 if ( is_string( $scripts ) ) {
1017 // Load scripts raw...
1018 $strContent = $scripts;
1019 } elseif ( is_array( $scripts ) ) {
1020 // ...except when $scripts is an array of URLs
1021 $strContent = self
::makeLoaderImplementScript( $name, $scripts, array(), array(), array() );
1025 $styles = $content['styles'];
1026 // We no longer seperate into media, they are all combined now with
1027 // custom media type groups into @media .. {} sections as part of the css string.
1028 // Module returns either an empty array or a numerical array with css strings.
1029 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1032 $strContent = self
::makeLoaderImplementScript(
1034 isset( $content['scripts'] ) ?
$content['scripts'] : '',
1035 isset( $content['styles'] ) ?
$content['styles'] : array(),
1036 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : array(),
1037 isset( $content['templates'] ) ?
$content['templates'] : array()
1042 if ( !$context->getDebug() ) {
1043 // Don't cache private modules. This is especially important in the case
1044 // of modules which change every time they are built, like the embedded
1045 // user.tokens module (bug T84960).
1046 $filterOptions = array( 'cache' => ( $module->getGroup() !== 'private' ) );
1047 $strContent = $this->filter( $filter, $strContent, $filterOptions );
1050 $out .= $strContent;
1052 } catch ( Exception
$e ) {
1053 MWExceptionHandler
::logException( $e );
1054 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1057 $this->errors
[] = self
::formatExceptionNoComment( $e );
1059 // Respond to client with error-state instead of module implementation
1060 $states[$name] = 'error';
1061 unset( $modules[$name] );
1063 $isRaw |
= $module->isRaw();
1066 // Update module states
1067 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1068 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1069 // Set the state of modules loaded as only scripts to ready as
1070 // they don't have an mw.loader.implement wrapper that sets the state
1071 foreach ( $modules as $name => $module ) {
1072 $states[$name] = 'ready';
1076 // Set the state of modules we didn't respond to with mw.loader.implement
1077 if ( count( $states ) ) {
1078 $stateScript = self
::makeLoaderStateScript( $states );
1079 if ( !$context->getDebug() ) {
1080 $stateScript = $this->filter( 'minify-js', $stateScript );
1082 $out .= $stateScript;
1085 if ( count( $states ) ) {
1086 $this->errors
[] = 'Problematic modules: ' .
1087 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1094 /* Static Methods */
1097 * Return JS code that calls mw.loader.implement with given module properties.
1099 * @param string $name Module name
1100 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1101 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1102 * to CSS files keyed by media type
1103 * @param mixed $messages List of messages associated with this module. May either be an
1104 * associative array mapping message key to value, or a JSON-encoded message blob containing
1105 * the same data, wrapped in an XmlJsCode object.
1106 * @param array $templates Keys are name of templates and values are the source of
1108 * @throws MWException
1111 public static function makeLoaderImplementScript(
1112 $name, $scripts, $styles, $messages, $templates
1114 if ( is_string( $scripts ) ) {
1115 // Site and user module are a legacy scripts that run in the global scope (no closure).
1116 // Transportation as string instructs mw.loader.implement to use globalEval.
1117 if ( $name === 'site' ||
$name === 'user' ) {
1118 // Minify manually because the general makeModuleResponse() minification won't be
1119 // effective here due to the script being a string instead of a function. (T107377)
1120 if ( !ResourceLoader
::inDebugMode() ) {
1121 $scripts = self
::applyFilter( 'minify-js', $scripts,
1122 ConfigFactory
::getDefaultInstance()->makeConfig( 'main' ) );
1125 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1127 } elseif ( !is_array( $scripts ) ) {
1128 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1130 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1131 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1132 // of "{}". Force them to objects.
1140 self
::trimArray( $module );
1142 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1146 * Returns JS code which, when called, will register a given list of messages.
1148 * @param mixed $messages Either an associative array mapping message key to value, or a
1149 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1152 public static function makeMessageSetScript( $messages ) {
1153 return Xml
::encodeJsCall(
1155 array( (object)$messages ),
1156 ResourceLoader
::inDebugMode()
1161 * Combines an associative array mapping media type to CSS into a
1162 * single stylesheet with "@media" blocks.
1164 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1167 public static function makeCombinedStyles( array $stylePairs ) {
1169 foreach ( $stylePairs as $media => $styles ) {
1170 // ResourceLoaderFileModule::getStyle can return the styles
1171 // as a string or an array of strings. This is to allow separation in
1173 $styles = (array)$styles;
1174 foreach ( $styles as $style ) {
1175 $style = trim( $style );
1176 // Don't output an empty "@media print { }" block (bug 40498)
1177 if ( $style !== '' ) {
1178 // Transform the media type based on request params and config
1179 // The way that this relies on $wgRequest to propagate request params is slightly evil
1180 $media = OutputPage
::transformCssMedia( $media );
1182 if ( $media === '' ||
$media == 'all' ) {
1184 } elseif ( is_string( $media ) ) {
1185 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1195 * Returns a JS call to mw.loader.state, which sets the state of a
1196 * module or modules to a given value. Has two calling conventions:
1198 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1199 * Set the state of a single module called $name to $state
1201 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1202 * Set the state of modules with the given names to the given states
1204 * @param string $name
1205 * @param string $state
1208 public static function makeLoaderStateScript( $name, $state = null ) {
1209 if ( is_array( $name ) ) {
1210 return Xml
::encodeJsCall(
1213 ResourceLoader
::inDebugMode()
1216 return Xml
::encodeJsCall(
1218 array( $name, $state ),
1219 ResourceLoader
::inDebugMode()
1225 * Returns JS code which calls the script given by $script. The script will
1226 * be called with local variables name, version, dependencies and group,
1227 * which will have values corresponding to $name, $version, $dependencies
1228 * and $group as supplied.
1230 * @param string $name Module name
1231 * @param string $version Module version hash
1232 * @param array $dependencies List of module names on which this module depends
1233 * @param string $group Group which the module is in.
1234 * @param string $source Source of the module, or 'local' if not foreign.
1235 * @param string $script JavaScript code
1238 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1239 $group, $source, $script
1241 $script = str_replace( "\n", "\n\t", trim( $script ) );
1242 return Xml
::encodeJsCall(
1243 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1244 array( $name, $version, $dependencies, $group, $source ),
1245 ResourceLoader
::inDebugMode()
1249 private static function isEmptyObject( stdClass
$obj ) {
1250 foreach ( $obj as $key => $value ) {
1257 * Remove empty values from the end of an array.
1259 * Values considered empty:
1263 * - new XmlJsCode( '{}' )
1264 * - new stdClass() // (object) array()
1266 * @param Array $array
1268 private static function trimArray( Array &$array ) {
1269 $i = count( $array );
1271 if ( $array[$i] === null
1272 ||
$array[$i] === array()
1273 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1274 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1276 unset( $array[$i] );
1284 * Returns JS code which calls mw.loader.register with the given
1285 * parameters. Has three calling conventions:
1287 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1288 * $dependencies, $group, $source, $skip
1290 * Register a single module.
1292 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1293 * Register modules with the given names.
1295 * - ResourceLoader::makeLoaderRegisterScript( array(
1296 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1297 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1300 * Registers modules with the given names and parameters.
1302 * @param string $name Module name
1303 * @param string $version Module version hash
1304 * @param array $dependencies List of module names on which this module depends
1305 * @param string $group Group which the module is in
1306 * @param string $source Source of the module, or 'local' if not foreign
1307 * @param string $skip Script body of the skip function
1310 public static function makeLoaderRegisterScript( $name, $version = null,
1311 $dependencies = null, $group = null, $source = null, $skip = null
1313 if ( is_array( $name ) ) {
1314 // Build module name index
1316 foreach ( $name as $i => &$module ) {
1317 $index[$module[0]] = $i;
1320 // Transform dependency names into indexes when possible, they will be resolved by
1321 // mw.loader.register on the other end
1322 foreach ( $name as &$module ) {
1323 if ( isset( $module[2] ) ) {
1324 foreach ( $module[2] as &$dependency ) {
1325 if ( isset( $index[$dependency] ) ) {
1326 $dependency = $index[$dependency];
1332 array_walk( $name, array( 'self', 'trimArray' ) );
1334 return Xml
::encodeJsCall(
1335 'mw.loader.register',
1337 ResourceLoader
::inDebugMode()
1340 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1341 self
::trimArray( $registration );
1342 return Xml
::encodeJsCall(
1343 'mw.loader.register',
1345 ResourceLoader
::inDebugMode()
1351 * Returns JS code which calls mw.loader.addSource() with the given
1352 * parameters. Has two calling conventions:
1354 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1355 * Register a single source
1357 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1358 * Register sources with the given IDs and properties.
1360 * @param string $id Source ID
1361 * @param array $properties Source properties (see addSource())
1364 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1365 if ( is_array( $id ) ) {
1366 return Xml
::encodeJsCall(
1367 'mw.loader.addSource',
1369 ResourceLoader
::inDebugMode()
1372 return Xml
::encodeJsCall(
1373 'mw.loader.addSource',
1374 array( $id, $properties ),
1375 ResourceLoader
::inDebugMode()
1381 * Returns JS code which runs given JS code if the client-side framework is
1384 * @deprecated since 1.25; use makeInlineScript instead
1385 * @param string $script JavaScript code
1388 public static function makeLoaderConditionalScript( $script ) {
1389 return "window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n" .
1390 trim( $script ) . "\n} );";
1394 * Construct an inline script tag with given JS code.
1396 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1397 * only if the client has adequate support for MediaWiki JavaScript code.
1399 * @param string $script JavaScript code
1400 * @return WrappedString HTML
1402 public static function makeInlineScript( $script ) {
1403 $js = self
::makeLoaderConditionalScript( $script );
1404 return new WrappedString(
1405 Html
::inlineScript( $js ),
1406 "<script>window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n",
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 if ( ResourceLoader
::inDebugMode() ) {
1420 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ), true );
1423 $config = RequestContext
::getMain()->getConfig();
1424 $js = Xml
::encodeJsCall( 'mw.config.set', array( $configuration ), false );
1425 return self
::applyFilter( 'minify-js', $js, $config );
1429 * Convert an array of module names to a packed query string.
1431 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1432 * becomes 'foo.bar,baz|bar.baz,quux'
1433 * @param array $modules List of module names (strings)
1434 * @return string Packed query string
1436 public static function makePackedModulesString( $modules ) {
1437 $groups = array(); // array( prefix => array( suffixes ) )
1438 foreach ( $modules as $module ) {
1439 $pos = strrpos( $module, '.' );
1440 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1441 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1442 $groups[$prefix][] = $suffix;
1446 foreach ( $groups as $prefix => $suffixes ) {
1447 $p = $prefix === '' ?
'' : $prefix . '.';
1448 $arr[] = $p . implode( ',', $suffixes );
1450 $str = implode( '|', $arr );
1455 * Determine whether debug mode was requested
1456 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1459 public static function inDebugMode() {
1460 if ( self
::$debugMode === null ) {
1461 global $wgRequest, $wgResourceLoaderDebug;
1462 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1463 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1466 return self
::$debugMode;
1470 * Reset static members used for caching.
1472 * Global state and $wgRequest are evil, but we're using it right
1473 * now and sometimes we need to be able to force ResourceLoader to
1474 * re-evaluate the context because it has changed (e.g. in the test suite).
1476 public static function clearCache() {
1477 self
::$debugMode = null;
1481 * Build a load.php URL
1484 * @param string $source Name of the ResourceLoader source
1485 * @param ResourceLoaderContext $context
1486 * @param array $extraQuery
1487 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1489 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1490 $extraQuery = array()
1492 $query = self
::createLoaderQuery( $context, $extraQuery );
1493 $script = $this->getLoadScript( $source );
1495 return wfAppendQuery( $script, $query );
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, too.
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 return wfAppendQuery( $wgLoadScript, $query );
1527 * Helper for createLoaderURL()
1530 * @see makeLoaderQuery
1531 * @param ResourceLoaderContext $context
1532 * @param array $extraQuery
1535 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1536 return self
::makeLoaderQuery(
1537 $context->getModules(),
1538 $context->getLanguage(),
1539 $context->getSkin(),
1540 $context->getUser(),
1541 $context->getVersion(),
1542 $context->getDebug(),
1543 $context->getOnly(),
1544 $context->getRequest()->getBool( 'printable' ),
1545 $context->getRequest()->getBool( 'handheld' ),
1551 * Build a query array (array representation of query string) for load.php. Helper
1552 * function for makeLoaderURL().
1554 * @param array $modules
1555 * @param string $lang
1556 * @param string $skin
1557 * @param string $user
1558 * @param string $version
1559 * @param bool $debug
1560 * @param string $only
1561 * @param bool $printable
1562 * @param bool $handheld
1563 * @param array $extraQuery
1567 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1568 $version = null, $debug = false, $only = null, $printable = false,
1569 $handheld = false, $extraQuery = array()
1572 'modules' => self
::makePackedModulesString( $modules ),
1575 'debug' => $debug ?
'true' : 'false',
1577 if ( $user !== null ) {
1578 $query['user'] = $user;
1580 if ( $version !== null ) {
1581 $query['version'] = $version;
1583 if ( $only !== null ) {
1584 $query['only'] = $only;
1587 $query['printable'] = 1;
1590 $query['handheld'] = 1;
1592 $query +
= $extraQuery;
1594 // Make queries uniform in order
1600 * Check a module name for validity.
1602 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1603 * at most 255 bytes.
1605 * @param string $moduleName Module name to check
1606 * @return bool Whether $moduleName is a valid module name
1608 public static function isValidModuleName( $moduleName ) {
1609 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1613 * Returns LESS compiler set up for use with MediaWiki
1616 * @since 1.26 added $extraVars parameter
1617 * @param Config $config
1618 * @param array $extraVars Associative array of extra (i.e., other than the
1619 * globally-configured ones) that should be used for compilation.
1620 * @throws MWException
1621 * @return Less_Parser
1623 public static function getLessCompiler( Config
$config, $extraVars = array() ) {
1624 // When called from the installer, it is possible that a required PHP extension
1625 // is missing (at least for now; see bug 47564). If this is the case, throw an
1626 // exception (caught by the installer) to prevent a fatal error later on.
1627 if ( !class_exists( 'Less_Parser' ) ) {
1628 throw new MWException( 'MediaWiki requires the less.php parser' );
1631 $parser = new Less_Parser
;
1632 $parser->ModifyVars( array_merge( self
::getLessVars( $config ), $extraVars ) );
1633 $parser->SetImportDirs( array_fill_keys( $config->get( 'ResourceLoaderLESSImportPaths' ), '' ) );
1634 $parser->SetOption( 'relativeUrls', false );
1635 $parser->SetCacheDir( $config->get( 'CacheDirectory' ) ?
: wfTempDir() );
1641 * Get global LESS variables.
1643 * @param Config $config
1645 * @return array Map of variable names to string CSS values.
1647 public static function getLessVars( Config
$config ) {
1648 if ( !self
::$lessVars ) {
1649 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1650 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1651 self
::$lessVars = $lessVars;
1653 return self
::$lessVars;