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() );
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 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
439 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
440 * backwards-compatibility.
441 * @throws MWException
443 public function addSource( $id, $loadUrl = null ) {
444 // Allow multiple sources to be registered in one call
445 if ( is_array( $id ) ) {
446 foreach ( $id as $key => $value ) {
447 $this->addSource( $key, $value );
452 // Disallow duplicates
453 if ( isset( $this->sources
[$id] ) ) {
454 throw new MWException(
455 'ResourceLoader duplicate source addition error. ' .
456 'Another source has already been registered as ' . $id
460 // Pre 1.24 backwards-compatibility
461 if ( is_array( $loadUrl ) ) {
462 if ( !isset( $loadUrl['loadScript'] ) ) {
463 throw new MWException(
464 __METHOD__
. ' was passed an array with no "loadScript" key.'
468 $loadUrl = $loadUrl['loadScript'];
471 $this->sources
[$id] = $loadUrl;
475 * Get a list of module names.
477 * @return array List of module names
479 public function getModuleNames() {
480 return array_keys( $this->moduleInfos
);
484 * Get a list of test module names for one (or all) frameworks.
486 * If the given framework id is unknkown, or if the in-object variable is not an array,
487 * then it will return an empty array.
489 * @param string $framework Get only the test module names for one
490 * particular framework (optional)
493 public function getTestModuleNames( $framework = 'all' ) {
494 /** @todo api siteinfo prop testmodulenames modulenames */
495 if ( $framework == 'all' ) {
496 return $this->testModuleNames
;
497 } elseif ( isset( $this->testModuleNames
[$framework] )
498 && is_array( $this->testModuleNames
[$framework] )
500 return $this->testModuleNames
[$framework];
507 * Check whether a ResourceLoader module is registered
510 * @param string $name
513 public function isModuleRegistered( $name ) {
514 return isset( $this->moduleInfos
[$name] );
518 * Get the ResourceLoaderModule object for a given module name.
520 * If an array of module parameters exists but a ResourceLoaderModule object has not
521 * yet been instantiated, this method will instantiate and cache that object such that
522 * subsequent calls simply return the same object.
524 * @param string $name Module name
525 * @return ResourceLoaderModule|null If module has been registered, return a
526 * ResourceLoaderModule instance. Otherwise, return null.
528 public function getModule( $name ) {
529 if ( !isset( $this->modules
[$name] ) ) {
530 if ( !isset( $this->moduleInfos
[$name] ) ) {
534 // Construct the requested object
535 $info = $this->moduleInfos
[$name];
536 /** @var ResourceLoaderModule $object */
537 if ( isset( $info['object'] ) ) {
538 // Object given in info array
539 $object = $info['object'];
541 if ( !isset( $info['class'] ) ) {
542 $class = 'ResourceLoaderFileModule';
544 $class = $info['class'];
546 /** @var ResourceLoaderModule $object */
547 $object = new $class( $info );
548 $object->setConfig( $this->getConfig() );
550 $object->setName( $name );
551 $this->modules
[$name] = $object;
554 return $this->modules
[$name];
558 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
560 * @param string $name Module name
563 protected function isFileModule( $name ) {
564 if ( !isset( $this->moduleInfos
[$name] ) ) {
567 $info = $this->moduleInfos
[$name];
568 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
575 * Get the list of sources.
577 * @return array Like array( id => load.php url, .. )
579 public function getSources() {
580 return $this->sources
;
584 * Get the URL to the load.php endpoint for the given
585 * ResourceLoader source
588 * @param string $source
589 * @throws MWException On an invalid $source name
592 public function getLoadScript( $source ) {
593 if ( !isset( $this->sources
[$source] ) ) {
594 throw new MWException( "The $source source was never registered in ResourceLoader." );
596 return $this->sources
[$source];
601 * @param string $value
602 * @return string Hash
604 public static function makeHash( $value ) {
605 // Use base64 to output more entropy in a more compact string (default hex is only base16).
606 // The first 8 chars of a base64 encoded digest represent the same binary as
607 // the first 12 chars of a hex encoded digest.
608 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
612 * Helper method to get and combine versions of multiple modules.
615 * @param ResourceLoaderContext $context
616 * @param array $modules List of ResourceLoaderModule objects
617 * @return string Hash
619 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
623 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
624 // http://php.net/functions.anonymous
626 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
627 return $rl->getModule( $module )->getVersionHash( $context );
629 return self
::makeHash( implode( $hashes ) );
633 * Output a response to a load request, including the content-type header.
635 * @param ResourceLoaderContext $context Context in which a response should be formed
637 public function respond( ResourceLoaderContext
$context ) {
638 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
639 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
640 // is used: ob_clean() will clear the GZIP header in that case and it won't come
641 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
642 // the whole thing in our own output buffer to be sure the active buffer
643 // doesn't use ob_gzhandler.
644 // See http://bugs.php.net/bug.php?id=36514
647 // Find out which modules are missing and instantiate the others
650 foreach ( $context->getModules() as $name ) {
651 $module = $this->getModule( $name );
653 // Do not allow private modules to be loaded from the web.
654 // This is a security issue, see bug 34907.
655 if ( $module->getGroup() === 'private' ) {
656 $this->logger
->debug( "Request for private module '$name' denied" );
657 $this->errors
[] = "Cannot show private module \"$name\"";
660 $modules[$name] = $module;
667 // Preload for getCombinedVersion()
668 $this->preloadModuleInfo( array_keys( $modules ), $context );
669 } catch ( Exception
$e ) {
670 MWExceptionHandler
::logException( $e );
671 $this->logger
->warning( 'Preloading module info failed: {exception}', array(
674 $this->errors
[] = self
::formatExceptionNoComment( $e );
677 // Combine versions to propagate cache invalidation
680 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
681 } catch ( Exception
$e ) {
682 MWExceptionHandler
::logException( $e );
683 $this->logger
->warning( 'Calculating version hash failed: {exception}', array(
686 $this->errors
[] = self
::formatExceptionNoComment( $e );
689 // See RFC 2616 § 3.11 Entity Tags
690 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
691 $etag = 'W/"' . $versionHash . '"';
693 // Try the client-side cache first
694 if ( $this->tryRespondNotModified( $context, $etag ) ) {
695 return; // output handled (buffers cleared)
698 // Use file cache if enabled and available...
699 if ( $this->config
->get( 'UseFileCache' ) ) {
700 $fileCache = ResourceFileCache
::newFromContext( $context );
701 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
702 return; // output handled
706 // Generate a response
707 $response = $this->makeModuleResponse( $context, $modules, $missing );
709 // Capture any PHP warnings from the output buffer and append them to the
710 // error list if we're in debug mode.
711 if ( $context->getDebug() ) {
712 $warnings = ob_get_contents();
713 if ( strlen( $warnings ) ) {
714 $this->errors
[] = $warnings;
718 // Save response to file cache unless there are errors
719 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
720 // Cache single modules and images...and other requests if there are enough hits
721 if ( ResourceFileCache
::useFileCache( $context ) ) {
722 if ( $fileCache->isCacheWorthy() ) {
723 $fileCache->saveText( $response );
725 $fileCache->incrMissesRecent( $context->getRequest() );
730 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
732 // Remove the output buffer and output the response
735 if ( $context->getImageObj() && $this->errors
) {
736 // We can't show both the error messages and the response when it's an image.
737 $response = implode( "\n\n", $this->errors
);
738 } elseif ( $this->errors
) {
739 $errorText = implode( "\n\n", $this->errors
);
740 $errorResponse = self
::makeComment( $errorText );
741 if ( $context->shouldIncludeScripts() ) {
742 $errorResponse .= 'if (window.console && console.error) {'
743 . Xml
::encodeJsCall( 'console.error', array( $errorText ) )
747 // Prepend error info to the response
748 $response = $errorResponse . $response;
751 $this->errors
= array();
757 * Send main response headers to the client.
759 * Deals with Content-Type, CORS (for stylesheets), and caching.
761 * @param ResourceLoaderContext $context
762 * @param string $etag ETag header value
763 * @param bool $errors Whether there are errors in the response
766 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
767 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
768 // If a version wasn't specified we need a shorter expiry time for updates
769 // to propagate to clients quickly
770 // If there were errors, we also need a shorter expiry time so we can recover quickly
771 if ( is_null( $context->getVersion() ) ||
$errors ) {
772 $maxage = $rlMaxage['unversioned']['client'];
773 $smaxage = $rlMaxage['unversioned']['server'];
774 // If a version was specified we can use a longer expiry time since changing
775 // version numbers causes cache misses
777 $maxage = $rlMaxage['versioned']['client'];
778 $smaxage = $rlMaxage['versioned']['server'];
780 if ( $context->getImageObj() ) {
781 // Output different headers if we're outputting textual errors.
783 header( 'Content-Type: text/plain; charset=utf-8' );
785 $context->getImageObj()->sendResponseHeaders( $context );
787 } elseif ( $context->getOnly() === 'styles' ) {
788 header( 'Content-Type: text/css; charset=utf-8' );
789 header( 'Access-Control-Allow-Origin: *' );
791 header( 'Content-Type: text/javascript; charset=utf-8' );
793 // See RFC 2616 § 14.19 ETag
794 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
795 header( 'ETag: ' . $etag );
796 if ( $context->getDebug() ) {
797 // Do not cache debug responses
798 header( 'Cache-Control: private, no-cache, must-revalidate' );
799 header( 'Pragma: no-cache' );
801 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
802 $exp = min( $maxage, $smaxage );
803 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
808 * Respond with HTTP 304 Not Modified if appropiate.
810 * If there's an If-None-Match header, respond with a 304 appropriately
811 * and clear out the output buffer. If the client cache is too old then do nothing.
813 * @param ResourceLoaderContext $context
814 * @param string $etag ETag header value
815 * @return bool True if HTTP 304 was sent and output handled
817 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
818 // See RFC 2616 § 14.26 If-None-Match
819 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
820 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
821 // Never send 304s in debug mode
822 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
823 // There's another bug in ob_gzhandler (see also the comment at
824 // the top of this function) that causes it to gzip even empty
825 // responses, meaning it's impossible to produce a truly empty
826 // response (because the gzip header is always there). This is
827 // a problem because 304 responses have to be completely empty
828 // per the HTTP spec, and Firefox behaves buggily when they're not.
829 // See also http://bugs.php.net/bug.php?id=51579
830 // To work around this, we tear down all output buffering before
832 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
834 HttpStatus
::header( 304 );
836 $this->sendResponseHeaders( $context, $etag, false );
843 * Send out code for a response from file cache if possible.
845 * @param ResourceFileCache $fileCache Cache object for this request URL
846 * @param ResourceLoaderContext $context Context in which to generate a response
847 * @param string $etag ETag header value
848 * @return bool If this found a cache file and handled the response
850 protected function tryRespondFromFileCache(
851 ResourceFileCache
$fileCache,
852 ResourceLoaderContext
$context,
855 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
856 // Buffer output to catch warnings.
858 // Get the maximum age the cache can be
859 $maxage = is_null( $context->getVersion() )
860 ?
$rlMaxage['unversioned']['server']
861 : $rlMaxage['versioned']['server'];
862 // Minimum timestamp the cache file must have
863 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
865 try { // RL always hits the DB on file cache miss...
867 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
868 $good = $fileCache->isCacheGood(); // cache existence check
872 $ts = $fileCache->cacheTimestamp();
873 // Send content type and cache headers
874 $this->sendResponseHeaders( $context, $etag, false );
875 $response = $fileCache->fetchText();
876 // Capture any PHP warnings from the output buffer and append them to the
877 // response in a comment if we're in debug mode.
878 if ( $context->getDebug() ) {
879 $warnings = ob_get_contents();
880 if ( strlen( $warnings ) ) {
881 $response = self
::makeComment( $warnings ) . $response;
884 // Remove the output buffer and output the response
886 echo $response . "\n/* Cached {$ts} */";
887 return true; // cache hit
892 return false; // cache miss
896 * Generate a CSS or JS comment block.
898 * Only use this for public data, not error message details.
900 * @param string $text
903 public static function makeComment( $text ) {
904 $encText = str_replace( '*/', '* /', $text );
905 return "/*\n$encText\n*/\n";
909 * Handle exception display.
911 * @param Exception $e Exception to be shown to the user
912 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
914 public static function formatException( $e ) {
915 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
919 * Handle exception display.
922 * @param Exception $e Exception to be shown to the user
923 * @return string Sanitized text that can be returned to the user
925 protected static function formatExceptionNoComment( $e ) {
926 global $wgShowExceptionDetails;
928 if ( !$wgShowExceptionDetails ) {
929 return MWExceptionHandler
::getPublicLogMessage( $e );
932 return MWExceptionHandler
::getLogMessage( $e );
936 * Generate code for a response.
938 * @param ResourceLoaderContext $context Context in which to generate a response
939 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
940 * @param string[] $missing List of requested module names that are unregistered (optional)
941 * @return string Response data
943 public function makeModuleResponse( ResourceLoaderContext
$context,
944 array $modules, array $missing = array()
949 if ( !count( $modules ) && !count( $missing ) ) {
951 /* This file is the Web entry point for MediaWiki's ResourceLoader:
952 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
953 no modules were requested. Max made me put this here. */
957 $image = $context->getImageObj();
959 $data = $image->getImageData( $context );
960 if ( $data === false ) {
962 $this->errors
[] = 'Image generation failed';
968 if ( $context->shouldIncludeMessages() ) {
970 $this->blobStore
->get( $this, $modules, $context->getLanguage() );
971 } catch ( Exception
$e ) {
972 MWExceptionHandler
::logException( $e );
973 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
976 $this->errors
[] = self
::formatExceptionNoComment( $e );
980 foreach ( $missing as $name ) {
981 $states[$name] = 'missing';
987 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
989 foreach ( $modules as $name => $module ) {
991 $content = $module->getModuleContent( $context );
995 switch ( $context->getOnly() ) {
997 $scripts = $content['scripts'];
998 if ( is_string( $scripts ) ) {
999 // Load scripts raw...
1000 $strContent = $scripts;
1001 } elseif ( is_array( $scripts ) ) {
1002 // ...except when $scripts is an array of URLs
1003 $strContent = self
::makeLoaderImplementScript( $name, $scripts, array(), array(), array() );
1007 $styles = $content['styles'];
1008 // We no longer seperate into media, they are all combined now with
1009 // custom media type groups into @media .. {} sections as part of the css string.
1010 // Module returns either an empty array or a numerical array with css strings.
1011 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1014 $strContent = self
::makeLoaderImplementScript(
1016 isset( $content['scripts'] ) ?
$content['scripts'] : '',
1017 isset( $content['styles'] ) ?
$content['styles'] : array(),
1018 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : array(),
1019 isset( $content['templates'] ) ?
$content['templates'] : array()
1024 if ( !$context->getDebug() ) {
1025 $strContent = self
::filter( $filter, $strContent );
1028 $out .= $strContent;
1030 } catch ( Exception
$e ) {
1031 MWExceptionHandler
::logException( $e );
1032 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1035 $this->errors
[] = self
::formatExceptionNoComment( $e );
1037 // Respond to client with error-state instead of module implementation
1038 $states[$name] = 'error';
1039 unset( $modules[$name] );
1041 $isRaw |
= $module->isRaw();
1044 // Update module states
1045 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1046 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1047 // Set the state of modules loaded as only scripts to ready as
1048 // they don't have an mw.loader.implement wrapper that sets the state
1049 foreach ( $modules as $name => $module ) {
1050 $states[$name] = 'ready';
1054 // Set the state of modules we didn't respond to with mw.loader.implement
1055 if ( count( $states ) ) {
1056 $stateScript = self
::makeLoaderStateScript( $states );
1057 if ( !$context->getDebug() ) {
1058 $stateScript = self
::filter( 'minify-js', $stateScript );
1060 $out .= $stateScript;
1063 if ( count( $states ) ) {
1064 $this->errors
[] = 'Problematic modules: ' .
1065 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1072 /* Static Methods */
1075 * Return JS code that calls mw.loader.implement with given module properties.
1077 * @param string $name Module name
1078 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1079 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1080 * to CSS files keyed by media type
1081 * @param mixed $messages List of messages associated with this module. May either be an
1082 * associative array mapping message key to value, or a JSON-encoded message blob containing
1083 * the same data, wrapped in an XmlJsCode object.
1084 * @param array $templates Keys are name of templates and values are the source of
1086 * @throws MWException
1089 public static function makeLoaderImplementScript(
1090 $name, $scripts, $styles, $messages, $templates
1092 if ( is_string( $scripts ) ) {
1093 // Site and user module are a legacy scripts that run in the global scope (no closure).
1094 // Transportation as string instructs mw.loader.implement to use globalEval.
1095 if ( $name === 'site' ||
$name === 'user' ) {
1096 // Minify manually because the general makeModuleResponse() minification won't be
1097 // effective here due to the script being a string instead of a function. (T107377)
1098 if ( !ResourceLoader
::inDebugMode() ) {
1099 $scripts = self
::filter( 'minify-js', $scripts );
1102 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1104 } elseif ( !is_array( $scripts ) ) {
1105 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1107 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1108 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1109 // of "{}". Force them to objects.
1117 self
::trimArray( $module );
1119 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1123 * Returns JS code which, when called, will register a given list of messages.
1125 * @param mixed $messages Either an associative array mapping message key to value, or a
1126 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1129 public static function makeMessageSetScript( $messages ) {
1130 return Xml
::encodeJsCall(
1132 array( (object)$messages ),
1133 ResourceLoader
::inDebugMode()
1138 * Combines an associative array mapping media type to CSS into a
1139 * single stylesheet with "@media" blocks.
1141 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1144 public static function makeCombinedStyles( array $stylePairs ) {
1146 foreach ( $stylePairs as $media => $styles ) {
1147 // ResourceLoaderFileModule::getStyle can return the styles
1148 // as a string or an array of strings. This is to allow separation in
1150 $styles = (array)$styles;
1151 foreach ( $styles as $style ) {
1152 $style = trim( $style );
1153 // Don't output an empty "@media print { }" block (bug 40498)
1154 if ( $style !== '' ) {
1155 // Transform the media type based on request params and config
1156 // The way that this relies on $wgRequest to propagate request params is slightly evil
1157 $media = OutputPage
::transformCssMedia( $media );
1159 if ( $media === '' ||
$media == 'all' ) {
1161 } elseif ( is_string( $media ) ) {
1162 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1172 * Returns a JS call to mw.loader.state, which sets the state of a
1173 * module or modules to a given value. Has two calling conventions:
1175 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1176 * Set the state of a single module called $name to $state
1178 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1179 * Set the state of modules with the given names to the given states
1181 * @param string $name
1182 * @param string $state
1185 public static function makeLoaderStateScript( $name, $state = null ) {
1186 if ( is_array( $name ) ) {
1187 return Xml
::encodeJsCall(
1190 ResourceLoader
::inDebugMode()
1193 return Xml
::encodeJsCall(
1195 array( $name, $state ),
1196 ResourceLoader
::inDebugMode()
1202 * Returns JS code which calls the script given by $script. The script will
1203 * be called with local variables name, version, dependencies and group,
1204 * which will have values corresponding to $name, $version, $dependencies
1205 * and $group as supplied.
1207 * @param string $name Module name
1208 * @param string $version Module version hash
1209 * @param array $dependencies List of module names on which this module depends
1210 * @param string $group Group which the module is in.
1211 * @param string $source Source of the module, or 'local' if not foreign.
1212 * @param string $script JavaScript code
1215 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1216 $group, $source, $script
1218 $script = str_replace( "\n", "\n\t", trim( $script ) );
1219 return Xml
::encodeJsCall(
1220 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1221 array( $name, $version, $dependencies, $group, $source ),
1222 ResourceLoader
::inDebugMode()
1226 private static function isEmptyObject( stdClass
$obj ) {
1227 foreach ( $obj as $key => $value ) {
1234 * Remove empty values from the end of an array.
1236 * Values considered empty:
1240 * - new XmlJsCode( '{}' )
1241 * - new stdClass() // (object) array()
1243 * @param Array $array
1245 private static function trimArray( Array &$array ) {
1246 $i = count( $array );
1248 if ( $array[$i] === null
1249 ||
$array[$i] === array()
1250 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1251 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1253 unset( $array[$i] );
1261 * Returns JS code which calls mw.loader.register with the given
1262 * parameters. Has three calling conventions:
1264 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1265 * $dependencies, $group, $source, $skip
1267 * Register a single module.
1269 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1270 * Register modules with the given names.
1272 * - ResourceLoader::makeLoaderRegisterScript( array(
1273 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1274 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1277 * Registers modules with the given names and parameters.
1279 * @param string $name Module name
1280 * @param string $version Module version hash
1281 * @param array $dependencies List of module names on which this module depends
1282 * @param string $group Group which the module is in
1283 * @param string $source Source of the module, or 'local' if not foreign
1284 * @param string $skip Script body of the skip function
1287 public static function makeLoaderRegisterScript( $name, $version = null,
1288 $dependencies = null, $group = null, $source = null, $skip = null
1290 if ( is_array( $name ) ) {
1291 // Build module name index
1293 foreach ( $name as $i => &$module ) {
1294 $index[$module[0]] = $i;
1297 // Transform dependency names into indexes when possible, they will be resolved by
1298 // mw.loader.register on the other end
1299 foreach ( $name as &$module ) {
1300 if ( isset( $module[2] ) ) {
1301 foreach ( $module[2] as &$dependency ) {
1302 if ( isset( $index[$dependency] ) ) {
1303 $dependency = $index[$dependency];
1309 array_walk( $name, array( 'self', 'trimArray' ) );
1311 return Xml
::encodeJsCall(
1312 'mw.loader.register',
1314 ResourceLoader
::inDebugMode()
1317 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1318 self
::trimArray( $registration );
1319 return Xml
::encodeJsCall(
1320 'mw.loader.register',
1322 ResourceLoader
::inDebugMode()
1328 * Returns JS code which calls mw.loader.addSource() with the given
1329 * parameters. Has two calling conventions:
1331 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1332 * Register a single source
1334 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1335 * Register sources with the given IDs and properties.
1337 * @param string $id Source ID
1338 * @param array $properties Source properties (see addSource())
1341 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1342 if ( is_array( $id ) ) {
1343 return Xml
::encodeJsCall(
1344 'mw.loader.addSource',
1346 ResourceLoader
::inDebugMode()
1349 return Xml
::encodeJsCall(
1350 'mw.loader.addSource',
1351 array( $id, $properties ),
1352 ResourceLoader
::inDebugMode()
1358 * Returns JS code which runs given JS code if the client-side framework is
1361 * @deprecated since 1.25; use makeInlineScript instead
1362 * @param string $script JavaScript code
1365 public static function makeLoaderConditionalScript( $script ) {
1366 return "window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n" .
1367 trim( $script ) . "\n} );";
1371 * Construct an inline script tag with given JS code.
1373 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1374 * only if the client has adequate support for MediaWiki JavaScript code.
1376 * @param string $script JavaScript code
1377 * @return WrappedString HTML
1379 public static function makeInlineScript( $script ) {
1380 $js = self
::makeLoaderConditionalScript( $script );
1381 return new WrappedString(
1382 Html
::inlineScript( $js ),
1383 "<script>window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n",
1389 * Returns JS code which will set the MediaWiki configuration array to
1392 * @param array $configuration List of configuration values keyed by variable name
1395 public static function makeConfigSetScript( array $configuration ) {
1396 return Xml
::encodeJsCall(
1398 array( $configuration ),
1399 ResourceLoader
::inDebugMode()
1400 ) . ResourceLoader
::FILTER_NOMIN
;
1404 * Convert an array of module names to a packed query string.
1406 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1407 * becomes 'foo.bar,baz|bar.baz,quux'
1408 * @param array $modules List of module names (strings)
1409 * @return string Packed query string
1411 public static function makePackedModulesString( $modules ) {
1412 $groups = array(); // array( prefix => array( suffixes ) )
1413 foreach ( $modules as $module ) {
1414 $pos = strrpos( $module, '.' );
1415 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1416 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1417 $groups[$prefix][] = $suffix;
1421 foreach ( $groups as $prefix => $suffixes ) {
1422 $p = $prefix === '' ?
'' : $prefix . '.';
1423 $arr[] = $p . implode( ',', $suffixes );
1425 $str = implode( '|', $arr );
1430 * Determine whether debug mode was requested
1431 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1434 public static function inDebugMode() {
1435 if ( self
::$debugMode === null ) {
1436 global $wgRequest, $wgResourceLoaderDebug;
1437 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1438 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1441 return self
::$debugMode;
1445 * Reset static members used for caching.
1447 * Global state and $wgRequest are evil, but we're using it right
1448 * now and sometimes we need to be able to force ResourceLoader to
1449 * re-evaluate the context because it has changed (e.g. in the test suite).
1451 public static function clearCache() {
1452 self
::$debugMode = null;
1456 * Build a load.php URL
1459 * @param string $source Name of the ResourceLoader source
1460 * @param ResourceLoaderContext $context
1461 * @param array $extraQuery
1462 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1464 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1465 $extraQuery = array()
1467 $query = self
::createLoaderQuery( $context, $extraQuery );
1468 $script = $this->getLoadScript( $source );
1470 return wfAppendQuery( $script, $query );
1474 * Build a load.php URL
1475 * @deprecated since 1.24 Use createLoaderURL() instead
1476 * @param array $modules Array of module names (strings)
1477 * @param string $lang Language code
1478 * @param string $skin Skin name
1479 * @param string|null $user User name. If null, the &user= parameter is omitted
1480 * @param string|null $version Versioning timestamp
1481 * @param bool $debug Whether the request should be in debug mode
1482 * @param string|null $only &only= parameter
1483 * @param bool $printable Printable mode
1484 * @param bool $handheld Handheld mode
1485 * @param array $extraQuery Extra query parameters to add
1486 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1488 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1489 $version = null, $debug = false, $only = null, $printable = false,
1490 $handheld = false, $extraQuery = array()
1492 global $wgLoadScript;
1494 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1495 $only, $printable, $handheld, $extraQuery
1498 return wfAppendQuery( $wgLoadScript, $query );
1502 * Helper for createLoaderURL()
1505 * @see makeLoaderQuery
1506 * @param ResourceLoaderContext $context
1507 * @param array $extraQuery
1510 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1511 return self
::makeLoaderQuery(
1512 $context->getModules(),
1513 $context->getLanguage(),
1514 $context->getSkin(),
1515 $context->getUser(),
1516 $context->getVersion(),
1517 $context->getDebug(),
1518 $context->getOnly(),
1519 $context->getRequest()->getBool( 'printable' ),
1520 $context->getRequest()->getBool( 'handheld' ),
1526 * Build a query array (array representation of query string) for load.php. Helper
1527 * function for makeLoaderURL().
1529 * @param array $modules
1530 * @param string $lang
1531 * @param string $skin
1532 * @param string $user
1533 * @param string $version
1534 * @param bool $debug
1535 * @param string $only
1536 * @param bool $printable
1537 * @param bool $handheld
1538 * @param array $extraQuery
1542 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1543 $version = null, $debug = false, $only = null, $printable = false,
1544 $handheld = false, $extraQuery = array()
1547 'modules' => self
::makePackedModulesString( $modules ),
1550 'debug' => $debug ?
'true' : 'false',
1552 if ( $user !== null ) {
1553 $query['user'] = $user;
1555 if ( $version !== null ) {
1556 $query['version'] = $version;
1558 if ( $only !== null ) {
1559 $query['only'] = $only;
1562 $query['printable'] = 1;
1565 $query['handheld'] = 1;
1567 $query +
= $extraQuery;
1569 // Make queries uniform in order
1575 * Check a module name for validity.
1577 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1578 * at most 255 bytes.
1580 * @param string $moduleName Module name to check
1581 * @return bool Whether $moduleName is a valid module name
1583 public static function isValidModuleName( $moduleName ) {
1584 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1588 * Returns LESS compiler set up for use with MediaWiki
1591 * @since 1.27 added $extraVars parameter
1592 * @param Config $config
1593 * @param array $extraVars Associative array of extra (i.e., other than the
1594 * globally-configured ones) that should be used for compilation.
1595 * @throws MWException
1596 * @return Less_Parser
1598 public static function getLessCompiler( Config
$config, $extraVars = array() ) {
1599 // When called from the installer, it is possible that a required PHP extension
1600 // is missing (at least for now; see bug 47564). If this is the case, throw an
1601 // exception (caught by the installer) to prevent a fatal error later on.
1602 if ( !class_exists( 'Less_Parser' ) ) {
1603 throw new MWException( 'MediaWiki requires the less.php parser' );
1606 $parser = new Less_Parser
;
1607 $parser->ModifyVars( array_merge( self
::getLessVars( $config ), $extraVars ) );
1608 $parser->SetImportDirs( array_fill_keys( $config->get( 'ResourceLoaderLESSImportPaths' ), '' ) );
1609 $parser->SetOption( 'relativeUrls', false );
1610 $parser->SetCacheDir( $config->get( 'CacheDirectory' ) ?
: wfTempDir() );
1616 * Get global LESS variables.
1618 * @param Config $config
1620 * @return array Map of variable names to string CSS values.
1622 public static function getLessVars( Config
$config ) {
1623 if ( !self
::$lessVars ) {
1624 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1625 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1626 self
::$lessVars = $lessVars;
1628 return self
::$lessVars;