wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / resourceloader / ResourceLoader.php
blob1f3085aa9fba964afcffb575fbc10fe1071ee967
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 use Psr\Log\LoggerAwareInterface;
26 use Psr\Log\LoggerInterface;
27 use Psr\Log\NullLogger;
28 use WrappedString\WrappedString;
30 /**
31 * Dynamic JavaScript and CSS resource loading system.
33 * Most of the documentation is on the MediaWiki documentation wiki starting at:
34 * https://www.mediawiki.org/wiki/ResourceLoader
36 class ResourceLoader implements LoggerAwareInterface {
37 /** @var int */
38 protected static $filterCacheVersion = 7;
40 /** @var bool */
41 protected static $debugMode = null;
43 /** @var array */
44 private static $lessVars = null;
46 /**
47 * Module name/ResourceLoaderModule object pairs
48 * @var array
50 protected $modules = array();
52 /**
53 * Associative array mapping module name to info associative array
54 * @var array
56 protected $moduleInfos = array();
58 /** @var Config $config */
59 private $config;
61 /**
62 * Associative array mapping framework ids to a list of names of test suite modules
63 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
64 * @var array
66 protected $testModuleNames = array();
68 /**
69 * E.g. array( 'source-id' => 'http://.../load.php' )
70 * @var array
72 protected $sources = array();
74 /**
75 * Errors accumulated during current respond() call.
76 * @var array
78 protected $errors = array();
80 /**
81 * @var MessageBlobStore
83 protected $blobStore;
85 /**
86 * @var LoggerInterface
88 private $logger;
90 /** @var string JavaScript / CSS pragma to disable minification. **/
91 const FILTER_NOMIN = ' /* @nomin */ ';
93 /**
94 * Load information stored in the database about modules.
96 * This method grabs modules dependencies from the database and updates modules
97 * objects.
99 * This is not inside the module code because it is much faster to
100 * request all of the information at once than it is to have each module
101 * requests its own information. This sacrifice of modularity yields a substantial
102 * performance improvement.
104 * @param array $moduleNames List of module names to preload information for
105 * @param ResourceLoaderContext $context Context to load the information within
107 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext $context ) {
108 if ( !$moduleNames ) {
109 // Or else Database*::select() will explode, plus it's cheaper!
110 return;
112 $dbr = wfGetDB( DB_SLAVE );
113 $skin = $context->getSkin();
114 $lang = $context->getLanguage();
116 // Batched version of ResourceLoaderModule::getFileDependencies
117 $vary = "$skin|$lang";
118 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
119 'md_module' => $moduleNames,
120 'md_skin' => $vary,
121 ), __METHOD__
124 // Prime in-object cache for file dependencies
125 $modulesWithDeps = array();
126 foreach ( $res as $row ) {
127 $module = $this->getModule( $row->md_module );
128 if ( $module ) {
129 $module->setFileDependencies( $context, ResourceLoaderModule::expandRelativePaths(
130 FormatJson::decode( $row->md_deps, true )
131 ) );
132 $modulesWithDeps[] = $row->md_module;
135 // Register the absence of a dependency row too
136 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
137 $module = $this->getModule( $name );
138 if ( $module ) {
139 $this->getModule( $name )->setFileDependencies( $context, array() );
143 // Prime in-object cache for message blobs for modules with messages
144 $modules = array();
145 foreach ( $moduleNames as $name ) {
146 $module = $this->getModule( $name );
147 if ( $module && $module->getMessages() ) {
148 $modules[$name] = $module;
151 $store = $this->getMessageBlobStore();
152 $blobs = $store->getBlobs( $modules, $lang );
153 foreach ( $blobs as $name => $blob ) {
154 $modules[$name]->setMessageBlob( $blob, $lang );
159 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
161 * Available filters are:
163 * - minify-js \see JavaScriptMinifier::minify
164 * - minify-css \see CSSMin::minify
166 * If $data is empty, only contains whitespace or the filter was unknown,
167 * $data is returned unmodified.
169 * @param string $filter Name of filter to run
170 * @param string $data Text to filter, such as JavaScript or CSS text
171 * @param array $options Keys:
172 * - (bool) cache: Whether to allow caching this data. Default: true.
173 * @return string Filtered data, or a comment containing an error message
175 public static function filter( $filter, $data, Array $options = array() ) {
176 if ( strpos( $data, ResourceLoader::FILTER_NOMIN ) !== false ) {
177 return $data;
180 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
181 return self::applyFilter( $filter, $data );
184 $stats = RequestContext::getMain()->getStats();
185 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
187 $key = $cache->makeGlobalKey(
188 'resourceloader',
189 'filter',
190 $filter,
191 self::$filterCacheVersion, md5( $data )
194 $result = $cache->get( $key );
195 if ( $result === false ) {
196 $stats->increment( "resourceloader_cache.$filter.miss" );
197 $result = self::applyFilter( $filter, $data );
198 $cache->set( $key, $result, 24 * 3600 );
199 } else {
200 $stats->increment( "resourceloader_cache.$filter.hit" );
202 if ( $result === null ) {
203 // Cached failure
204 $result = $data;
207 return $result;
210 private static function applyFilter( $filter, $data ) {
211 $data = trim( $data );
212 if ( $data ) {
213 try {
214 $data = ( $filter === 'minify-css' )
215 ? CSSMin::minify( $data )
216 : JavaScriptMinifier::minify( $data );
217 } catch ( Exception $e ) {
218 MWExceptionHandler::logException( $e );
219 return null;
222 return $data;
225 /* Methods */
228 * Register core modules and runs registration hooks.
229 * @param Config $config [optional]
230 * @param LoggerInterface $logger [optional]
232 public function __construct( Config $config = null, LoggerInterface $logger = null ) {
233 global $IP;
235 $this->logger = $logger ?: new NullLogger();
237 if ( !$config ) {
238 $this->logger->debug( __METHOD__ . ' was called without providing a Config instance' );
239 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
241 $this->config = $config;
243 // Add 'local' source first
244 $this->addSource( 'local', wfScript( 'load' ) );
246 // Add other sources
247 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
249 // Register core modules
250 $this->register( include "$IP/resources/Resources.php" );
251 $this->register( include "$IP/resources/ResourcesOOUI.php" );
252 // Register extension modules
253 $this->register( $config->get( 'ResourceModules' ) );
254 Hooks::run( 'ResourceLoaderRegisterModules', array( &$this ) );
256 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
257 $this->registerTestModules();
260 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger ) );
264 * @return Config
266 public function getConfig() {
267 return $this->config;
271 * @since 1.26
272 * @param LoggerInterface $logger
274 public function setLogger( LoggerInterface $logger ) {
275 $this->logger = $logger;
279 * @since 1.27
280 * @return LoggerInterface
282 public function getLogger() {
283 return $this->logger;
287 * @since 1.26
288 * @return MessageBlobStore
290 public function getMessageBlobStore() {
291 return $this->blobStore;
295 * @since 1.25
296 * @param MessageBlobStore $blobStore
298 public function setMessageBlobStore( MessageBlobStore $blobStore ) {
299 $this->blobStore = $blobStore;
303 * Register a module with the ResourceLoader system.
305 * @param mixed $name Name of module as a string or List of name/object pairs as an array
306 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
307 * this may also be a ResourceLoaderModule object. Optional when using
308 * multiple-registration calling style.
309 * @throws MWException If a duplicate module registration is attempted
310 * @throws MWException If a module name contains illegal characters (pipes or commas)
311 * @throws MWException If something other than a ResourceLoaderModule is being registered
312 * @return bool False if there were any errors, in which case one or more modules were
313 * not registered
315 public function register( $name, $info = null ) {
317 // Allow multiple modules to be registered in one call
318 $registrations = is_array( $name ) ? $name : array( $name => $info );
319 foreach ( $registrations as $name => $info ) {
320 // Warn on duplicate registrations
321 if ( isset( $this->moduleInfos[$name] ) ) {
322 // A module has already been registered by this name
323 $this->logger->warning(
324 'ResourceLoader duplicate registration warning. ' .
325 'Another module has already been registered as ' . $name
329 // Check $name for validity
330 if ( !self::isValidModuleName( $name ) ) {
331 throw new MWException( "ResourceLoader module name '$name' is invalid, "
332 . "see ResourceLoader::isValidModuleName()" );
335 // Attach module
336 if ( $info instanceof ResourceLoaderModule ) {
337 $this->moduleInfos[$name] = array( 'object' => $info );
338 $info->setName( $name );
339 $this->modules[$name] = $info;
340 } elseif ( is_array( $info ) ) {
341 // New calling convention
342 $this->moduleInfos[$name] = $info;
343 } else {
344 throw new MWException(
345 'ResourceLoader module info type error for module \'' . $name .
346 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
350 // Last-minute changes
352 // Apply custom skin-defined styles to existing modules.
353 if ( $this->isFileModule( $name ) ) {
354 foreach ( $this->config->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
355 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
356 if ( isset( $this->moduleInfos[$name]['skinStyles'][$skinName] ) ) {
357 continue;
360 // If $name is preceded with a '+', the defined style files will be added to 'default'
361 // skinStyles, otherwise 'default' will be ignored as it normally would be.
362 if ( isset( $skinStyles[$name] ) ) {
363 $paths = (array)$skinStyles[$name];
364 $styleFiles = array();
365 } elseif ( isset( $skinStyles['+' . $name] ) ) {
366 $paths = (array)$skinStyles['+' . $name];
367 $styleFiles = isset( $this->moduleInfos[$name]['skinStyles']['default'] ) ?
368 (array)$this->moduleInfos[$name]['skinStyles']['default'] :
369 array();
370 } else {
371 continue;
374 // Add new file paths, remapping them to refer to our directories and not use settings
375 // from the module we're modifying, which come from the base definition.
376 list( $localBasePath, $remoteBasePath ) =
377 ResourceLoaderFileModule::extractBasePaths( $skinStyles );
379 foreach ( $paths as $path ) {
380 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
383 $this->moduleInfos[$name]['skinStyles'][$skinName] = $styleFiles;
392 public function registerTestModules() {
393 global $IP;
395 if ( $this->config->get( 'EnableJavaScriptTest' ) !== true ) {
396 throw new MWException( 'Attempt to register JavaScript test modules '
397 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
398 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
401 // Get core test suites
402 $testModules = array();
403 $testModules['qunit'] = array();
404 // Get other test suites (e.g. from extensions)
405 Hooks::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
407 // Add the testrunner (which configures QUnit) to the dependencies.
408 // Since it must be ready before any of the test suites are executed.
409 foreach ( $testModules['qunit'] as &$module ) {
410 // Make sure all test modules are top-loading so that when QUnit starts
411 // on document-ready, it will run once and finish. If some tests arrive
412 // later (possibly after QUnit has already finished) they will be ignored.
413 $module['position'] = 'top';
414 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
417 $testModules['qunit'] =
418 ( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules['qunit'];
420 foreach ( $testModules as $id => $names ) {
421 // Register test modules
422 $this->register( $testModules[$id] );
424 // Keep track of their names so that they can be loaded together
425 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
431 * Add a foreign source of modules.
433 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
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 );
446 return;
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)
488 * @return array
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];
498 } else {
499 return array();
504 * Check whether a ResourceLoader module is registered
506 * @since 1.25
507 * @param string $name
508 * @return bool
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] ) ) {
528 // No such module
529 return null;
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'];
537 } else {
538 if ( !isset( $info['class'] ) ) {
539 $class = 'ResourceLoaderFileModule';
540 } else {
541 $class = $info['class'];
543 /** @var ResourceLoaderModule $object */
544 $object = new $class( $info );
545 $object->setConfig( $this->getConfig() );
546 $object->setLogger( $this->logger );
548 $object->setName( $name );
549 $this->modules[$name] = $object;
552 return $this->modules[$name];
556 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
558 * @param string $name Module name
559 * @return bool
561 protected function isFileModule( $name ) {
562 if ( !isset( $this->moduleInfos[$name] ) ) {
563 return false;
565 $info = $this->moduleInfos[$name];
566 if ( isset( $info['object'] ) || isset( $info['class'] ) ) {
567 return false;
569 return true;
573 * Get the list of sources.
575 * @return array Like array( id => load.php url, .. )
577 public function getSources() {
578 return $this->sources;
582 * Get the URL to the load.php endpoint for the given
583 * ResourceLoader source
585 * @since 1.24
586 * @param string $source
587 * @throws MWException On an invalid $source name
588 * @return string
590 public function getLoadScript( $source ) {
591 if ( !isset( $this->sources[$source] ) ) {
592 throw new MWException( "The $source source was never registered in ResourceLoader." );
594 return $this->sources[$source];
598 * @since 1.26
599 * @param string $value
600 * @return string Hash
602 public static function makeHash( $value ) {
603 // Use base64 to output more entropy in a more compact string (default hex is only base16).
604 // The first 8 chars of a base64 encoded digest represent the same binary as
605 // the first 12 chars of a hex encoded digest.
606 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
610 * Helper method to get and combine versions of multiple modules.
612 * @since 1.26
613 * @param ResourceLoaderContext $context
614 * @param array $modules List of ResourceLoaderModule objects
615 * @return string Hash
617 public function getCombinedVersion( ResourceLoaderContext $context, Array $modules ) {
618 if ( !$modules ) {
619 return '';
621 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
622 // http://php.net/functions.anonymous
623 $rl = $this;
624 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
625 return $rl->getModule( $module )->getVersionHash( $context );
626 }, $modules );
627 return self::makeHash( implode( $hashes ) );
631 * Output a response to a load request, including the content-type header.
633 * @param ResourceLoaderContext $context Context in which a response should be formed
635 public function respond( ResourceLoaderContext $context ) {
636 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
637 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
638 // is used: ob_clean() will clear the GZIP header in that case and it won't come
639 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
640 // the whole thing in our own output buffer to be sure the active buffer
641 // doesn't use ob_gzhandler.
642 // See http://bugs.php.net/bug.php?id=36514
643 ob_start();
645 // Find out which modules are missing and instantiate the others
646 $modules = array();
647 $missing = array();
648 foreach ( $context->getModules() as $name ) {
649 $module = $this->getModule( $name );
650 if ( $module ) {
651 // Do not allow private modules to be loaded from the web.
652 // This is a security issue, see bug 34907.
653 if ( $module->getGroup() === 'private' ) {
654 $this->logger->debug( "Request for private module '$name' denied" );
655 $this->errors[] = "Cannot show private module \"$name\"";
656 continue;
658 $modules[$name] = $module;
659 } else {
660 $missing[] = $name;
664 try {
665 // Preload for getCombinedVersion() and for batch makeModuleResponse()
666 $this->preloadModuleInfo( array_keys( $modules ), $context );
667 } catch ( Exception $e ) {
668 MWExceptionHandler::logException( $e );
669 $this->logger->warning( 'Preloading module info failed: {exception}', array(
670 'exception' => $e
671 ) );
672 $this->errors[] = self::formatExceptionNoComment( $e );
675 // Combine versions to propagate cache invalidation
676 $versionHash = '';
677 try {
678 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
679 } catch ( Exception $e ) {
680 MWExceptionHandler::logException( $e );
681 $this->logger->warning( 'Calculating version hash failed: {exception}', array(
682 'exception' => $e
683 ) );
684 $this->errors[] = self::formatExceptionNoComment( $e );
687 // See RFC 2616 § 3.11 Entity Tags
688 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
689 $etag = 'W/"' . $versionHash . '"';
691 // Try the client-side cache first
692 if ( $this->tryRespondNotModified( $context, $etag ) ) {
693 return; // output handled (buffers cleared)
696 // Use file cache if enabled and available...
697 if ( $this->config->get( 'UseFileCache' ) ) {
698 $fileCache = ResourceFileCache::newFromContext( $context );
699 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
700 return; // output handled
704 // Generate a response
705 $response = $this->makeModuleResponse( $context, $modules, $missing );
707 // Capture any PHP warnings from the output buffer and append them to the
708 // error list if we're in debug mode.
709 if ( $context->getDebug() ) {
710 $warnings = ob_get_contents();
711 if ( strlen( $warnings ) ) {
712 $this->errors[] = $warnings;
716 // Save response to file cache unless there are errors
717 if ( isset( $fileCache ) && !$this->errors && !count( $missing ) ) {
718 // Cache single modules and images...and other requests if there are enough hits
719 if ( ResourceFileCache::useFileCache( $context ) ) {
720 if ( $fileCache->isCacheWorthy() ) {
721 $fileCache->saveText( $response );
722 } else {
723 $fileCache->incrMissesRecent( $context->getRequest() );
728 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors );
730 // Remove the output buffer and output the response
731 ob_end_clean();
733 if ( $context->getImageObj() && $this->errors ) {
734 // We can't show both the error messages and the response when it's an image.
735 $response = implode( "\n\n", $this->errors );
736 } elseif ( $this->errors ) {
737 $errorText = implode( "\n\n", $this->errors );
738 $errorResponse = self::makeComment( $errorText );
739 if ( $context->shouldIncludeScripts() ) {
740 $errorResponse .= 'if (window.console && console.error) {'
741 . Xml::encodeJsCall( 'console.error', array( $errorText ) )
742 . "}\n";
745 // Prepend error info to the response
746 $response = $errorResponse . $response;
749 $this->errors = array();
750 echo $response;
755 * Send main response headers to the client.
757 * Deals with Content-Type, CORS (for stylesheets), and caching.
759 * @param ResourceLoaderContext $context
760 * @param string $etag ETag header value
761 * @param bool $errors Whether there are errors in the response
762 * @return void
764 protected function sendResponseHeaders( ResourceLoaderContext $context, $etag, $errors ) {
765 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
766 // If a version wasn't specified we need a shorter expiry time for updates
767 // to propagate to clients quickly
768 // If there were errors, we also need a shorter expiry time so we can recover quickly
769 if ( is_null( $context->getVersion() ) || $errors ) {
770 $maxage = $rlMaxage['unversioned']['client'];
771 $smaxage = $rlMaxage['unversioned']['server'];
772 // If a version was specified we can use a longer expiry time since changing
773 // version numbers causes cache misses
774 } else {
775 $maxage = $rlMaxage['versioned']['client'];
776 $smaxage = $rlMaxage['versioned']['server'];
778 if ( $context->getImageObj() ) {
779 // Output different headers if we're outputting textual errors.
780 if ( $errors ) {
781 header( 'Content-Type: text/plain; charset=utf-8' );
782 } else {
783 $context->getImageObj()->sendResponseHeaders( $context );
785 } elseif ( $context->getOnly() === 'styles' ) {
786 header( 'Content-Type: text/css; charset=utf-8' );
787 header( 'Access-Control-Allow-Origin: *' );
788 } else {
789 header( 'Content-Type: text/javascript; charset=utf-8' );
791 // See RFC 2616 § 14.19 ETag
792 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
793 header( 'ETag: ' . $etag );
794 if ( $context->getDebug() ) {
795 // Do not cache debug responses
796 header( 'Cache-Control: private, no-cache, must-revalidate' );
797 header( 'Pragma: no-cache' );
798 } else {
799 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
800 $exp = min( $maxage, $smaxage );
801 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
806 * Respond with HTTP 304 Not Modified if appropiate.
808 * If there's an If-None-Match header, respond with a 304 appropriately
809 * and clear out the output buffer. If the client cache is too old then do nothing.
811 * @param ResourceLoaderContext $context
812 * @param string $etag ETag header value
813 * @return bool True if HTTP 304 was sent and output handled
815 protected function tryRespondNotModified( ResourceLoaderContext $context, $etag ) {
816 // See RFC 2616 § 14.26 If-None-Match
817 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
818 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST );
819 // Never send 304s in debug mode
820 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
821 // There's another bug in ob_gzhandler (see also the comment at
822 // the top of this function) that causes it to gzip even empty
823 // responses, meaning it's impossible to produce a truly empty
824 // response (because the gzip header is always there). This is
825 // a problem because 304 responses have to be completely empty
826 // per the HTTP spec, and Firefox behaves buggily when they're not.
827 // See also http://bugs.php.net/bug.php?id=51579
828 // To work around this, we tear down all output buffering before
829 // sending the 304.
830 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
832 HttpStatus::header( 304 );
834 $this->sendResponseHeaders( $context, $etag, false );
835 return true;
837 return false;
841 * Send out code for a response from file cache if possible.
843 * @param ResourceFileCache $fileCache Cache object for this request URL
844 * @param ResourceLoaderContext $context Context in which to generate a response
845 * @param string $etag ETag header value
846 * @return bool If this found a cache file and handled the response
848 protected function tryRespondFromFileCache(
849 ResourceFileCache $fileCache,
850 ResourceLoaderContext $context,
851 $etag
853 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
854 // Buffer output to catch warnings.
855 ob_start();
856 // Get the maximum age the cache can be
857 $maxage = is_null( $context->getVersion() )
858 ? $rlMaxage['unversioned']['server']
859 : $rlMaxage['versioned']['server'];
860 // Minimum timestamp the cache file must have
861 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
862 if ( !$good ) {
863 try { // RL always hits the DB on file cache miss...
864 wfGetDB( DB_SLAVE );
865 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
866 $good = $fileCache->isCacheGood(); // cache existence check
869 if ( $good ) {
870 $ts = $fileCache->cacheTimestamp();
871 // Send content type and cache headers
872 $this->sendResponseHeaders( $context, $etag, false );
873 $response = $fileCache->fetchText();
874 // Capture any PHP warnings from the output buffer and append them to the
875 // response in a comment if we're in debug mode.
876 if ( $context->getDebug() ) {
877 $warnings = ob_get_contents();
878 if ( strlen( $warnings ) ) {
879 $response = self::makeComment( $warnings ) . $response;
882 // Remove the output buffer and output the response
883 ob_end_clean();
884 echo $response . "\n/* Cached {$ts} */";
885 return true; // cache hit
887 // Clear buffer
888 ob_end_clean();
890 return false; // cache miss
894 * Generate a CSS or JS comment block.
896 * Only use this for public data, not error message details.
898 * @param string $text
899 * @return string
901 public static function makeComment( $text ) {
902 $encText = str_replace( '*/', '* /', $text );
903 return "/*\n$encText\n*/\n";
907 * Handle exception display.
909 * @param Exception $e Exception to be shown to the user
910 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
912 public static function formatException( $e ) {
913 return self::makeComment( self::formatExceptionNoComment( $e ) );
917 * Handle exception display.
919 * @since 1.25
920 * @param Exception $e Exception to be shown to the user
921 * @return string Sanitized text that can be returned to the user
923 protected static function formatExceptionNoComment( $e ) {
924 global $wgShowExceptionDetails;
926 if ( !$wgShowExceptionDetails ) {
927 return MWExceptionHandler::getPublicLogMessage( $e );
930 return MWExceptionHandler::getLogMessage( $e );
934 * Generate code for a response.
936 * @param ResourceLoaderContext $context Context in which to generate a response
937 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
938 * @param string[] $missing List of requested module names that are unregistered (optional)
939 * @return string Response data
941 public function makeModuleResponse( ResourceLoaderContext $context,
942 array $modules, array $missing = array()
944 $out = '';
945 $states = array();
947 if ( !count( $modules ) && !count( $missing ) ) {
948 return <<<MESSAGE
949 /* This file is the Web entry point for MediaWiki's ResourceLoader:
950 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
951 no modules were requested. Max made me put this here. */
952 MESSAGE;
955 $image = $context->getImageObj();
956 if ( $image ) {
957 $data = $image->getImageData( $context );
958 if ( $data === false ) {
959 $data = '';
960 $this->errors[] = 'Image generation failed';
962 return $data;
965 foreach ( $missing as $name ) {
966 $states[$name] = 'missing';
969 // Generate output
970 $isRaw = false;
972 $filter = $context->getOnly() === 'styles' ? 'minify-css' : 'minify-js';
974 foreach ( $modules as $name => $module ) {
975 try {
976 $content = $module->getModuleContent( $context );
977 $strContent = '';
979 // Append output
980 switch ( $context->getOnly() ) {
981 case 'scripts':
982 $scripts = $content['scripts'];
983 if ( is_string( $scripts ) ) {
984 // Load scripts raw...
985 $strContent = $scripts;
986 } elseif ( is_array( $scripts ) ) {
987 // ...except when $scripts is an array of URLs
988 $strContent = self::makeLoaderImplementScript( $name, $scripts, array(), array(), array() );
990 break;
991 case 'styles':
992 $styles = $content['styles'];
993 // We no longer seperate into media, they are all combined now with
994 // custom media type groups into @media .. {} sections as part of the css string.
995 // Module returns either an empty array or a numerical array with css strings.
996 $strContent = isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
997 break;
998 default:
999 $strContent = self::makeLoaderImplementScript(
1000 $name,
1001 isset( $content['scripts'] ) ? $content['scripts'] : '',
1002 isset( $content['styles'] ) ? $content['styles'] : array(),
1003 isset( $content['messagesBlob'] ) ? new XmlJsCode( $content['messagesBlob'] ) : array(),
1004 isset( $content['templates'] ) ? $content['templates'] : array()
1006 break;
1009 if ( !$context->getDebug() ) {
1010 $strContent = self::filter( $filter, $strContent );
1013 $out .= $strContent;
1015 } catch ( Exception $e ) {
1016 MWExceptionHandler::logException( $e );
1017 $this->logger->warning( 'Generating module package failed: {exception}', array(
1018 'exception' => $e
1019 ) );
1020 $this->errors[] = self::formatExceptionNoComment( $e );
1022 // Respond to client with error-state instead of module implementation
1023 $states[$name] = 'error';
1024 unset( $modules[$name] );
1026 $isRaw |= $module->isRaw();
1029 // Update module states
1030 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1031 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1032 // Set the state of modules loaded as only scripts to ready as
1033 // they don't have an mw.loader.implement wrapper that sets the state
1034 foreach ( $modules as $name => $module ) {
1035 $states[$name] = 'ready';
1039 // Set the state of modules we didn't respond to with mw.loader.implement
1040 if ( count( $states ) ) {
1041 $stateScript = self::makeLoaderStateScript( $states );
1042 if ( !$context->getDebug() ) {
1043 $stateScript = self::filter( 'minify-js', $stateScript );
1045 $out .= $stateScript;
1047 } else {
1048 if ( count( $states ) ) {
1049 $this->errors[] = 'Problematic modules: ' .
1050 FormatJson::encode( $states, ResourceLoader::inDebugMode() );
1054 return $out;
1058 * Get names of modules that use a certain message.
1060 * @param string $messageKey
1061 * @return array List of module names
1063 public function getModulesByMessage( $messageKey ) {
1064 $moduleNames = array();
1065 foreach ( $this->getModuleNames() as $moduleName ) {
1066 $module = $this->getModule( $moduleName );
1067 if ( in_array( $messageKey, $module->getMessages() ) ) {
1068 $moduleNames[] = $moduleName;
1071 return $moduleNames;
1074 /* Static Methods */
1077 * Return JS code that calls mw.loader.implement with given module properties.
1079 * @param string $name Module name
1080 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1081 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1082 * to CSS files keyed by media type
1083 * @param mixed $messages List of messages associated with this module. May either be an
1084 * associative array mapping message key to value, or a JSON-encoded message blob containing
1085 * the same data, wrapped in an XmlJsCode object.
1086 * @param array $templates Keys are name of templates and values are the source of
1087 * the template.
1088 * @throws MWException
1089 * @return string
1091 public static function makeLoaderImplementScript(
1092 $name, $scripts, $styles, $messages, $templates
1094 if ( is_string( $scripts ) ) {
1095 // Site and user module are a legacy scripts that run in the global scope (no closure).
1096 // Transportation as string instructs mw.loader.implement to use globalEval.
1097 if ( $name === 'site' || $name === 'user' ) {
1098 // Minify manually because the general makeModuleResponse() minification won't be
1099 // effective here due to the script being a string instead of a function. (T107377)
1100 if ( !ResourceLoader::inDebugMode() ) {
1101 $scripts = self::filter( 'minify-js', $scripts );
1103 } else {
1104 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1106 } elseif ( !is_array( $scripts ) ) {
1107 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1109 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1110 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1111 // of "{}". Force them to objects.
1112 $module = array(
1113 $name,
1114 $scripts,
1115 (object)$styles,
1116 (object)$messages,
1117 (object)$templates,
1119 self::trimArray( $module );
1121 return Xml::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader::inDebugMode() );
1125 * Returns JS code which, when called, will register a given list of messages.
1127 * @param mixed $messages Either an associative array mapping message key to value, or a
1128 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1129 * @return string
1131 public static function makeMessageSetScript( $messages ) {
1132 return Xml::encodeJsCall(
1133 'mw.messages.set',
1134 array( (object)$messages ),
1135 ResourceLoader::inDebugMode()
1140 * Combines an associative array mapping media type to CSS into a
1141 * single stylesheet with "@media" blocks.
1143 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1144 * @return array
1146 public static function makeCombinedStyles( array $stylePairs ) {
1147 $out = array();
1148 foreach ( $stylePairs as $media => $styles ) {
1149 // ResourceLoaderFileModule::getStyle can return the styles
1150 // as a string or an array of strings. This is to allow separation in
1151 // the front-end.
1152 $styles = (array)$styles;
1153 foreach ( $styles as $style ) {
1154 $style = trim( $style );
1155 // Don't output an empty "@media print { }" block (bug 40498)
1156 if ( $style !== '' ) {
1157 // Transform the media type based on request params and config
1158 // The way that this relies on $wgRequest to propagate request params is slightly evil
1159 $media = OutputPage::transformCssMedia( $media );
1161 if ( $media === '' || $media == 'all' ) {
1162 $out[] = $style;
1163 } elseif ( is_string( $media ) ) {
1164 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1166 // else: skip
1170 return $out;
1174 * Returns a JS call to mw.loader.state, which sets the state of a
1175 * module or modules to a given value. Has two calling conventions:
1177 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1178 * Set the state of a single module called $name to $state
1180 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1181 * Set the state of modules with the given names to the given states
1183 * @param string $name
1184 * @param string $state
1185 * @return string
1187 public static function makeLoaderStateScript( $name, $state = null ) {
1188 if ( is_array( $name ) ) {
1189 return Xml::encodeJsCall(
1190 'mw.loader.state',
1191 array( $name ),
1192 ResourceLoader::inDebugMode()
1194 } else {
1195 return Xml::encodeJsCall(
1196 'mw.loader.state',
1197 array( $name, $state ),
1198 ResourceLoader::inDebugMode()
1204 * Returns JS code which calls the script given by $script. The script will
1205 * be called with local variables name, version, dependencies and group,
1206 * which will have values corresponding to $name, $version, $dependencies
1207 * and $group as supplied.
1209 * @param string $name Module name
1210 * @param string $version Module version hash
1211 * @param array $dependencies List of module names on which this module depends
1212 * @param string $group Group which the module is in.
1213 * @param string $source Source of the module, or 'local' if not foreign.
1214 * @param string $script JavaScript code
1215 * @return string
1217 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1218 $group, $source, $script
1220 $script = str_replace( "\n", "\n\t", trim( $script ) );
1221 return Xml::encodeJsCall(
1222 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1223 array( $name, $version, $dependencies, $group, $source ),
1224 ResourceLoader::inDebugMode()
1228 private static function isEmptyObject( stdClass $obj ) {
1229 foreach ( $obj as $key => $value ) {
1230 return false;
1232 return true;
1236 * Remove empty values from the end of an array.
1238 * Values considered empty:
1240 * - null
1241 * - array()
1242 * - new XmlJsCode( '{}' )
1243 * - new stdClass() // (object) array()
1245 * @param Array $array
1247 private static function trimArray( Array &$array ) {
1248 $i = count( $array );
1249 while ( $i-- ) {
1250 if ( $array[$i] === null
1251 || $array[$i] === array()
1252 || ( $array[$i] instanceof XmlJsCode && $array[$i]->value === '{}' )
1253 || ( $array[$i] instanceof stdClass && self::isEmptyObject( $array[$i] ) )
1255 unset( $array[$i] );
1256 } else {
1257 break;
1263 * Returns JS code which calls mw.loader.register with the given
1264 * parameters. Has three calling conventions:
1266 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1267 * $dependencies, $group, $source, $skip
1268 * ):
1269 * Register a single module.
1271 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1272 * Register modules with the given names.
1274 * - ResourceLoader::makeLoaderRegisterScript( array(
1275 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1276 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1277 * ...
1278 * ) ):
1279 * Registers modules with the given names and parameters.
1281 * @param string $name Module name
1282 * @param string $version Module version hash
1283 * @param array $dependencies List of module names on which this module depends
1284 * @param string $group Group which the module is in
1285 * @param string $source Source of the module, or 'local' if not foreign
1286 * @param string $skip Script body of the skip function
1287 * @return string
1289 public static function makeLoaderRegisterScript( $name, $version = null,
1290 $dependencies = null, $group = null, $source = null, $skip = null
1292 if ( is_array( $name ) ) {
1293 // Build module name index
1294 $index = array();
1295 foreach ( $name as $i => &$module ) {
1296 $index[$module[0]] = $i;
1299 // Transform dependency names into indexes when possible, they will be resolved by
1300 // mw.loader.register on the other end
1301 foreach ( $name as &$module ) {
1302 if ( isset( $module[2] ) ) {
1303 foreach ( $module[2] as &$dependency ) {
1304 if ( isset( $index[$dependency] ) ) {
1305 $dependency = $index[$dependency];
1311 array_walk( $name, array( 'self', 'trimArray' ) );
1313 return Xml::encodeJsCall(
1314 'mw.loader.register',
1315 array( $name ),
1316 ResourceLoader::inDebugMode()
1318 } else {
1319 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1320 self::trimArray( $registration );
1321 return Xml::encodeJsCall(
1322 'mw.loader.register',
1323 $registration,
1324 ResourceLoader::inDebugMode()
1330 * Returns JS code which calls mw.loader.addSource() with the given
1331 * parameters. Has two calling conventions:
1333 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1334 * Register a single source
1336 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1337 * Register sources with the given IDs and properties.
1339 * @param string $id Source ID
1340 * @param array $properties Source properties (see addSource())
1341 * @return string
1343 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1344 if ( is_array( $id ) ) {
1345 return Xml::encodeJsCall(
1346 'mw.loader.addSource',
1347 array( $id ),
1348 ResourceLoader::inDebugMode()
1350 } else {
1351 return Xml::encodeJsCall(
1352 'mw.loader.addSource',
1353 array( $id, $properties ),
1354 ResourceLoader::inDebugMode()
1360 * Returns JS code which runs given JS code if the client-side framework is
1361 * present.
1363 * @deprecated since 1.25; use makeInlineScript instead
1364 * @param string $script JavaScript code
1365 * @return string
1367 public static function makeLoaderConditionalScript( $script ) {
1368 return "window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n" .
1369 trim( $script ) . "\n} );";
1373 * Construct an inline script tag with given JS code.
1375 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1376 * only if the client has adequate support for MediaWiki JavaScript code.
1378 * @param string $script JavaScript code
1379 * @return WrappedString HTML
1381 public static function makeInlineScript( $script ) {
1382 $js = self::makeLoaderConditionalScript( $script );
1383 return new WrappedString(
1384 Html::inlineScript( $js ),
1385 "<script>window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n",
1386 "\n} );</script>"
1391 * Returns JS code which will set the MediaWiki configuration array to
1392 * the given value.
1394 * @param array $configuration List of configuration values keyed by variable name
1395 * @return string
1397 public static function makeConfigSetScript( array $configuration ) {
1398 return Xml::encodeJsCall(
1399 'mw.config.set',
1400 array( $configuration ),
1401 ResourceLoader::inDebugMode()
1402 ) . ResourceLoader::FILTER_NOMIN;
1406 * Convert an array of module names to a packed query string.
1408 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1409 * becomes 'foo.bar,baz|bar.baz,quux'
1410 * @param array $modules List of module names (strings)
1411 * @return string Packed query string
1413 public static function makePackedModulesString( $modules ) {
1414 $groups = array(); // array( prefix => array( suffixes ) )
1415 foreach ( $modules as $module ) {
1416 $pos = strrpos( $module, '.' );
1417 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1418 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1419 $groups[$prefix][] = $suffix;
1422 $arr = array();
1423 foreach ( $groups as $prefix => $suffixes ) {
1424 $p = $prefix === '' ? '' : $prefix . '.';
1425 $arr[] = $p . implode( ',', $suffixes );
1427 $str = implode( '|', $arr );
1428 return $str;
1432 * Determine whether debug mode was requested
1433 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1434 * @return bool
1436 public static function inDebugMode() {
1437 if ( self::$debugMode === null ) {
1438 global $wgRequest, $wgResourceLoaderDebug;
1439 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1440 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1443 return self::$debugMode;
1447 * Reset static members used for caching.
1449 * Global state and $wgRequest are evil, but we're using it right
1450 * now and sometimes we need to be able to force ResourceLoader to
1451 * re-evaluate the context because it has changed (e.g. in the test suite).
1453 public static function clearCache() {
1454 self::$debugMode = null;
1458 * Build a load.php URL
1460 * @since 1.24
1461 * @param string $source Name of the ResourceLoader source
1462 * @param ResourceLoaderContext $context
1463 * @param array $extraQuery
1464 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1466 public function createLoaderURL( $source, ResourceLoaderContext $context,
1467 $extraQuery = array()
1469 $query = self::createLoaderQuery( $context, $extraQuery );
1470 $script = $this->getLoadScript( $source );
1472 return wfAppendQuery( $script, $query );
1476 * Build a load.php URL
1477 * @deprecated since 1.24 Use createLoaderURL() instead
1478 * @param array $modules Array of module names (strings)
1479 * @param string $lang Language code
1480 * @param string $skin Skin name
1481 * @param string|null $user User name. If null, the &user= parameter is omitted
1482 * @param string|null $version Versioning timestamp
1483 * @param bool $debug Whether the request should be in debug mode
1484 * @param string|null $only &only= parameter
1485 * @param bool $printable Printable mode
1486 * @param bool $handheld Handheld mode
1487 * @param array $extraQuery Extra query parameters to add
1488 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1490 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1491 $version = null, $debug = false, $only = null, $printable = false,
1492 $handheld = false, $extraQuery = array()
1494 global $wgLoadScript;
1496 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1497 $only, $printable, $handheld, $extraQuery
1500 return wfAppendQuery( $wgLoadScript, $query );
1504 * Helper for createLoaderURL()
1506 * @since 1.24
1507 * @see makeLoaderQuery
1508 * @param ResourceLoaderContext $context
1509 * @param array $extraQuery
1510 * @return array
1512 public static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = array() ) {
1513 return self::makeLoaderQuery(
1514 $context->getModules(),
1515 $context->getLanguage(),
1516 $context->getSkin(),
1517 $context->getUser(),
1518 $context->getVersion(),
1519 $context->getDebug(),
1520 $context->getOnly(),
1521 $context->getRequest()->getBool( 'printable' ),
1522 $context->getRequest()->getBool( 'handheld' ),
1523 $extraQuery
1528 * Build a query array (array representation of query string) for load.php. Helper
1529 * function for makeLoaderURL().
1531 * @param array $modules
1532 * @param string $lang
1533 * @param string $skin
1534 * @param string $user
1535 * @param string $version
1536 * @param bool $debug
1537 * @param string $only
1538 * @param bool $printable
1539 * @param bool $handheld
1540 * @param array $extraQuery
1542 * @return array
1544 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1545 $version = null, $debug = false, $only = null, $printable = false,
1546 $handheld = false, $extraQuery = array()
1548 $query = array(
1549 'modules' => self::makePackedModulesString( $modules ),
1550 'lang' => $lang,
1551 'skin' => $skin,
1552 'debug' => $debug ? 'true' : 'false',
1554 if ( $user !== null ) {
1555 $query['user'] = $user;
1557 if ( $version !== null ) {
1558 $query['version'] = $version;
1560 if ( $only !== null ) {
1561 $query['only'] = $only;
1563 if ( $printable ) {
1564 $query['printable'] = 1;
1566 if ( $handheld ) {
1567 $query['handheld'] = 1;
1569 $query += $extraQuery;
1571 // Make queries uniform in order
1572 ksort( $query );
1573 return $query;
1577 * Check a module name for validity.
1579 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1580 * at most 255 bytes.
1582 * @param string $moduleName Module name to check
1583 * @return bool Whether $moduleName is a valid module name
1585 public static function isValidModuleName( $moduleName ) {
1586 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1590 * Returns LESS compiler set up for use with MediaWiki
1592 * @since 1.22
1593 * @since 1.27 added $extraVars parameter
1594 * @param Config $config
1595 * @param array $extraVars Associative array of extra (i.e., other than the
1596 * globally-configured ones) that should be used for compilation.
1597 * @throws MWException
1598 * @return Less_Parser
1600 public static function getLessCompiler( Config $config, $extraVars = array() ) {
1601 // When called from the installer, it is possible that a required PHP extension
1602 // is missing (at least for now; see bug 47564). If this is the case, throw an
1603 // exception (caught by the installer) to prevent a fatal error later on.
1604 if ( !class_exists( 'Less_Parser' ) ) {
1605 throw new MWException( 'MediaWiki requires the less.php parser' );
1608 $parser = new Less_Parser;
1609 $parser->ModifyVars( array_merge( self::getLessVars( $config ), $extraVars ) );
1610 $parser->SetImportDirs( array_fill_keys( $config->get( 'ResourceLoaderLESSImportPaths' ), '' ) );
1611 $parser->SetOption( 'relativeUrls', false );
1612 $parser->SetCacheDir( $config->get( 'CacheDirectory' ) ?: wfTempDir() );
1614 return $parser;
1618 * Get global LESS variables.
1620 * @param Config $config
1621 * @since 1.22
1622 * @return array Map of variable names to string CSS values.
1624 public static function getLessVars( Config $config ) {
1625 if ( !self::$lessVars ) {
1626 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1627 Hooks::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1628 self::$lessVars = $lessVars;
1630 return self::$lessVars;