Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / resourceloader / ResourceLoader.php
blob1922999d1ab5138903983373514b2b4cc916af61
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 bool */
36 protected static $debugMode = null;
38 /** @var array */
39 private static $lessVars = null;
41 /**
42 * Module name/ResourceLoaderModule object pairs
43 * @var array
45 protected $modules = array();
47 /**
48 * Associative array mapping module name to info associative array
49 * @var array
51 protected $moduleInfos = array();
53 /** @var Config $config */
54 private $config;
56 /**
57 * Associative array mapping framework ids to a list of names of test suite modules
58 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
59 * @var array
61 protected $testModuleNames = array();
63 /**
64 * E.g. array( 'source-id' => 'http://.../load.php' )
65 * @var array
67 protected $sources = array();
69 /**
70 * Errors accumulated during current respond() call.
71 * @var array
73 protected $errors = array();
75 /**
76 * Load information stored in the database about modules.
78 * This method grabs modules dependencies from the database and updates modules
79 * objects.
81 * This is not inside the module code because it is much faster to
82 * request all of the information at once than it is to have each module
83 * requests its own information. This sacrifice of modularity yields a substantial
84 * performance improvement.
86 * @param array $modules List of module names to preload information for
87 * @param ResourceLoaderContext $context Context to load the information within
89 public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
90 if ( !count( $modules ) ) {
91 // Or else Database*::select() will explode, plus it's cheaper!
92 return;
94 $dbr = wfGetDB( DB_SLAVE );
95 $skin = $context->getSkin();
96 $lang = $context->getLanguage();
98 // Get file dependency information
99 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
100 'md_module' => $modules,
101 'md_skin' => $skin
102 ), __METHOD__
105 // Set modules' dependencies
106 $modulesWithDeps = array();
107 foreach ( $res as $row ) {
108 $module = $this->getModule( $row->md_module );
109 if ( $module ) {
110 $module->setFileDependencies( $skin, FormatJson::decode( $row->md_deps, true ) );
111 $modulesWithDeps[] = $row->md_module;
115 // Register the absence of a dependency row too
116 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
117 $module = $this->getModule( $name );
118 if ( $module ) {
119 $this->getModule( $name )->setFileDependencies( $skin, array() );
123 // Get message blob mtimes. Only do this for modules with messages
124 $modulesWithMessages = array();
125 foreach ( $modules as $name ) {
126 $module = $this->getModule( $name );
127 if ( $module && count( $module->getMessages() ) ) {
128 $modulesWithMessages[] = $name;
131 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
132 if ( count( $modulesWithMessages ) ) {
133 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
134 'mr_resource' => $modulesWithMessages,
135 'mr_lang' => $lang
136 ), __METHOD__
138 foreach ( $res as $row ) {
139 $module = $this->getModule( $row->mr_resource );
140 if ( $module ) {
141 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX, $row->mr_timestamp ) );
142 unset( $modulesWithoutMessages[$row->mr_resource] );
146 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
147 $module = $this->getModule( $name );
148 if ( $module ) {
149 $module->setMsgBlobMtime( $lang, 1 );
155 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
157 * Available filters are:
159 * - minify-js \see JavaScriptMinifier::minify
160 * - minify-css \see CSSMin::minify
162 * If $data is empty, only contains whitespace or the filter was unknown,
163 * $data is returned unmodified.
165 * @param string $filter Name of filter to run
166 * @param string $data Text to filter, such as JavaScript or CSS text
167 * @param string $cacheReport Whether to include the cache key report
168 * @return string Filtered data, or a comment containing an error message
170 public function filter( $filter, $data, $cacheReport = true ) {
172 // For empty/whitespace-only data or for unknown filters, don't perform
173 // any caching or processing
174 if ( trim( $data ) === '' || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
175 return $data;
178 // Try for cache hit
179 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
180 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self::$filterCacheVersion, md5( $data ) );
181 $cache = wfGetCache( CACHE_ANYTHING );
182 $cacheEntry = $cache->get( $key );
183 if ( is_string( $cacheEntry ) ) {
184 wfIncrStats( "rl-$filter-cache-hits" );
185 return $cacheEntry;
188 $result = '';
189 // Run the filter - we've already verified one of these will work
190 try {
191 wfIncrStats( "rl-$filter-cache-misses" );
192 switch ( $filter ) {
193 case 'minify-js':
194 $result = JavaScriptMinifier::minify( $data,
195 $this->config->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
196 $this->config->get( 'ResourceLoaderMinifierMaxLineLength' )
198 if ( $cacheReport ) {
199 $result .= "\n/* cache key: $key */";
201 break;
202 case 'minify-css':
203 $result = CSSMin::minify( $data );
204 if ( $cacheReport ) {
205 $result .= "\n/* cache key: $key */";
207 break;
210 // Save filtered text to Memcached
211 $cache->set( $key, $result );
212 } catch ( Exception $e ) {
213 MWExceptionHandler::logException( $e );
214 wfDebugLog( 'resourceloader', __METHOD__ . ": minification failed: $e" );
215 $this->errors[] = self::formatExceptionNoComment( $e );
218 return $result;
221 /* Methods */
224 * Register core modules and runs registration hooks.
225 * @param Config|null $config
227 public function __construct( Config $config = null ) {
228 global $IP;
230 if ( $config === null ) {
231 wfDebug( __METHOD__ . ' was called without providing a Config instance' );
232 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
235 $this->config = $config;
237 // Add 'local' source first
238 $this->addSource( 'local', wfScript( 'load' ) );
240 // Add other sources
241 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
243 // Register core modules
244 $this->register( include "$IP/resources/Resources.php" );
245 // Register extension modules
246 Hooks::run( 'ResourceLoaderRegisterModules', array( &$this ) );
247 $this->register( $config->get( 'ResourceModules' ) );
249 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
250 $this->registerTestModules();
256 * @return Config
258 public function getConfig() {
259 return $this->config;
263 * Register a module with the ResourceLoader system.
265 * @param mixed $name Name of module as a string or List of name/object pairs as an array
266 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
267 * this may also be a ResourceLoaderModule object. Optional when using
268 * multiple-registration calling style.
269 * @throws MWException If a duplicate module registration is attempted
270 * @throws MWException If a module name contains illegal characters (pipes or commas)
271 * @throws MWException If something other than a ResourceLoaderModule is being registered
272 * @return bool False if there were any errors, in which case one or more modules were
273 * not registered
275 public function register( $name, $info = null ) {
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 // A module has already been registered by this name
283 throw new MWException(
284 'ResourceLoader duplicate registration error. ' .
285 'Another module has already been registered as ' . $name
289 // Check $name for validity
290 if ( !self::isValidModuleName( $name ) ) {
291 throw new MWException( "ResourceLoader module name '$name' is invalid, "
292 . "see ResourceLoader::isValidModuleName()" );
295 // Attach module
296 if ( $info instanceof ResourceLoaderModule ) {
297 $this->moduleInfos[$name] = array( 'object' => $info );
298 $info->setName( $name );
299 $this->modules[$name] = $info;
300 } elseif ( is_array( $info ) ) {
301 // New calling convention
302 $this->moduleInfos[$name] = $info;
303 } else {
304 throw new MWException(
305 'ResourceLoader module info type error for module \'' . $name .
306 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
310 // Last-minute changes
312 // Apply custom skin-defined styles to existing modules.
313 if ( $this->isFileModule( $name ) ) {
314 foreach ( $this->config->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
315 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
316 if ( isset( $this->moduleInfos[$name]['skinStyles'][$skinName] ) ) {
317 continue;
320 // If $name is preceded with a '+', the defined style files will be added to 'default'
321 // skinStyles, otherwise 'default' will be ignored as it normally would be.
322 if ( isset( $skinStyles[$name] ) ) {
323 $paths = (array)$skinStyles[$name];
324 $styleFiles = array();
325 } elseif ( isset( $skinStyles['+' . $name] ) ) {
326 $paths = (array)$skinStyles['+' . $name];
327 $styleFiles = isset( $this->moduleInfos[$name]['skinStyles']['default'] ) ?
328 $this->moduleInfos[$name]['skinStyles']['default'] :
329 array();
330 } else {
331 continue;
334 // Add new file paths, remapping them to refer to our directories and not use settings
335 // from the module we're modifying. These can come from the base definition or be defined
336 // for each module.
337 list( $localBasePath, $remoteBasePath ) =
338 ResourceLoaderFileModule::extractBasePaths( $skinStyles );
339 list( $localBasePath, $remoteBasePath ) =
340 ResourceLoaderFileModule::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
342 foreach ( $paths as $path ) {
343 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
346 $this->moduleInfos[$name]['skinStyles'][$skinName] = $styleFiles;
355 public function registerTestModules() {
356 global $IP;
358 if ( $this->config->get( 'EnableJavaScriptTest' ) !== true ) {
359 throw new MWException( 'Attempt to register JavaScript test modules '
360 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
361 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
364 // Get core test suites
365 $testModules = array();
366 $testModules['qunit'] = array();
367 // Get other test suites (e.g. from extensions)
368 Hooks::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
370 // Add the testrunner (which configures QUnit) to the dependencies.
371 // Since it must be ready before any of the test suites are executed.
372 foreach ( $testModules['qunit'] as &$module ) {
373 // Make sure all test modules are top-loading so that when QUnit starts
374 // on document-ready, it will run once and finish. If some tests arrive
375 // later (possibly after QUnit has already finished) they will be ignored.
376 $module['position'] = 'top';
377 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
380 $testModules['qunit'] =
381 ( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules['qunit'];
383 foreach ( $testModules as $id => $names ) {
384 // Register test modules
385 $this->register( $testModules[$id] );
387 // Keep track of their names so that they can be loaded together
388 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
394 * Add a foreign source of modules.
396 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
397 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
398 * backwards-compatibility.
399 * @throws MWException
401 public function addSource( $id, $loadUrl = null ) {
402 // Allow multiple sources to be registered in one call
403 if ( is_array( $id ) ) {
404 foreach ( $id as $key => $value ) {
405 $this->addSource( $key, $value );
407 return;
410 // Disallow duplicates
411 if ( isset( $this->sources[$id] ) ) {
412 throw new MWException(
413 'ResourceLoader duplicate source addition error. ' .
414 'Another source has already been registered as ' . $id
418 // Pre 1.24 backwards-compatibility
419 if ( is_array( $loadUrl ) ) {
420 if ( !isset( $loadUrl['loadScript'] ) ) {
421 throw new MWException(
422 __METHOD__ . ' was passed an array with no "loadScript" key.'
426 $loadUrl = $loadUrl['loadScript'];
429 $this->sources[$id] = $loadUrl;
433 * Get a list of module names.
435 * @return array List of module names
437 public function getModuleNames() {
438 return array_keys( $this->moduleInfos );
442 * Get a list of test module names for one (or all) frameworks.
444 * If the given framework id is unknkown, or if the in-object variable is not an array,
445 * then it will return an empty array.
447 * @param string $framework Get only the test module names for one
448 * particular framework (optional)
449 * @return array
451 public function getTestModuleNames( $framework = 'all' ) {
452 /** @todo api siteinfo prop testmodulenames modulenames */
453 if ( $framework == 'all' ) {
454 return $this->testModuleNames;
455 } elseif ( isset( $this->testModuleNames[$framework] )
456 && is_array( $this->testModuleNames[$framework] )
458 return $this->testModuleNames[$framework];
459 } else {
460 return array();
465 * Get the ResourceLoaderModule object for a given module name.
467 * If an array of module parameters exists but a ResourceLoaderModule object has not
468 * yet been instantiated, this method will instantiate and cache that object such that
469 * subsequent calls simply return the same object.
471 * @param string $name Module name
472 * @return ResourceLoaderModule|null If module has been registered, return a
473 * ResourceLoaderModule instance. Otherwise, return null.
475 public function getModule( $name ) {
476 if ( !isset( $this->modules[$name] ) ) {
477 if ( !isset( $this->moduleInfos[$name] ) ) {
478 // No such module
479 return null;
481 // Construct the requested object
482 $info = $this->moduleInfos[$name];
483 /** @var ResourceLoaderModule $object */
484 if ( isset( $info['object'] ) ) {
485 // Object given in info array
486 $object = $info['object'];
487 } else {
488 if ( !isset( $info['class'] ) ) {
489 $class = 'ResourceLoaderFileModule';
490 } else {
491 $class = $info['class'];
493 /** @var ResourceLoaderModule $object */
494 $object = new $class( $info );
495 $object->setConfig( $this->getConfig() );
497 $object->setName( $name );
498 $this->modules[$name] = $object;
501 return $this->modules[$name];
505 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
507 * @param string $name Module name
508 * @return bool
510 protected function isFileModule( $name ) {
511 if ( !isset( $this->moduleInfos[$name] ) ) {
512 return false;
514 $info = $this->moduleInfos[$name];
515 if ( isset( $info['object'] ) || isset( $info['class'] ) ) {
516 return false;
518 return true;
522 * Get the list of sources.
524 * @return array Like array( id => load.php url, .. )
526 public function getSources() {
527 return $this->sources;
531 * Get the URL to the load.php endpoint for the given
532 * ResourceLoader source
534 * @since 1.24
535 * @param string $source
536 * @throws MWException On an invalid $source name
537 * @return string
539 public function getLoadScript( $source ) {
540 if ( !isset( $this->sources[$source] ) ) {
541 throw new MWException( "The $source source was never registered in ResourceLoader." );
543 return $this->sources[$source];
547 * Output a response to a load request, including the content-type header.
549 * @param ResourceLoaderContext $context Context in which a response should be formed
551 public function respond( ResourceLoaderContext $context ) {
552 // Use file cache if enabled and available...
553 if ( $this->config->get( 'UseFileCache' ) ) {
554 $fileCache = ResourceFileCache::newFromContext( $context );
555 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
556 return; // output handled
560 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
561 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
562 // is used: ob_clean() will clear the GZIP header in that case and it won't come
563 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
564 // the whole thing in our own output buffer to be sure the active buffer
565 // doesn't use ob_gzhandler.
566 // See http://bugs.php.net/bug.php?id=36514
567 ob_start();
569 // Find out which modules are missing and instantiate the others
570 $modules = array();
571 $missing = array();
572 foreach ( $context->getModules() as $name ) {
573 $module = $this->getModule( $name );
574 if ( $module ) {
575 // Do not allow private modules to be loaded from the web.
576 // This is a security issue, see bug 34907.
577 if ( $module->getGroup() === 'private' ) {
578 wfDebugLog( 'resourceloader', __METHOD__ . ": request for private module '$name' denied" );
579 $this->errors[] = "Cannot show private module \"$name\"";
580 continue;
582 $modules[$name] = $module;
583 } else {
584 $missing[] = $name;
588 // Preload information needed to the mtime calculation below
589 try {
590 $this->preloadModuleInfo( array_keys( $modules ), $context );
591 } catch ( Exception $e ) {
592 MWExceptionHandler::logException( $e );
593 wfDebugLog( 'resourceloader', __METHOD__ . ": preloading module info failed: $e" );
594 $this->errors[] = self::formatExceptionNoComment( $e );
597 // To send Last-Modified and support If-Modified-Since, we need to detect
598 // the last modified time
599 $mtime = wfTimestamp( TS_UNIX, $this->config->get( 'CacheEpoch' ) );
600 foreach ( $modules as $module ) {
602 * @var $module ResourceLoaderModule
604 try {
605 // Calculate maximum modified time
606 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
607 } catch ( Exception $e ) {
608 MWExceptionHandler::logException( $e );
609 wfDebugLog( 'resourceloader', __METHOD__ . ": calculating maximum modified time failed: $e" );
610 $this->errors[] = self::formatExceptionNoComment( $e );
614 // If there's an If-Modified-Since header, respond with a 304 appropriately
615 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
616 return; // output handled (buffers cleared)
619 // Generate a response
620 $response = $this->makeModuleResponse( $context, $modules, $missing );
622 // Capture any PHP warnings from the output buffer and append them to the
623 // error list if we're in debug mode.
624 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
625 $this->errors[] = $warnings;
628 // Save response to file cache unless there are errors
629 if ( isset( $fileCache ) && !$this->errors && !count( $missing ) ) {
630 // Cache single modules and images...and other requests if there are enough hits
631 if ( ResourceFileCache::useFileCache( $context ) ) {
632 if ( $fileCache->isCacheWorthy() ) {
633 $fileCache->saveText( $response );
634 } else {
635 $fileCache->incrMissesRecent( $context->getRequest() );
640 // Send content type and cache related headers
641 $this->sendResponseHeaders( $context, $mtime, (bool)$this->errors );
643 // Remove the output buffer and output the response
644 ob_end_clean();
646 if ( $context->getImageObj() && $this->errors ) {
647 // We can't show both the error messages and the response when it's an image.
648 $errorText = '';
649 foreach ( $this->errors as $error ) {
650 $errorText .= $error . "\n";
652 $response = $errorText;
653 } elseif ( $this->errors ) {
654 // Prepend comments indicating errors
655 $errorText = '';
656 foreach ( $this->errors as $error ) {
657 $errorText .= self::makeComment( $error );
659 $response = $errorText . $response;
662 $this->errors = array();
663 echo $response;
668 * Send content type and last modified headers to the client.
669 * @param ResourceLoaderContext $context
670 * @param string $mtime TS_MW timestamp to use for last-modified
671 * @param bool $errors Whether there are errors in the response
672 * @return void
674 protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $errors ) {
675 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
676 // If a version wasn't specified we need a shorter expiry time for updates
677 // to propagate to clients quickly
678 // If there were errors, we also need a shorter expiry time so we can recover quickly
679 if ( is_null( $context->getVersion() ) || $errors ) {
680 $maxage = $rlMaxage['unversioned']['client'];
681 $smaxage = $rlMaxage['unversioned']['server'];
682 // If a version was specified we can use a longer expiry time since changing
683 // version numbers causes cache misses
684 } else {
685 $maxage = $rlMaxage['versioned']['client'];
686 $smaxage = $rlMaxage['versioned']['server'];
688 if ( $context->getImageObj() ) {
689 // Output different headers if we're outputting textual errors.
690 if ( $errors ) {
691 header( 'Content-Type: text/plain; charset=utf-8' );
692 } else {
693 $context->getImageObj()->sendResponseHeaders( $context );
695 } elseif ( $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 in a CSS/JS comment that can be returned to the user
821 public static function formatException( $e ) {
822 return self::makeComment( self::formatExceptionNoComment( $e ) );
826 * Handle exception display.
828 * @since 1.25
829 * @param Exception $e Exception to be shown to the user
830 * @return string Sanitized text that can be returned to the user
832 protected static function formatExceptionNoComment( $e ) {
833 global $wgShowExceptionDetails;
835 if ( $wgShowExceptionDetails ) {
836 return $e->__toString();
837 } else {
838 return wfMessage( 'internalerror' )->text();
843 * Generate code for a response.
845 * @param ResourceLoaderContext $context Context in which to generate a response
846 * @param array $modules List of module objects keyed by module name
847 * @param array $missing List of requested module names that are unregistered (optional)
848 * @return string Response data
850 public function makeModuleResponse( ResourceLoaderContext $context,
851 array $modules, array $missing = array()
853 $out = '';
854 $states = array();
856 if ( !count( $modules ) && !count( $missing ) ) {
857 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
858 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
859 no modules were requested. Max made me put this here. */";
862 $image = $context->getImageObj();
863 if ( $image ) {
864 $data = $image->getImageData( $context );
865 if ( $data === false ) {
866 $data = '';
867 $this->errors[] = 'Image generation failed';
869 return $data;
872 // Pre-fetch blobs
873 if ( $context->shouldIncludeMessages() ) {
874 try {
875 $blobs = MessageBlobStore::getInstance()->get( $this, $modules, $context->getLanguage() );
876 } catch ( Exception $e ) {
877 MWExceptionHandler::logException( $e );
878 wfDebugLog(
879 'resourceloader',
880 __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e"
882 $this->errors[] = self::formatExceptionNoComment( $e );
884 } else {
885 $blobs = array();
888 foreach ( $missing as $name ) {
889 $states[$name] = 'missing';
892 // Generate output
893 $isRaw = false;
894 foreach ( $modules as $name => $module ) {
896 * @var $module ResourceLoaderModule
899 try {
900 $scripts = '';
901 if ( $context->shouldIncludeScripts() ) {
902 // If we are in debug mode, we'll want to return an array of URLs if possible
903 // However, we can't do this if the module doesn't support it
904 // We also can't do this if there is an only= parameter, because we have to give
905 // the module a way to return a load.php URL without causing an infinite loop
906 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
907 $scripts = $module->getScriptURLsForDebug( $context );
908 } else {
909 $scripts = $module->getScript( $context );
910 // rtrim() because there are usually a few line breaks
911 // after the last ';'. A new line at EOF, a new line
912 // added by ResourceLoaderFileModule::readScriptFiles, etc.
913 if ( is_string( $scripts )
914 && strlen( $scripts )
915 && substr( rtrim( $scripts ), -1 ) !== ';'
917 // Append semicolon to prevent weird bugs caused by files not
918 // terminating their statements right (bug 27054)
919 $scripts .= ";\n";
923 // Styles
924 $styles = array();
925 if ( $context->shouldIncludeStyles() ) {
926 // Don't create empty stylesheets like array( '' => '' ) for modules
927 // that don't *have* any stylesheets (bug 38024).
928 $stylePairs = $module->getStyles( $context );
929 if ( count( $stylePairs ) ) {
930 // If we are in debug mode without &only= set, we'll want to return an array of URLs
931 // See comment near shouldIncludeScripts() for more details
932 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
933 $styles = array(
934 'url' => $module->getStyleURLsForDebug( $context )
936 } else {
937 // Minify CSS before embedding in mw.loader.implement call
938 // (unless in debug mode)
939 if ( !$context->getDebug() ) {
940 foreach ( $stylePairs as $media => $style ) {
941 // Can be either a string or an array of strings.
942 if ( is_array( $style ) ) {
943 $stylePairs[$media] = array();
944 foreach ( $style as $cssText ) {
945 if ( is_string( $cssText ) ) {
946 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
949 } elseif ( is_string( $style ) ) {
950 $stylePairs[$media] = $this->filter( 'minify-css', $style );
954 // Wrap styles into @media groups as needed and flatten into a numerical array
955 $styles = array(
956 'css' => self::makeCombinedStyles( $stylePairs )
962 // Messages
963 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
965 // Append output
966 switch ( $context->getOnly() ) {
967 case 'scripts':
968 if ( is_string( $scripts ) ) {
969 // Load scripts raw...
970 $out .= $scripts;
971 } elseif ( is_array( $scripts ) ) {
972 // ...except when $scripts is an array of URLs
973 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
975 break;
976 case 'styles':
977 // We no longer seperate into media, they are all combined now with
978 // custom media type groups into @media .. {} sections as part of the css string.
979 // Module returns either an empty array or a numerical array with css strings.
980 $out .= isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
981 break;
982 case 'messages':
983 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
984 break;
985 case 'templates':
986 $out .= Xml::encodeJsCall(
987 'mw.templates.set',
988 array( $name, (object)$module->getTemplates() ),
989 ResourceLoader::inDebugMode()
991 break;
992 default:
993 $out .= self::makeLoaderImplementScript(
994 $name,
995 $scripts,
996 $styles,
997 new XmlJsCode( $messagesBlob ),
998 $module->getTemplates()
1000 break;
1002 } catch ( Exception $e ) {
1003 MWExceptionHandler::logException( $e );
1004 wfDebugLog( 'resourceloader', __METHOD__ . ": generating module package failed: $e" );
1005 $this->errors[] = self::formatExceptionNoComment( $e );
1007 // Respond to client with error-state instead of module implementation
1008 $states[$name] = 'error';
1009 unset( $modules[$name] );
1011 $isRaw |= $module->isRaw();
1014 // Update module states
1015 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1016 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1017 // Set the state of modules loaded as only scripts to ready as
1018 // they don't have an mw.loader.implement wrapper that sets the state
1019 foreach ( $modules as $name => $module ) {
1020 $states[$name] = 'ready';
1024 // Set the state of modules we didn't respond to with mw.loader.implement
1025 if ( count( $states ) ) {
1026 $out .= self::makeLoaderStateScript( $states );
1028 } else {
1029 if ( count( $states ) ) {
1030 $this->errors[] = 'Problematic modules: ' .
1031 FormatJson::encode( $states, ResourceLoader::inDebugMode() );
1035 if ( !$context->getDebug() ) {
1036 if ( $context->getOnly() === 'styles' ) {
1037 $out = $this->filter( 'minify-css', $out );
1038 } else {
1039 $out = $this->filter( 'minify-js', $out );
1043 return $out;
1046 /* Static Methods */
1049 * Return JS code that calls mw.loader.implement with given module properties.
1051 * @param string $name Module name
1052 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1053 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1054 * to CSS files keyed by media type
1055 * @param mixed $messages List of messages associated with this module. May either be an
1056 * associative array mapping message key to value, or a JSON-encoded message blob containing
1057 * the same data, wrapped in an XmlJsCode object.
1058 * @param array $templates Keys are name of templates and values are the source of
1059 * the template.
1060 * @throws MWException
1061 * @return string
1063 public static function makeLoaderImplementScript( $name, $scripts, $styles,
1064 $messages, $templates
1066 if ( is_string( $scripts ) ) {
1067 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1068 } elseif ( !is_array( $scripts ) ) {
1069 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1072 return Xml::encodeJsCall(
1073 'mw.loader.implement',
1074 array(
1075 $name,
1076 $scripts,
1077 // Force objects. mw.loader.implement requires them to be javascript objects.
1078 // Although these variables are associative arrays, which become javascript
1079 // objects through json_encode. In many cases they will be empty arrays, and
1080 // PHP/json_encode() consider empty arrays to be numerical arrays and
1081 // output javascript "[]" instead of "{}". This fixes that.
1082 (object)$styles,
1083 (object)$messages,
1084 (object)$templates,
1086 ResourceLoader::inDebugMode()
1091 * Returns JS code which, when called, will register a given list of messages.
1093 * @param mixed $messages Either an associative array mapping message key to value, or a
1094 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1095 * @return string
1097 public static function makeMessageSetScript( $messages ) {
1098 return Xml::encodeJsCall(
1099 'mw.messages.set',
1100 array( (object)$messages ),
1101 ResourceLoader::inDebugMode()
1106 * Combines an associative array mapping media type to CSS into a
1107 * single stylesheet with "@media" blocks.
1109 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1110 * @return array
1112 public static function makeCombinedStyles( array $stylePairs ) {
1113 $out = array();
1114 foreach ( $stylePairs as $media => $styles ) {
1115 // ResourceLoaderFileModule::getStyle can return the styles
1116 // as a string or an array of strings. This is to allow separation in
1117 // the front-end.
1118 $styles = (array)$styles;
1119 foreach ( $styles as $style ) {
1120 $style = trim( $style );
1121 // Don't output an empty "@media print { }" block (bug 40498)
1122 if ( $style !== '' ) {
1123 // Transform the media type based on request params and config
1124 // The way that this relies on $wgRequest to propagate request params is slightly evil
1125 $media = OutputPage::transformCssMedia( $media );
1127 if ( $media === '' || $media == 'all' ) {
1128 $out[] = $style;
1129 } elseif ( is_string( $media ) ) {
1130 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1132 // else: skip
1136 return $out;
1140 * Returns a JS call to mw.loader.state, which sets the state of a
1141 * module or modules to a given value. Has two calling conventions:
1143 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1144 * Set the state of a single module called $name to $state
1146 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1147 * Set the state of modules with the given names to the given states
1149 * @param string $name
1150 * @param string $state
1151 * @return string
1153 public static function makeLoaderStateScript( $name, $state = null ) {
1154 if ( is_array( $name ) ) {
1155 return Xml::encodeJsCall(
1156 'mw.loader.state',
1157 array( $name ),
1158 ResourceLoader::inDebugMode()
1160 } else {
1161 return Xml::encodeJsCall(
1162 'mw.loader.state',
1163 array( $name, $state ),
1164 ResourceLoader::inDebugMode()
1170 * Returns JS code which calls the script given by $script. The script will
1171 * be called with local variables name, version, dependencies and group,
1172 * which will have values corresponding to $name, $version, $dependencies
1173 * and $group as supplied.
1175 * @param string $name Module name
1176 * @param int $version Module version number as a timestamp
1177 * @param array $dependencies List of module names on which this module depends
1178 * @param string $group Group which the module is in.
1179 * @param string $source Source of the module, or 'local' if not foreign.
1180 * @param string $script JavaScript code
1181 * @return string
1183 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1184 $group, $source, $script
1186 $script = str_replace( "\n", "\n\t", trim( $script ) );
1187 return Xml::encodeJsCall(
1188 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1189 array( $name, $version, $dependencies, $group, $source ),
1190 ResourceLoader::inDebugMode()
1195 * Remove empty values from the end of an array.
1197 * Values considered empty:
1199 * - null
1200 * - empty array
1202 * @param Array $array
1204 private static function trimArray( Array &$array ) {
1205 $i = count( $array );
1206 while ( $i-- ) {
1207 if ( $array[$i] === null || $array[$i] === array() ) {
1208 unset( $array[$i] );
1209 } else {
1210 break;
1216 * Returns JS code which calls mw.loader.register with the given
1217 * parameters. Has three calling conventions:
1219 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1220 * $dependencies, $group, $source, $skip
1221 * ):
1222 * Register a single module.
1224 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1225 * Register modules with the given names.
1227 * - ResourceLoader::makeLoaderRegisterScript( array(
1228 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1229 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1230 * ...
1231 * ) ):
1232 * Registers modules with the given names and parameters.
1234 * @param string $name Module name
1235 * @param int $version Module version number as a timestamp
1236 * @param array $dependencies List of module names on which this module depends
1237 * @param string $group Group which the module is in
1238 * @param string $source Source of the module, or 'local' if not foreign
1239 * @param string $skip Script body of the skip function
1240 * @return string
1242 public static function makeLoaderRegisterScript( $name, $version = null,
1243 $dependencies = null, $group = null, $source = null, $skip = null
1245 if ( is_array( $name ) ) {
1246 // Build module name index
1247 $index = array();
1248 foreach ( $name as $i => &$module ) {
1249 $index[$module[0]] = $i;
1252 // Transform dependency names into indexes when possible, they will be resolved by
1253 // mw.loader.register on the other end
1254 foreach ( $name as &$module ) {
1255 if ( isset( $module[2] ) ) {
1256 foreach ( $module[2] as &$dependency ) {
1257 if ( isset( $index[$dependency] ) ) {
1258 $dependency = $index[$dependency];
1264 array_walk( $name, array( 'self', 'trimArray' ) );
1266 return Xml::encodeJsCall(
1267 'mw.loader.register',
1268 array( $name ),
1269 ResourceLoader::inDebugMode()
1271 } else {
1272 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1273 self::trimArray( $registration );
1274 return Xml::encodeJsCall(
1275 'mw.loader.register',
1276 $registration,
1277 ResourceLoader::inDebugMode()
1283 * Returns JS code which calls mw.loader.addSource() with the given
1284 * parameters. Has two calling conventions:
1286 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1287 * Register a single source
1289 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1290 * Register sources with the given IDs and properties.
1292 * @param string $id Source ID
1293 * @param array $properties Source properties (see addSource())
1294 * @return string
1296 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1297 if ( is_array( $id ) ) {
1298 return Xml::encodeJsCall(
1299 'mw.loader.addSource',
1300 array( $id ),
1301 ResourceLoader::inDebugMode()
1303 } else {
1304 return Xml::encodeJsCall(
1305 'mw.loader.addSource',
1306 array( $id, $properties ),
1307 ResourceLoader::inDebugMode()
1313 * Returns JS code which runs given JS code if the client-side framework is
1314 * present.
1316 * @param string $script JavaScript code
1317 * @return string
1319 public static function makeLoaderConditionalScript( $script ) {
1320 return "if(window.mw){\n" . trim( $script ) . "\n}";
1324 * Returns JS code which will set the MediaWiki configuration array to
1325 * the given value.
1327 * @param array $configuration List of configuration values keyed by variable name
1328 * @return string
1330 public static function makeConfigSetScript( array $configuration ) {
1331 return Xml::encodeJsCall(
1332 'mw.config.set',
1333 array( $configuration ),
1334 ResourceLoader::inDebugMode()
1339 * Convert an array of module names to a packed query string.
1341 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1342 * becomes 'foo.bar,baz|bar.baz,quux'
1343 * @param array $modules List of module names (strings)
1344 * @return string Packed query string
1346 public static function makePackedModulesString( $modules ) {
1347 $groups = array(); // array( prefix => array( suffixes ) )
1348 foreach ( $modules as $module ) {
1349 $pos = strrpos( $module, '.' );
1350 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1351 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1352 $groups[$prefix][] = $suffix;
1355 $arr = array();
1356 foreach ( $groups as $prefix => $suffixes ) {
1357 $p = $prefix === '' ? '' : $prefix . '.';
1358 $arr[] = $p . implode( ',', $suffixes );
1360 $str = implode( '|', $arr );
1361 return $str;
1365 * Determine whether debug mode was requested
1366 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1367 * @return bool
1369 public static function inDebugMode() {
1370 if ( self::$debugMode === null ) {
1371 global $wgRequest, $wgResourceLoaderDebug;
1372 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1373 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1376 return self::$debugMode;
1380 * Reset static members used for caching.
1382 * Global state and $wgRequest are evil, but we're using it right
1383 * now and sometimes we need to be able to force ResourceLoader to
1384 * re-evaluate the context because it has changed (e.g. in the test suite).
1386 public static function clearCache() {
1387 self::$debugMode = null;
1391 * Build a load.php URL
1393 * @since 1.24
1394 * @param string $source Name of the ResourceLoader source
1395 * @param ResourceLoaderContext $context
1396 * @param array $extraQuery
1397 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1399 public function createLoaderURL( $source, ResourceLoaderContext $context,
1400 $extraQuery = array()
1402 $query = self::createLoaderQuery( $context, $extraQuery );
1403 $script = $this->getLoadScript( $source );
1405 // Prevent the IE6 extension check from being triggered (bug 28840)
1406 // by appending a character that's invalid in Windows extensions ('*')
1407 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE );
1411 * Build a load.php URL
1412 * @deprecated since 1.24, use createLoaderURL instead
1413 * @param array $modules Array of module names (strings)
1414 * @param string $lang Language code
1415 * @param string $skin Skin name
1416 * @param string|null $user User name. If null, the &user= parameter is omitted
1417 * @param string|null $version Versioning timestamp
1418 * @param bool $debug Whether the request should be in debug mode
1419 * @param string|null $only &only= parameter
1420 * @param bool $printable Printable mode
1421 * @param bool $handheld Handheld mode
1422 * @param array $extraQuery Extra query parameters to add
1423 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1425 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1426 $version = null, $debug = false, $only = null, $printable = false,
1427 $handheld = false, $extraQuery = array()
1429 global $wgLoadScript;
1431 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1432 $only, $printable, $handheld, $extraQuery
1435 // Prevent the IE6 extension check from being triggered (bug 28840)
1436 // by appending a character that's invalid in Windows extensions ('*')
1437 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
1441 * Helper for createLoaderURL()
1443 * @since 1.24
1444 * @see makeLoaderQuery
1445 * @param ResourceLoaderContext $context
1446 * @param array $extraQuery
1447 * @return array
1449 public static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = array() ) {
1450 return self::makeLoaderQuery(
1451 $context->getModules(),
1452 $context->getLanguage(),
1453 $context->getSkin(),
1454 $context->getUser(),
1455 $context->getVersion(),
1456 $context->getDebug(),
1457 $context->getOnly(),
1458 $context->getRequest()->getBool( 'printable' ),
1459 $context->getRequest()->getBool( 'handheld' ),
1460 $extraQuery
1465 * Build a query array (array representation of query string) for load.php. Helper
1466 * function for makeLoaderURL().
1468 * @param array $modules
1469 * @param string $lang
1470 * @param string $skin
1471 * @param string $user
1472 * @param string $version
1473 * @param bool $debug
1474 * @param string $only
1475 * @param bool $printable
1476 * @param bool $handheld
1477 * @param array $extraQuery
1479 * @return array
1481 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1482 $version = null, $debug = false, $only = null, $printable = false,
1483 $handheld = false, $extraQuery = array()
1485 $query = array(
1486 'modules' => self::makePackedModulesString( $modules ),
1487 'lang' => $lang,
1488 'skin' => $skin,
1489 'debug' => $debug ? 'true' : 'false',
1491 if ( $user !== null ) {
1492 $query['user'] = $user;
1494 if ( $version !== null ) {
1495 $query['version'] = $version;
1497 if ( $only !== null ) {
1498 $query['only'] = $only;
1500 if ( $printable ) {
1501 $query['printable'] = 1;
1503 if ( $handheld ) {
1504 $query['handheld'] = 1;
1506 $query += $extraQuery;
1508 // Make queries uniform in order
1509 ksort( $query );
1510 return $query;
1514 * Check a module name for validity.
1516 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1517 * at most 255 bytes.
1519 * @param string $moduleName Module name to check
1520 * @return bool Whether $moduleName is a valid module name
1522 public static function isValidModuleName( $moduleName ) {
1523 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1527 * Returns LESS compiler set up for use with MediaWiki
1529 * @param Config $config
1530 * @throws MWException
1531 * @since 1.22
1532 * @return lessc
1534 public static function getLessCompiler( Config $config ) {
1535 // When called from the installer, it is possible that a required PHP extension
1536 // is missing (at least for now; see bug 47564). If this is the case, throw an
1537 // exception (caught by the installer) to prevent a fatal error later on.
1538 if ( !class_exists( 'lessc' ) ) {
1539 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1541 if ( !function_exists( 'ctype_digit' ) ) {
1542 throw new MWException( 'lessc requires the Ctype extension' );
1545 $less = new lessc();
1546 $less->setPreserveComments( true );
1547 $less->setVariables( self::getLessVars( $config ) );
1548 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1549 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1550 $less->registerFunction( $name, $func );
1552 return $less;
1556 * Get global LESS variables.
1558 * @param Config $config
1559 * @since 1.22
1560 * @return array Map of variable names to string CSS values.
1562 public static function getLessVars( Config $config ) {
1563 if ( !self::$lessVars ) {
1564 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1565 Hooks::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1566 // Sort by key to ensure consistent hashing for cache lookups.
1567 ksort( $lessVars );
1568 self::$lessVars = $lessVars;
1570 return self::$lessVars;