3 * Base class for resource loading system.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Roan Kattouw
22 * @author Trevor Parscal
25 use Psr\Log\LoggerAwareInterface
;
26 use Psr\Log\LoggerInterface
;
27 use Psr\Log\NullLogger
;
28 use WrappedString\WrappedString
;
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
{
38 protected static $filterCacheVersion = 7;
41 protected static $debugMode = null;
44 private static $lessVars = null;
47 * Module name/ResourceLoaderModule object pairs
50 protected $modules = array();
53 * Associative array mapping module name to info associative array
56 protected $moduleInfos = array();
58 /** @var Config $config */
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', .. ), .. )
66 protected $testModuleNames = array();
69 * E.g. array( 'source-id' => 'http://.../load.php' )
72 protected $sources = array();
75 * Errors accumulated during current respond() call.
78 protected $errors = array();
81 * @var MessageBlobStore
86 * @var LoggerInterface
90 /** @var string JavaScript / CSS pragma to disable minification. **/
91 const FILTER_NOMIN
= ' /* @nomin */ ';
94 * Load information stored in the database about modules.
96 * This method grabs modules dependencies from the database and updates modules
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 $modules List of module names to preload information for
105 * @param ResourceLoaderContext $context Context to load the information within
107 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
108 if ( !count( $modules ) ) {
109 // Or else Database*::select() will explode, plus it's cheaper!
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' => $modules,
123 // Prime in-object cache values for each module
124 $modulesWithDeps = array();
125 foreach ( $res as $row ) {
126 $module = $this->getModule( $row->md_module
);
128 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
129 FormatJson
::decode( $row->md_deps
, true )
131 $modulesWithDeps[] = $row->md_module
;
134 // Register the absence of a dependency row too
135 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
136 $module = $this->getModule( $name );
138 $this->getModule( $name )->setFileDependencies( $context, array() );
142 // Get message blob mtimes. Only do this for modules with messages
143 $modulesWithMessages = array();
144 foreach ( $modules as $name ) {
145 $module = $this->getModule( $name );
146 if ( $module && count( $module->getMessages() ) ) {
147 $modulesWithMessages[] = $name;
150 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
151 if ( count( $modulesWithMessages ) ) {
152 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
153 'mr_resource' => $modulesWithMessages,
157 foreach ( $res as $row ) {
158 $module = $this->getModule( $row->mr_resource
);
160 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
161 unset( $modulesWithoutMessages[$row->mr_resource
] );
165 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
166 $module = $this->getModule( $name );
168 $module->setMsgBlobMtime( $lang, 1 );
174 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
176 * Available filters are:
178 * - minify-js \see JavaScriptMinifier::minify
179 * - minify-css \see CSSMin::minify
181 * If $data is empty, only contains whitespace or the filter was unknown,
182 * $data is returned unmodified.
184 * @param string $filter Name of filter to run
185 * @param string $data Text to filter, such as JavaScript or CSS text
186 * @param array $options Keys:
187 * - (bool) cache: Whether to allow caching this data. Default: true.
188 * @return string Filtered data, or a comment containing an error message
190 public static function filter( $filter, $data, Array $options = array() ) {
191 if ( strpos( $data, ResourceLoader
::FILTER_NOMIN
) !== false ) {
195 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
196 return self
::applyFilter( $filter, $data );
199 $stats = RequestContext
::getMain()->getStats();
200 $cache = ObjectCache
::newAccelerator( CACHE_ANYTHING
);
202 $key = $cache->makeGlobalKey(
206 self
::$filterCacheVersion, md5( $data )
209 $result = $cache->get( $key );
210 if ( $result === false ) {
211 $stats->increment( "resourceloader_cache.$filter.miss" );
212 $result = self
::applyFilter( $filter, $data );
213 $cache->set( $key, $result, 24 * 3600 );
215 $stats->increment( "resourceloader_cache.$filter.hit" );
217 if ( $result === null ) {
225 private static function applyFilter( $filter, $data ) {
226 $data = trim( $data );
229 $data = ( $filter === 'minify-css' )
230 ? CSSMin
::minify( $data )
231 : JavaScriptMinifier
::minify( $data );
232 } catch ( Exception
$e ) {
233 MWExceptionHandler
::logException( $e );
243 * Register core modules and runs registration hooks.
244 * @param Config|null $config
246 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
250 $logger = new NullLogger();
252 $this->setLogger( $logger );
255 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
256 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
258 $this->config
= $config;
260 // Add 'local' source first
261 $this->addSource( 'local', wfScript( 'load' ) );
264 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
266 // Register core modules
267 $this->register( include "$IP/resources/Resources.php" );
268 $this->register( include "$IP/resources/ResourcesOOUI.php" );
269 // Register extension modules
270 $this->register( $config->get( 'ResourceModules' ) );
271 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
273 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
274 $this->registerTestModules();
277 $this->setMessageBlobStore( new MessageBlobStore() );
283 public function getConfig() {
284 return $this->config
;
287 public function setLogger( LoggerInterface
$logger ) {
288 $this->logger
= $logger;
293 * @return MessageBlobStore
295 public function getMessageBlobStore() {
296 return $this->blobStore
;
301 * @param MessageBlobStore $blobStore
303 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
304 $this->blobStore
= $blobStore;
308 * Register a module with the ResourceLoader system.
310 * @param mixed $name Name of module as a string or List of name/object pairs as an array
311 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
312 * this may also be a ResourceLoaderModule object. Optional when using
313 * multiple-registration calling style.
314 * @throws MWException If a duplicate module registration is attempted
315 * @throws MWException If a module name contains illegal characters (pipes or commas)
316 * @throws MWException If something other than a ResourceLoaderModule is being registered
317 * @return bool False if there were any errors, in which case one or more modules were
320 public function register( $name, $info = null ) {
322 // Allow multiple modules to be registered in one call
323 $registrations = is_array( $name ) ?
$name : array( $name => $info );
324 foreach ( $registrations as $name => $info ) {
325 // Warn on duplicate registrations
326 if ( isset( $this->moduleInfos
[$name] ) ) {
327 // A module has already been registered by this name
328 if ( $this->moduleInfos
[$name] === $info ) {
329 $this->logger
->warning(
330 'ResourceLoader duplicate registration warning. ' .
331 'Another module has already been registered as ' . $name
336 // Check $name for validity
337 if ( !self
::isValidModuleName( $name ) ) {
338 throw new MWException( "ResourceLoader module name '$name' is invalid, "
339 . "see ResourceLoader::isValidModuleName()" );
343 if ( $info instanceof ResourceLoaderModule
) {
344 $this->moduleInfos
[$name] = array( 'object' => $info );
345 $info->setName( $name );
346 $this->modules
[$name] = $info;
347 } elseif ( is_array( $info ) ) {
348 // New calling convention
349 $this->moduleInfos
[$name] = $info;
351 throw new MWException(
352 'ResourceLoader module info type error for module \'' . $name .
353 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
357 // Last-minute changes
359 // Apply custom skin-defined styles to existing modules.
360 if ( $this->isFileModule( $name ) ) {
361 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
362 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
363 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
367 // If $name is preceded with a '+', the defined style files will be added to 'default'
368 // skinStyles, otherwise 'default' will be ignored as it normally would be.
369 if ( isset( $skinStyles[$name] ) ) {
370 $paths = (array)$skinStyles[$name];
371 $styleFiles = array();
372 } elseif ( isset( $skinStyles['+' . $name] ) ) {
373 $paths = (array)$skinStyles['+' . $name];
374 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
375 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
381 // Add new file paths, remapping them to refer to our directories and not use settings
382 // from the module we're modifying, which come from the base definition.
383 list( $localBasePath, $remoteBasePath ) =
384 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
386 foreach ( $paths as $path ) {
387 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
390 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
399 public function registerTestModules() {
402 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
403 throw new MWException( 'Attempt to register JavaScript test modules '
404 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
405 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
408 // Get core test suites
409 $testModules = array();
410 $testModules['qunit'] = array();
411 // Get other test suites (e.g. from extensions)
412 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
414 // Add the testrunner (which configures QUnit) to the dependencies.
415 // Since it must be ready before any of the test suites are executed.
416 foreach ( $testModules['qunit'] as &$module ) {
417 // Make sure all test modules are top-loading so that when QUnit starts
418 // on document-ready, it will run once and finish. If some tests arrive
419 // later (possibly after QUnit has already finished) they will be ignored.
420 $module['position'] = 'top';
421 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
424 $testModules['qunit'] =
425 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
427 foreach ( $testModules as $id => $names ) {
428 // Register test modules
429 $this->register( $testModules[$id] );
431 // Keep track of their names so that they can be loaded together
432 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
438 * Add a foreign source of modules.
440 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
441 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
442 * backwards-compatibility.
443 * @throws MWException
445 public function addSource( $id, $loadUrl = null ) {
446 // Allow multiple sources to be registered in one call
447 if ( is_array( $id ) ) {
448 foreach ( $id as $key => $value ) {
449 $this->addSource( $key, $value );
454 // Disallow duplicates
455 if ( isset( $this->sources
[$id] ) ) {
456 throw new MWException(
457 'ResourceLoader duplicate source addition error. ' .
458 'Another source has already been registered as ' . $id
462 // Pre 1.24 backwards-compatibility
463 if ( is_array( $loadUrl ) ) {
464 if ( !isset( $loadUrl['loadScript'] ) ) {
465 throw new MWException(
466 __METHOD__
. ' was passed an array with no "loadScript" key.'
470 $loadUrl = $loadUrl['loadScript'];
473 $this->sources
[$id] = $loadUrl;
477 * Get a list of module names.
479 * @return array List of module names
481 public function getModuleNames() {
482 return array_keys( $this->moduleInfos
);
486 * Get a list of test module names for one (or all) frameworks.
488 * If the given framework id is unknkown, or if the in-object variable is not an array,
489 * then it will return an empty array.
491 * @param string $framework Get only the test module names for one
492 * particular framework (optional)
495 public function getTestModuleNames( $framework = 'all' ) {
496 /** @todo api siteinfo prop testmodulenames modulenames */
497 if ( $framework == 'all' ) {
498 return $this->testModuleNames
;
499 } elseif ( isset( $this->testModuleNames
[$framework] )
500 && is_array( $this->testModuleNames
[$framework] )
502 return $this->testModuleNames
[$framework];
509 * Check whether a ResourceLoader module is registered
512 * @param string $name
515 public function isModuleRegistered( $name ) {
516 return isset( $this->moduleInfos
[$name] );
520 * Get the ResourceLoaderModule object for a given module name.
522 * If an array of module parameters exists but a ResourceLoaderModule object has not
523 * yet been instantiated, this method will instantiate and cache that object such that
524 * subsequent calls simply return the same object.
526 * @param string $name Module name
527 * @return ResourceLoaderModule|null If module has been registered, return a
528 * ResourceLoaderModule instance. Otherwise, return null.
530 public function getModule( $name ) {
531 if ( !isset( $this->modules
[$name] ) ) {
532 if ( !isset( $this->moduleInfos
[$name] ) ) {
536 // Construct the requested object
537 $info = $this->moduleInfos
[$name];
538 /** @var ResourceLoaderModule $object */
539 if ( isset( $info['object'] ) ) {
540 // Object given in info array
541 $object = $info['object'];
543 if ( !isset( $info['class'] ) ) {
544 $class = 'ResourceLoaderFileModule';
546 $class = $info['class'];
548 /** @var ResourceLoaderModule $object */
549 $object = new $class( $info );
550 $object->setConfig( $this->getConfig() );
552 $object->setName( $name );
553 $this->modules
[$name] = $object;
556 return $this->modules
[$name];
560 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
562 * @param string $name Module name
565 protected function isFileModule( $name ) {
566 if ( !isset( $this->moduleInfos
[$name] ) ) {
569 $info = $this->moduleInfos
[$name];
570 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
577 * Get the list of sources.
579 * @return array Like array( id => load.php url, .. )
581 public function getSources() {
582 return $this->sources
;
586 * Get the URL to the load.php endpoint for the given
587 * ResourceLoader source
590 * @param string $source
591 * @throws MWException On an invalid $source name
594 public function getLoadScript( $source ) {
595 if ( !isset( $this->sources
[$source] ) ) {
596 throw new MWException( "The $source source was never registered in ResourceLoader." );
598 return $this->sources
[$source];
603 * @param string $value
604 * @return string Hash
606 public static function makeHash( $value ) {
607 // Use base64 to output more entropy in a more compact string (default hex is only base16).
608 // The first 8 chars of a base64 encoded digest represent the same binary as
609 // the first 12 chars of a hex encoded digest.
610 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
614 * Helper method to get and combine versions of multiple modules.
617 * @param ResourceLoaderContext $context
618 * @param array $modules List of ResourceLoaderModule objects
619 * @return string Hash
621 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
625 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
626 // http://php.net/functions.anonymous
628 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
629 return $rl->getModule( $module )->getVersionHash( $context );
631 return self
::makeHash( implode( $hashes ) );
635 * Output a response to a load request, including the content-type header.
637 * @param ResourceLoaderContext $context Context in which a response should be formed
639 public function respond( ResourceLoaderContext
$context ) {
640 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
641 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
642 // is used: ob_clean() will clear the GZIP header in that case and it won't come
643 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
644 // the whole thing in our own output buffer to be sure the active buffer
645 // doesn't use ob_gzhandler.
646 // See http://bugs.php.net/bug.php?id=36514
649 // Find out which modules are missing and instantiate the others
652 foreach ( $context->getModules() as $name ) {
653 $module = $this->getModule( $name );
655 // Do not allow private modules to be loaded from the web.
656 // This is a security issue, see bug 34907.
657 if ( $module->getGroup() === 'private' ) {
658 $this->logger
->debug( "Request for private module '$name' denied" );
659 $this->errors
[] = "Cannot show private module \"$name\"";
662 $modules[$name] = $module;
669 // Preload for getCombinedVersion()
670 $this->preloadModuleInfo( array_keys( $modules ), $context );
671 } catch ( Exception
$e ) {
672 MWExceptionHandler
::logException( $e );
673 $this->logger
->warning( 'Preloading module info failed: {exception}', array(
676 $this->errors
[] = self
::formatExceptionNoComment( $e );
679 // Combine versions to propagate cache invalidation
682 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
683 } catch ( Exception
$e ) {
684 MWExceptionHandler
::logException( $e );
685 $this->logger
->warning( 'Calculating version hash failed: {exception}', array(
688 $this->errors
[] = self
::formatExceptionNoComment( $e );
691 // See RFC 2616 § 3.11 Entity Tags
692 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
693 $etag = 'W/"' . $versionHash . '"';
695 // Try the client-side cache first
696 if ( $this->tryRespondNotModified( $context, $etag ) ) {
697 return; // output handled (buffers cleared)
700 // Use file cache if enabled and available...
701 if ( $this->config
->get( 'UseFileCache' ) ) {
702 $fileCache = ResourceFileCache
::newFromContext( $context );
703 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
704 return; // output handled
708 // Generate a response
709 $response = $this->makeModuleResponse( $context, $modules, $missing );
711 // Capture any PHP warnings from the output buffer and append them to the
712 // error list if we're in debug mode.
713 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
714 $this->errors
[] = $warnings;
717 // Save response to file cache unless there are errors
718 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
719 // Cache single modules and images...and other requests if there are enough hits
720 if ( ResourceFileCache
::useFileCache( $context ) ) {
721 if ( $fileCache->isCacheWorthy() ) {
722 $fileCache->saveText( $response );
724 $fileCache->incrMissesRecent( $context->getRequest() );
729 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
731 // Remove the output buffer and output the response
734 if ( $context->getImageObj() && $this->errors
) {
735 // We can't show both the error messages and the response when it's an image.
736 $response = implode( "\n\n", $this->errors
);
737 } elseif ( $this->errors
) {
738 $errorText = implode( "\n\n", $this->errors
);
739 $errorResponse = self
::makeComment( $errorText );
740 if ( $context->shouldIncludeScripts() ) {
741 $errorResponse .= 'if (window.console && console.error) {'
742 . Xml
::encodeJsCall( 'console.error', array( $errorText ) )
746 // Prepend error info to the response
747 $response = $errorResponse . $response;
750 $this->errors
= array();
756 * Send main response headers to the client.
758 * Deals with Content-Type, CORS (for stylesheets), and caching.
760 * @param ResourceLoaderContext $context
761 * @param string $etag ETag header value
762 * @param bool $errors Whether there are errors in the response
765 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
766 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
767 // If a version wasn't specified we need a shorter expiry time for updates
768 // to propagate to clients quickly
769 // If there were errors, we also need a shorter expiry time so we can recover quickly
770 if ( is_null( $context->getVersion() ) ||
$errors ) {
771 $maxage = $rlMaxage['unversioned']['client'];
772 $smaxage = $rlMaxage['unversioned']['server'];
773 // If a version was specified we can use a longer expiry time since changing
774 // version numbers causes cache misses
776 $maxage = $rlMaxage['versioned']['client'];
777 $smaxage = $rlMaxage['versioned']['server'];
779 if ( $context->getImageObj() ) {
780 // Output different headers if we're outputting textual errors.
782 header( 'Content-Type: text/plain; charset=utf-8' );
784 $context->getImageObj()->sendResponseHeaders( $context );
786 } elseif ( $context->getOnly() === 'styles' ) {
787 header( 'Content-Type: text/css; charset=utf-8' );
788 header( 'Access-Control-Allow-Origin: *' );
790 header( 'Content-Type: text/javascript; charset=utf-8' );
792 // See RFC 2616 § 14.19 ETag
793 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
794 header( 'ETag: ' . $etag );
795 if ( $context->getDebug() ) {
796 // Do not cache debug responses
797 header( 'Cache-Control: private, no-cache, must-revalidate' );
798 header( 'Pragma: no-cache' );
800 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
801 $exp = min( $maxage, $smaxage );
802 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
805 // Send the current time expressed as fractional seconds since epoch,
806 // with microsecond precision. This helps distinguish hits from misses
808 header( 'MediaWiki-Timestamp: ' . microtime( true ) );
812 * Respond with HTTP 304 Not Modified if appropiate.
814 * If there's an If-None-Match header, respond with a 304 appropriately
815 * and clear out the output buffer. If the client cache is too old then do nothing.
817 * @param ResourceLoaderContext $context
818 * @param string $etag ETag header value
819 * @return bool True if HTTP 304 was sent and output handled
821 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
822 // See RFC 2616 § 14.26 If-None-Match
823 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
824 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
825 // Never send 304s in debug mode
826 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
827 // There's another bug in ob_gzhandler (see also the comment at
828 // the top of this function) that causes it to gzip even empty
829 // responses, meaning it's impossible to produce a truly empty
830 // response (because the gzip header is always there). This is
831 // a problem because 304 responses have to be completely empty
832 // per the HTTP spec, and Firefox behaves buggily when they're not.
833 // See also http://bugs.php.net/bug.php?id=51579
834 // To work around this, we tear down all output buffering before
836 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
838 HttpStatus
::header( 304 );
840 $this->sendResponseHeaders( $context, $etag, false );
847 * Send out code for a response from file cache if possible.
849 * @param ResourceFileCache $fileCache Cache object for this request URL
850 * @param ResourceLoaderContext $context Context in which to generate a response
851 * @param string $etag ETag header value
852 * @return bool If this found a cache file and handled the response
854 protected function tryRespondFromFileCache(
855 ResourceFileCache
$fileCache,
856 ResourceLoaderContext
$context,
859 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
860 // Buffer output to catch warnings.
862 // Get the maximum age the cache can be
863 $maxage = is_null( $context->getVersion() )
864 ?
$rlMaxage['unversioned']['server']
865 : $rlMaxage['versioned']['server'];
866 // Minimum timestamp the cache file must have
867 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
869 try { // RL always hits the DB on file cache miss...
871 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
872 $good = $fileCache->isCacheGood(); // cache existence check
876 $ts = $fileCache->cacheTimestamp();
877 // Send content type and cache headers
878 $this->sendResponseHeaders( $context, $etag, false );
879 $response = $fileCache->fetchText();
880 // Capture any PHP warnings from the output buffer and append them to the
881 // response in a comment if we're in debug mode.
882 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
883 $response = self
::makeComment( $warnings ) . $response;
885 // Remove the output buffer and output the response
887 echo $response . "\n/* Cached {$ts} */";
888 return true; // cache hit
893 return false; // cache miss
897 * Generate a CSS or JS comment block.
899 * Only use this for public data, not error message details.
901 * @param string $text
904 public static function makeComment( $text ) {
905 $encText = str_replace( '*/', '* /', $text );
906 return "/*\n$encText\n*/\n";
910 * Handle exception display.
912 * @param Exception $e Exception to be shown to the user
913 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
915 public static function formatException( $e ) {
916 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
920 * Handle exception display.
923 * @param Exception $e Exception to be shown to the user
924 * @return string Sanitized text that can be returned to the user
926 protected static function formatExceptionNoComment( $e ) {
927 global $wgShowExceptionDetails;
929 if ( !$wgShowExceptionDetails ) {
930 return MWExceptionHandler
::getPublicLogMessage( $e );
933 return MWExceptionHandler
::getLogMessage( $e );
937 * Generate code for a response.
939 * @param ResourceLoaderContext $context Context in which to generate a response
940 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
941 * @param string[] $missing List of requested module names that are unregistered (optional)
942 * @return string Response data
944 public function makeModuleResponse( ResourceLoaderContext
$context,
945 array $modules, array $missing = array()
950 if ( !count( $modules ) && !count( $missing ) ) {
952 /* This file is the Web entry point for MediaWiki's ResourceLoader:
953 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
954 no modules were requested. Max made me put this here. */
958 $image = $context->getImageObj();
960 $data = $image->getImageData( $context );
961 if ( $data === false ) {
963 $this->errors
[] = 'Image generation failed';
969 if ( $context->shouldIncludeMessages() ) {
971 $this->blobStore
->get( $this, $modules, $context->getLanguage() );
972 } catch ( Exception
$e ) {
973 MWExceptionHandler
::logException( $e );
974 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
977 $this->errors
[] = self
::formatExceptionNoComment( $e );
981 foreach ( $missing as $name ) {
982 $states[$name] = 'missing';
988 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
990 foreach ( $modules as $name => $module ) {
992 $content = $module->getModuleContent( $context );
996 switch ( $context->getOnly() ) {
998 $scripts = $content['scripts'];
999 if ( is_string( $scripts ) ) {
1000 // Load scripts raw...
1001 $strContent = $scripts;
1002 } elseif ( is_array( $scripts ) ) {
1003 // ...except when $scripts is an array of URLs
1004 $strContent = self
::makeLoaderImplementScript( $name, $scripts, array(), array(), array() );
1008 $styles = $content['styles'];
1009 // We no longer seperate into media, they are all combined now with
1010 // custom media type groups into @media .. {} sections as part of the css string.
1011 // Module returns either an empty array or a numerical array with css strings.
1012 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1015 $strContent = self
::makeLoaderImplementScript(
1017 isset( $content['scripts'] ) ?
$content['scripts'] : '',
1018 isset( $content['styles'] ) ?
$content['styles'] : array(),
1019 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : array(),
1020 isset( $content['templates'] ) ?
$content['templates'] : array()
1025 if ( !$context->getDebug() ) {
1026 $strContent = self
::filter( $filter, $strContent );
1029 $out .= $strContent;
1031 } catch ( Exception
$e ) {
1032 MWExceptionHandler
::logException( $e );
1033 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1036 $this->errors
[] = self
::formatExceptionNoComment( $e );
1038 // Respond to client with error-state instead of module implementation
1039 $states[$name] = 'error';
1040 unset( $modules[$name] );
1042 $isRaw |
= $module->isRaw();
1045 // Update module states
1046 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1047 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1048 // Set the state of modules loaded as only scripts to ready as
1049 // they don't have an mw.loader.implement wrapper that sets the state
1050 foreach ( $modules as $name => $module ) {
1051 $states[$name] = 'ready';
1055 // Set the state of modules we didn't respond to with mw.loader.implement
1056 if ( count( $states ) ) {
1057 $stateScript = self
::makeLoaderStateScript( $states );
1058 if ( !$context->getDebug() ) {
1059 $stateScript = self
::filter( 'minify-js', $stateScript );
1061 $out .= $stateScript;
1064 if ( count( $states ) ) {
1065 $this->errors
[] = 'Problematic modules: ' .
1066 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1073 /* Static Methods */
1076 * Return JS code that calls mw.loader.implement with given module properties.
1078 * @param string $name Module name
1079 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1080 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1081 * to CSS files keyed by media type
1082 * @param mixed $messages List of messages associated with this module. May either be an
1083 * associative array mapping message key to value, or a JSON-encoded message blob containing
1084 * the same data, wrapped in an XmlJsCode object.
1085 * @param array $templates Keys are name of templates and values are the source of
1087 * @throws MWException
1090 public static function makeLoaderImplementScript(
1091 $name, $scripts, $styles, $messages, $templates
1093 if ( is_string( $scripts ) ) {
1094 // Site and user module are a legacy scripts that run in the global scope (no closure).
1095 // Transportation as string instructs mw.loader.implement to use globalEval.
1096 if ( $name === 'site' ||
$name === 'user' ) {
1097 // Minify manually because the general makeModuleResponse() minification won't be
1098 // effective here due to the script being a string instead of a function. (T107377)
1099 if ( !ResourceLoader
::inDebugMode() ) {
1100 $scripts = self
::filter( 'minify-js', $scripts );
1103 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1105 } elseif ( !is_array( $scripts ) ) {
1106 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1108 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1109 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1110 // of "{}". Force them to objects.
1118 self
::trimArray( $module );
1120 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1124 * Returns JS code which, when called, will register a given list of messages.
1126 * @param mixed $messages Either an associative array mapping message key to value, or a
1127 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1130 public static function makeMessageSetScript( $messages ) {
1131 return Xml
::encodeJsCall(
1133 array( (object)$messages ),
1134 ResourceLoader
::inDebugMode()
1139 * Combines an associative array mapping media type to CSS into a
1140 * single stylesheet with "@media" blocks.
1142 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1145 public static function makeCombinedStyles( array $stylePairs ) {
1147 foreach ( $stylePairs as $media => $styles ) {
1148 // ResourceLoaderFileModule::getStyle can return the styles
1149 // as a string or an array of strings. This is to allow separation in
1151 $styles = (array)$styles;
1152 foreach ( $styles as $style ) {
1153 $style = trim( $style );
1154 // Don't output an empty "@media print { }" block (bug 40498)
1155 if ( $style !== '' ) {
1156 // Transform the media type based on request params and config
1157 // The way that this relies on $wgRequest to propagate request params is slightly evil
1158 $media = OutputPage
::transformCssMedia( $media );
1160 if ( $media === '' ||
$media == 'all' ) {
1162 } elseif ( is_string( $media ) ) {
1163 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1173 * Returns a JS call to mw.loader.state, which sets the state of a
1174 * module or modules to a given value. Has two calling conventions:
1176 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1177 * Set the state of a single module called $name to $state
1179 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1180 * Set the state of modules with the given names to the given states
1182 * @param string $name
1183 * @param string $state
1186 public static function makeLoaderStateScript( $name, $state = null ) {
1187 if ( is_array( $name ) ) {
1188 return Xml
::encodeJsCall(
1191 ResourceLoader
::inDebugMode()
1194 return Xml
::encodeJsCall(
1196 array( $name, $state ),
1197 ResourceLoader
::inDebugMode()
1203 * Returns JS code which calls the script given by $script. The script will
1204 * be called with local variables name, version, dependencies and group,
1205 * which will have values corresponding to $name, $version, $dependencies
1206 * and $group as supplied.
1208 * @param string $name Module name
1209 * @param string $version Module version hash
1210 * @param array $dependencies List of module names on which this module depends
1211 * @param string $group Group which the module is in.
1212 * @param string $source Source of the module, or 'local' if not foreign.
1213 * @param string $script JavaScript code
1216 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1217 $group, $source, $script
1219 $script = str_replace( "\n", "\n\t", trim( $script ) );
1220 return Xml
::encodeJsCall(
1221 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1222 array( $name, $version, $dependencies, $group, $source ),
1223 ResourceLoader
::inDebugMode()
1227 private static function isEmptyObject( stdClass
$obj ) {
1228 foreach ( $obj as $key => $value ) {
1235 * Remove empty values from the end of an array.
1237 * Values considered empty:
1241 * - new XmlJsCode( '{}' )
1242 * - new stdClass() // (object) array()
1244 * @param Array $array
1246 private static function trimArray( Array &$array ) {
1247 $i = count( $array );
1249 if ( $array[$i] === null
1250 ||
$array[$i] === array()
1251 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1252 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1254 unset( $array[$i] );
1262 * Returns JS code which calls mw.loader.register with the given
1263 * parameters. Has three calling conventions:
1265 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1266 * $dependencies, $group, $source, $skip
1268 * Register a single module.
1270 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1271 * Register modules with the given names.
1273 * - ResourceLoader::makeLoaderRegisterScript( array(
1274 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1275 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1278 * Registers modules with the given names and parameters.
1280 * @param string $name Module name
1281 * @param string $version Module version hash
1282 * @param array $dependencies List of module names on which this module depends
1283 * @param string $group Group which the module is in
1284 * @param string $source Source of the module, or 'local' if not foreign
1285 * @param string $skip Script body of the skip function
1288 public static function makeLoaderRegisterScript( $name, $version = null,
1289 $dependencies = null, $group = null, $source = null, $skip = null
1291 if ( is_array( $name ) ) {
1292 // Build module name index
1294 foreach ( $name as $i => &$module ) {
1295 $index[$module[0]] = $i;
1298 // Transform dependency names into indexes when possible, they will be resolved by
1299 // mw.loader.register on the other end
1300 foreach ( $name as &$module ) {
1301 if ( isset( $module[2] ) ) {
1302 foreach ( $module[2] as &$dependency ) {
1303 if ( isset( $index[$dependency] ) ) {
1304 $dependency = $index[$dependency];
1310 array_walk( $name, array( 'self', 'trimArray' ) );
1312 return Xml
::encodeJsCall(
1313 'mw.loader.register',
1315 ResourceLoader
::inDebugMode()
1318 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1319 self
::trimArray( $registration );
1320 return Xml
::encodeJsCall(
1321 'mw.loader.register',
1323 ResourceLoader
::inDebugMode()
1329 * Returns JS code which calls mw.loader.addSource() with the given
1330 * parameters. Has two calling conventions:
1332 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1333 * Register a single source
1335 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1336 * Register sources with the given IDs and properties.
1338 * @param string $id Source ID
1339 * @param array $properties Source properties (see addSource())
1342 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1343 if ( is_array( $id ) ) {
1344 return Xml
::encodeJsCall(
1345 'mw.loader.addSource',
1347 ResourceLoader
::inDebugMode()
1350 return Xml
::encodeJsCall(
1351 'mw.loader.addSource',
1352 array( $id, $properties ),
1353 ResourceLoader
::inDebugMode()
1359 * Returns JS code which runs given JS code if the client-side framework is
1362 * @deprecated since 1.25; use makeInlineScript instead
1363 * @param string $script JavaScript code
1366 public static function makeLoaderConditionalScript( $script ) {
1367 return "window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n" .
1368 trim( $script ) . "\n} );";
1372 * Construct an inline script tag with given JS code.
1374 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1375 * only if the client has adequate support for MediaWiki JavaScript code.
1377 * @param string $script JavaScript code
1378 * @return WrappedString HTML
1380 public static function makeInlineScript( $script ) {
1381 $js = self
::makeLoaderConditionalScript( $script );
1382 return new WrappedString(
1383 Html
::inlineScript( $js ),
1384 "<script>window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n",
1390 * Returns JS code which will set the MediaWiki configuration array to
1393 * @param array $configuration List of configuration values keyed by variable name
1396 public static function makeConfigSetScript( array $configuration ) {
1397 return Xml
::encodeJsCall(
1399 array( $configuration ),
1400 ResourceLoader
::inDebugMode()
1401 ) . ResourceLoader
::FILTER_NOMIN
;
1405 * Convert an array of module names to a packed query string.
1407 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1408 * becomes 'foo.bar,baz|bar.baz,quux'
1409 * @param array $modules List of module names (strings)
1410 * @return string Packed query string
1412 public static function makePackedModulesString( $modules ) {
1413 $groups = array(); // array( prefix => array( suffixes ) )
1414 foreach ( $modules as $module ) {
1415 $pos = strrpos( $module, '.' );
1416 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1417 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1418 $groups[$prefix][] = $suffix;
1422 foreach ( $groups as $prefix => $suffixes ) {
1423 $p = $prefix === '' ?
'' : $prefix . '.';
1424 $arr[] = $p . implode( ',', $suffixes );
1426 $str = implode( '|', $arr );
1431 * Determine whether debug mode was requested
1432 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1435 public static function inDebugMode() {
1436 if ( self
::$debugMode === null ) {
1437 global $wgRequest, $wgResourceLoaderDebug;
1438 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1439 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1442 return self
::$debugMode;
1446 * Reset static members used for caching.
1448 * Global state and $wgRequest are evil, but we're using it right
1449 * now and sometimes we need to be able to force ResourceLoader to
1450 * re-evaluate the context because it has changed (e.g. in the test suite).
1452 public static function clearCache() {
1453 self
::$debugMode = null;
1457 * Build a load.php URL
1460 * @param string $source Name of the ResourceLoader source
1461 * @param ResourceLoaderContext $context
1462 * @param array $extraQuery
1463 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1465 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1466 $extraQuery = array()
1468 $query = self
::createLoaderQuery( $context, $extraQuery );
1469 $script = $this->getLoadScript( $source );
1471 return wfAppendQuery( $script, $query );
1475 * Build a load.php URL
1476 * @deprecated since 1.24 Use createLoaderURL() instead
1477 * @param array $modules Array of module names (strings)
1478 * @param string $lang Language code
1479 * @param string $skin Skin name
1480 * @param string|null $user User name. If null, the &user= parameter is omitted
1481 * @param string|null $version Versioning timestamp
1482 * @param bool $debug Whether the request should be in debug mode
1483 * @param string|null $only &only= parameter
1484 * @param bool $printable Printable mode
1485 * @param bool $handheld Handheld mode
1486 * @param array $extraQuery Extra query parameters to add
1487 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1489 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1490 $version = null, $debug = false, $only = null, $printable = false,
1491 $handheld = false, $extraQuery = array()
1493 global $wgLoadScript;
1495 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1496 $only, $printable, $handheld, $extraQuery
1499 return wfAppendQuery( $wgLoadScript, $query );
1503 * Helper for createLoaderURL()
1506 * @see makeLoaderQuery
1507 * @param ResourceLoaderContext $context
1508 * @param array $extraQuery
1511 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1512 return self
::makeLoaderQuery(
1513 $context->getModules(),
1514 $context->getLanguage(),
1515 $context->getSkin(),
1516 $context->getUser(),
1517 $context->getVersion(),
1518 $context->getDebug(),
1519 $context->getOnly(),
1520 $context->getRequest()->getBool( 'printable' ),
1521 $context->getRequest()->getBool( 'handheld' ),
1527 * Build a query array (array representation of query string) for load.php. Helper
1528 * function for makeLoaderURL().
1530 * @param array $modules
1531 * @param string $lang
1532 * @param string $skin
1533 * @param string $user
1534 * @param string $version
1535 * @param bool $debug
1536 * @param string $only
1537 * @param bool $printable
1538 * @param bool $handheld
1539 * @param array $extraQuery
1543 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1544 $version = null, $debug = false, $only = null, $printable = false,
1545 $handheld = false, $extraQuery = array()
1548 'modules' => self
::makePackedModulesString( $modules ),
1551 'debug' => $debug ?
'true' : 'false',
1553 if ( $user !== null ) {
1554 $query['user'] = $user;
1556 if ( $version !== null ) {
1557 $query['version'] = $version;
1559 if ( $only !== null ) {
1560 $query['only'] = $only;
1563 $query['printable'] = 1;
1566 $query['handheld'] = 1;
1568 $query +
= $extraQuery;
1570 // Make queries uniform in order
1576 * Check a module name for validity.
1578 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1579 * at most 255 bytes.
1581 * @param string $moduleName Module name to check
1582 * @return bool Whether $moduleName is a valid module name
1584 public static function isValidModuleName( $moduleName ) {
1585 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1589 * Returns LESS compiler set up for use with MediaWiki
1592 * @since 1.27 added $extraVars parameter
1593 * @param Config $config
1594 * @param array $extraVars Associative array of extra (i.e., other than the
1595 * globally-configured ones) that should be used for compilation.
1596 * @throws MWException
1597 * @return Less_Parser
1599 public static function getLessCompiler( Config
$config, $extraVars = array() ) {
1600 // When called from the installer, it is possible that a required PHP extension
1601 // is missing (at least for now; see bug 47564). If this is the case, throw an
1602 // exception (caught by the installer) to prevent a fatal error later on.
1603 if ( !class_exists( 'Less_Parser' ) ) {
1604 throw new MWException( 'MediaWiki requires the less.php parser' );
1607 $parser = new Less_Parser
;
1608 $parser->ModifyVars( array_merge( self
::getLessVars( $config ), $extraVars ) );
1609 $parser->SetImportDirs( array_fill_keys( $config->get( 'ResourceLoaderLESSImportPaths' ), '' ) );
1610 $parser->SetOption( 'relativeUrls', false );
1611 $parser->SetCacheDir( $config->get( 'CacheDirectory' ) ?
: wfTempDir() );
1617 * Get global LESS variables.
1619 * @param Config $config
1621 * @return array Map of variable names to string CSS values.
1623 public static function getLessVars( Config
$config ) {
1624 if ( !self
::$lessVars ) {
1625 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1626 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1627 self
::$lessVars = $lessVars;
1629 return self
::$lessVars;