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
::getLocalServerInstance( 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( $this ) );
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 $this->logger
->warning(
329 'ResourceLoader duplicate registration warning. ' .
330 'Another module has already been registered as ' . $name
334 // Check $name for validity
335 if ( !self
::isValidModuleName( $name ) ) {
336 throw new MWException( "ResourceLoader module name '$name' is invalid, "
337 . "see ResourceLoader::isValidModuleName()" );
341 if ( $info instanceof ResourceLoaderModule
) {
342 $this->moduleInfos
[$name] = array( 'object' => $info );
343 $info->setName( $name );
344 $this->modules
[$name] = $info;
345 } elseif ( is_array( $info ) ) {
346 // New calling convention
347 $this->moduleInfos
[$name] = $info;
349 throw new MWException(
350 'ResourceLoader module info type error for module \'' . $name .
351 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
355 // Last-minute changes
357 // Apply custom skin-defined styles to existing modules.
358 if ( $this->isFileModule( $name ) ) {
359 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
360 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
361 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
365 // If $name is preceded with a '+', the defined style files will be added to 'default'
366 // skinStyles, otherwise 'default' will be ignored as it normally would be.
367 if ( isset( $skinStyles[$name] ) ) {
368 $paths = (array)$skinStyles[$name];
369 $styleFiles = array();
370 } elseif ( isset( $skinStyles['+' . $name] ) ) {
371 $paths = (array)$skinStyles['+' . $name];
372 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
373 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
379 // Add new file paths, remapping them to refer to our directories and not use settings
380 // from the module we're modifying, which come from the base definition.
381 list( $localBasePath, $remoteBasePath ) =
382 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
384 foreach ( $paths as $path ) {
385 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
388 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
397 public function registerTestModules() {
400 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
401 throw new MWException( 'Attempt to register JavaScript test modules '
402 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
403 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
406 // Get core test suites
407 $testModules = array();
408 $testModules['qunit'] = array();
409 // Get other test suites (e.g. from extensions)
410 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
412 // Add the testrunner (which configures QUnit) to the dependencies.
413 // Since it must be ready before any of the test suites are executed.
414 foreach ( $testModules['qunit'] as &$module ) {
415 // Make sure all test modules are top-loading so that when QUnit starts
416 // on document-ready, it will run once and finish. If some tests arrive
417 // later (possibly after QUnit has already finished) they will be ignored.
418 $module['position'] = 'top';
419 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
422 $testModules['qunit'] =
423 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
425 foreach ( $testModules as $id => $names ) {
426 // Register test modules
427 $this->register( $testModules[$id] );
429 // Keep track of their names so that they can be loaded together
430 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
436 * Add a foreign source of modules.
438 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
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() ) {
714 $warnings = ob_get_contents();
715 if ( strlen( $warnings ) ) {
716 $this->errors
[] = $warnings;
720 // Save response to file cache unless there are errors
721 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
722 // Cache single modules and images...and other requests if there are enough hits
723 if ( ResourceFileCache
::useFileCache( $context ) ) {
724 if ( $fileCache->isCacheWorthy() ) {
725 $fileCache->saveText( $response );
727 $fileCache->incrMissesRecent( $context->getRequest() );
732 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
734 // Remove the output buffer and output the response
737 if ( $context->getImageObj() && $this->errors
) {
738 // We can't show both the error messages and the response when it's an image.
739 $response = implode( "\n\n", $this->errors
);
740 } elseif ( $this->errors
) {
741 $errorText = implode( "\n\n", $this->errors
);
742 $errorResponse = self
::makeComment( $errorText );
743 if ( $context->shouldIncludeScripts() ) {
744 $errorResponse .= 'if (window.console && console.error) {'
745 . Xml
::encodeJsCall( 'console.error', array( $errorText ) )
749 // Prepend error info to the response
750 $response = $errorResponse . $response;
753 $this->errors
= array();
759 * Send main response headers to the client.
761 * Deals with Content-Type, CORS (for stylesheets), and caching.
763 * @param ResourceLoaderContext $context
764 * @param string $etag ETag header value
765 * @param bool $errors Whether there are errors in the response
768 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
769 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
770 // If a version wasn't specified we need a shorter expiry time for updates
771 // to propagate to clients quickly
772 // If there were errors, we also need a shorter expiry time so we can recover quickly
773 if ( is_null( $context->getVersion() ) ||
$errors ) {
774 $maxage = $rlMaxage['unversioned']['client'];
775 $smaxage = $rlMaxage['unversioned']['server'];
776 // If a version was specified we can use a longer expiry time since changing
777 // version numbers causes cache misses
779 $maxage = $rlMaxage['versioned']['client'];
780 $smaxage = $rlMaxage['versioned']['server'];
782 if ( $context->getImageObj() ) {
783 // Output different headers if we're outputting textual errors.
785 header( 'Content-Type: text/plain; charset=utf-8' );
787 $context->getImageObj()->sendResponseHeaders( $context );
789 } elseif ( $context->getOnly() === 'styles' ) {
790 header( 'Content-Type: text/css; charset=utf-8' );
791 header( 'Access-Control-Allow-Origin: *' );
793 header( 'Content-Type: text/javascript; charset=utf-8' );
795 // See RFC 2616 § 14.19 ETag
796 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
797 header( 'ETag: ' . $etag );
798 if ( $context->getDebug() ) {
799 // Do not cache debug responses
800 header( 'Cache-Control: private, no-cache, must-revalidate' );
801 header( 'Pragma: no-cache' );
803 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
804 $exp = min( $maxage, $smaxage );
805 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
810 * Respond with HTTP 304 Not Modified if appropiate.
812 * If there's an If-None-Match header, respond with a 304 appropriately
813 * and clear out the output buffer. If the client cache is too old then do nothing.
815 * @param ResourceLoaderContext $context
816 * @param string $etag ETag header value
817 * @return bool True if HTTP 304 was sent and output handled
819 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
820 // See RFC 2616 § 14.26 If-None-Match
821 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
822 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
823 // Never send 304s in debug mode
824 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
825 // There's another bug in ob_gzhandler (see also the comment at
826 // the top of this function) that causes it to gzip even empty
827 // responses, meaning it's impossible to produce a truly empty
828 // response (because the gzip header is always there). This is
829 // a problem because 304 responses have to be completely empty
830 // per the HTTP spec, and Firefox behaves buggily when they're not.
831 // See also http://bugs.php.net/bug.php?id=51579
832 // To work around this, we tear down all output buffering before
834 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
836 HttpStatus
::header( 304 );
838 $this->sendResponseHeaders( $context, $etag, false );
845 * Send out code for a response from file cache if possible.
847 * @param ResourceFileCache $fileCache Cache object for this request URL
848 * @param ResourceLoaderContext $context Context in which to generate a response
849 * @param string $etag ETag header value
850 * @return bool If this found a cache file and handled the response
852 protected function tryRespondFromFileCache(
853 ResourceFileCache
$fileCache,
854 ResourceLoaderContext
$context,
857 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
858 // Buffer output to catch warnings.
860 // Get the maximum age the cache can be
861 $maxage = is_null( $context->getVersion() )
862 ?
$rlMaxage['unversioned']['server']
863 : $rlMaxage['versioned']['server'];
864 // Minimum timestamp the cache file must have
865 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
867 try { // RL always hits the DB on file cache miss...
869 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
870 $good = $fileCache->isCacheGood(); // cache existence check
874 $ts = $fileCache->cacheTimestamp();
875 // Send content type and cache headers
876 $this->sendResponseHeaders( $context, $etag, false );
877 $response = $fileCache->fetchText();
878 // Capture any PHP warnings from the output buffer and append them to the
879 // response in a comment if we're in debug mode.
880 if ( $context->getDebug() ) {
881 $warnings = ob_get_contents();
882 if ( strlen( $warnings ) ) {
883 $response = self
::makeComment( $warnings ) . $response;
886 // Remove the output buffer and output the response
888 echo $response . "\n/* Cached {$ts} */";
889 return true; // cache hit
894 return false; // cache miss
898 * Generate a CSS or JS comment block.
900 * Only use this for public data, not error message details.
902 * @param string $text
905 public static function makeComment( $text ) {
906 $encText = str_replace( '*/', '* /', $text );
907 return "/*\n$encText\n*/\n";
911 * Handle exception display.
913 * @param Exception $e Exception to be shown to the user
914 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
916 public static function formatException( $e ) {
917 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
921 * Handle exception display.
924 * @param Exception $e Exception to be shown to the user
925 * @return string Sanitized text that can be returned to the user
927 protected static function formatExceptionNoComment( $e ) {
928 global $wgShowExceptionDetails;
930 if ( !$wgShowExceptionDetails ) {
931 return MWExceptionHandler
::getPublicLogMessage( $e );
934 return MWExceptionHandler
::getLogMessage( $e );
938 * Generate code for a response.
940 * @param ResourceLoaderContext $context Context in which to generate a response
941 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
942 * @param string[] $missing List of requested module names that are unregistered (optional)
943 * @return string Response data
945 public function makeModuleResponse( ResourceLoaderContext
$context,
946 array $modules, array $missing = array()
951 if ( !count( $modules ) && !count( $missing ) ) {
953 /* This file is the Web entry point for MediaWiki's ResourceLoader:
954 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
955 no modules were requested. Max made me put this here. */
959 $image = $context->getImageObj();
961 $data = $image->getImageData( $context );
962 if ( $data === false ) {
964 $this->errors
[] = 'Image generation failed';
970 if ( $context->shouldIncludeMessages() ) {
972 $this->blobStore
->get( $this, $modules, $context->getLanguage() );
973 } catch ( Exception
$e ) {
974 MWExceptionHandler
::logException( $e );
975 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
978 $this->errors
[] = self
::formatExceptionNoComment( $e );
982 foreach ( $missing as $name ) {
983 $states[$name] = 'missing';
989 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
991 foreach ( $modules as $name => $module ) {
993 $content = $module->getModuleContent( $context );
997 switch ( $context->getOnly() ) {
999 $scripts = $content['scripts'];
1000 if ( is_string( $scripts ) ) {
1001 // Load scripts raw...
1002 $strContent = $scripts;
1003 } elseif ( is_array( $scripts ) ) {
1004 // ...except when $scripts is an array of URLs
1005 $strContent = self
::makeLoaderImplementScript( $name, $scripts, array(), array(), array() );
1009 $styles = $content['styles'];
1010 // We no longer seperate into media, they are all combined now with
1011 // custom media type groups into @media .. {} sections as part of the css string.
1012 // Module returns either an empty array or a numerical array with css strings.
1013 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1016 $strContent = self
::makeLoaderImplementScript(
1018 isset( $content['scripts'] ) ?
$content['scripts'] : '',
1019 isset( $content['styles'] ) ?
$content['styles'] : array(),
1020 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : array(),
1021 isset( $content['templates'] ) ?
$content['templates'] : array()
1026 if ( !$context->getDebug() ) {
1027 $strContent = self
::filter( $filter, $strContent );
1030 $out .= $strContent;
1032 } catch ( Exception
$e ) {
1033 MWExceptionHandler
::logException( $e );
1034 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1037 $this->errors
[] = self
::formatExceptionNoComment( $e );
1039 // Respond to client with error-state instead of module implementation
1040 $states[$name] = 'error';
1041 unset( $modules[$name] );
1043 $isRaw |
= $module->isRaw();
1046 // Update module states
1047 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1048 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1049 // Set the state of modules loaded as only scripts to ready as
1050 // they don't have an mw.loader.implement wrapper that sets the state
1051 foreach ( $modules as $name => $module ) {
1052 $states[$name] = 'ready';
1056 // Set the state of modules we didn't respond to with mw.loader.implement
1057 if ( count( $states ) ) {
1058 $stateScript = self
::makeLoaderStateScript( $states );
1059 if ( !$context->getDebug() ) {
1060 $stateScript = self
::filter( 'minify-js', $stateScript );
1062 $out .= $stateScript;
1065 if ( count( $states ) ) {
1066 $this->errors
[] = 'Problematic modules: ' .
1067 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1075 * Get names of modules that use a certain message.
1077 * @param string $messageKey
1078 * @return array List of module names
1080 public function getModulesByMessage( $messageKey ) {
1081 $moduleNames = array();
1082 foreach ( $this->getModuleNames() as $moduleName ) {
1083 $module = $this->getModule( $moduleName );
1084 if ( in_array( $messageKey, $module->getMessages() ) ) {
1085 $moduleNames[] = $moduleName;
1088 return $moduleNames;
1091 /* Static Methods */
1094 * Return JS code that calls mw.loader.implement with given module properties.
1096 * @param string $name Module name
1097 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1098 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1099 * to CSS files keyed by media type
1100 * @param mixed $messages List of messages associated with this module. May either be an
1101 * associative array mapping message key to value, or a JSON-encoded message blob containing
1102 * the same data, wrapped in an XmlJsCode object.
1103 * @param array $templates Keys are name of templates and values are the source of
1105 * @throws MWException
1108 public static function makeLoaderImplementScript(
1109 $name, $scripts, $styles, $messages, $templates
1111 if ( is_string( $scripts ) ) {
1112 // Site and user module are a legacy scripts that run in the global scope (no closure).
1113 // Transportation as string instructs mw.loader.implement to use globalEval.
1114 if ( $name === 'site' ||
$name === 'user' ) {
1115 // Minify manually because the general makeModuleResponse() minification won't be
1116 // effective here due to the script being a string instead of a function. (T107377)
1117 if ( !ResourceLoader
::inDebugMode() ) {
1118 $scripts = self
::filter( 'minify-js', $scripts );
1121 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1123 } elseif ( !is_array( $scripts ) ) {
1124 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1126 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1127 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1128 // of "{}". Force them to objects.
1136 self
::trimArray( $module );
1138 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1142 * Returns JS code which, when called, will register a given list of messages.
1144 * @param mixed $messages Either an associative array mapping message key to value, or a
1145 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1148 public static function makeMessageSetScript( $messages ) {
1149 return Xml
::encodeJsCall(
1151 array( (object)$messages ),
1152 ResourceLoader
::inDebugMode()
1157 * Combines an associative array mapping media type to CSS into a
1158 * single stylesheet with "@media" blocks.
1160 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1163 public static function makeCombinedStyles( array $stylePairs ) {
1165 foreach ( $stylePairs as $media => $styles ) {
1166 // ResourceLoaderFileModule::getStyle can return the styles
1167 // as a string or an array of strings. This is to allow separation in
1169 $styles = (array)$styles;
1170 foreach ( $styles as $style ) {
1171 $style = trim( $style );
1172 // Don't output an empty "@media print { }" block (bug 40498)
1173 if ( $style !== '' ) {
1174 // Transform the media type based on request params and config
1175 // The way that this relies on $wgRequest to propagate request params is slightly evil
1176 $media = OutputPage
::transformCssMedia( $media );
1178 if ( $media === '' ||
$media == 'all' ) {
1180 } elseif ( is_string( $media ) ) {
1181 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1191 * Returns a JS call to mw.loader.state, which sets the state of a
1192 * module or modules to a given value. Has two calling conventions:
1194 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1195 * Set the state of a single module called $name to $state
1197 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1198 * Set the state of modules with the given names to the given states
1200 * @param string $name
1201 * @param string $state
1204 public static function makeLoaderStateScript( $name, $state = null ) {
1205 if ( is_array( $name ) ) {
1206 return Xml
::encodeJsCall(
1209 ResourceLoader
::inDebugMode()
1212 return Xml
::encodeJsCall(
1214 array( $name, $state ),
1215 ResourceLoader
::inDebugMode()
1221 * Returns JS code which calls the script given by $script. The script will
1222 * be called with local variables name, version, dependencies and group,
1223 * which will have values corresponding to $name, $version, $dependencies
1224 * and $group as supplied.
1226 * @param string $name Module name
1227 * @param string $version Module version hash
1228 * @param array $dependencies List of module names on which this module depends
1229 * @param string $group Group which the module is in.
1230 * @param string $source Source of the module, or 'local' if not foreign.
1231 * @param string $script JavaScript code
1234 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1235 $group, $source, $script
1237 $script = str_replace( "\n", "\n\t", trim( $script ) );
1238 return Xml
::encodeJsCall(
1239 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1240 array( $name, $version, $dependencies, $group, $source ),
1241 ResourceLoader
::inDebugMode()
1245 private static function isEmptyObject( stdClass
$obj ) {
1246 foreach ( $obj as $key => $value ) {
1253 * Remove empty values from the end of an array.
1255 * Values considered empty:
1259 * - new XmlJsCode( '{}' )
1260 * - new stdClass() // (object) array()
1262 * @param Array $array
1264 private static function trimArray( Array &$array ) {
1265 $i = count( $array );
1267 if ( $array[$i] === null
1268 ||
$array[$i] === array()
1269 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1270 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1272 unset( $array[$i] );
1280 * Returns JS code which calls mw.loader.register with the given
1281 * parameters. Has three calling conventions:
1283 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1284 * $dependencies, $group, $source, $skip
1286 * Register a single module.
1288 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1289 * Register modules with the given names.
1291 * - ResourceLoader::makeLoaderRegisterScript( array(
1292 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1293 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1296 * Registers modules with the given names and parameters.
1298 * @param string $name Module name
1299 * @param string $version Module version hash
1300 * @param array $dependencies List of module names on which this module depends
1301 * @param string $group Group which the module is in
1302 * @param string $source Source of the module, or 'local' if not foreign
1303 * @param string $skip Script body of the skip function
1306 public static function makeLoaderRegisterScript( $name, $version = null,
1307 $dependencies = null, $group = null, $source = null, $skip = null
1309 if ( is_array( $name ) ) {
1310 // Build module name index
1312 foreach ( $name as $i => &$module ) {
1313 $index[$module[0]] = $i;
1316 // Transform dependency names into indexes when possible, they will be resolved by
1317 // mw.loader.register on the other end
1318 foreach ( $name as &$module ) {
1319 if ( isset( $module[2] ) ) {
1320 foreach ( $module[2] as &$dependency ) {
1321 if ( isset( $index[$dependency] ) ) {
1322 $dependency = $index[$dependency];
1328 array_walk( $name, array( 'self', 'trimArray' ) );
1330 return Xml
::encodeJsCall(
1331 'mw.loader.register',
1333 ResourceLoader
::inDebugMode()
1336 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1337 self
::trimArray( $registration );
1338 return Xml
::encodeJsCall(
1339 'mw.loader.register',
1341 ResourceLoader
::inDebugMode()
1347 * Returns JS code which calls mw.loader.addSource() with the given
1348 * parameters. Has two calling conventions:
1350 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1351 * Register a single source
1353 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1354 * Register sources with the given IDs and properties.
1356 * @param string $id Source ID
1357 * @param array $properties Source properties (see addSource())
1360 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1361 if ( is_array( $id ) ) {
1362 return Xml
::encodeJsCall(
1363 'mw.loader.addSource',
1365 ResourceLoader
::inDebugMode()
1368 return Xml
::encodeJsCall(
1369 'mw.loader.addSource',
1370 array( $id, $properties ),
1371 ResourceLoader
::inDebugMode()
1377 * Returns JS code which runs given JS code if the client-side framework is
1380 * @deprecated since 1.25; use makeInlineScript instead
1381 * @param string $script JavaScript code
1384 public static function makeLoaderConditionalScript( $script ) {
1385 return "window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n" .
1386 trim( $script ) . "\n} );";
1390 * Construct an inline script tag with given JS code.
1392 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1393 * only if the client has adequate support for MediaWiki JavaScript code.
1395 * @param string $script JavaScript code
1396 * @return WrappedString HTML
1398 public static function makeInlineScript( $script ) {
1399 $js = self
::makeLoaderConditionalScript( $script );
1400 return new WrappedString(
1401 Html
::inlineScript( $js ),
1402 "<script>window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n",
1408 * Returns JS code which will set the MediaWiki configuration array to
1411 * @param array $configuration List of configuration values keyed by variable name
1414 public static function makeConfigSetScript( array $configuration ) {
1415 return Xml
::encodeJsCall(
1417 array( $configuration ),
1418 ResourceLoader
::inDebugMode()
1419 ) . ResourceLoader
::FILTER_NOMIN
;
1423 * Convert an array of module names to a packed query string.
1425 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1426 * becomes 'foo.bar,baz|bar.baz,quux'
1427 * @param array $modules List of module names (strings)
1428 * @return string Packed query string
1430 public static function makePackedModulesString( $modules ) {
1431 $groups = array(); // array( prefix => array( suffixes ) )
1432 foreach ( $modules as $module ) {
1433 $pos = strrpos( $module, '.' );
1434 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1435 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1436 $groups[$prefix][] = $suffix;
1440 foreach ( $groups as $prefix => $suffixes ) {
1441 $p = $prefix === '' ?
'' : $prefix . '.';
1442 $arr[] = $p . implode( ',', $suffixes );
1444 $str = implode( '|', $arr );
1449 * Determine whether debug mode was requested
1450 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1453 public static function inDebugMode() {
1454 if ( self
::$debugMode === null ) {
1455 global $wgRequest, $wgResourceLoaderDebug;
1456 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1457 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1460 return self
::$debugMode;
1464 * Reset static members used for caching.
1466 * Global state and $wgRequest are evil, but we're using it right
1467 * now and sometimes we need to be able to force ResourceLoader to
1468 * re-evaluate the context because it has changed (e.g. in the test suite).
1470 public static function clearCache() {
1471 self
::$debugMode = null;
1475 * Build a load.php URL
1478 * @param string $source Name of the ResourceLoader source
1479 * @param ResourceLoaderContext $context
1480 * @param array $extraQuery
1481 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1483 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1484 $extraQuery = array()
1486 $query = self
::createLoaderQuery( $context, $extraQuery );
1487 $script = $this->getLoadScript( $source );
1489 return wfAppendQuery( $script, $query );
1493 * Build a load.php URL
1494 * @deprecated since 1.24 Use createLoaderURL() instead
1495 * @param array $modules Array of module names (strings)
1496 * @param string $lang Language code
1497 * @param string $skin Skin name
1498 * @param string|null $user User name. If null, the &user= parameter is omitted
1499 * @param string|null $version Versioning timestamp
1500 * @param bool $debug Whether the request should be in debug mode
1501 * @param string|null $only &only= parameter
1502 * @param bool $printable Printable mode
1503 * @param bool $handheld Handheld mode
1504 * @param array $extraQuery Extra query parameters to add
1505 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1507 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1508 $version = null, $debug = false, $only = null, $printable = false,
1509 $handheld = false, $extraQuery = array()
1511 global $wgLoadScript;
1513 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1514 $only, $printable, $handheld, $extraQuery
1517 return wfAppendQuery( $wgLoadScript, $query );
1521 * Helper for createLoaderURL()
1524 * @see makeLoaderQuery
1525 * @param ResourceLoaderContext $context
1526 * @param array $extraQuery
1529 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1530 return self
::makeLoaderQuery(
1531 $context->getModules(),
1532 $context->getLanguage(),
1533 $context->getSkin(),
1534 $context->getUser(),
1535 $context->getVersion(),
1536 $context->getDebug(),
1537 $context->getOnly(),
1538 $context->getRequest()->getBool( 'printable' ),
1539 $context->getRequest()->getBool( 'handheld' ),
1545 * Build a query array (array representation of query string) for load.php. Helper
1546 * function for makeLoaderURL().
1548 * @param array $modules
1549 * @param string $lang
1550 * @param string $skin
1551 * @param string $user
1552 * @param string $version
1553 * @param bool $debug
1554 * @param string $only
1555 * @param bool $printable
1556 * @param bool $handheld
1557 * @param array $extraQuery
1561 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1562 $version = null, $debug = false, $only = null, $printable = false,
1563 $handheld = false, $extraQuery = array()
1566 'modules' => self
::makePackedModulesString( $modules ),
1569 'debug' => $debug ?
'true' : 'false',
1571 if ( $user !== null ) {
1572 $query['user'] = $user;
1574 if ( $version !== null ) {
1575 $query['version'] = $version;
1577 if ( $only !== null ) {
1578 $query['only'] = $only;
1581 $query['printable'] = 1;
1584 $query['handheld'] = 1;
1586 $query +
= $extraQuery;
1588 // Make queries uniform in order
1594 * Check a module name for validity.
1596 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1597 * at most 255 bytes.
1599 * @param string $moduleName Module name to check
1600 * @return bool Whether $moduleName is a valid module name
1602 public static function isValidModuleName( $moduleName ) {
1603 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1607 * Returns LESS compiler set up for use with MediaWiki
1610 * @since 1.27 added $extraVars parameter
1611 * @param Config $config
1612 * @param array $extraVars Associative array of extra (i.e., other than the
1613 * globally-configured ones) that should be used for compilation.
1614 * @throws MWException
1615 * @return Less_Parser
1617 public static function getLessCompiler( Config
$config, $extraVars = array() ) {
1618 // When called from the installer, it is possible that a required PHP extension
1619 // is missing (at least for now; see bug 47564). If this is the case, throw an
1620 // exception (caught by the installer) to prevent a fatal error later on.
1621 if ( !class_exists( 'Less_Parser' ) ) {
1622 throw new MWException( 'MediaWiki requires the less.php parser' );
1625 $parser = new Less_Parser
;
1626 $parser->ModifyVars( array_merge( self
::getLessVars( $config ), $extraVars ) );
1627 $parser->SetImportDirs( array_fill_keys( $config->get( 'ResourceLoaderLESSImportPaths' ), '' ) );
1628 $parser->SetOption( 'relativeUrls', false );
1629 $parser->SetCacheDir( $config->get( 'CacheDirectory' ) ?
: wfTempDir() );
1635 * Get global LESS variables.
1637 * @param Config $config
1639 * @return array Map of variable names to string CSS values.
1641 public static function getLessVars( Config
$config ) {
1642 if ( !self
::$lessVars ) {
1643 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1644 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1645 self
::$lessVars = $lessVars;
1647 return self
::$lessVars;