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
26 * Dynamic JavaScript and CSS resource loading system.
28 * Most of the documentation is on the MediaWiki documentation wiki starting at:
29 * https://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader
{
33 protected static $filterCacheVersion = 7;
36 protected static $debugMode = null;
39 private static $lessVars = null;
42 * Module name/ResourceLoaderModule object pairs
45 protected $modules = array();
48 * Associative array mapping module name to info associative array
51 protected $moduleInfos = array();
53 /** @var Config $config */
57 * Associative array mapping framework ids to a list of names of test suite modules
58 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
61 protected $testModuleNames = array();
64 * E.g. array( 'source-id' => 'http://.../load.php' )
67 protected $sources = array();
70 * Errors accumulated during current respond() call.
73 protected $errors = array();
76 * @var MessageBlobStore
81 * Load information stored in the database about modules.
83 * This method grabs modules dependencies from the database and updates modules
86 * This is not inside the module code because it is much faster to
87 * request all of the information at once than it is to have each module
88 * requests its own information. This sacrifice of modularity yields a substantial
89 * performance improvement.
91 * @param array $modules List of module names to preload information for
92 * @param ResourceLoaderContext $context Context to load the information within
94 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
95 if ( !count( $modules ) ) {
96 // Or else Database*::select() will explode, plus it's cheaper!
99 $dbr = wfGetDB( DB_SLAVE
);
100 $skin = $context->getSkin();
101 $lang = $context->getLanguage();
103 // Get file dependency information
104 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
105 'md_module' => $modules,
110 // Set modules' dependencies
111 $modulesWithDeps = array();
112 foreach ( $res as $row ) {
113 $module = $this->getModule( $row->md_module
);
115 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
116 $modulesWithDeps[] = $row->md_module
;
120 // Register the absence of a dependency row too
121 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
122 $module = $this->getModule( $name );
124 $this->getModule( $name )->setFileDependencies( $skin, array() );
128 // Get message blob mtimes. Only do this for modules with messages
129 $modulesWithMessages = array();
130 foreach ( $modules as $name ) {
131 $module = $this->getModule( $name );
132 if ( $module && count( $module->getMessages() ) ) {
133 $modulesWithMessages[] = $name;
136 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
137 if ( count( $modulesWithMessages ) ) {
138 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
139 'mr_resource' => $modulesWithMessages,
143 foreach ( $res as $row ) {
144 $module = $this->getModule( $row->mr_resource
);
146 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
147 unset( $modulesWithoutMessages[$row->mr_resource
] );
151 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
152 $module = $this->getModule( $name );
154 $module->setMsgBlobMtime( $lang, 1 );
160 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
162 * Available filters are:
164 * - minify-js \see JavaScriptMinifier::minify
165 * - minify-css \see CSSMin::minify
167 * If $data is empty, only contains whitespace or the filter was unknown,
168 * $data is returned unmodified.
170 * @param string $filter Name of filter to run
171 * @param string $data Text to filter, such as JavaScript or CSS text
172 * @param string $cacheReport Whether to include the cache key report
173 * @return string Filtered data, or a comment containing an error message
175 public function filter( $filter, $data, $cacheReport = true ) {
177 // For empty/whitespace-only data or for unknown filters, don't perform
178 // any caching or processing
179 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
184 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
185 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
186 $cache = wfGetCache( CACHE_ANYTHING
);
187 $cacheEntry = $cache->get( $key );
188 if ( is_string( $cacheEntry ) ) {
189 wfIncrStats( "rl-$filter-cache-hits" );
194 // Run the filter - we've already verified one of these will work
196 wfIncrStats( "rl-$filter-cache-misses" );
199 $result = JavaScriptMinifier
::minify( $data,
200 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
201 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
203 if ( $cacheReport ) {
204 $result .= "\n/* cache key: $key */";
208 $result = CSSMin
::minify( $data );
209 if ( $cacheReport ) {
210 $result .= "\n/* cache key: $key */";
215 // Save filtered text to Memcached
216 $cache->set( $key, $result );
217 } catch ( Exception
$e ) {
218 MWExceptionHandler
::logException( $e );
219 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
220 $this->errors
[] = self
::formatExceptionNoComment( $e );
229 * Register core modules and runs registration hooks.
230 * @param Config|null $config
232 public function __construct( Config
$config = null ) {
235 if ( $config === null ) {
236 wfDebug( __METHOD__
. ' was called without providing a Config instance' );
237 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
240 $this->config
= $config;
242 // Add 'local' source first
243 $this->addSource( 'local', wfScript( 'load' ) );
246 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
248 // Register core modules
249 $this->register( include "$IP/resources/Resources.php" );
250 $this->register( include "$IP/resources/ResourcesOOUI.php" );
251 // Register extension modules
252 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
253 $this->register( $config->get( 'ResourceModules' ) );
255 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
256 $this->registerTestModules();
259 $this->setMessageBlobStore( new MessageBlobStore() );
265 public function getConfig() {
266 return $this->config
;
270 * @param MessageBlobStore $blobStore
273 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
274 $this->blobStore
= $blobStore;
278 * Register a module with the ResourceLoader system.
280 * @param mixed $name Name of module as a string or List of name/object pairs as an array
281 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
282 * this may also be a ResourceLoaderModule object. Optional when using
283 * multiple-registration calling style.
284 * @throws MWException If a duplicate module registration is attempted
285 * @throws MWException If a module name contains illegal characters (pipes or commas)
286 * @throws MWException If something other than a ResourceLoaderModule is being registered
287 * @return bool False if there were any errors, in which case one or more modules were
290 public function register( $name, $info = null ) {
292 // Allow multiple modules to be registered in one call
293 $registrations = is_array( $name ) ?
$name : array( $name => $info );
294 foreach ( $registrations as $name => $info ) {
295 // Disallow duplicate registrations
296 if ( isset( $this->moduleInfos
[$name] ) ) {
297 // A module has already been registered by this name
298 throw new MWException(
299 'ResourceLoader duplicate registration error. ' .
300 'Another module has already been registered as ' . $name
304 // Check $name for validity
305 if ( !self
::isValidModuleName( $name ) ) {
306 throw new MWException( "ResourceLoader module name '$name' is invalid, "
307 . "see ResourceLoader::isValidModuleName()" );
311 if ( $info instanceof ResourceLoaderModule
) {
312 $this->moduleInfos
[$name] = array( 'object' => $info );
313 $info->setName( $name );
314 $this->modules
[$name] = $info;
315 } elseif ( is_array( $info ) ) {
316 // New calling convention
317 $this->moduleInfos
[$name] = $info;
319 throw new MWException(
320 'ResourceLoader module info type error for module \'' . $name .
321 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
325 // Last-minute changes
327 // Apply custom skin-defined styles to existing modules.
328 if ( $this->isFileModule( $name ) ) {
329 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
330 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
331 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
335 // If $name is preceded with a '+', the defined style files will be added to 'default'
336 // skinStyles, otherwise 'default' will be ignored as it normally would be.
337 if ( isset( $skinStyles[$name] ) ) {
338 $paths = (array)$skinStyles[$name];
339 $styleFiles = array();
340 } elseif ( isset( $skinStyles['+' . $name] ) ) {
341 $paths = (array)$skinStyles['+' . $name];
342 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
343 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
349 // Add new file paths, remapping them to refer to our directories and not use settings
350 // from the module we're modifying, which come from the base definition.
351 list( $localBasePath, $remoteBasePath ) =
352 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
354 foreach ( $paths as $path ) {
355 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
358 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
367 public function registerTestModules() {
370 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
371 throw new MWException( 'Attempt to register JavaScript test modules '
372 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
373 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
376 // Get core test suites
377 $testModules = array();
378 $testModules['qunit'] = array();
379 // Get other test suites (e.g. from extensions)
380 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
382 // Add the testrunner (which configures QUnit) to the dependencies.
383 // Since it must be ready before any of the test suites are executed.
384 foreach ( $testModules['qunit'] as &$module ) {
385 // Make sure all test modules are top-loading so that when QUnit starts
386 // on document-ready, it will run once and finish. If some tests arrive
387 // later (possibly after QUnit has already finished) they will be ignored.
388 $module['position'] = 'top';
389 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
392 $testModules['qunit'] =
393 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
395 foreach ( $testModules as $id => $names ) {
396 // Register test modules
397 $this->register( $testModules[$id] );
399 // Keep track of their names so that they can be loaded together
400 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
406 * Add a foreign source of modules.
408 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
409 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
410 * backwards-compatibility.
411 * @throws MWException
413 public function addSource( $id, $loadUrl = null ) {
414 // Allow multiple sources to be registered in one call
415 if ( is_array( $id ) ) {
416 foreach ( $id as $key => $value ) {
417 $this->addSource( $key, $value );
422 // Disallow duplicates
423 if ( isset( $this->sources
[$id] ) ) {
424 throw new MWException(
425 'ResourceLoader duplicate source addition error. ' .
426 'Another source has already been registered as ' . $id
430 // Pre 1.24 backwards-compatibility
431 if ( is_array( $loadUrl ) ) {
432 if ( !isset( $loadUrl['loadScript'] ) ) {
433 throw new MWException(
434 __METHOD__
. ' was passed an array with no "loadScript" key.'
438 $loadUrl = $loadUrl['loadScript'];
441 $this->sources
[$id] = $loadUrl;
445 * Get a list of module names.
447 * @return array List of module names
449 public function getModuleNames() {
450 return array_keys( $this->moduleInfos
);
454 * Get a list of test module names for one (or all) frameworks.
456 * If the given framework id is unknkown, or if the in-object variable is not an array,
457 * then it will return an empty array.
459 * @param string $framework Get only the test module names for one
460 * particular framework (optional)
463 public function getTestModuleNames( $framework = 'all' ) {
464 /** @todo api siteinfo prop testmodulenames modulenames */
465 if ( $framework == 'all' ) {
466 return $this->testModuleNames
;
467 } elseif ( isset( $this->testModuleNames
[$framework] )
468 && is_array( $this->testModuleNames
[$framework] )
470 return $this->testModuleNames
[$framework];
477 * Check whether a ResourceLoader module is registered
480 * @param string $name
483 public function isModuleRegistered( $name ) {
484 return isset( $this->moduleInfos
[$name] );
488 * Get the ResourceLoaderModule object for a given module name.
490 * If an array of module parameters exists but a ResourceLoaderModule object has not
491 * yet been instantiated, this method will instantiate and cache that object such that
492 * subsequent calls simply return the same object.
494 * @param string $name Module name
495 * @return ResourceLoaderModule|null If module has been registered, return a
496 * ResourceLoaderModule instance. Otherwise, return null.
498 public function getModule( $name ) {
499 if ( !isset( $this->modules
[$name] ) ) {
500 if ( !isset( $this->moduleInfos
[$name] ) ) {
504 // Construct the requested object
505 $info = $this->moduleInfos
[$name];
506 /** @var ResourceLoaderModule $object */
507 if ( isset( $info['object'] ) ) {
508 // Object given in info array
509 $object = $info['object'];
511 if ( !isset( $info['class'] ) ) {
512 $class = 'ResourceLoaderFileModule';
514 $class = $info['class'];
516 /** @var ResourceLoaderModule $object */
517 $object = new $class( $info );
518 $object->setConfig( $this->getConfig() );
520 $object->setName( $name );
521 $this->modules
[$name] = $object;
524 return $this->modules
[$name];
528 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
530 * @param string $name Module name
533 protected function isFileModule( $name ) {
534 if ( !isset( $this->moduleInfos
[$name] ) ) {
537 $info = $this->moduleInfos
[$name];
538 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
545 * Get the list of sources.
547 * @return array Like array( id => load.php url, .. )
549 public function getSources() {
550 return $this->sources
;
554 * Get the URL to the load.php endpoint for the given
555 * ResourceLoader source
558 * @param string $source
559 * @throws MWException On an invalid $source name
562 public function getLoadScript( $source ) {
563 if ( !isset( $this->sources
[$source] ) ) {
564 throw new MWException( "The $source source was never registered in ResourceLoader." );
566 return $this->sources
[$source];
571 * @param string $value
572 * @return string Hash
574 public static function makeHash( $value ) {
575 // Use base64 to output more entropy in a more compact string (default hex is only base16).
576 // The first 8 chars of a base64 encoded digest represent the same binary as
577 // the first 12 chars of a hex encoded digest.
578 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
582 * Helper method to get and combine versions of multiple modules.
585 * @param ResourceLoaderContext $context
586 * @param array $modules List of ResourceLoaderModule objects
587 * @return string Hash
589 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
593 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
594 // http://php.net/functions.anonymous
596 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
597 return $rl->getModule( $module )->getVersionHash( $context );
599 return self
::makeHash( implode( $hashes ) );
603 * Output a response to a load request, including the content-type header.
605 * @param ResourceLoaderContext $context Context in which a response should be formed
607 public function respond( ResourceLoaderContext
$context ) {
608 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
609 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
610 // is used: ob_clean() will clear the GZIP header in that case and it won't come
611 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
612 // the whole thing in our own output buffer to be sure the active buffer
613 // doesn't use ob_gzhandler.
614 // See http://bugs.php.net/bug.php?id=36514
617 // Find out which modules are missing and instantiate the others
620 foreach ( $context->getModules() as $name ) {
621 $module = $this->getModule( $name );
623 // Do not allow private modules to be loaded from the web.
624 // This is a security issue, see bug 34907.
625 if ( $module->getGroup() === 'private' ) {
626 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
627 $this->errors
[] = "Cannot show private module \"$name\"";
630 $modules[$name] = $module;
637 // Preload for getCombinedVersion()
638 $this->preloadModuleInfo( array_keys( $modules ), $context );
639 } catch ( Exception
$e ) {
640 MWExceptionHandler
::logException( $e );
641 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
642 $this->errors
[] = self
::formatExceptionNoComment( $e );
645 // Combine versions to propagate cache invalidation
648 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
649 } catch ( Exception
$e ) {
650 MWExceptionHandler
::logException( $e );
651 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating version hash failed: $e" );
652 $this->errors
[] = self
::formatExceptionNoComment( $e );
655 // See RFC 2616 § 3.11 Entity Tags
656 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
657 $etag = 'W/"' . $versionHash . '"';
659 // Try the client-side cache first
660 if ( $this->tryRespondNotModified( $context, $etag ) ) {
661 return; // output handled (buffers cleared)
664 // Use file cache if enabled and available...
665 if ( $this->config
->get( 'UseFileCache' ) ) {
666 $fileCache = ResourceFileCache
::newFromContext( $context );
667 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
668 return; // output handled
672 // Generate a response
673 $response = $this->makeModuleResponse( $context, $modules, $missing );
675 // Capture any PHP warnings from the output buffer and append them to the
676 // error list if we're in debug mode.
677 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
678 $this->errors
[] = $warnings;
681 // Save response to file cache unless there are errors
682 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
683 // Cache single modules and images...and other requests if there are enough hits
684 if ( ResourceFileCache
::useFileCache( $context ) ) {
685 if ( $fileCache->isCacheWorthy() ) {
686 $fileCache->saveText( $response );
688 $fileCache->incrMissesRecent( $context->getRequest() );
693 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
695 // Remove the output buffer and output the response
698 if ( $context->getImageObj() && $this->errors
) {
699 // We can't show both the error messages and the response when it's an image.
701 foreach ( $this->errors
as $error ) {
702 $errorText .= $error . "\n";
704 $response = $errorText;
705 } elseif ( $this->errors
) {
706 // Prepend comments indicating errors
708 foreach ( $this->errors
as $error ) {
709 $errorText .= self
::makeComment( $error );
711 $response = $errorText . $response;
714 $this->errors
= array();
720 * Send main response headers to the client.
722 * Deals with Content-Type, CORS (for stylesheets), and caching.
724 * @param ResourceLoaderContext $context
725 * @param string $etag ETag header value
726 * @param bool $errors Whether there are errors in the response
729 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
730 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
731 // If a version wasn't specified we need a shorter expiry time for updates
732 // to propagate to clients quickly
733 // If there were errors, we also need a shorter expiry time so we can recover quickly
734 if ( is_null( $context->getVersion() ) ||
$errors ) {
735 $maxage = $rlMaxage['unversioned']['client'];
736 $smaxage = $rlMaxage['unversioned']['server'];
737 // If a version was specified we can use a longer expiry time since changing
738 // version numbers causes cache misses
740 $maxage = $rlMaxage['versioned']['client'];
741 $smaxage = $rlMaxage['versioned']['server'];
743 if ( $context->getImageObj() ) {
744 // Output different headers if we're outputting textual errors.
746 header( 'Content-Type: text/plain; charset=utf-8' );
748 $context->getImageObj()->sendResponseHeaders( $context );
750 } elseif ( $context->getOnly() === 'styles' ) {
751 header( 'Content-Type: text/css; charset=utf-8' );
752 header( 'Access-Control-Allow-Origin: *' );
754 header( 'Content-Type: text/javascript; charset=utf-8' );
756 // See RFC 2616 § 14.19 ETag
757 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
758 header( 'ETag: ' . $etag );
759 if ( $context->getDebug() ) {
760 // Do not cache debug responses
761 header( 'Cache-Control: private, no-cache, must-revalidate' );
762 header( 'Pragma: no-cache' );
764 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
765 $exp = min( $maxage, $smaxage );
766 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
771 * Respond with HTTP 304 Not Modified if appropiate.
773 * If there's an If-None-Match header, respond with a 304 appropriately
774 * and clear out the output buffer. If the client cache is too old then do nothing.
776 * @param ResourceLoaderContext $context
777 * @param string $etag ETag header value
778 * @return bool True if HTTP 304 was sent and output handled
780 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
781 // See RFC 2616 § 14.26 If-None-Match
782 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
783 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
784 // Never send 304s in debug mode
785 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
786 // There's another bug in ob_gzhandler (see also the comment at
787 // the top of this function) that causes it to gzip even empty
788 // responses, meaning it's impossible to produce a truly empty
789 // response (because the gzip header is always there). This is
790 // a problem because 304 responses have to be completely empty
791 // per the HTTP spec, and Firefox behaves buggily when they're not.
792 // See also http://bugs.php.net/bug.php?id=51579
793 // To work around this, we tear down all output buffering before
795 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
797 header( 'HTTP/1.0 304 Not Modified' );
798 header( 'Status: 304 Not Modified' );
800 $this->sendResponseHeaders( $context, $etag, false );
807 * Send out code for a response from file cache if possible.
809 * @param ResourceFileCache $fileCache Cache object for this request URL
810 * @param ResourceLoaderContext $context Context in which to generate a response
811 * @param string $etag ETag header value
812 * @return bool If this found a cache file and handled the response
814 protected function tryRespondFromFileCache(
815 ResourceFileCache
$fileCache,
816 ResourceLoaderContext
$context,
819 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
820 // Buffer output to catch warnings.
822 // Get the maximum age the cache can be
823 $maxage = is_null( $context->getVersion() )
824 ?
$rlMaxage['unversioned']['server']
825 : $rlMaxage['versioned']['server'];
826 // Minimum timestamp the cache file must have
827 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
829 try { // RL always hits the DB on file cache miss...
831 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
832 $good = $fileCache->isCacheGood(); // cache existence check
836 $ts = $fileCache->cacheTimestamp();
837 // Send content type and cache headers
838 $this->sendResponseHeaders( $context, $etag, false );
839 $response = $fileCache->fetchText();
840 // Capture any PHP warnings from the output buffer and append them to the
841 // response in a comment if we're in debug mode.
842 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
843 $response = self
::makeComment( $warnings ) . $response;
845 // Remove the output buffer and output the response
847 echo $response . "\n/* Cached {$ts} */";
848 return true; // cache hit
853 return false; // cache miss
857 * Generate a CSS or JS comment block.
859 * Only use this for public data, not error message details.
861 * @param string $text
864 public static function makeComment( $text ) {
865 $encText = str_replace( '*/', '* /', $text );
866 return "/*\n$encText\n*/\n";
870 * Handle exception display.
872 * @param Exception $e Exception to be shown to the user
873 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
875 public static function formatException( $e ) {
876 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
880 * Handle exception display.
883 * @param Exception $e Exception to be shown to the user
884 * @return string Sanitized text that can be returned to the user
886 protected static function formatExceptionNoComment( $e ) {
887 global $wgShowExceptionDetails;
889 if ( $wgShowExceptionDetails ) {
890 return $e->__toString();
892 return wfMessage( 'internalerror' )->text();
897 * Generate code for a response.
899 * @param ResourceLoaderContext $context Context in which to generate a response
900 * @param array $modules List of module objects keyed by module name
901 * @param array $missing List of requested module names that are unregistered (optional)
902 * @return string Response data
904 public function makeModuleResponse( ResourceLoaderContext
$context,
905 array $modules, array $missing = array()
910 if ( !count( $modules ) && !count( $missing ) ) {
912 /* This file is the Web entry point for MediaWiki's ResourceLoader:
913 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
914 no modules were requested. Max made me put this here. */
918 $image = $context->getImageObj();
920 $data = $image->getImageData( $context );
921 if ( $data === false ) {
923 $this->errors
[] = 'Image generation failed';
929 if ( $context->shouldIncludeMessages() ) {
931 $blobs = $this->blobStore
->get( $this, $modules, $context->getLanguage() );
932 } catch ( Exception
$e ) {
933 MWExceptionHandler
::logException( $e );
936 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
938 $this->errors
[] = self
::formatExceptionNoComment( $e );
944 foreach ( $missing as $name ) {
945 $states[$name] = 'missing';
950 foreach ( $modules as $name => $module ) {
952 * @var $module ResourceLoaderModule
957 if ( $context->shouldIncludeScripts() ) {
958 // If we are in debug mode, we'll want to return an array of URLs if possible
959 // However, we can't do this if the module doesn't support it
960 // We also can't do this if there is an only= parameter, because we have to give
961 // the module a way to return a load.php URL without causing an infinite loop
962 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
963 $scripts = $module->getScriptURLsForDebug( $context );
965 $scripts = $module->getScript( $context );
966 // rtrim() because there are usually a few line breaks
967 // after the last ';'. A new line at EOF, a new line
968 // added by ResourceLoaderFileModule::readScriptFiles, etc.
969 if ( is_string( $scripts )
970 && strlen( $scripts )
971 && substr( rtrim( $scripts ), -1 ) !== ';'
973 // Append semicolon to prevent weird bugs caused by files not
974 // terminating their statements right (bug 27054)
981 if ( $context->shouldIncludeStyles() ) {
982 // Don't create empty stylesheets like array( '' => '' ) for modules
983 // that don't *have* any stylesheets (bug 38024).
984 $stylePairs = $module->getStyles( $context );
985 if ( count( $stylePairs ) ) {
986 // If we are in debug mode without &only= set, we'll want to return an array of URLs
987 // See comment near shouldIncludeScripts() for more details
988 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
990 'url' => $module->getStyleURLsForDebug( $context )
993 // Minify CSS before embedding in mw.loader.implement call
994 // (unless in debug mode)
995 if ( !$context->getDebug() ) {
996 foreach ( $stylePairs as $media => $style ) {
997 // Can be either a string or an array of strings.
998 if ( is_array( $style ) ) {
999 $stylePairs[$media] = array();
1000 foreach ( $style as $cssText ) {
1001 if ( is_string( $cssText ) ) {
1002 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
1005 } elseif ( is_string( $style ) ) {
1006 $stylePairs[$media] = $this->filter( 'minify-css', $style );
1010 // Wrap styles into @media groups as needed and flatten into a numerical array
1012 'css' => self
::makeCombinedStyles( $stylePairs )
1019 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
1022 switch ( $context->getOnly() ) {
1024 if ( is_string( $scripts ) ) {
1025 // Load scripts raw...
1027 } elseif ( is_array( $scripts ) ) {
1028 // ...except when $scripts is an array of URLs
1029 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1033 // We no longer seperate into media, they are all combined now with
1034 // custom media type groups into @media .. {} sections as part of the css string.
1035 // Module returns either an empty array or a numerical array with css strings.
1036 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1039 $out .= self
::makeLoaderImplementScript(
1043 new XmlJsCode( $messagesBlob ),
1044 $module->getTemplates()
1048 } catch ( Exception
$e ) {
1049 MWExceptionHandler
::logException( $e );
1050 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
1051 $this->errors
[] = self
::formatExceptionNoComment( $e );
1053 // Respond to client with error-state instead of module implementation
1054 $states[$name] = 'error';
1055 unset( $modules[$name] );
1057 $isRaw |
= $module->isRaw();
1060 // Update module states
1061 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1062 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1063 // Set the state of modules loaded as only scripts to ready as
1064 // they don't have an mw.loader.implement wrapper that sets the state
1065 foreach ( $modules as $name => $module ) {
1066 $states[$name] = 'ready';
1070 // Set the state of modules we didn't respond to with mw.loader.implement
1071 if ( count( $states ) ) {
1072 $out .= self
::makeLoaderStateScript( $states );
1075 if ( count( $states ) ) {
1076 $this->errors
[] = 'Problematic modules: ' .
1077 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1081 if ( !$context->getDebug() ) {
1082 if ( $context->getOnly() === 'styles' ) {
1083 $out = $this->filter( 'minify-css', $out );
1085 $out = $this->filter( 'minify-js', $out );
1092 /* Static Methods */
1095 * Return JS code that calls mw.loader.implement with given module properties.
1097 * @param string $name Module name
1098 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1099 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1100 * to CSS files keyed by media type
1101 * @param mixed $messages List of messages associated with this module. May either be an
1102 * associative array mapping message key to value, or a JSON-encoded message blob containing
1103 * the same data, wrapped in an XmlJsCode object.
1104 * @param array $templates Keys are name of templates and values are the source of
1106 * @throws MWException
1109 public static function makeLoaderImplementScript(
1110 $name, $scripts, $styles, $messages, $templates
1112 if ( is_string( $scripts ) ) {
1113 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1114 } elseif ( !is_array( $scripts ) ) {
1115 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1117 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1118 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1119 // of "{}". Force them to objects.
1125 (object) $templates,
1127 self
::trimArray( $module );
1129 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1133 * Returns JS code which, when called, will register a given list of messages.
1135 * @param mixed $messages Either an associative array mapping message key to value, or a
1136 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1139 public static function makeMessageSetScript( $messages ) {
1140 return Xml
::encodeJsCall(
1142 array( (object)$messages ),
1143 ResourceLoader
::inDebugMode()
1148 * Combines an associative array mapping media type to CSS into a
1149 * single stylesheet with "@media" blocks.
1151 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1154 public static function makeCombinedStyles( array $stylePairs ) {
1156 foreach ( $stylePairs as $media => $styles ) {
1157 // ResourceLoaderFileModule::getStyle can return the styles
1158 // as a string or an array of strings. This is to allow separation in
1160 $styles = (array)$styles;
1161 foreach ( $styles as $style ) {
1162 $style = trim( $style );
1163 // Don't output an empty "@media print { }" block (bug 40498)
1164 if ( $style !== '' ) {
1165 // Transform the media type based on request params and config
1166 // The way that this relies on $wgRequest to propagate request params is slightly evil
1167 $media = OutputPage
::transformCssMedia( $media );
1169 if ( $media === '' ||
$media == 'all' ) {
1171 } elseif ( is_string( $media ) ) {
1172 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1182 * Returns a JS call to mw.loader.state, which sets the state of a
1183 * module or modules to a given value. Has two calling conventions:
1185 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1186 * Set the state of a single module called $name to $state
1188 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1189 * Set the state of modules with the given names to the given states
1191 * @param string $name
1192 * @param string $state
1195 public static function makeLoaderStateScript( $name, $state = null ) {
1196 if ( is_array( $name ) ) {
1197 return Xml
::encodeJsCall(
1200 ResourceLoader
::inDebugMode()
1203 return Xml
::encodeJsCall(
1205 array( $name, $state ),
1206 ResourceLoader
::inDebugMode()
1212 * Returns JS code which calls the script given by $script. The script will
1213 * be called with local variables name, version, dependencies and group,
1214 * which will have values corresponding to $name, $version, $dependencies
1215 * and $group as supplied.
1217 * @param string $name Module name
1218 * @param string $version Module version hash
1219 * @param array $dependencies List of module names on which this module depends
1220 * @param string $group Group which the module is in.
1221 * @param string $source Source of the module, or 'local' if not foreign.
1222 * @param string $script JavaScript code
1225 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1226 $group, $source, $script
1228 $script = str_replace( "\n", "\n\t", trim( $script ) );
1229 return Xml
::encodeJsCall(
1230 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1231 array( $name, $version, $dependencies, $group, $source ),
1232 ResourceLoader
::inDebugMode()
1236 private static function isEmptyObject( stdClass
$obj ) {
1237 foreach ( $obj as $key => &$value ) {
1244 * Remove empty values from the end of an array.
1246 * Values considered empty:
1250 * - new XmlJsCode( '{}' )
1251 * - new stdClass() // (object) array()
1253 * @param Array $array
1255 private static function trimArray( Array &$array ) {
1256 $i = count( $array );
1258 if ( $array[$i] === null
1259 ||
$array[$i] === array()
1260 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1261 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1263 unset( $array[$i] );
1271 * Returns JS code which calls mw.loader.register with the given
1272 * parameters. Has three calling conventions:
1274 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1275 * $dependencies, $group, $source, $skip
1277 * Register a single module.
1279 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1280 * Register modules with the given names.
1282 * - ResourceLoader::makeLoaderRegisterScript( array(
1283 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1284 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1287 * Registers modules with the given names and parameters.
1289 * @param string $name Module name
1290 * @param string $version Module version hash
1291 * @param array $dependencies List of module names on which this module depends
1292 * @param string $group Group which the module is in
1293 * @param string $source Source of the module, or 'local' if not foreign
1294 * @param string $skip Script body of the skip function
1297 public static function makeLoaderRegisterScript( $name, $version = null,
1298 $dependencies = null, $group = null, $source = null, $skip = null
1300 if ( is_array( $name ) ) {
1301 // Build module name index
1303 foreach ( $name as $i => &$module ) {
1304 $index[$module[0]] = $i;
1307 // Transform dependency names into indexes when possible, they will be resolved by
1308 // mw.loader.register on the other end
1309 foreach ( $name as &$module ) {
1310 if ( isset( $module[2] ) ) {
1311 foreach ( $module[2] as &$dependency ) {
1312 if ( isset( $index[$dependency] ) ) {
1313 $dependency = $index[$dependency];
1319 array_walk( $name, array( 'self', 'trimArray' ) );
1321 return Xml
::encodeJsCall(
1322 'mw.loader.register',
1324 ResourceLoader
::inDebugMode()
1327 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1328 self
::trimArray( $registration );
1329 return Xml
::encodeJsCall(
1330 'mw.loader.register',
1332 ResourceLoader
::inDebugMode()
1338 * Returns JS code which calls mw.loader.addSource() with the given
1339 * parameters. Has two calling conventions:
1341 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1342 * Register a single source
1344 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1345 * Register sources with the given IDs and properties.
1347 * @param string $id Source ID
1348 * @param array $properties Source properties (see addSource())
1351 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1352 if ( is_array( $id ) ) {
1353 return Xml
::encodeJsCall(
1354 'mw.loader.addSource',
1356 ResourceLoader
::inDebugMode()
1359 return Xml
::encodeJsCall(
1360 'mw.loader.addSource',
1361 array( $id, $properties ),
1362 ResourceLoader
::inDebugMode()
1368 * Returns JS code which runs given JS code if the client-side framework is
1371 * @deprecated since 1.25; use makeInlineScript instead
1372 * @param string $script JavaScript code
1375 public static function makeLoaderConditionalScript( $script ) {
1376 return "if(window.mw){\n" . trim( $script ) . "\n}";
1380 * Construct an inline script tag with given JS code.
1382 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1383 * only if the client has adequate support for MediaWiki JavaScript code.
1385 * @param string $script JavaScript code
1386 * @return string HTML
1388 public static function makeInlineScript( $script ) {
1389 $js = self
::makeLoaderConditionalScript( $script );
1390 return Html
::inlineScript( $js );
1394 * Returns JS code which will set the MediaWiki configuration array to
1397 * @param array $configuration List of configuration values keyed by variable name
1400 public static function makeConfigSetScript( array $configuration ) {
1401 return Xml
::encodeJsCall(
1403 array( $configuration ),
1404 ResourceLoader
::inDebugMode()
1409 * Convert an array of module names to a packed query string.
1411 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1412 * becomes 'foo.bar,baz|bar.baz,quux'
1413 * @param array $modules List of module names (strings)
1414 * @return string Packed query string
1416 public static function makePackedModulesString( $modules ) {
1417 $groups = array(); // array( prefix => array( suffixes ) )
1418 foreach ( $modules as $module ) {
1419 $pos = strrpos( $module, '.' );
1420 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1421 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1422 $groups[$prefix][] = $suffix;
1426 foreach ( $groups as $prefix => $suffixes ) {
1427 $p = $prefix === '' ?
'' : $prefix . '.';
1428 $arr[] = $p . implode( ',', $suffixes );
1430 $str = implode( '|', $arr );
1435 * Determine whether debug mode was requested
1436 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1439 public static function inDebugMode() {
1440 if ( self
::$debugMode === null ) {
1441 global $wgRequest, $wgResourceLoaderDebug;
1442 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1443 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1446 return self
::$debugMode;
1450 * Reset static members used for caching.
1452 * Global state and $wgRequest are evil, but we're using it right
1453 * now and sometimes we need to be able to force ResourceLoader to
1454 * re-evaluate the context because it has changed (e.g. in the test suite).
1456 public static function clearCache() {
1457 self
::$debugMode = null;
1461 * Build a load.php URL
1464 * @param string $source Name of the ResourceLoader source
1465 * @param ResourceLoaderContext $context
1466 * @param array $extraQuery
1467 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1469 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1470 $extraQuery = array()
1472 $query = self
::createLoaderQuery( $context, $extraQuery );
1473 $script = $this->getLoadScript( $source );
1475 // Prevent the IE6 extension check from being triggered (bug 28840)
1476 // by appending a character that's invalid in Windows extensions ('*')
1477 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1481 * Build a load.php URL
1482 * @deprecated since 1.24 Use createLoaderURL() instead
1483 * @param array $modules Array of module names (strings)
1484 * @param string $lang Language code
1485 * @param string $skin Skin name
1486 * @param string|null $user User name. If null, the &user= parameter is omitted
1487 * @param string|null $version Versioning timestamp
1488 * @param bool $debug Whether the request should be in debug mode
1489 * @param string|null $only &only= parameter
1490 * @param bool $printable Printable mode
1491 * @param bool $handheld Handheld mode
1492 * @param array $extraQuery Extra query parameters to add
1493 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1495 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1496 $version = null, $debug = false, $only = null, $printable = false,
1497 $handheld = false, $extraQuery = array()
1499 global $wgLoadScript;
1501 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1502 $only, $printable, $handheld, $extraQuery
1505 // Prevent the IE6 extension check from being triggered (bug 28840)
1506 // by appending a character that's invalid in Windows extensions ('*')
1507 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1511 * Helper for createLoaderURL()
1514 * @see makeLoaderQuery
1515 * @param ResourceLoaderContext $context
1516 * @param array $extraQuery
1519 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1520 return self
::makeLoaderQuery(
1521 $context->getModules(),
1522 $context->getLanguage(),
1523 $context->getSkin(),
1524 $context->getUser(),
1525 $context->getVersion(),
1526 $context->getDebug(),
1527 $context->getOnly(),
1528 $context->getRequest()->getBool( 'printable' ),
1529 $context->getRequest()->getBool( 'handheld' ),
1535 * Build a query array (array representation of query string) for load.php. Helper
1536 * function for makeLoaderURL().
1538 * @param array $modules
1539 * @param string $lang
1540 * @param string $skin
1541 * @param string $user
1542 * @param string $version
1543 * @param bool $debug
1544 * @param string $only
1545 * @param bool $printable
1546 * @param bool $handheld
1547 * @param array $extraQuery
1551 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1552 $version = null, $debug = false, $only = null, $printable = false,
1553 $handheld = false, $extraQuery = array()
1556 'modules' => self
::makePackedModulesString( $modules ),
1559 'debug' => $debug ?
'true' : 'false',
1561 if ( $user !== null ) {
1562 $query['user'] = $user;
1564 if ( $version !== null ) {
1565 $query['version'] = $version;
1567 if ( $only !== null ) {
1568 $query['only'] = $only;
1571 $query['printable'] = 1;
1574 $query['handheld'] = 1;
1576 $query +
= $extraQuery;
1578 // Make queries uniform in order
1584 * Check a module name for validity.
1586 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1587 * at most 255 bytes.
1589 * @param string $moduleName Module name to check
1590 * @return bool Whether $moduleName is a valid module name
1592 public static function isValidModuleName( $moduleName ) {
1593 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1597 * Returns LESS compiler set up for use with MediaWiki
1599 * @param Config $config
1600 * @throws MWException
1604 public static function getLessCompiler( Config
$config ) {
1605 // When called from the installer, it is possible that a required PHP extension
1606 // is missing (at least for now; see bug 47564). If this is the case, throw an
1607 // exception (caught by the installer) to prevent a fatal error later on.
1608 if ( !class_exists( 'lessc' ) ) {
1609 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1611 if ( !function_exists( 'ctype_digit' ) ) {
1612 throw new MWException( 'lessc requires the Ctype extension' );
1615 $less = new lessc();
1616 $less->setPreserveComments( true );
1617 $less->setVariables( self
::getLessVars( $config ) );
1618 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1619 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1620 $less->registerFunction( $name, $func );
1626 * Get global LESS variables.
1628 * @param Config $config
1630 * @return array Map of variable names to string CSS values.
1632 public static function getLessVars( Config
$config ) {
1633 if ( !self
::$lessVars ) {
1634 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1635 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1636 // Sort by key to ensure consistent hashing for cache lookups.
1638 self
::$lessVars = $lessVars;
1640 return self
::$lessVars;