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
->info( __METHOD__
. ": Invalid filter: $filter" );
204 if ( !$options['cache'] ) {
205 $result = $this->applyFilter( $filter, $data );
207 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
208 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL
: CACHE_ANYTHING
);
209 $cacheEntry = $cache->get( $key );
210 if ( is_string( $cacheEntry ) ) {
211 wfIncrStats( "resourceloader_cache.$filter.hit" );
216 wfIncrStats( "resourceloader_cache.$filter.miss" );
217 $result = $this->applyFilter( $filter, $data );
218 if ( $options['cacheReport'] ) {
219 $result .= "\n/* cache key: $key */";
221 $cache->set( $key, $result );
222 } catch ( Exception
$e ) {
223 MWExceptionHandler
::logException( $e );
224 $this->logger
->info( __METHOD__
. ": minification failed: $e" );
225 $this->errors
[] = self
::formatExceptionNoComment( $e );
232 private function applyFilter( $filter, $data ) {
235 return JavaScriptMinifier
::minify( $data,
236 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
237 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
240 return CSSMin
::minify( $data );
248 * Register core modules and runs registration hooks.
249 * @param Config|null $config
251 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
255 $logger = new NullLogger();
257 $this->setLogger( $logger );
260 $this->logger
->info( __METHOD__
. ' was called without providing a Config instance' );
261 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
263 $this->config
= $config;
265 // Add 'local' source first
266 $this->addSource( 'local', wfScript( 'load' ) );
269 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
271 // Register core modules
272 $this->register( include "$IP/resources/Resources.php" );
273 $this->register( include "$IP/resources/ResourcesOOUI.php" );
274 // Register extension modules
275 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
276 $this->register( $config->get( 'ResourceModules' ) );
278 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
279 $this->registerTestModules();
282 $this->setMessageBlobStore( new MessageBlobStore() );
288 public function getConfig() {
289 return $this->config
;
292 public function setLogger( LoggerInterface
$logger ) {
293 $this->logger
= $logger;
297 * @param MessageBlobStore $blobStore
300 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
301 $this->blobStore
= $blobStore;
305 * Register a module with the ResourceLoader system.
307 * @param mixed $name Name of module as a string or List of name/object pairs as an array
308 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
309 * this may also be a ResourceLoaderModule object. Optional when using
310 * multiple-registration calling style.
311 * @throws MWException If a duplicate module registration is attempted
312 * @throws MWException If a module name contains illegal characters (pipes or commas)
313 * @throws MWException If something other than a ResourceLoaderModule is being registered
314 * @return bool False if there were any errors, in which case one or more modules were
317 public function register( $name, $info = null ) {
319 // Allow multiple modules to be registered in one call
320 $registrations = is_array( $name ) ?
$name : array( $name => $info );
321 foreach ( $registrations as $name => $info ) {
322 // Disallow duplicate registrations
323 if ( isset( $this->moduleInfos
[$name] ) ) {
324 // A module has already been registered by this name
325 throw new MWException(
326 'ResourceLoader duplicate registration error. ' .
327 'Another module has already been registered as ' . $name
331 // Check $name for validity
332 if ( !self
::isValidModuleName( $name ) ) {
333 throw new MWException( "ResourceLoader module name '$name' is invalid, "
334 . "see ResourceLoader::isValidModuleName()" );
338 if ( $info instanceof ResourceLoaderModule
) {
339 $this->moduleInfos
[$name] = array( 'object' => $info );
340 $info->setName( $name );
341 $this->modules
[$name] = $info;
342 } elseif ( is_array( $info ) ) {
343 // New calling convention
344 $this->moduleInfos
[$name] = $info;
346 throw new MWException(
347 'ResourceLoader module info type error for module \'' . $name .
348 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
352 // Last-minute changes
354 // Apply custom skin-defined styles to existing modules.
355 if ( $this->isFileModule( $name ) ) {
356 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
357 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
358 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
362 // If $name is preceded with a '+', the defined style files will be added to 'default'
363 // skinStyles, otherwise 'default' will be ignored as it normally would be.
364 if ( isset( $skinStyles[$name] ) ) {
365 $paths = (array)$skinStyles[$name];
366 $styleFiles = array();
367 } elseif ( isset( $skinStyles['+' . $name] ) ) {
368 $paths = (array)$skinStyles['+' . $name];
369 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
370 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
376 // Add new file paths, remapping them to refer to our directories and not use settings
377 // from the module we're modifying, which come from the base definition.
378 list( $localBasePath, $remoteBasePath ) =
379 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
381 foreach ( $paths as $path ) {
382 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
385 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
394 public function registerTestModules() {
397 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
398 throw new MWException( 'Attempt to register JavaScript test modules '
399 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
400 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
403 // Get core test suites
404 $testModules = array();
405 $testModules['qunit'] = array();
406 // Get other test suites (e.g. from extensions)
407 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
409 // Add the testrunner (which configures QUnit) to the dependencies.
410 // Since it must be ready before any of the test suites are executed.
411 foreach ( $testModules['qunit'] as &$module ) {
412 // Make sure all test modules are top-loading so that when QUnit starts
413 // on document-ready, it will run once and finish. If some tests arrive
414 // later (possibly after QUnit has already finished) they will be ignored.
415 $module['position'] = 'top';
416 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
419 $testModules['qunit'] =
420 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
422 foreach ( $testModules as $id => $names ) {
423 // Register test modules
424 $this->register( $testModules[$id] );
426 // Keep track of their names so that they can be loaded together
427 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
433 * Add a foreign source of modules.
435 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
436 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
437 * backwards-compatibility.
438 * @throws MWException
440 public function addSource( $id, $loadUrl = null ) {
441 // Allow multiple sources to be registered in one call
442 if ( is_array( $id ) ) {
443 foreach ( $id as $key => $value ) {
444 $this->addSource( $key, $value );
449 // Disallow duplicates
450 if ( isset( $this->sources
[$id] ) ) {
451 throw new MWException(
452 'ResourceLoader duplicate source addition error. ' .
453 'Another source has already been registered as ' . $id
457 // Pre 1.24 backwards-compatibility
458 if ( is_array( $loadUrl ) ) {
459 if ( !isset( $loadUrl['loadScript'] ) ) {
460 throw new MWException(
461 __METHOD__
. ' was passed an array with no "loadScript" key.'
465 $loadUrl = $loadUrl['loadScript'];
468 $this->sources
[$id] = $loadUrl;
472 * Get a list of module names.
474 * @return array List of module names
476 public function getModuleNames() {
477 return array_keys( $this->moduleInfos
);
481 * Get a list of test module names for one (or all) frameworks.
483 * If the given framework id is unknkown, or if the in-object variable is not an array,
484 * then it will return an empty array.
486 * @param string $framework Get only the test module names for one
487 * particular framework (optional)
490 public function getTestModuleNames( $framework = 'all' ) {
491 /** @todo api siteinfo prop testmodulenames modulenames */
492 if ( $framework == 'all' ) {
493 return $this->testModuleNames
;
494 } elseif ( isset( $this->testModuleNames
[$framework] )
495 && is_array( $this->testModuleNames
[$framework] )
497 return $this->testModuleNames
[$framework];
504 * Check whether a ResourceLoader module is registered
507 * @param string $name
510 public function isModuleRegistered( $name ) {
511 return isset( $this->moduleInfos
[$name] );
515 * Get the ResourceLoaderModule object for a given module name.
517 * If an array of module parameters exists but a ResourceLoaderModule object has not
518 * yet been instantiated, this method will instantiate and cache that object such that
519 * subsequent calls simply return the same object.
521 * @param string $name Module name
522 * @return ResourceLoaderModule|null If module has been registered, return a
523 * ResourceLoaderModule instance. Otherwise, return null.
525 public function getModule( $name ) {
526 if ( !isset( $this->modules
[$name] ) ) {
527 if ( !isset( $this->moduleInfos
[$name] ) ) {
531 // Construct the requested object
532 $info = $this->moduleInfos
[$name];
533 /** @var ResourceLoaderModule $object */
534 if ( isset( $info['object'] ) ) {
535 // Object given in info array
536 $object = $info['object'];
538 if ( !isset( $info['class'] ) ) {
539 $class = 'ResourceLoaderFileModule';
541 $class = $info['class'];
543 /** @var ResourceLoaderModule $object */
544 $object = new $class( $info );
545 $object->setConfig( $this->getConfig() );
547 $object->setName( $name );
548 $this->modules
[$name] = $object;
551 return $this->modules
[$name];
555 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
557 * @param string $name Module name
560 protected function isFileModule( $name ) {
561 if ( !isset( $this->moduleInfos
[$name] ) ) {
564 $info = $this->moduleInfos
[$name];
565 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
572 * Get the list of sources.
574 * @return array Like array( id => load.php url, .. )
576 public function getSources() {
577 return $this->sources
;
581 * Get the URL to the load.php endpoint for the given
582 * ResourceLoader source
585 * @param string $source
586 * @throws MWException On an invalid $source name
589 public function getLoadScript( $source ) {
590 if ( !isset( $this->sources
[$source] ) ) {
591 throw new MWException( "The $source source was never registered in ResourceLoader." );
593 return $this->sources
[$source];
598 * @param string $value
599 * @return string Hash
601 public static function makeHash( $value ) {
602 // Use base64 to output more entropy in a more compact string (default hex is only base16).
603 // The first 8 chars of a base64 encoded digest represent the same binary as
604 // the first 12 chars of a hex encoded digest.
605 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
609 * Helper method to get and combine versions of multiple modules.
612 * @param ResourceLoaderContext $context
613 * @param array $modules List of ResourceLoaderModule objects
614 * @return string Hash
616 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
620 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
621 // http://php.net/functions.anonymous
623 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
624 return $rl->getModule( $module )->getVersionHash( $context );
626 return self
::makeHash( implode( $hashes ) );
630 * Output a response to a load request, including the content-type header.
632 * @param ResourceLoaderContext $context Context in which a response should be formed
634 public function respond( ResourceLoaderContext
$context ) {
635 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
636 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
637 // is used: ob_clean() will clear the GZIP header in that case and it won't come
638 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
639 // the whole thing in our own output buffer to be sure the active buffer
640 // doesn't use ob_gzhandler.
641 // See http://bugs.php.net/bug.php?id=36514
644 // Find out which modules are missing and instantiate the others
647 foreach ( $context->getModules() as $name ) {
648 $module = $this->getModule( $name );
650 // Do not allow private modules to be loaded from the web.
651 // This is a security issue, see bug 34907.
652 if ( $module->getGroup() === 'private' ) {
653 $this->logger
->info( __METHOD__
. ": request for private module '$name' denied" );
654 $this->errors
[] = "Cannot show private module \"$name\"";
657 $modules[$name] = $module;
664 // Preload for getCombinedVersion()
665 $this->preloadModuleInfo( array_keys( $modules ), $context );
666 } catch ( Exception
$e ) {
667 MWExceptionHandler
::logException( $e );
668 $this->logger
->info( __METHOD__
. ": preloading module info failed: $e" );
669 $this->errors
[] = self
::formatExceptionNoComment( $e );
672 // Combine versions to propagate cache invalidation
675 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
676 } catch ( Exception
$e ) {
677 MWExceptionHandler
::logException( $e );
678 $this->logger
->info( __METHOD__
. ": calculating version hash failed: $e" );
679 $this->errors
[] = self
::formatExceptionNoComment( $e );
682 // See RFC 2616 § 3.11 Entity Tags
683 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
684 $etag = 'W/"' . $versionHash . '"';
686 // Try the client-side cache first
687 if ( $this->tryRespondNotModified( $context, $etag ) ) {
688 return; // output handled (buffers cleared)
691 // Use file cache if enabled and available...
692 if ( $this->config
->get( 'UseFileCache' ) ) {
693 $fileCache = ResourceFileCache
::newFromContext( $context );
694 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
695 return; // output handled
699 // Generate a response
700 $response = $this->makeModuleResponse( $context, $modules, $missing );
702 // Capture any PHP warnings from the output buffer and append them to the
703 // error list if we're in debug mode.
704 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
705 $this->errors
[] = $warnings;
708 // Save response to file cache unless there are errors
709 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
710 // Cache single modules and images...and other requests if there are enough hits
711 if ( ResourceFileCache
::useFileCache( $context ) ) {
712 if ( $fileCache->isCacheWorthy() ) {
713 $fileCache->saveText( $response );
715 $fileCache->incrMissesRecent( $context->getRequest() );
720 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
722 // Remove the output buffer and output the response
725 if ( $context->getImageObj() && $this->errors
) {
726 // We can't show both the error messages and the response when it's an image.
728 foreach ( $this->errors
as $error ) {
729 $errorText .= $error . "\n";
731 $response = $errorText;
732 } elseif ( $this->errors
) {
733 // Prepend comments indicating errors
735 foreach ( $this->errors
as $error ) {
736 $errorText .= self
::makeComment( $error );
738 $response = $errorText . $response;
741 $this->errors
= array();
747 * Send main response headers to the client.
749 * Deals with Content-Type, CORS (for stylesheets), and caching.
751 * @param ResourceLoaderContext $context
752 * @param string $etag ETag header value
753 * @param bool $errors Whether there are errors in the response
756 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
757 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
758 // If a version wasn't specified we need a shorter expiry time for updates
759 // to propagate to clients quickly
760 // If there were errors, we also need a shorter expiry time so we can recover quickly
761 if ( is_null( $context->getVersion() ) ||
$errors ) {
762 $maxage = $rlMaxage['unversioned']['client'];
763 $smaxage = $rlMaxage['unversioned']['server'];
764 // If a version was specified we can use a longer expiry time since changing
765 // version numbers causes cache misses
767 $maxage = $rlMaxage['versioned']['client'];
768 $smaxage = $rlMaxage['versioned']['server'];
770 if ( $context->getImageObj() ) {
771 // Output different headers if we're outputting textual errors.
773 header( 'Content-Type: text/plain; charset=utf-8' );
775 $context->getImageObj()->sendResponseHeaders( $context );
777 } elseif ( $context->getOnly() === 'styles' ) {
778 header( 'Content-Type: text/css; charset=utf-8' );
779 header( 'Access-Control-Allow-Origin: *' );
781 header( 'Content-Type: text/javascript; charset=utf-8' );
783 // See RFC 2616 § 14.19 ETag
784 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
785 header( 'ETag: ' . $etag );
786 if ( $context->getDebug() ) {
787 // Do not cache debug responses
788 header( 'Cache-Control: private, no-cache, must-revalidate' );
789 header( 'Pragma: no-cache' );
791 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
792 $exp = min( $maxage, $smaxage );
793 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
798 * Respond with HTTP 304 Not Modified if appropiate.
800 * If there's an If-None-Match header, respond with a 304 appropriately
801 * and clear out the output buffer. If the client cache is too old then do nothing.
803 * @param ResourceLoaderContext $context
804 * @param string $etag ETag header value
805 * @return bool True if HTTP 304 was sent and output handled
807 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
808 // See RFC 2616 § 14.26 If-None-Match
809 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
810 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
811 // Never send 304s in debug mode
812 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
813 // There's another bug in ob_gzhandler (see also the comment at
814 // the top of this function) that causes it to gzip even empty
815 // responses, meaning it's impossible to produce a truly empty
816 // response (because the gzip header is always there). This is
817 // a problem because 304 responses have to be completely empty
818 // per the HTTP spec, and Firefox behaves buggily when they're not.
819 // See also http://bugs.php.net/bug.php?id=51579
820 // To work around this, we tear down all output buffering before
822 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
824 HttpStatus
::header( 304 );
826 $this->sendResponseHeaders( $context, $etag, false );
833 * Send out code for a response from file cache if possible.
835 * @param ResourceFileCache $fileCache Cache object for this request URL
836 * @param ResourceLoaderContext $context Context in which to generate a response
837 * @param string $etag ETag header value
838 * @return bool If this found a cache file and handled the response
840 protected function tryRespondFromFileCache(
841 ResourceFileCache
$fileCache,
842 ResourceLoaderContext
$context,
845 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
846 // Buffer output to catch warnings.
848 // Get the maximum age the cache can be
849 $maxage = is_null( $context->getVersion() )
850 ?
$rlMaxage['unversioned']['server']
851 : $rlMaxage['versioned']['server'];
852 // Minimum timestamp the cache file must have
853 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
855 try { // RL always hits the DB on file cache miss...
857 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
858 $good = $fileCache->isCacheGood(); // cache existence check
862 $ts = $fileCache->cacheTimestamp();
863 // Send content type and cache headers
864 $this->sendResponseHeaders( $context, $etag, false );
865 $response = $fileCache->fetchText();
866 // Capture any PHP warnings from the output buffer and append them to the
867 // response in a comment if we're in debug mode.
868 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
869 $response = self
::makeComment( $warnings ) . $response;
871 // Remove the output buffer and output the response
873 echo $response . "\n/* Cached {$ts} */";
874 return true; // cache hit
879 return false; // cache miss
883 * Generate a CSS or JS comment block.
885 * Only use this for public data, not error message details.
887 * @param string $text
890 public static function makeComment( $text ) {
891 $encText = str_replace( '*/', '* /', $text );
892 return "/*\n$encText\n*/\n";
896 * Handle exception display.
898 * @param Exception $e Exception to be shown to the user
899 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
901 public static function formatException( $e ) {
902 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
906 * Handle exception display.
909 * @param Exception $e Exception to be shown to the user
910 * @return string Sanitized text that can be returned to the user
912 protected static function formatExceptionNoComment( $e ) {
913 global $wgShowExceptionDetails;
915 if ( $wgShowExceptionDetails ) {
916 return $e->__toString();
918 return wfMessage( 'internalerror' )->text();
923 * Generate code for a response.
925 * @param ResourceLoaderContext $context Context in which to generate a response
926 * @param array $modules List of module objects keyed by module name
927 * @param array $missing List of requested module names that are unregistered (optional)
928 * @return string Response data
930 public function makeModuleResponse( ResourceLoaderContext
$context,
931 array $modules, array $missing = array()
936 if ( !count( $modules ) && !count( $missing ) ) {
938 /* This file is the Web entry point for MediaWiki's ResourceLoader:
939 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
940 no modules were requested. Max made me put this here. */
944 $image = $context->getImageObj();
946 $data = $image->getImageData( $context );
947 if ( $data === false ) {
949 $this->errors
[] = 'Image generation failed';
955 if ( $context->shouldIncludeMessages() ) {
957 $blobs = $this->blobStore
->get( $this, $modules, $context->getLanguage() );
958 } catch ( Exception
$e ) {
959 MWExceptionHandler
::logException( $e );
961 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
963 $this->errors
[] = self
::formatExceptionNoComment( $e );
969 foreach ( $missing as $name ) {
970 $states[$name] = 'missing';
975 foreach ( $modules as $name => $module ) {
977 * @var $module ResourceLoaderModule
982 if ( $context->shouldIncludeScripts() ) {
983 // If we are in debug mode, we'll want to return an array of URLs if possible
984 // However, we can't do this if the module doesn't support it
985 // We also can't do this if there is an only= parameter, because we have to give
986 // the module a way to return a load.php URL without causing an infinite loop
987 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
988 $scripts = $module->getScriptURLsForDebug( $context );
990 $scripts = $module->getScript( $context );
991 // rtrim() because there are usually a few line breaks
992 // after the last ';'. A new line at EOF, a new line
993 // added by ResourceLoaderFileModule::readScriptFiles, etc.
994 if ( is_string( $scripts )
995 && strlen( $scripts )
996 && substr( rtrim( $scripts ), -1 ) !== ';'
998 // Append semicolon to prevent weird bugs caused by files not
999 // terminating their statements right (bug 27054)
1006 if ( $context->shouldIncludeStyles() ) {
1007 // Don't create empty stylesheets like array( '' => '' ) for modules
1008 // that don't *have* any stylesheets (bug 38024).
1009 $stylePairs = $module->getStyles( $context );
1010 if ( count( $stylePairs ) ) {
1011 // If we are in debug mode without &only= set, we'll want to return an array of URLs
1012 // See comment near shouldIncludeScripts() for more details
1013 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
1015 'url' => $module->getStyleURLsForDebug( $context )
1018 // Minify CSS before embedding in mw.loader.implement call
1019 // (unless in debug mode)
1020 if ( !$context->getDebug() ) {
1021 foreach ( $stylePairs as $media => $style ) {
1022 // Can be either a string or an array of strings.
1023 if ( is_array( $style ) ) {
1024 $stylePairs[$media] = array();
1025 foreach ( $style as $cssText ) {
1026 if ( is_string( $cssText ) ) {
1027 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
1030 } elseif ( is_string( $style ) ) {
1031 $stylePairs[$media] = $this->filter( 'minify-css', $style );
1035 // Wrap styles into @media groups as needed and flatten into a numerical array
1037 'css' => self
::makeCombinedStyles( $stylePairs )
1044 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
1047 switch ( $context->getOnly() ) {
1049 if ( is_string( $scripts ) ) {
1050 // Load scripts raw...
1052 } elseif ( is_array( $scripts ) ) {
1053 // ...except when $scripts is an array of URLs
1054 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1058 // We no longer seperate into media, they are all combined now with
1059 // custom media type groups into @media .. {} sections as part of the css string.
1060 // Module returns either an empty array or a numerical array with css strings.
1061 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1064 $out .= self
::makeLoaderImplementScript(
1068 new XmlJsCode( $messagesBlob ),
1069 $module->getTemplates()
1073 } catch ( Exception
$e ) {
1074 MWExceptionHandler
::logException( $e );
1075 $this->logger
->info( __METHOD__
. ": generating module package failed: $e" );
1076 $this->errors
[] = self
::formatExceptionNoComment( $e );
1078 // Respond to client with error-state instead of module implementation
1079 $states[$name] = 'error';
1080 unset( $modules[$name] );
1082 $isRaw |
= $module->isRaw();
1085 // Update module states
1086 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1087 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1088 // Set the state of modules loaded as only scripts to ready as
1089 // they don't have an mw.loader.implement wrapper that sets the state
1090 foreach ( $modules as $name => $module ) {
1091 $states[$name] = 'ready';
1095 // Set the state of modules we didn't respond to with mw.loader.implement
1096 if ( count( $states ) ) {
1097 $out .= self
::makeLoaderStateScript( $states );
1100 if ( count( $states ) ) {
1101 $this->errors
[] = 'Problematic modules: ' .
1102 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1106 $enableFilterCache = true;
1107 if ( count( $modules ) === 1 && reset( $modules ) instanceof ResourceLoaderUserTokensModule
) {
1108 // If we're building the embedded user.tokens, don't cache (T84960)
1109 $enableFilterCache = false;
1112 if ( !$context->getDebug() ) {
1113 if ( $context->getOnly() === 'styles' ) {
1114 $out = $this->filter( 'minify-css', $out );
1116 $out = $this->filter( 'minify-js', $out, array(
1117 'cache' => $enableFilterCache
1125 /* Static Methods */
1128 * Return JS code that calls mw.loader.implement with given module properties.
1130 * @param string $name Module name
1131 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1132 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1133 * to CSS files keyed by media type
1134 * @param mixed $messages List of messages associated with this module. May either be an
1135 * associative array mapping message key to value, or a JSON-encoded message blob containing
1136 * the same data, wrapped in an XmlJsCode object.
1137 * @param array $templates Keys are name of templates and values are the source of
1139 * @throws MWException
1142 public static function makeLoaderImplementScript(
1143 $name, $scripts, $styles, $messages, $templates
1145 if ( is_string( $scripts ) ) {
1146 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1147 } elseif ( !is_array( $scripts ) ) {
1148 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1150 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1151 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1152 // of "{}". Force them to objects.
1158 (object) $templates,
1160 self
::trimArray( $module );
1162 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1166 * Returns JS code which, when called, will register a given list of messages.
1168 * @param mixed $messages Either an associative array mapping message key to value, or a
1169 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1172 public static function makeMessageSetScript( $messages ) {
1173 return Xml
::encodeJsCall(
1175 array( (object)$messages ),
1176 ResourceLoader
::inDebugMode()
1181 * Combines an associative array mapping media type to CSS into a
1182 * single stylesheet with "@media" blocks.
1184 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1187 public static function makeCombinedStyles( array $stylePairs ) {
1189 foreach ( $stylePairs as $media => $styles ) {
1190 // ResourceLoaderFileModule::getStyle can return the styles
1191 // as a string or an array of strings. This is to allow separation in
1193 $styles = (array)$styles;
1194 foreach ( $styles as $style ) {
1195 $style = trim( $style );
1196 // Don't output an empty "@media print { }" block (bug 40498)
1197 if ( $style !== '' ) {
1198 // Transform the media type based on request params and config
1199 // The way that this relies on $wgRequest to propagate request params is slightly evil
1200 $media = OutputPage
::transformCssMedia( $media );
1202 if ( $media === '' ||
$media == 'all' ) {
1204 } elseif ( is_string( $media ) ) {
1205 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1215 * Returns a JS call to mw.loader.state, which sets the state of a
1216 * module or modules to a given value. Has two calling conventions:
1218 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1219 * Set the state of a single module called $name to $state
1221 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1222 * Set the state of modules with the given names to the given states
1224 * @param string $name
1225 * @param string $state
1228 public static function makeLoaderStateScript( $name, $state = null ) {
1229 if ( is_array( $name ) ) {
1230 return Xml
::encodeJsCall(
1233 ResourceLoader
::inDebugMode()
1236 return Xml
::encodeJsCall(
1238 array( $name, $state ),
1239 ResourceLoader
::inDebugMode()
1245 * Returns JS code which calls the script given by $script. The script will
1246 * be called with local variables name, version, dependencies and group,
1247 * which will have values corresponding to $name, $version, $dependencies
1248 * and $group as supplied.
1250 * @param string $name Module name
1251 * @param string $version Module version hash
1252 * @param array $dependencies List of module names on which this module depends
1253 * @param string $group Group which the module is in.
1254 * @param string $source Source of the module, or 'local' if not foreign.
1255 * @param string $script JavaScript code
1258 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1259 $group, $source, $script
1261 $script = str_replace( "\n", "\n\t", trim( $script ) );
1262 return Xml
::encodeJsCall(
1263 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1264 array( $name, $version, $dependencies, $group, $source ),
1265 ResourceLoader
::inDebugMode()
1269 private static function isEmptyObject( stdClass
$obj ) {
1270 foreach ( $obj as $key => &$value ) {
1277 * Remove empty values from the end of an array.
1279 * Values considered empty:
1283 * - new XmlJsCode( '{}' )
1284 * - new stdClass() // (object) array()
1286 * @param Array $array
1288 private static function trimArray( Array &$array ) {
1289 $i = count( $array );
1291 if ( $array[$i] === null
1292 ||
$array[$i] === array()
1293 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1294 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1296 unset( $array[$i] );
1304 * Returns JS code which calls mw.loader.register with the given
1305 * parameters. Has three calling conventions:
1307 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1308 * $dependencies, $group, $source, $skip
1310 * Register a single module.
1312 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1313 * Register modules with the given names.
1315 * - ResourceLoader::makeLoaderRegisterScript( array(
1316 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1317 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1320 * Registers modules with the given names and parameters.
1322 * @param string $name Module name
1323 * @param string $version Module version hash
1324 * @param array $dependencies List of module names on which this module depends
1325 * @param string $group Group which the module is in
1326 * @param string $source Source of the module, or 'local' if not foreign
1327 * @param string $skip Script body of the skip function
1330 public static function makeLoaderRegisterScript( $name, $version = null,
1331 $dependencies = null, $group = null, $source = null, $skip = null
1333 if ( is_array( $name ) ) {
1334 // Build module name index
1336 foreach ( $name as $i => &$module ) {
1337 $index[$module[0]] = $i;
1340 // Transform dependency names into indexes when possible, they will be resolved by
1341 // mw.loader.register on the other end
1342 foreach ( $name as &$module ) {
1343 if ( isset( $module[2] ) ) {
1344 foreach ( $module[2] as &$dependency ) {
1345 if ( isset( $index[$dependency] ) ) {
1346 $dependency = $index[$dependency];
1352 array_walk( $name, array( 'self', 'trimArray' ) );
1354 return Xml
::encodeJsCall(
1355 'mw.loader.register',
1357 ResourceLoader
::inDebugMode()
1360 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1361 self
::trimArray( $registration );
1362 return Xml
::encodeJsCall(
1363 'mw.loader.register',
1365 ResourceLoader
::inDebugMode()
1371 * Returns JS code which calls mw.loader.addSource() with the given
1372 * parameters. Has two calling conventions:
1374 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1375 * Register a single source
1377 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1378 * Register sources with the given IDs and properties.
1380 * @param string $id Source ID
1381 * @param array $properties Source properties (see addSource())
1384 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1385 if ( is_array( $id ) ) {
1386 return Xml
::encodeJsCall(
1387 'mw.loader.addSource',
1389 ResourceLoader
::inDebugMode()
1392 return Xml
::encodeJsCall(
1393 'mw.loader.addSource',
1394 array( $id, $properties ),
1395 ResourceLoader
::inDebugMode()
1401 * Returns JS code which runs given JS code if the client-side framework is
1404 * @deprecated since 1.25; use makeInlineScript instead
1405 * @param string $script JavaScript code
1408 public static function makeLoaderConditionalScript( $script ) {
1409 return "if(window.mw){\n" . trim( $script ) . "\n}";
1413 * Construct an inline script tag with given JS code.
1415 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1416 * only if the client has adequate support for MediaWiki JavaScript code.
1418 * @param string $script JavaScript code
1419 * @return string HTML
1421 public static function makeInlineScript( $script ) {
1422 $js = self
::makeLoaderConditionalScript( $script );
1423 return Html
::inlineScript( $js );
1427 * Returns JS code which will set the MediaWiki configuration array to
1430 * @param array $configuration List of configuration values keyed by variable name
1433 public static function makeConfigSetScript( array $configuration ) {
1434 return Xml
::encodeJsCall(
1436 array( $configuration ),
1437 ResourceLoader
::inDebugMode()
1442 * Convert an array of module names to a packed query string.
1444 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1445 * becomes 'foo.bar,baz|bar.baz,quux'
1446 * @param array $modules List of module names (strings)
1447 * @return string Packed query string
1449 public static function makePackedModulesString( $modules ) {
1450 $groups = array(); // array( prefix => array( suffixes ) )
1451 foreach ( $modules as $module ) {
1452 $pos = strrpos( $module, '.' );
1453 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1454 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1455 $groups[$prefix][] = $suffix;
1459 foreach ( $groups as $prefix => $suffixes ) {
1460 $p = $prefix === '' ?
'' : $prefix . '.';
1461 $arr[] = $p . implode( ',', $suffixes );
1463 $str = implode( '|', $arr );
1468 * Determine whether debug mode was requested
1469 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1472 public static function inDebugMode() {
1473 if ( self
::$debugMode === null ) {
1474 global $wgRequest, $wgResourceLoaderDebug;
1475 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1476 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1479 return self
::$debugMode;
1483 * Reset static members used for caching.
1485 * Global state and $wgRequest are evil, but we're using it right
1486 * now and sometimes we need to be able to force ResourceLoader to
1487 * re-evaluate the context because it has changed (e.g. in the test suite).
1489 public static function clearCache() {
1490 self
::$debugMode = null;
1494 * Build a load.php URL
1497 * @param string $source Name of the ResourceLoader source
1498 * @param ResourceLoaderContext $context
1499 * @param array $extraQuery
1500 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1502 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1503 $extraQuery = array()
1505 $query = self
::createLoaderQuery( $context, $extraQuery );
1506 $script = $this->getLoadScript( $source );
1508 // Prevent the IE6 extension check from being triggered (bug 28840)
1509 // by appending a character that's invalid in Windows extensions ('*')
1510 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1514 * Build a load.php URL
1515 * @deprecated since 1.24 Use createLoaderURL() instead
1516 * @param array $modules Array of module names (strings)
1517 * @param string $lang Language code
1518 * @param string $skin Skin name
1519 * @param string|null $user User name. If null, the &user= parameter is omitted
1520 * @param string|null $version Versioning timestamp
1521 * @param bool $debug Whether the request should be in debug mode
1522 * @param string|null $only &only= parameter
1523 * @param bool $printable Printable mode
1524 * @param bool $handheld Handheld mode
1525 * @param array $extraQuery Extra query parameters to add
1526 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1528 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1529 $version = null, $debug = false, $only = null, $printable = false,
1530 $handheld = false, $extraQuery = array()
1532 global $wgLoadScript;
1534 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1535 $only, $printable, $handheld, $extraQuery
1538 // Prevent the IE6 extension check from being triggered (bug 28840)
1539 // by appending a character that's invalid in Windows extensions ('*')
1540 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1544 * Helper for createLoaderURL()
1547 * @see makeLoaderQuery
1548 * @param ResourceLoaderContext $context
1549 * @param array $extraQuery
1552 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1553 return self
::makeLoaderQuery(
1554 $context->getModules(),
1555 $context->getLanguage(),
1556 $context->getSkin(),
1557 $context->getUser(),
1558 $context->getVersion(),
1559 $context->getDebug(),
1560 $context->getOnly(),
1561 $context->getRequest()->getBool( 'printable' ),
1562 $context->getRequest()->getBool( 'handheld' ),
1568 * Build a query array (array representation of query string) for load.php. Helper
1569 * function for makeLoaderURL().
1571 * @param array $modules
1572 * @param string $lang
1573 * @param string $skin
1574 * @param string $user
1575 * @param string $version
1576 * @param bool $debug
1577 * @param string $only
1578 * @param bool $printable
1579 * @param bool $handheld
1580 * @param array $extraQuery
1584 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1585 $version = null, $debug = false, $only = null, $printable = false,
1586 $handheld = false, $extraQuery = array()
1589 'modules' => self
::makePackedModulesString( $modules ),
1592 'debug' => $debug ?
'true' : 'false',
1594 if ( $user !== null ) {
1595 $query['user'] = $user;
1597 if ( $version !== null ) {
1598 $query['version'] = $version;
1600 if ( $only !== null ) {
1601 $query['only'] = $only;
1604 $query['printable'] = 1;
1607 $query['handheld'] = 1;
1609 $query +
= $extraQuery;
1611 // Make queries uniform in order
1617 * Check a module name for validity.
1619 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1620 * at most 255 bytes.
1622 * @param string $moduleName Module name to check
1623 * @return bool Whether $moduleName is a valid module name
1625 public static function isValidModuleName( $moduleName ) {
1626 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1630 * Returns LESS compiler set up for use with MediaWiki
1632 * @param Config $config
1633 * @throws MWException
1637 public static function getLessCompiler( Config
$config ) {
1638 // When called from the installer, it is possible that a required PHP extension
1639 // is missing (at least for now; see bug 47564). If this is the case, throw an
1640 // exception (caught by the installer) to prevent a fatal error later on.
1641 if ( !class_exists( 'lessc' ) ) {
1642 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1644 if ( !function_exists( 'ctype_digit' ) ) {
1645 throw new MWException( 'lessc requires the Ctype extension' );
1648 $less = new lessc();
1649 $less->setPreserveComments( true );
1650 $less->setVariables( self
::getLessVars( $config ) );
1651 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1652 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1653 $less->registerFunction( $name, $func );
1659 * Get global LESS variables.
1661 * @param Config $config
1663 * @return array Map of variable names to string CSS values.
1665 public static function getLessVars( Config
$config ) {
1666 if ( !self
::$lessVars ) {
1667 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1668 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1669 // Sort by key to ensure consistent hashing for cache lookups.
1671 self
::$lessVars = $lessVars;
1673 return self
::$lessVars;