Merge "Support GENDER in MediaWiki:Blockip and Special:Block"
[mediawiki.git] / includes / resourceloader / ResourceLoader.php
blob354264c700050add6cb6550341413964c5b771e8
1 <?php
2 /**
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
20 * @file
21 * @author Roan Kattouw
22 * @author Trevor Parscal
25 /**
26 * Dynamic JavaScript and CSS resource loading system.
28 * Most of the documentation is on the MediaWiki documentation wiki starting at:
29 * https://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader {
32 /** @var int */
33 protected static $filterCacheVersion = 7;
35 /** @var array */
36 protected static $requiredSourceProperties = array( 'loadScript' );
38 /** @var bool */
39 protected static $debugMode = null;
41 /** @var array Module name/ResourceLoaderModule object pairs */
42 protected $modules = array();
44 /** @var array Associative array mapping module name to info associative array */
45 protected $moduleInfos = array();
47 /** @var Config $config */
48 private $config;
50 /**
51 * @var array Associative array mapping framework ids to a list of names of test suite modules
52 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
54 protected $testModuleNames = array();
56 /** @var array E.g. array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) */
57 protected $sources = array();
59 /** @var bool */
60 protected $hasErrors = false;
62 /**
63 * Load information stored in the database about modules.
65 * This method grabs modules dependencies from the database and updates modules
66 * objects.
68 * This is not inside the module code because it is much faster to
69 * request all of the information at once than it is to have each module
70 * requests its own information. This sacrifice of modularity yields a substantial
71 * performance improvement.
73 * @param array $modules List of module names to preload information for
74 * @param ResourceLoaderContext $context Context to load the information within
76 public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
77 if ( !count( $modules ) ) {
78 // Or else Database*::select() will explode, plus it's cheaper!
79 return;
81 $dbr = wfGetDB( DB_SLAVE );
82 $skin = $context->getSkin();
83 $lang = $context->getLanguage();
85 // Get file dependency information
86 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
87 'md_module' => $modules,
88 'md_skin' => $skin
89 ), __METHOD__
92 // Set modules' dependencies
93 $modulesWithDeps = array();
94 foreach ( $res as $row ) {
95 $module = $this->getModule( $row->md_module );
96 if ( $module ) {
97 $module->setFileDependencies( $skin, FormatJson::decode( $row->md_deps, true ) );
98 $modulesWithDeps[] = $row->md_module;
102 // Register the absence of a dependency row too
103 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
104 $module = $this->getModule( $name );
105 if ( $module ) {
106 $this->getModule( $name )->setFileDependencies( $skin, array() );
110 // Get message blob mtimes. Only do this for modules with messages
111 $modulesWithMessages = array();
112 foreach ( $modules as $name ) {
113 $module = $this->getModule( $name );
114 if ( $module && count( $module->getMessages() ) ) {
115 $modulesWithMessages[] = $name;
118 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
119 if ( count( $modulesWithMessages ) ) {
120 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
121 'mr_resource' => $modulesWithMessages,
122 'mr_lang' => $lang
123 ), __METHOD__
125 foreach ( $res as $row ) {
126 $module = $this->getModule( $row->mr_resource );
127 if ( $module ) {
128 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX, $row->mr_timestamp ) );
129 unset( $modulesWithoutMessages[$row->mr_resource] );
133 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
134 $module = $this->getModule( $name );
135 if ( $module ) {
136 $module->setMsgBlobMtime( $lang, 0 );
142 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
144 * Available filters are:
146 * - minify-js \see JavaScriptMinifier::minify
147 * - minify-css \see CSSMin::minify
149 * If $data is empty, only contains whitespace or the filter was unknown,
150 * $data is returned unmodified.
152 * @param string $filter Name of filter to run
153 * @param string $data Text to filter, such as JavaScript or CSS text
154 * @param string $cacheReport Whether to include the cache key report
155 * @return string Filtered data, or a comment containing an error message
157 public function filter( $filter, $data, $cacheReport = true ) {
158 wfProfileIn( __METHOD__ );
160 // For empty/whitespace-only data or for unknown filters, don't perform
161 // any caching or processing
162 if ( trim( $data ) === '' || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
163 wfProfileOut( __METHOD__ );
164 return $data;
167 // Try for cache hit
168 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
169 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self::$filterCacheVersion, md5( $data ) );
170 $cache = wfGetCache( CACHE_ANYTHING );
171 $cacheEntry = $cache->get( $key );
172 if ( is_string( $cacheEntry ) ) {
173 wfIncrStats( "rl-$filter-cache-hits" );
174 wfProfileOut( __METHOD__ );
175 return $cacheEntry;
178 $result = '';
179 // Run the filter - we've already verified one of these will work
180 try {
181 wfIncrStats( "rl-$filter-cache-misses" );
182 switch ( $filter ) {
183 case 'minify-js':
184 $result = JavaScriptMinifier::minify( $data,
185 $this->config->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
186 $this->config->get( 'ResourceLoaderMinifierMaxLineLength' )
188 if ( $cacheReport ) {
189 $result .= "\n/* cache key: $key */";
191 break;
192 case 'minify-css':
193 $result = CSSMin::minify( $data );
194 if ( $cacheReport ) {
195 $result .= "\n/* cache key: $key */";
197 break;
200 // Save filtered text to Memcached
201 $cache->set( $key, $result );
202 } catch ( Exception $e ) {
203 MWExceptionHandler::logException( $e );
204 wfDebugLog( 'resourceloader', __METHOD__ . ": minification failed: $e" );
205 $this->hasErrors = true;
206 // Return exception as a comment
207 $result = self::formatException( $e );
210 wfProfileOut( __METHOD__ );
212 return $result;
215 /* Methods */
218 * Register core modules and runs registration hooks.
220 public function __construct( Config $config = null ) {
221 global $IP;
223 wfProfileIn( __METHOD__ );
225 if ( $config === null ) {
226 wfDebug( __METHOD__ . ' was called without providing a Config instance' );
227 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
230 $this->config = $config;
232 // Add 'local' source first
233 $this->addSource(
234 'local',
235 array( 'loadScript' => wfScript( 'load' ), 'apiScript' => wfScript( 'api' ) )
238 // Add other sources
239 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
241 // Register core modules
242 $this->register( include "$IP/resources/Resources.php" );
243 // Register extension modules
244 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
245 $this->register( $config->get( 'ResourceModules' ) );
247 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
248 $this->registerTestModules();
251 wfProfileOut( __METHOD__ );
255 * @return Config
257 public function getConfig() {
258 return $this->config;
262 * Register a module with the ResourceLoader system.
264 * @param mixed $name Name of module as a string or List of name/object pairs as an array
265 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
266 * this may also be a ResourceLoaderModule object. Optional when using
267 * multiple-registration calling style.
268 * @throws MWException If a duplicate module registration is attempted
269 * @throws MWException If a module name contains illegal characters (pipes or commas)
270 * @throws MWException If something other than a ResourceLoaderModule is being registered
271 * @return bool False if there were any errors, in which case one or more modules were
272 * not registered
274 public function register( $name, $info = null ) {
275 wfProfileIn( __METHOD__ );
277 // Allow multiple modules to be registered in one call
278 $registrations = is_array( $name ) ? $name : array( $name => $info );
279 foreach ( $registrations as $name => $info ) {
280 // Disallow duplicate registrations
281 if ( isset( $this->moduleInfos[$name] ) ) {
282 wfProfileOut( __METHOD__ );
283 // A module has already been registered by this name
284 throw new MWException(
285 'ResourceLoader duplicate registration error. ' .
286 'Another module has already been registered as ' . $name
290 // Check $name for validity
291 if ( !self::isValidModuleName( $name ) ) {
292 wfProfileOut( __METHOD__ );
293 throw new MWException( "ResourceLoader module name '$name' is invalid, "
294 . "see ResourceLoader::isValidModuleName()" );
297 // Attach module
298 if ( $info instanceof ResourceLoaderModule ) {
299 $this->moduleInfos[$name] = array( 'object' => $info );
300 $info->setName( $name );
301 $this->modules[$name] = $info;
302 } elseif ( is_array( $info ) ) {
303 // New calling convention
304 $this->moduleInfos[$name] = $info;
305 } else {
306 wfProfileOut( __METHOD__ );
307 throw new MWException(
308 'ResourceLoader module info type error for module \'' . $name .
309 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
313 // Last-minute changes
315 // Apply custom skin-defined styles to existing modules.
316 if ( $this->isFileModule( $name ) ) {
317 foreach ( $this->config->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
318 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
319 if ( isset( $this->moduleInfos[$name]['skinStyles'][$skinName] ) ) {
320 continue;
323 // If $name is preceded with a '+', the defined style files will be added to 'default'
324 // skinStyles, otherwise 'default' will be ignored as it normally would be.
325 if ( isset( $skinStyles[$name] ) ) {
326 $paths = (array)$skinStyles[$name];
327 $styleFiles = array();
328 } elseif ( isset( $skinStyles['+' . $name] ) ) {
329 $paths = (array)$skinStyles['+' . $name];
330 $styleFiles = isset( $this->moduleInfos[$name]['skinStyles']['default'] ) ?
331 $this->moduleInfos[$name]['skinStyles']['default'] :
332 array();
333 } else {
334 continue;
337 // Add new file paths, remapping them to refer to our directories and not use settings
338 // from the module we're modifying. These can come from the base definition or be defined
339 // for each module.
340 list( $localBasePath, $remoteBasePath ) =
341 ResourceLoaderFileModule::extractBasePaths( $skinStyles );
342 list( $localBasePath, $remoteBasePath ) =
343 ResourceLoaderFileModule::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
345 foreach ( $paths as $path ) {
346 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
349 $this->moduleInfos[$name]['skinStyles'][$skinName] = $styleFiles;
354 wfProfileOut( __METHOD__ );
359 public function registerTestModules() {
360 global $IP;
362 if ( $this->config->get( 'EnableJavaScriptTest' ) !== true ) {
363 throw new MWException( 'Attempt to register JavaScript test modules '
364 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
365 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
368 wfProfileIn( __METHOD__ );
370 // Get core test suites
371 $testModules = array();
372 $testModules['qunit'] = array();
373 // Get other test suites (e.g. from extensions)
374 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
376 // Add the testrunner (which configures QUnit) to the dependencies.
377 // Since it must be ready before any of the test suites are executed.
378 foreach ( $testModules['qunit'] as &$module ) {
379 // Make sure all test modules are top-loading so that when QUnit starts
380 // on document-ready, it will run once and finish. If some tests arrive
381 // later (possibly after QUnit has already finished) they will be ignored.
382 $module['position'] = 'top';
383 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
386 $testModules['qunit'] =
387 ( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules['qunit'];
389 foreach ( $testModules as $id => $names ) {
390 // Register test modules
391 $this->register( $testModules[$id] );
393 // Keep track of their names so that they can be loaded together
394 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
397 wfProfileOut( __METHOD__ );
401 * Add a foreign source of modules.
403 * Source properties:
404 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
406 * @param mixed $id Source ID (string), or array( id1 => props1, id2 => props2, ... )
407 * @param array $properties Source properties
408 * @throws MWException
410 public function addSource( $id, $properties = null ) {
411 // Allow multiple sources to be registered in one call
412 if ( is_array( $id ) ) {
413 foreach ( $id as $key => $value ) {
414 $this->addSource( $key, $value );
416 return;
419 // Disallow duplicates
420 if ( isset( $this->sources[$id] ) ) {
421 throw new MWException(
422 'ResourceLoader duplicate source addition error. ' .
423 'Another source has already been registered as ' . $id
427 // Validate properties
428 foreach ( self::$requiredSourceProperties as $prop ) {
429 if ( !isset( $properties[$prop] ) ) {
430 throw new MWException( "Required property $prop missing from source ID $id" );
434 $this->sources[$id] = $properties;
438 * Get a list of module names.
440 * @return array List of module names
442 public function getModuleNames() {
443 return array_keys( $this->moduleInfos );
447 * Get a list of test module names for one (or all) frameworks.
449 * If the given framework id is unknkown, or if the in-object variable is not an array,
450 * then it will return an empty array.
452 * @param string $framework Get only the test module names for one
453 * particular framework (optional)
454 * @return array
456 public function getTestModuleNames( $framework = 'all' ) {
457 /** @todo api siteinfo prop testmodulenames modulenames */
458 if ( $framework == 'all' ) {
459 return $this->testModuleNames;
460 } elseif ( isset( $this->testModuleNames[$framework] )
461 && is_array( $this->testModuleNames[$framework] )
463 return $this->testModuleNames[$framework];
464 } else {
465 return array();
470 * Get the ResourceLoaderModule object for a given module name.
472 * If an array of module parameters exists but a ResourceLoaderModule object has not
473 * yet been instantiated, this method will instantiate and cache that object such that
474 * subsequent calls simply return the same object.
476 * @param string $name Module name
477 * @return ResourceLoaderModule|null If module has been registered, return a
478 * ResourceLoaderModule instance. Otherwise, return null.
480 public function getModule( $name ) {
481 if ( !isset( $this->modules[$name] ) ) {
482 if ( !isset( $this->moduleInfos[$name] ) ) {
483 // No such module
484 return null;
486 // Construct the requested object
487 $info = $this->moduleInfos[$name];
488 /** @var ResourceLoaderModule $object */
489 if ( isset( $info['object'] ) ) {
490 // Object given in info array
491 $object = $info['object'];
492 } else {
493 if ( !isset( $info['class'] ) ) {
494 $class = 'ResourceLoaderFileModule';
495 } else {
496 $class = $info['class'];
498 /** @var ResourceLoaderModule $object */
499 $object = new $class( $info );
500 $object->setConfig( $this->getConfig() );
502 $object->setName( $name );
503 $this->modules[$name] = $object;
506 return $this->modules[$name];
510 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
512 * @param string $name Module name
513 * @return bool
515 protected function isFileModule( $name ) {
516 if ( !isset( $this->moduleInfos[$name] ) ) {
517 return false;
519 $info = $this->moduleInfos[$name];
520 if ( isset( $info['object'] ) || isset( $info['class'] ) ) {
521 return false;
523 return true;
527 * Get the list of sources.
529 * @return array Like array( id => array of properties, .. )
531 public function getSources() {
532 return $this->sources;
536 * Get the URL to the load.php endpoint for the given
537 * ResourceLoader source
539 * @since 1.24
540 * @param string $source
541 * @throws MWException On an invalid $source name
542 * @return string
544 public function getLoadScript( $source ) {
545 if ( !isset( $this->sources[$source] ) ) {
546 throw new MWException( "The $source source was never registered in ResourceLoader." );
548 return $this->sources[$source]['loadScript'];
552 * Output a response to a load request, including the content-type header.
554 * @param ResourceLoaderContext $context Context in which a response should be formed
556 public function respond( ResourceLoaderContext $context ) {
557 // Use file cache if enabled and available...
558 if ( $this->config->get( 'UseFileCache' ) ) {
559 $fileCache = ResourceFileCache::newFromContext( $context );
560 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
561 return; // output handled
565 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
566 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
567 // is used: ob_clean() will clear the GZIP header in that case and it won't come
568 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
569 // the whole thing in our own output buffer to be sure the active buffer
570 // doesn't use ob_gzhandler.
571 // See http://bugs.php.net/bug.php?id=36514
572 ob_start();
574 wfProfileIn( __METHOD__ );
575 $errors = '';
577 // Find out which modules are missing and instantiate the others
578 $modules = array();
579 $missing = array();
580 foreach ( $context->getModules() as $name ) {
581 $module = $this->getModule( $name );
582 if ( $module ) {
583 // Do not allow private modules to be loaded from the web.
584 // This is a security issue, see bug 34907.
585 if ( $module->getGroup() === 'private' ) {
586 wfDebugLog( 'resourceloader', __METHOD__ . ": request for private module '$name' denied" );
587 $this->hasErrors = true;
588 // Add exception to the output as a comment
589 $errors .= self::makeComment( "Cannot show private module \"$name\"" );
591 continue;
593 $modules[$name] = $module;
594 } else {
595 $missing[] = $name;
599 // Preload information needed to the mtime calculation below
600 try {
601 $this->preloadModuleInfo( array_keys( $modules ), $context );
602 } catch ( Exception $e ) {
603 MWExceptionHandler::logException( $e );
604 wfDebugLog( 'resourceloader', __METHOD__ . ": preloading module info failed: $e" );
605 $this->hasErrors = true;
606 // Add exception to the output as a comment
607 $errors .= self::formatException( $e );
610 wfProfileIn( __METHOD__ . '-getModifiedTime' );
612 // To send Last-Modified and support If-Modified-Since, we need to detect
613 // the last modified time
614 $mtime = wfTimestamp( TS_UNIX, $this->config->get( 'CacheEpoch' ) );
615 foreach ( $modules as $module ) {
617 * @var $module ResourceLoaderModule
619 try {
620 // Calculate maximum modified time
621 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
622 } catch ( Exception $e ) {
623 MWExceptionHandler::logException( $e );
624 wfDebugLog( 'resourceloader', __METHOD__ . ": calculating maximum modified time failed: $e" );
625 $this->hasErrors = true;
626 // Add exception to the output as a comment
627 $errors .= self::formatException( $e );
631 wfProfileOut( __METHOD__ . '-getModifiedTime' );
633 // If there's an If-Modified-Since header, respond with a 304 appropriately
634 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
635 wfProfileOut( __METHOD__ );
636 return; // output handled (buffers cleared)
639 // Generate a response
640 $response = $this->makeModuleResponse( $context, $modules, $missing );
642 // Prepend comments indicating exceptions
643 $response = $errors . $response;
645 // Capture any PHP warnings from the output buffer and append them to the
646 // response in a comment if we're in debug mode.
647 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
648 $response = self::makeComment( $warnings ) . $response;
649 $this->hasErrors = true;
652 // Save response to file cache unless there are errors
653 if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
654 // Cache single modules...and other requests if there are enough hits
655 if ( ResourceFileCache::useFileCache( $context ) ) {
656 if ( $fileCache->isCacheWorthy() ) {
657 $fileCache->saveText( $response );
658 } else {
659 $fileCache->incrMissesRecent( $context->getRequest() );
664 // Send content type and cache related headers
665 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors );
667 // Remove the output buffer and output the response
668 ob_end_clean();
669 echo $response;
671 wfProfileOut( __METHOD__ );
675 * Send content type and last modified headers to the client.
676 * @param ResourceLoaderContext $context
677 * @param string $mtime TS_MW timestamp to use for last-modified
678 * @param bool $errors Whether there are commented-out errors in the response
679 * @return void
681 protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $errors ) {
682 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
683 // If a version wasn't specified we need a shorter expiry time for updates
684 // to propagate to clients quickly
685 // If there were errors, we also need a shorter expiry time so we can recover quickly
686 if ( is_null( $context->getVersion() ) || $errors ) {
687 $maxage = $rlMaxage['unversioned']['client'];
688 $smaxage = $rlMaxage['unversioned']['server'];
689 // If a version was specified we can use a longer expiry time since changing
690 // version numbers causes cache misses
691 } else {
692 $maxage = $rlMaxage['versioned']['client'];
693 $smaxage = $rlMaxage['versioned']['server'];
695 if ( $context->getOnly() === 'styles' ) {
696 header( 'Content-Type: text/css; charset=utf-8' );
697 header( 'Access-Control-Allow-Origin: *' );
698 } else {
699 header( 'Content-Type: text/javascript; charset=utf-8' );
701 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
702 if ( $context->getDebug() ) {
703 // Do not cache debug responses
704 header( 'Cache-Control: private, no-cache, must-revalidate' );
705 header( 'Pragma: no-cache' );
706 } else {
707 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
708 $exp = min( $maxage, $smaxage );
709 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
714 * Respond with 304 Last Modified if appropiate.
716 * If there's an If-Modified-Since header, respond with a 304 appropriately
717 * and clear out the output buffer. If the client cache is too old then do nothing.
719 * @param ResourceLoaderContext $context
720 * @param string $mtime The TS_MW timestamp to check the header against
721 * @return bool True if 304 header sent and output handled
723 protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) {
724 // If there's an If-Modified-Since header, respond with a 304 appropriately
725 // Some clients send "timestamp;length=123". Strip the part after the first ';'
726 // so we get a valid timestamp.
727 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
728 // Never send 304s in debug mode
729 if ( $ims !== false && !$context->getDebug() ) {
730 $imsTS = strtok( $ims, ';' );
731 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
732 // There's another bug in ob_gzhandler (see also the comment at
733 // the top of this function) that causes it to gzip even empty
734 // responses, meaning it's impossible to produce a truly empty
735 // response (because the gzip header is always there). This is
736 // a problem because 304 responses have to be completely empty
737 // per the HTTP spec, and Firefox behaves buggily when they're not.
738 // See also http://bugs.php.net/bug.php?id=51579
739 // To work around this, we tear down all output buffering before
740 // sending the 304.
741 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
743 header( 'HTTP/1.0 304 Not Modified' );
744 header( 'Status: 304 Not Modified' );
745 return true;
748 return false;
752 * Send out code for a response from file cache if possible.
754 * @param ResourceFileCache $fileCache Cache object for this request URL
755 * @param ResourceLoaderContext $context Context in which to generate a response
756 * @return bool If this found a cache file and handled the response
758 protected function tryRespondFromFileCache(
759 ResourceFileCache $fileCache, ResourceLoaderContext $context
761 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
762 // Buffer output to catch warnings.
763 ob_start();
764 // Get the maximum age the cache can be
765 $maxage = is_null( $context->getVersion() )
766 ? $rlMaxage['unversioned']['server']
767 : $rlMaxage['versioned']['server'];
768 // Minimum timestamp the cache file must have
769 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
770 if ( !$good ) {
771 try { // RL always hits the DB on file cache miss...
772 wfGetDB( DB_SLAVE );
773 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
774 $good = $fileCache->isCacheGood(); // cache existence check
777 if ( $good ) {
778 $ts = $fileCache->cacheTimestamp();
779 // Send content type and cache headers
780 $this->sendResponseHeaders( $context, $ts, false );
781 // If there's an If-Modified-Since header, respond with a 304 appropriately
782 if ( $this->tryRespondLastModified( $context, $ts ) ) {
783 return false; // output handled (buffers cleared)
785 $response = $fileCache->fetchText();
786 // Capture any PHP warnings from the output buffer and append them to the
787 // response in a comment if we're in debug mode.
788 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
789 $response = "/*\n$warnings\n*/\n" . $response;
791 // Remove the output buffer and output the response
792 ob_end_clean();
793 echo $response . "\n/* Cached {$ts} */";
794 return true; // cache hit
796 // Clear buffer
797 ob_end_clean();
799 return false; // cache miss
803 * Generate a CSS or JS comment block.
805 * Only use this for public data, not error message details.
807 * @param string $text
808 * @return string
810 public static function makeComment( $text ) {
811 $encText = str_replace( '*/', '* /', $text );
812 return "/*\n$encText\n*/\n";
816 * Handle exception display.
818 * @param Exception $e Exception to be shown to the user
819 * @return string Sanitized text that can be returned to the user
821 public static function formatException( $e ) {
822 global $wgShowExceptionDetails;
824 if ( $wgShowExceptionDetails ) {
825 return self::makeComment( $e->__toString() );
826 } else {
827 return self::makeComment( wfMessage( 'internalerror' )->text() );
832 * Generate code for a response.
834 * @param ResourceLoaderContext $context Context in which to generate a response
835 * @param array $modules List of module objects keyed by module name
836 * @param array $missing List of requested module names that are unregistered (optional)
837 * @return string Response data
839 public function makeModuleResponse( ResourceLoaderContext $context,
840 array $modules, array $missing = array()
842 $out = '';
843 $exceptions = '';
844 $states = array();
846 if ( !count( $modules ) && !count( $missing ) ) {
847 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
848 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
849 no modules were requested. Max made me put this here. */";
852 wfProfileIn( __METHOD__ );
854 // Pre-fetch blobs
855 if ( $context->shouldIncludeMessages() ) {
856 try {
857 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
858 } catch ( Exception $e ) {
859 MWExceptionHandler::logException( $e );
860 wfDebugLog(
861 'resourceloader',
862 __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e"
864 $this->hasErrors = true;
865 // Add exception to the output as a comment
866 $exceptions .= self::formatException( $e );
868 } else {
869 $blobs = array();
872 foreach ( $missing as $name ) {
873 $states[$name] = 'missing';
876 // Generate output
877 $isRaw = false;
878 foreach ( $modules as $name => $module ) {
880 * @var $module ResourceLoaderModule
883 wfProfileIn( __METHOD__ . '-' . $name );
884 try {
885 $scripts = '';
886 if ( $context->shouldIncludeScripts() ) {
887 // If we are in debug mode, we'll want to return an array of URLs if possible
888 // However, we can't do this if the module doesn't support it
889 // We also can't do this if there is an only= parameter, because we have to give
890 // the module a way to return a load.php URL without causing an infinite loop
891 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
892 $scripts = $module->getScriptURLsForDebug( $context );
893 } else {
894 $scripts = $module->getScript( $context );
895 // rtrim() because there are usually a few line breaks
896 // after the last ';'. A new line at EOF, a new line
897 // added by ResourceLoaderFileModule::readScriptFiles, etc.
898 if ( is_string( $scripts )
899 && strlen( $scripts )
900 && substr( rtrim( $scripts ), -1 ) !== ';'
902 // Append semicolon to prevent weird bugs caused by files not
903 // terminating their statements right (bug 27054)
904 $scripts .= ";\n";
908 // Styles
909 $styles = array();
910 if ( $context->shouldIncludeStyles() ) {
911 // Don't create empty stylesheets like array( '' => '' ) for modules
912 // that don't *have* any stylesheets (bug 38024).
913 $stylePairs = $module->getStyles( $context );
914 if ( count( $stylePairs ) ) {
915 // If we are in debug mode without &only= set, we'll want to return an array of URLs
916 // See comment near shouldIncludeScripts() for more details
917 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
918 $styles = array(
919 'url' => $module->getStyleURLsForDebug( $context )
921 } else {
922 // Minify CSS before embedding in mw.loader.implement call
923 // (unless in debug mode)
924 if ( !$context->getDebug() ) {
925 foreach ( $stylePairs as $media => $style ) {
926 // Can be either a string or an array of strings.
927 if ( is_array( $style ) ) {
928 $stylePairs[$media] = array();
929 foreach ( $style as $cssText ) {
930 if ( is_string( $cssText ) ) {
931 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
934 } elseif ( is_string( $style ) ) {
935 $stylePairs[$media] = $this->filter( 'minify-css', $style );
939 // Wrap styles into @media groups as needed and flatten into a numerical array
940 $styles = array(
941 'css' => self::makeCombinedStyles( $stylePairs )
947 // Messages
948 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
950 // Append output
951 switch ( $context->getOnly() ) {
952 case 'scripts':
953 if ( is_string( $scripts ) ) {
954 // Load scripts raw...
955 $out .= $scripts;
956 } elseif ( is_array( $scripts ) ) {
957 // ...except when $scripts is an array of URLs
958 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
960 break;
961 case 'styles':
962 // We no longer seperate into media, they are all combined now with
963 // custom media type groups into @media .. {} sections as part of the css string.
964 // Module returns either an empty array or a numerical array with css strings.
965 $out .= isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
966 break;
967 case 'messages':
968 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
969 break;
970 default:
971 $out .= self::makeLoaderImplementScript(
972 $name,
973 $scripts,
974 $styles,
975 new XmlJsCode( $messagesBlob )
977 break;
979 } catch ( Exception $e ) {
980 MWExceptionHandler::logException( $e );
981 wfDebugLog( 'resourceloader', __METHOD__ . ": generating module package failed: $e" );
982 $this->hasErrors = true;
983 // Add exception to the output as a comment
984 $exceptions .= self::formatException( $e );
986 // Respond to client with error-state instead of module implementation
987 $states[$name] = 'error';
988 unset( $modules[$name] );
990 $isRaw |= $module->isRaw();
991 wfProfileOut( __METHOD__ . '-' . $name );
994 // Update module states
995 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
996 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
997 // Set the state of modules loaded as only scripts to ready as
998 // they don't have an mw.loader.implement wrapper that sets the state
999 foreach ( $modules as $name => $module ) {
1000 $states[$name] = 'ready';
1004 // Set the state of modules we didn't respond to with mw.loader.implement
1005 if ( count( $states ) ) {
1006 $out .= self::makeLoaderStateScript( $states );
1008 } else {
1009 if ( count( $states ) ) {
1010 $exceptions .= self::makeComment(
1011 'Problematic modules: ' . FormatJson::encode( $states, ResourceLoader::inDebugMode() )
1016 if ( !$context->getDebug() ) {
1017 if ( $context->getOnly() === 'styles' ) {
1018 $out = $this->filter( 'minify-css', $out );
1019 } else {
1020 $out = $this->filter( 'minify-js', $out );
1024 wfProfileOut( __METHOD__ );
1025 return $exceptions . $out;
1028 /* Static Methods */
1031 * Return JS code that calls mw.loader.implement with given module properties.
1033 * @param string $name Module name
1034 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1035 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1036 * to CSS files keyed by media type
1037 * @param mixed $messages List of messages associated with this module. May either be an
1038 * associative array mapping message key to value, or a JSON-encoded message blob containing
1039 * the same data, wrapped in an XmlJsCode object.
1040 * @throws MWException
1041 * @return string
1043 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
1044 if ( is_string( $scripts ) ) {
1045 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1046 } elseif ( !is_array( $scripts ) ) {
1047 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1049 return Xml::encodeJsCall(
1050 'mw.loader.implement',
1051 array(
1052 $name,
1053 $scripts,
1054 // Force objects. mw.loader.implement requires them to be javascript objects.
1055 // Although these variables are associative arrays, which become javascript
1056 // objects through json_encode. In many cases they will be empty arrays, and
1057 // PHP/json_encode() consider empty arrays to be numerical arrays and
1058 // output javascript "[]" instead of "{}". This fixes that.
1059 (object)$styles,
1060 (object)$messages
1062 ResourceLoader::inDebugMode()
1067 * Returns JS code which, when called, will register a given list of messages.
1069 * @param mixed $messages Either an associative array mapping message key to value, or a
1070 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1071 * @return string
1073 public static function makeMessageSetScript( $messages ) {
1074 return Xml::encodeJsCall(
1075 'mw.messages.set',
1076 array( (object)$messages ),
1077 ResourceLoader::inDebugMode()
1082 * Combines an associative array mapping media type to CSS into a
1083 * single stylesheet with "@media" blocks.
1085 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1086 * @return array
1088 public static function makeCombinedStyles( array $stylePairs ) {
1089 $out = array();
1090 foreach ( $stylePairs as $media => $styles ) {
1091 // ResourceLoaderFileModule::getStyle can return the styles
1092 // as a string or an array of strings. This is to allow separation in
1093 // the front-end.
1094 $styles = (array)$styles;
1095 foreach ( $styles as $style ) {
1096 $style = trim( $style );
1097 // Don't output an empty "@media print { }" block (bug 40498)
1098 if ( $style !== '' ) {
1099 // Transform the media type based on request params and config
1100 // The way that this relies on $wgRequest to propagate request params is slightly evil
1101 $media = OutputPage::transformCssMedia( $media );
1103 if ( $media === '' || $media == 'all' ) {
1104 $out[] = $style;
1105 } elseif ( is_string( $media ) ) {
1106 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1108 // else: skip
1112 return $out;
1116 * Returns a JS call to mw.loader.state, which sets the state of a
1117 * module or modules to a given value. Has two calling conventions:
1119 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1120 * Set the state of a single module called $name to $state
1122 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1123 * Set the state of modules with the given names to the given states
1125 * @param string $name
1126 * @param string $state
1127 * @return string
1129 public static function makeLoaderStateScript( $name, $state = null ) {
1130 if ( is_array( $name ) ) {
1131 return Xml::encodeJsCall(
1132 'mw.loader.state',
1133 array( $name ),
1134 ResourceLoader::inDebugMode()
1136 } else {
1137 return Xml::encodeJsCall(
1138 'mw.loader.state',
1139 array( $name, $state ),
1140 ResourceLoader::inDebugMode()
1146 * Returns JS code which calls the script given by $script. The script will
1147 * be called with local variables name, version, dependencies and group,
1148 * which will have values corresponding to $name, $version, $dependencies
1149 * and $group as supplied.
1151 * @param string $name Module name
1152 * @param int $version Module version number as a timestamp
1153 * @param array $dependencies List of module names on which this module depends
1154 * @param string $group Group which the module is in.
1155 * @param string $source Source of the module, or 'local' if not foreign.
1156 * @param string $script JavaScript code
1157 * @return string
1159 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1160 $group, $source, $script
1162 $script = str_replace( "\n", "\n\t", trim( $script ) );
1163 return Xml::encodeJsCall(
1164 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1165 array( $name, $version, $dependencies, $group, $source ),
1166 ResourceLoader::inDebugMode()
1171 * Returns JS code which calls mw.loader.register with the given
1172 * parameters. Has three calling conventions:
1174 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source, $skip ):
1175 * Register a single module.
1177 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1178 * Register modules with the given names.
1180 * - ResourceLoader::makeLoaderRegisterScript( array(
1181 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1182 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1183 * ...
1184 * ) ):
1185 * Registers modules with the given names and parameters.
1187 * @param string $name Module name
1188 * @param int $version Module version number as a timestamp
1189 * @param array $dependencies List of module names on which this module depends
1190 * @param string $group Group which the module is in
1191 * @param string $source Source of the module, or 'local' if not foreign
1192 * @param string $skip Script body of the skip function
1193 * @return string
1195 public static function makeLoaderRegisterScript( $name, $version = null,
1196 $dependencies = null, $group = null, $source = null, $skip = null
1198 if ( is_array( $name ) ) {
1199 return Xml::encodeJsCall(
1200 'mw.loader.register',
1201 array( $name ),
1202 ResourceLoader::inDebugMode()
1204 } else {
1205 $version = (int)$version > 1 ? (int)$version : 1;
1206 return Xml::encodeJsCall(
1207 'mw.loader.register',
1208 array( $name, $version, $dependencies, $group, $source, $skip ),
1209 ResourceLoader::inDebugMode()
1215 * Returns JS code which calls mw.loader.addSource() with the given
1216 * parameters. Has two calling conventions:
1218 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1219 * Register a single source
1221 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1222 * Register sources with the given IDs and properties.
1224 * @param string $id Source ID
1225 * @param array $properties Source properties (see addSource())
1226 * @return string
1228 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1229 if ( is_array( $id ) ) {
1230 return Xml::encodeJsCall(
1231 'mw.loader.addSource',
1232 array( $id ),
1233 ResourceLoader::inDebugMode()
1235 } else {
1236 return Xml::encodeJsCall(
1237 'mw.loader.addSource',
1238 array( $id, $properties ),
1239 ResourceLoader::inDebugMode()
1245 * Returns JS code which runs given JS code if the client-side framework is
1246 * present.
1248 * @param string $script JavaScript code
1249 * @return string
1251 public static function makeLoaderConditionalScript( $script ) {
1252 return "if(window.mw){\n" . trim( $script ) . "\n}";
1256 * Returns JS code which will set the MediaWiki configuration array to
1257 * the given value.
1259 * @param array $configuration List of configuration values keyed by variable name
1260 * @return string
1262 public static function makeConfigSetScript( array $configuration ) {
1263 return Xml::encodeJsCall(
1264 'mw.config.set',
1265 array( $configuration ),
1266 ResourceLoader::inDebugMode()
1271 * Convert an array of module names to a packed query string.
1273 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1274 * becomes 'foo.bar,baz|bar.baz,quux'
1275 * @param array $modules List of module names (strings)
1276 * @return string Packed query string
1278 public static function makePackedModulesString( $modules ) {
1279 $groups = array(); // array( prefix => array( suffixes ) )
1280 foreach ( $modules as $module ) {
1281 $pos = strrpos( $module, '.' );
1282 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1283 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1284 $groups[$prefix][] = $suffix;
1287 $arr = array();
1288 foreach ( $groups as $prefix => $suffixes ) {
1289 $p = $prefix === '' ? '' : $prefix . '.';
1290 $arr[] = $p . implode( ',', $suffixes );
1292 $str = implode( '|', $arr );
1293 return $str;
1297 * Determine whether debug mode was requested
1298 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1299 * @return bool
1301 public static function inDebugMode() {
1302 if ( self::$debugMode === null ) {
1303 global $wgRequest, $wgResourceLoaderDebug;
1304 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1305 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1308 return self::$debugMode;
1312 * Reset static members used for caching.
1314 * Global state and $wgRequest are evil, but we're using it right
1315 * now and sometimes we need to be able to force ResourceLoader to
1316 * re-evaluate the context because it has changed (e.g. in the test suite).
1318 public static function clearCache() {
1319 self::$debugMode = null;
1323 * Build a load.php URL
1325 * @since 1.24
1326 * @param string $source Name of the ResourceLoader source
1327 * @param ResourceLoaderContext $context
1328 * @param array $extraQuery
1329 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1331 public function createLoaderURL( $source, ResourceLoaderContext $context,
1332 $extraQuery = array()
1334 $query = self::createLoaderQuery( $context, $extraQuery );
1335 $script = $this->getLoadScript( $source );
1337 // Prevent the IE6 extension check from being triggered (bug 28840)
1338 // by appending a character that's invalid in Windows extensions ('*')
1339 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE );
1343 * Build a load.php URL
1344 * @deprecated since 1.24, use createLoaderURL instead
1345 * @param array $modules Array of module names (strings)
1346 * @param string $lang Language code
1347 * @param string $skin Skin name
1348 * @param string|null $user User name. If null, the &user= parameter is omitted
1349 * @param string|null $version Versioning timestamp
1350 * @param bool $debug Whether the request should be in debug mode
1351 * @param string|null $only &only= parameter
1352 * @param bool $printable Printable mode
1353 * @param bool $handheld Handheld mode
1354 * @param array $extraQuery Extra query parameters to add
1355 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1357 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1358 $version = null, $debug = false, $only = null, $printable = false,
1359 $handheld = false, $extraQuery = array()
1361 global $wgLoadScript;
1363 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1364 $only, $printable, $handheld, $extraQuery
1367 // Prevent the IE6 extension check from being triggered (bug 28840)
1368 // by appending a character that's invalid in Windows extensions ('*')
1369 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
1373 * Helper for createLoaderURL()
1375 * @since 1.24
1376 * @see makeLoaderQuery
1377 * @param ResourceLoaderContext $context
1378 * @param array $extraQuery
1379 * @return array
1381 public static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = array() ) {
1382 return self::makeLoaderQuery(
1383 $context->getModules(),
1384 $context->getLanguage(),
1385 $context->getSkin(),
1386 $context->getUser(),
1387 $context->getVersion(),
1388 $context->getDebug(),
1389 $context->getOnly(),
1390 $context->getRequest()->getBool( 'printable' ),
1391 $context->getRequest()->getBool( 'handheld' ),
1392 $extraQuery
1397 * Build a query array (array representation of query string) for load.php. Helper
1398 * function for makeLoaderURL().
1400 * @param array $modules
1401 * @param string $lang
1402 * @param string $skin
1403 * @param string $user
1404 * @param string $version
1405 * @param bool $debug
1406 * @param string $only
1407 * @param bool $printable
1408 * @param bool $handheld
1409 * @param array $extraQuery
1411 * @return array
1413 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1414 $version = null, $debug = false, $only = null, $printable = false,
1415 $handheld = false, $extraQuery = array()
1417 $query = array(
1418 'modules' => self::makePackedModulesString( $modules ),
1419 'lang' => $lang,
1420 'skin' => $skin,
1421 'debug' => $debug ? 'true' : 'false',
1423 if ( $user !== null ) {
1424 $query['user'] = $user;
1426 if ( $version !== null ) {
1427 $query['version'] = $version;
1429 if ( $only !== null ) {
1430 $query['only'] = $only;
1432 if ( $printable ) {
1433 $query['printable'] = 1;
1435 if ( $handheld ) {
1436 $query['handheld'] = 1;
1438 $query += $extraQuery;
1440 // Make queries uniform in order
1441 ksort( $query );
1442 return $query;
1446 * Check a module name for validity.
1448 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1449 * at most 255 bytes.
1451 * @param string $moduleName Module name to check
1452 * @return bool Whether $moduleName is a valid module name
1454 public static function isValidModuleName( $moduleName ) {
1455 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1459 * Returns LESS compiler set up for use with MediaWiki
1461 * @param Config $config
1462 * @throws MWException
1463 * @since 1.22
1464 * @return lessc
1466 public static function getLessCompiler( Config $config ) {
1467 // When called from the installer, it is possible that a required PHP extension
1468 // is missing (at least for now; see bug 47564). If this is the case, throw an
1469 // exception (caught by the installer) to prevent a fatal error later on.
1470 if ( !function_exists( 'ctype_digit' ) ) {
1471 throw new MWException( 'lessc requires the Ctype extension' );
1474 $less = new lessc();
1475 $less->setPreserveComments( true );
1476 $less->setVariables( self::getLESSVars( $config ) );
1477 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1478 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1479 $less->registerFunction( $name, $func );
1481 return $less;
1485 * Get global LESS variables.
1487 * @param Config $config
1488 * @since 1.22
1489 * @return array Map of variable names to string CSS values.
1491 public static function getLESSVars( Config $config ) {
1492 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1493 // Sort by key to ensure consistent hashing for cache lookups.
1494 ksort( $lessVars );
1495 return $lessVars;