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
;
30 * Dynamic JavaScript and CSS resource loading system.
32 * Most of the documentation is on the MediaWiki documentation wiki starting at:
33 * https://www.mediawiki.org/wiki/ResourceLoader
35 class ResourceLoader
implements LoggerAwareInterface
{
37 protected static $filterCacheVersion = 7;
40 protected static $debugMode = null;
43 private static $lessVars = null;
46 * Module name/ResourceLoaderModule object pairs
49 protected $modules = array();
52 * Associative array mapping module name to info associative array
55 protected $moduleInfos = array();
57 /** @var Config $config */
61 * Associative array mapping framework ids to a list of names of test suite modules
62 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
65 protected $testModuleNames = array();
68 * E.g. array( 'source-id' => 'http://.../load.php' )
71 protected $sources = array();
74 * Errors accumulated during current respond() call.
77 protected $errors = array();
80 * @var MessageBlobStore
85 * @var LoggerInterface
90 * Load information stored in the database about modules.
92 * This method grabs modules dependencies from the database and updates modules
95 * This is not inside the module code because it is much faster to
96 * request all of the information at once than it is to have each module
97 * requests its own information. This sacrifice of modularity yields a substantial
98 * performance improvement.
100 * @param array $modules List of module names to preload information for
101 * @param ResourceLoaderContext $context Context to load the information within
103 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
104 if ( !count( $modules ) ) {
105 // Or else Database*::select() will explode, plus it's cheaper!
108 $dbr = wfGetDB( DB_SLAVE
);
109 $skin = $context->getSkin();
110 $lang = $context->getLanguage();
112 // Get file dependency information
113 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
114 'md_module' => $modules,
119 // Set modules' dependencies
120 $modulesWithDeps = array();
121 foreach ( $res as $row ) {
122 $module = $this->getModule( $row->md_module
);
124 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
125 $modulesWithDeps[] = $row->md_module
;
129 // Register the absence of a dependency row too
130 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
131 $module = $this->getModule( $name );
133 $this->getModule( $name )->setFileDependencies( $skin, array() );
137 // Get message blob mtimes. Only do this for modules with messages
138 $modulesWithMessages = array();
139 foreach ( $modules as $name ) {
140 $module = $this->getModule( $name );
141 if ( $module && count( $module->getMessages() ) ) {
142 $modulesWithMessages[] = $name;
145 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
146 if ( count( $modulesWithMessages ) ) {
147 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
148 'mr_resource' => $modulesWithMessages,
152 foreach ( $res as $row ) {
153 $module = $this->getModule( $row->mr_resource
);
155 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
156 unset( $modulesWithoutMessages[$row->mr_resource
] );
160 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
161 $module = $this->getModule( $name );
163 $module->setMsgBlobMtime( $lang, 1 );
169 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
171 * Available filters are:
173 * - minify-js \see JavaScriptMinifier::minify
174 * - minify-css \see CSSMin::minify
176 * If $data is empty, only contains whitespace or the filter was unknown,
177 * $data is returned unmodified.
179 * @param string $filter Name of filter to run
180 * @param string $data Text to filter, such as JavaScript or CSS text
181 * @param array $options For back-compat, can also be the boolean value for "cacheReport". Keys:
182 * - (bool) cache: Whether to allow caching this data. Default: true.
183 * - (bool) cacheReport: Whether to include the "cache key" report comment. Default: true.
184 * @return string Filtered data, or a comment containing an error message
186 public function filter( $filter, $data, $options = array() ) {
188 if ( is_bool( $options ) ) {
189 $options = array( 'cacheReport' => $options );
192 $options +
= array( 'cache' => true, 'cacheReport' => true );
194 // Don't filter empty content
195 if ( trim( $data ) === '' ) {
199 if ( !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
200 $this->logger
->warning( 'Invalid filter {filter}', array(
206 if ( !$options['cache'] ) {
207 $result = $this->applyFilter( $filter, $data );
209 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
210 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL
: CACHE_ANYTHING
);
211 $cacheEntry = $cache->get( $key );
212 if ( is_string( $cacheEntry ) ) {
213 wfIncrStats( "resourceloader_cache.$filter.hit" );
218 wfIncrStats( "resourceloader_cache.$filter.miss" );
219 $result = $this->applyFilter( $filter, $data );
220 if ( $options['cacheReport'] ) {
221 $result .= "\n/* cache key: $key */";
223 $cache->set( $key, $result );
224 } catch ( Exception
$e ) {
225 MWExceptionHandler
::logException( $e );
226 $this->logger
->warning( 'Minification failed: {exception}', array(
229 $this->errors
[] = self
::formatExceptionNoComment( $e );
236 private function applyFilter( $filter, $data ) {
239 return JavaScriptMinifier
::minify( $data,
240 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
241 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
244 return CSSMin
::minify( $data );
252 * Register core modules and runs registration hooks.
253 * @param Config|null $config
255 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
259 $logger = new NullLogger();
261 $this->setLogger( $logger );
264 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
265 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
267 $this->config
= $config;
269 // Add 'local' source first
270 $this->addSource( 'local', wfScript( 'load' ) );
273 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
275 // Register core modules
276 $this->register( include "$IP/resources/Resources.php" );
277 $this->register( include "$IP/resources/ResourcesOOUI.php" );
278 // Register extension modules
279 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
280 $this->register( $config->get( 'ResourceModules' ) );
282 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
283 $this->registerTestModules();
286 $this->setMessageBlobStore( new MessageBlobStore() );
292 public function getConfig() {
293 return $this->config
;
296 public function setLogger( LoggerInterface
$logger ) {
297 $this->logger
= $logger;
301 * @param MessageBlobStore $blobStore
304 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
305 $this->blobStore
= $blobStore;
309 * Register a module with the ResourceLoader system.
311 * @param mixed $name Name of module as a string or List of name/object pairs as an array
312 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
313 * this may also be a ResourceLoaderModule object. Optional when using
314 * multiple-registration calling style.
315 * @throws MWException If a duplicate module registration is attempted
316 * @throws MWException If a module name contains illegal characters (pipes or commas)
317 * @throws MWException If something other than a ResourceLoaderModule is being registered
318 * @return bool False if there were any errors, in which case one or more modules were
321 public function register( $name, $info = null ) {
323 // Allow multiple modules to be registered in one call
324 $registrations = is_array( $name ) ?
$name : array( $name => $info );
325 foreach ( $registrations as $name => $info ) {
326 // Disallow duplicate registrations
327 if ( isset( $this->moduleInfos
[$name] ) ) {
328 // A module has already been registered by this name
329 throw new MWException(
330 'ResourceLoader duplicate registration error. ' .
331 'Another module has already been registered as ' . $name
335 // Check $name for validity
336 if ( !self
::isValidModuleName( $name ) ) {
337 throw new MWException( "ResourceLoader module name '$name' is invalid, "
338 . "see ResourceLoader::isValidModuleName()" );
342 if ( $info instanceof ResourceLoaderModule
) {
343 $this->moduleInfos
[$name] = array( 'object' => $info );
344 $info->setName( $name );
345 $this->modules
[$name] = $info;
346 } elseif ( is_array( $info ) ) {
347 // New calling convention
348 $this->moduleInfos
[$name] = $info;
350 throw new MWException(
351 'ResourceLoader module info type error for module \'' . $name .
352 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
356 // Last-minute changes
358 // Apply custom skin-defined styles to existing modules.
359 if ( $this->isFileModule( $name ) ) {
360 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
361 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
362 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
366 // If $name is preceded with a '+', the defined style files will be added to 'default'
367 // skinStyles, otherwise 'default' will be ignored as it normally would be.
368 if ( isset( $skinStyles[$name] ) ) {
369 $paths = (array)$skinStyles[$name];
370 $styleFiles = array();
371 } elseif ( isset( $skinStyles['+' . $name] ) ) {
372 $paths = (array)$skinStyles['+' . $name];
373 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
374 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
380 // Add new file paths, remapping them to refer to our directories and not use settings
381 // from the module we're modifying, which come from the base definition.
382 list( $localBasePath, $remoteBasePath ) =
383 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
385 foreach ( $paths as $path ) {
386 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
389 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
398 public function registerTestModules() {
401 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
402 throw new MWException( 'Attempt to register JavaScript test modules '
403 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
404 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
407 // Get core test suites
408 $testModules = array();
409 $testModules['qunit'] = array();
410 // Get other test suites (e.g. from extensions)
411 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
413 // Add the testrunner (which configures QUnit) to the dependencies.
414 // Since it must be ready before any of the test suites are executed.
415 foreach ( $testModules['qunit'] as &$module ) {
416 // Make sure all test modules are top-loading so that when QUnit starts
417 // on document-ready, it will run once and finish. If some tests arrive
418 // later (possibly after QUnit has already finished) they will be ignored.
419 $module['position'] = 'top';
420 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
423 $testModules['qunit'] =
424 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
426 foreach ( $testModules as $id => $names ) {
427 // Register test modules
428 $this->register( $testModules[$id] );
430 // Keep track of their names so that they can be loaded together
431 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
437 * Add a foreign source of modules.
439 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
440 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
441 * backwards-compatibility.
442 * @throws MWException
444 public function addSource( $id, $loadUrl = null ) {
445 // Allow multiple sources to be registered in one call
446 if ( is_array( $id ) ) {
447 foreach ( $id as $key => $value ) {
448 $this->addSource( $key, $value );
453 // Disallow duplicates
454 if ( isset( $this->sources
[$id] ) ) {
455 throw new MWException(
456 'ResourceLoader duplicate source addition error. ' .
457 'Another source has already been registered as ' . $id
461 // Pre 1.24 backwards-compatibility
462 if ( is_array( $loadUrl ) ) {
463 if ( !isset( $loadUrl['loadScript'] ) ) {
464 throw new MWException(
465 __METHOD__
. ' was passed an array with no "loadScript" key.'
469 $loadUrl = $loadUrl['loadScript'];
472 $this->sources
[$id] = $loadUrl;
476 * Get a list of module names.
478 * @return array List of module names
480 public function getModuleNames() {
481 return array_keys( $this->moduleInfos
);
485 * Get a list of test module names for one (or all) frameworks.
487 * If the given framework id is unknkown, or if the in-object variable is not an array,
488 * then it will return an empty array.
490 * @param string $framework Get only the test module names for one
491 * particular framework (optional)
494 public function getTestModuleNames( $framework = 'all' ) {
495 /** @todo api siteinfo prop testmodulenames modulenames */
496 if ( $framework == 'all' ) {
497 return $this->testModuleNames
;
498 } elseif ( isset( $this->testModuleNames
[$framework] )
499 && is_array( $this->testModuleNames
[$framework] )
501 return $this->testModuleNames
[$framework];
508 * Check whether a ResourceLoader module is registered
511 * @param string $name
514 public function isModuleRegistered( $name ) {
515 return isset( $this->moduleInfos
[$name] );
519 * Get the ResourceLoaderModule object for a given module name.
521 * If an array of module parameters exists but a ResourceLoaderModule object has not
522 * yet been instantiated, this method will instantiate and cache that object such that
523 * subsequent calls simply return the same object.
525 * @param string $name Module name
526 * @return ResourceLoaderModule|null If module has been registered, return a
527 * ResourceLoaderModule instance. Otherwise, return null.
529 public function getModule( $name ) {
530 if ( !isset( $this->modules
[$name] ) ) {
531 if ( !isset( $this->moduleInfos
[$name] ) ) {
535 // Construct the requested object
536 $info = $this->moduleInfos
[$name];
537 /** @var ResourceLoaderModule $object */
538 if ( isset( $info['object'] ) ) {
539 // Object given in info array
540 $object = $info['object'];
542 if ( !isset( $info['class'] ) ) {
543 $class = 'ResourceLoaderFileModule';
545 $class = $info['class'];
547 /** @var ResourceLoaderModule $object */
548 $object = new $class( $info );
549 $object->setConfig( $this->getConfig() );
551 $object->setName( $name );
552 $this->modules
[$name] = $object;
555 return $this->modules
[$name];
559 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
561 * @param string $name Module name
564 protected function isFileModule( $name ) {
565 if ( !isset( $this->moduleInfos
[$name] ) ) {
568 $info = $this->moduleInfos
[$name];
569 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
576 * Get the list of sources.
578 * @return array Like array( id => load.php url, .. )
580 public function getSources() {
581 return $this->sources
;
585 * Get the URL to the load.php endpoint for the given
586 * ResourceLoader source
589 * @param string $source
590 * @throws MWException On an invalid $source name
593 public function getLoadScript( $source ) {
594 if ( !isset( $this->sources
[$source] ) ) {
595 throw new MWException( "The $source source was never registered in ResourceLoader." );
597 return $this->sources
[$source];
602 * @param string $value
603 * @return string Hash
605 public static function makeHash( $value ) {
606 // Use base64 to output more entropy in a more compact string (default hex is only base16).
607 // The first 8 chars of a base64 encoded digest represent the same binary as
608 // the first 12 chars of a hex encoded digest.
609 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
613 * Helper method to get and combine versions of multiple modules.
616 * @param ResourceLoaderContext $context
617 * @param array $modules List of ResourceLoaderModule objects
618 * @return string Hash
620 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
624 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
625 // http://php.net/functions.anonymous
627 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
628 return $rl->getModule( $module )->getVersionHash( $context );
630 return self
::makeHash( implode( $hashes ) );
634 * Output a response to a load request, including the content-type header.
636 * @param ResourceLoaderContext $context Context in which a response should be formed
638 public function respond( ResourceLoaderContext
$context ) {
639 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
640 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
641 // is used: ob_clean() will clear the GZIP header in that case and it won't come
642 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
643 // the whole thing in our own output buffer to be sure the active buffer
644 // doesn't use ob_gzhandler.
645 // See http://bugs.php.net/bug.php?id=36514
648 // Find out which modules are missing and instantiate the others
651 foreach ( $context->getModules() as $name ) {
652 $module = $this->getModule( $name );
654 // Do not allow private modules to be loaded from the web.
655 // This is a security issue, see bug 34907.
656 if ( $module->getGroup() === 'private' ) {
657 $this->logger
->debug( "Request for private module '$name' denied" );
658 $this->errors
[] = "Cannot show private module \"$name\"";
661 $modules[$name] = $module;
668 // Preload for getCombinedVersion()
669 $this->preloadModuleInfo( array_keys( $modules ), $context );
670 } catch ( Exception
$e ) {
671 MWExceptionHandler
::logException( $e );
672 $this->logger
->warning( 'Preloading module info failed: {exception}', array(
675 $this->errors
[] = self
::formatExceptionNoComment( $e );
678 // Combine versions to propagate cache invalidation
681 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
682 } catch ( Exception
$e ) {
683 MWExceptionHandler
::logException( $e );
684 $this->logger
->warning( 'Calculating version hash failed: {exception}', array(
687 $this->errors
[] = self
::formatExceptionNoComment( $e );
690 // See RFC 2616 § 3.11 Entity Tags
691 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
692 $etag = 'W/"' . $versionHash . '"';
694 // Try the client-side cache first
695 if ( $this->tryRespondNotModified( $context, $etag ) ) {
696 return; // output handled (buffers cleared)
699 // Use file cache if enabled and available...
700 if ( $this->config
->get( 'UseFileCache' ) ) {
701 $fileCache = ResourceFileCache
::newFromContext( $context );
702 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
703 return; // output handled
707 // Generate a response
708 $response = $this->makeModuleResponse( $context, $modules, $missing );
710 // Capture any PHP warnings from the output buffer and append them to the
711 // error list if we're in debug mode.
712 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
713 $this->errors
[] = $warnings;
716 // Save response to file cache unless there are errors
717 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
718 // Cache single modules and images...and other requests if there are enough hits
719 if ( ResourceFileCache
::useFileCache( $context ) ) {
720 if ( $fileCache->isCacheWorthy() ) {
721 $fileCache->saveText( $response );
723 $fileCache->incrMissesRecent( $context->getRequest() );
728 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
730 // Remove the output buffer and output the response
733 if ( $context->getImageObj() && $this->errors
) {
734 // We can't show both the error messages and the response when it's an image.
736 foreach ( $this->errors
as $error ) {
737 $errorText .= $error . "\n";
739 $response = $errorText;
740 } elseif ( $this->errors
) {
741 // Prepend comments indicating errors
743 foreach ( $this->errors
as $error ) {
744 $errorText .= self
::makeComment( $error );
746 $response = $errorText . $response;
749 $this->errors
= array();
755 * Send main response headers to the client.
757 * Deals with Content-Type, CORS (for stylesheets), and caching.
759 * @param ResourceLoaderContext $context
760 * @param string $etag ETag header value
761 * @param bool $errors Whether there are errors in the response
764 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
765 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
766 // If a version wasn't specified we need a shorter expiry time for updates
767 // to propagate to clients quickly
768 // If there were errors, we also need a shorter expiry time so we can recover quickly
769 if ( is_null( $context->getVersion() ) ||
$errors ) {
770 $maxage = $rlMaxage['unversioned']['client'];
771 $smaxage = $rlMaxage['unversioned']['server'];
772 // If a version was specified we can use a longer expiry time since changing
773 // version numbers causes cache misses
775 $maxage = $rlMaxage['versioned']['client'];
776 $smaxage = $rlMaxage['versioned']['server'];
778 if ( $context->getImageObj() ) {
779 // Output different headers if we're outputting textual errors.
781 header( 'Content-Type: text/plain; charset=utf-8' );
783 $context->getImageObj()->sendResponseHeaders( $context );
785 } elseif ( $context->getOnly() === 'styles' ) {
786 header( 'Content-Type: text/css; charset=utf-8' );
787 header( 'Access-Control-Allow-Origin: *' );
789 header( 'Content-Type: text/javascript; charset=utf-8' );
791 // See RFC 2616 § 14.19 ETag
792 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
793 header( 'ETag: ' . $etag );
794 if ( $context->getDebug() ) {
795 // Do not cache debug responses
796 header( 'Cache-Control: private, no-cache, must-revalidate' );
797 header( 'Pragma: no-cache' );
799 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
800 $exp = min( $maxage, $smaxage );
801 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
806 * Respond with HTTP 304 Not Modified if appropiate.
808 * If there's an If-None-Match header, respond with a 304 appropriately
809 * and clear out the output buffer. If the client cache is too old then do nothing.
811 * @param ResourceLoaderContext $context
812 * @param string $etag ETag header value
813 * @return bool True if HTTP 304 was sent and output handled
815 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
816 // See RFC 2616 § 14.26 If-None-Match
817 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
818 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
819 // Never send 304s in debug mode
820 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
821 // There's another bug in ob_gzhandler (see also the comment at
822 // the top of this function) that causes it to gzip even empty
823 // responses, meaning it's impossible to produce a truly empty
824 // response (because the gzip header is always there). This is
825 // a problem because 304 responses have to be completely empty
826 // per the HTTP spec, and Firefox behaves buggily when they're not.
827 // See also http://bugs.php.net/bug.php?id=51579
828 // To work around this, we tear down all output buffering before
830 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
832 HttpStatus
::header( 304 );
834 $this->sendResponseHeaders( $context, $etag, false );
841 * Send out code for a response from file cache if possible.
843 * @param ResourceFileCache $fileCache Cache object for this request URL
844 * @param ResourceLoaderContext $context Context in which to generate a response
845 * @param string $etag ETag header value
846 * @return bool If this found a cache file and handled the response
848 protected function tryRespondFromFileCache(
849 ResourceFileCache
$fileCache,
850 ResourceLoaderContext
$context,
853 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
854 // Buffer output to catch warnings.
856 // Get the maximum age the cache can be
857 $maxage = is_null( $context->getVersion() )
858 ?
$rlMaxage['unversioned']['server']
859 : $rlMaxage['versioned']['server'];
860 // Minimum timestamp the cache file must have
861 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
863 try { // RL always hits the DB on file cache miss...
865 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
866 $good = $fileCache->isCacheGood(); // cache existence check
870 $ts = $fileCache->cacheTimestamp();
871 // Send content type and cache headers
872 $this->sendResponseHeaders( $context, $etag, false );
873 $response = $fileCache->fetchText();
874 // Capture any PHP warnings from the output buffer and append them to the
875 // response in a comment if we're in debug mode.
876 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
877 $response = self
::makeComment( $warnings ) . $response;
879 // Remove the output buffer and output the response
881 echo $response . "\n/* Cached {$ts} */";
882 return true; // cache hit
887 return false; // cache miss
891 * Generate a CSS or JS comment block.
893 * Only use this for public data, not error message details.
895 * @param string $text
898 public static function makeComment( $text ) {
899 $encText = str_replace( '*/', '* /', $text );
900 return "/*\n$encText\n*/\n";
904 * Handle exception display.
906 * @param Exception $e Exception to be shown to the user
907 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
909 public static function formatException( $e ) {
910 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
914 * Handle exception display.
917 * @param Exception $e Exception to be shown to the user
918 * @return string Sanitized text that can be returned to the user
920 protected static function formatExceptionNoComment( $e ) {
921 global $wgShowExceptionDetails;
923 if ( $wgShowExceptionDetails ) {
924 return $e->__toString();
926 return wfMessage( 'internalerror' )->text();
931 * Generate code for a response.
933 * @param ResourceLoaderContext $context Context in which to generate a response
934 * @param array $modules List of module objects keyed by module name
935 * @param array $missing List of requested module names that are unregistered (optional)
936 * @return string Response data
938 public function makeModuleResponse( ResourceLoaderContext
$context,
939 array $modules, array $missing = array()
944 if ( !count( $modules ) && !count( $missing ) ) {
946 /* This file is the Web entry point for MediaWiki's ResourceLoader:
947 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
948 no modules were requested. Max made me put this here. */
952 $image = $context->getImageObj();
954 $data = $image->getImageData( $context );
955 if ( $data === false ) {
957 $this->errors
[] = 'Image generation failed';
963 if ( $context->shouldIncludeMessages() ) {
965 $blobs = $this->blobStore
->get( $this, $modules, $context->getLanguage() );
966 } catch ( Exception
$e ) {
967 MWExceptionHandler
::logException( $e );
968 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
971 $this->errors
[] = self
::formatExceptionNoComment( $e );
977 foreach ( $missing as $name ) {
978 $states[$name] = 'missing';
983 foreach ( $modules as $name => $module ) {
985 * @var $module ResourceLoaderModule
990 if ( $context->shouldIncludeScripts() ) {
991 // If we are in debug mode, we'll want to return an array of URLs if possible
992 // However, we can't do this if the module doesn't support it
993 // We also can't do this if there is an only= parameter, because we have to give
994 // the module a way to return a load.php URL without causing an infinite loop
995 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
996 $scripts = $module->getScriptURLsForDebug( $context );
998 $scripts = $module->getScript( $context );
999 // rtrim() because there are usually a few line breaks
1000 // after the last ';'. A new line at EOF, a new line
1001 // added by ResourceLoaderFileModule::readScriptFiles, etc.
1002 if ( is_string( $scripts )
1003 && strlen( $scripts )
1004 && substr( rtrim( $scripts ), -1 ) !== ';'
1006 // Append semicolon to prevent weird bugs caused by files not
1007 // terminating their statements right (bug 27054)
1014 if ( $context->shouldIncludeStyles() ) {
1015 // Don't create empty stylesheets like array( '' => '' ) for modules
1016 // that don't *have* any stylesheets (bug 38024).
1017 $stylePairs = $module->getStyles( $context );
1018 if ( count( $stylePairs ) ) {
1019 // If we are in debug mode without &only= set, we'll want to return an array of URLs
1020 // See comment near shouldIncludeScripts() for more details
1021 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
1023 'url' => $module->getStyleURLsForDebug( $context )
1026 // Minify CSS before embedding in mw.loader.implement call
1027 // (unless in debug mode)
1028 if ( !$context->getDebug() ) {
1029 foreach ( $stylePairs as $media => $style ) {
1030 // Can be either a string or an array of strings.
1031 if ( is_array( $style ) ) {
1032 $stylePairs[$media] = array();
1033 foreach ( $style as $cssText ) {
1034 if ( is_string( $cssText ) ) {
1035 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
1038 } elseif ( is_string( $style ) ) {
1039 $stylePairs[$media] = $this->filter( 'minify-css', $style );
1043 // Wrap styles into @media groups as needed and flatten into a numerical array
1045 'css' => self
::makeCombinedStyles( $stylePairs )
1052 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
1055 switch ( $context->getOnly() ) {
1057 if ( is_string( $scripts ) ) {
1058 // Load scripts raw...
1060 } elseif ( is_array( $scripts ) ) {
1061 // ...except when $scripts is an array of URLs
1062 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1066 // We no longer seperate into media, they are all combined now with
1067 // custom media type groups into @media .. {} sections as part of the css string.
1068 // Module returns either an empty array or a numerical array with css strings.
1069 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1072 $out .= self
::makeLoaderImplementScript(
1076 new XmlJsCode( $messagesBlob ),
1077 $module->getTemplates()
1081 } catch ( Exception
$e ) {
1082 MWExceptionHandler
::logException( $e );
1083 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1086 $this->errors
[] = self
::formatExceptionNoComment( $e );
1088 // Respond to client with error-state instead of module implementation
1089 $states[$name] = 'error';
1090 unset( $modules[$name] );
1092 $isRaw |
= $module->isRaw();
1095 // Update module states
1096 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1097 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1098 // Set the state of modules loaded as only scripts to ready as
1099 // they don't have an mw.loader.implement wrapper that sets the state
1100 foreach ( $modules as $name => $module ) {
1101 $states[$name] = 'ready';
1105 // Set the state of modules we didn't respond to with mw.loader.implement
1106 if ( count( $states ) ) {
1107 $out .= self
::makeLoaderStateScript( $states );
1110 if ( count( $states ) ) {
1111 $this->errors
[] = 'Problematic modules: ' .
1112 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1116 $enableFilterCache = true;
1117 if ( count( $modules ) === 1 && reset( $modules ) instanceof ResourceLoaderUserTokensModule
) {
1118 // If we're building the embedded user.tokens, don't cache (T84960)
1119 $enableFilterCache = false;
1122 if ( !$context->getDebug() ) {
1123 if ( $context->getOnly() === 'styles' ) {
1124 $out = $this->filter( 'minify-css', $out );
1126 $out = $this->filter( 'minify-js', $out, array(
1127 'cache' => $enableFilterCache
1135 /* Static Methods */
1138 * Return JS code that calls mw.loader.implement with given module properties.
1140 * @param string $name Module name
1141 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1142 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1143 * to CSS files keyed by media type
1144 * @param mixed $messages List of messages associated with this module. May either be an
1145 * associative array mapping message key to value, or a JSON-encoded message blob containing
1146 * the same data, wrapped in an XmlJsCode object.
1147 * @param array $templates Keys are name of templates and values are the source of
1149 * @throws MWException
1152 public static function makeLoaderImplementScript(
1153 $name, $scripts, $styles, $messages, $templates
1155 if ( is_string( $scripts ) ) {
1156 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1157 } elseif ( !is_array( $scripts ) ) {
1158 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1160 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1161 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1162 // of "{}". Force them to objects.
1168 (object) $templates,
1170 self
::trimArray( $module );
1172 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1176 * Returns JS code which, when called, will register a given list of messages.
1178 * @param mixed $messages Either an associative array mapping message key to value, or a
1179 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1182 public static function makeMessageSetScript( $messages ) {
1183 return Xml
::encodeJsCall(
1185 array( (object)$messages ),
1186 ResourceLoader
::inDebugMode()
1191 * Combines an associative array mapping media type to CSS into a
1192 * single stylesheet with "@media" blocks.
1194 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1197 public static function makeCombinedStyles( array $stylePairs ) {
1199 foreach ( $stylePairs as $media => $styles ) {
1200 // ResourceLoaderFileModule::getStyle can return the styles
1201 // as a string or an array of strings. This is to allow separation in
1203 $styles = (array)$styles;
1204 foreach ( $styles as $style ) {
1205 $style = trim( $style );
1206 // Don't output an empty "@media print { }" block (bug 40498)
1207 if ( $style !== '' ) {
1208 // Transform the media type based on request params and config
1209 // The way that this relies on $wgRequest to propagate request params is slightly evil
1210 $media = OutputPage
::transformCssMedia( $media );
1212 if ( $media === '' ||
$media == 'all' ) {
1214 } elseif ( is_string( $media ) ) {
1215 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1225 * Returns a JS call to mw.loader.state, which sets the state of a
1226 * module or modules to a given value. Has two calling conventions:
1228 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1229 * Set the state of a single module called $name to $state
1231 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1232 * Set the state of modules with the given names to the given states
1234 * @param string $name
1235 * @param string $state
1238 public static function makeLoaderStateScript( $name, $state = null ) {
1239 if ( is_array( $name ) ) {
1240 return Xml
::encodeJsCall(
1243 ResourceLoader
::inDebugMode()
1246 return Xml
::encodeJsCall(
1248 array( $name, $state ),
1249 ResourceLoader
::inDebugMode()
1255 * Returns JS code which calls the script given by $script. The script will
1256 * be called with local variables name, version, dependencies and group,
1257 * which will have values corresponding to $name, $version, $dependencies
1258 * and $group as supplied.
1260 * @param string $name Module name
1261 * @param string $version Module version hash
1262 * @param array $dependencies List of module names on which this module depends
1263 * @param string $group Group which the module is in.
1264 * @param string $source Source of the module, or 'local' if not foreign.
1265 * @param string $script JavaScript code
1268 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1269 $group, $source, $script
1271 $script = str_replace( "\n", "\n\t", trim( $script ) );
1272 return Xml
::encodeJsCall(
1273 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1274 array( $name, $version, $dependencies, $group, $source ),
1275 ResourceLoader
::inDebugMode()
1279 private static function isEmptyObject( stdClass
$obj ) {
1280 foreach ( $obj as $key => &$value ) {
1287 * Remove empty values from the end of an array.
1289 * Values considered empty:
1293 * - new XmlJsCode( '{}' )
1294 * - new stdClass() // (object) array()
1296 * @param Array $array
1298 private static function trimArray( Array &$array ) {
1299 $i = count( $array );
1301 if ( $array[$i] === null
1302 ||
$array[$i] === array()
1303 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1304 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1306 unset( $array[$i] );
1314 * Returns JS code which calls mw.loader.register with the given
1315 * parameters. Has three calling conventions:
1317 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1318 * $dependencies, $group, $source, $skip
1320 * Register a single module.
1322 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1323 * Register modules with the given names.
1325 * - ResourceLoader::makeLoaderRegisterScript( array(
1326 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1327 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1330 * Registers modules with the given names and parameters.
1332 * @param string $name Module name
1333 * @param string $version Module version hash
1334 * @param array $dependencies List of module names on which this module depends
1335 * @param string $group Group which the module is in
1336 * @param string $source Source of the module, or 'local' if not foreign
1337 * @param string $skip Script body of the skip function
1340 public static function makeLoaderRegisterScript( $name, $version = null,
1341 $dependencies = null, $group = null, $source = null, $skip = null
1343 if ( is_array( $name ) ) {
1344 // Build module name index
1346 foreach ( $name as $i => &$module ) {
1347 $index[$module[0]] = $i;
1350 // Transform dependency names into indexes when possible, they will be resolved by
1351 // mw.loader.register on the other end
1352 foreach ( $name as &$module ) {
1353 if ( isset( $module[2] ) ) {
1354 foreach ( $module[2] as &$dependency ) {
1355 if ( isset( $index[$dependency] ) ) {
1356 $dependency = $index[$dependency];
1362 array_walk( $name, array( 'self', 'trimArray' ) );
1364 return Xml
::encodeJsCall(
1365 'mw.loader.register',
1367 ResourceLoader
::inDebugMode()
1370 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1371 self
::trimArray( $registration );
1372 return Xml
::encodeJsCall(
1373 'mw.loader.register',
1375 ResourceLoader
::inDebugMode()
1381 * Returns JS code which calls mw.loader.addSource() with the given
1382 * parameters. Has two calling conventions:
1384 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1385 * Register a single source
1387 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1388 * Register sources with the given IDs and properties.
1390 * @param string $id Source ID
1391 * @param array $properties Source properties (see addSource())
1394 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1395 if ( is_array( $id ) ) {
1396 return Xml
::encodeJsCall(
1397 'mw.loader.addSource',
1399 ResourceLoader
::inDebugMode()
1402 return Xml
::encodeJsCall(
1403 'mw.loader.addSource',
1404 array( $id, $properties ),
1405 ResourceLoader
::inDebugMode()
1411 * Returns JS code which runs given JS code if the client-side framework is
1414 * @deprecated since 1.25; use makeInlineScript instead
1415 * @param string $script JavaScript code
1418 public static function makeLoaderConditionalScript( $script ) {
1419 return "if(window.mw){\n" . trim( $script ) . "\n}";
1423 * Construct an inline script tag with given JS code.
1425 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1426 * only if the client has adequate support for MediaWiki JavaScript code.
1428 * @param string $script JavaScript code
1429 * @return string HTML
1431 public static function makeInlineScript( $script ) {
1432 $js = self
::makeLoaderConditionalScript( $script );
1433 return Html
::inlineScript( $js );
1437 * Returns JS code which will set the MediaWiki configuration array to
1440 * @param array $configuration List of configuration values keyed by variable name
1443 public static function makeConfigSetScript( array $configuration ) {
1444 return Xml
::encodeJsCall(
1446 array( $configuration ),
1447 ResourceLoader
::inDebugMode()
1452 * Convert an array of module names to a packed query string.
1454 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1455 * becomes 'foo.bar,baz|bar.baz,quux'
1456 * @param array $modules List of module names (strings)
1457 * @return string Packed query string
1459 public static function makePackedModulesString( $modules ) {
1460 $groups = array(); // array( prefix => array( suffixes ) )
1461 foreach ( $modules as $module ) {
1462 $pos = strrpos( $module, '.' );
1463 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1464 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1465 $groups[$prefix][] = $suffix;
1469 foreach ( $groups as $prefix => $suffixes ) {
1470 $p = $prefix === '' ?
'' : $prefix . '.';
1471 $arr[] = $p . implode( ',', $suffixes );
1473 $str = implode( '|', $arr );
1478 * Determine whether debug mode was requested
1479 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1482 public static function inDebugMode() {
1483 if ( self
::$debugMode === null ) {
1484 global $wgRequest, $wgResourceLoaderDebug;
1485 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1486 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1489 return self
::$debugMode;
1493 * Reset static members used for caching.
1495 * Global state and $wgRequest are evil, but we're using it right
1496 * now and sometimes we need to be able to force ResourceLoader to
1497 * re-evaluate the context because it has changed (e.g. in the test suite).
1499 public static function clearCache() {
1500 self
::$debugMode = null;
1504 * Build a load.php URL
1507 * @param string $source Name of the ResourceLoader source
1508 * @param ResourceLoaderContext $context
1509 * @param array $extraQuery
1510 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1512 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1513 $extraQuery = array()
1515 $query = self
::createLoaderQuery( $context, $extraQuery );
1516 $script = $this->getLoadScript( $source );
1518 // Prevent the IE6 extension check from being triggered (bug 28840)
1519 // by appending a character that's invalid in Windows extensions ('*')
1520 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1524 * Build a load.php URL
1525 * @deprecated since 1.24 Use createLoaderURL() instead
1526 * @param array $modules Array of module names (strings)
1527 * @param string $lang Language code
1528 * @param string $skin Skin name
1529 * @param string|null $user User name. If null, the &user= parameter is omitted
1530 * @param string|null $version Versioning timestamp
1531 * @param bool $debug Whether the request should be in debug mode
1532 * @param string|null $only &only= parameter
1533 * @param bool $printable Printable mode
1534 * @param bool $handheld Handheld mode
1535 * @param array $extraQuery Extra query parameters to add
1536 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1538 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1539 $version = null, $debug = false, $only = null, $printable = false,
1540 $handheld = false, $extraQuery = array()
1542 global $wgLoadScript;
1544 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1545 $only, $printable, $handheld, $extraQuery
1548 // Prevent the IE6 extension check from being triggered (bug 28840)
1549 // by appending a character that's invalid in Windows extensions ('*')
1550 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1554 * Helper for createLoaderURL()
1557 * @see makeLoaderQuery
1558 * @param ResourceLoaderContext $context
1559 * @param array $extraQuery
1562 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1563 return self
::makeLoaderQuery(
1564 $context->getModules(),
1565 $context->getLanguage(),
1566 $context->getSkin(),
1567 $context->getUser(),
1568 $context->getVersion(),
1569 $context->getDebug(),
1570 $context->getOnly(),
1571 $context->getRequest()->getBool( 'printable' ),
1572 $context->getRequest()->getBool( 'handheld' ),
1578 * Build a query array (array representation of query string) for load.php. Helper
1579 * function for makeLoaderURL().
1581 * @param array $modules
1582 * @param string $lang
1583 * @param string $skin
1584 * @param string $user
1585 * @param string $version
1586 * @param bool $debug
1587 * @param string $only
1588 * @param bool $printable
1589 * @param bool $handheld
1590 * @param array $extraQuery
1594 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1595 $version = null, $debug = false, $only = null, $printable = false,
1596 $handheld = false, $extraQuery = array()
1599 'modules' => self
::makePackedModulesString( $modules ),
1602 'debug' => $debug ?
'true' : 'false',
1604 if ( $user !== null ) {
1605 $query['user'] = $user;
1607 if ( $version !== null ) {
1608 $query['version'] = $version;
1610 if ( $only !== null ) {
1611 $query['only'] = $only;
1614 $query['printable'] = 1;
1617 $query['handheld'] = 1;
1619 $query +
= $extraQuery;
1621 // Make queries uniform in order
1627 * Check a module name for validity.
1629 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1630 * at most 255 bytes.
1632 * @param string $moduleName Module name to check
1633 * @return bool Whether $moduleName is a valid module name
1635 public static function isValidModuleName( $moduleName ) {
1636 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1640 * Returns LESS compiler set up for use with MediaWiki
1642 * @param Config $config
1643 * @throws MWException
1647 public static function getLessCompiler( Config
$config ) {
1648 // When called from the installer, it is possible that a required PHP extension
1649 // is missing (at least for now; see bug 47564). If this is the case, throw an
1650 // exception (caught by the installer) to prevent a fatal error later on.
1651 if ( !class_exists( 'lessc' ) ) {
1652 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1654 if ( !function_exists( 'ctype_digit' ) ) {
1655 throw new MWException( 'lessc requires the Ctype extension' );
1658 $less = new lessc();
1659 $less->setPreserveComments( true );
1660 $less->setVariables( self
::getLessVars( $config ) );
1661 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1662 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1663 $less->registerFunction( $name, $func );
1669 * Get global LESS variables.
1671 * @param Config $config
1673 * @return array Map of variable names to string CSS values.
1675 public static function getLessVars( Config
$config ) {
1676 if ( !self
::$lessVars ) {
1677 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1678 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1679 // Sort by key to ensure consistent hashing for cache lookups.
1681 self
::$lessVars = $lessVars;
1683 return self
::$lessVars;