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
91 * Load information stored in the database about modules.
93 * This method grabs modules dependencies from the database and updates modules
96 * This is not inside the module code because it is much faster to
97 * request all of the information at once than it is to have each module
98 * requests its own information. This sacrifice of modularity yields a substantial
99 * performance improvement.
101 * @param array $modules List of module names to preload information for
102 * @param ResourceLoaderContext $context Context to load the information within
104 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
105 if ( !count( $modules ) ) {
106 // Or else Database*::select() will explode, plus it's cheaper!
109 $dbr = wfGetDB( DB_SLAVE
);
110 $skin = $context->getSkin();
111 $lang = $context->getLanguage();
113 // Get file dependency information
114 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
115 'md_module' => $modules,
120 // Set modules' dependencies
121 $modulesWithDeps = array();
122 foreach ( $res as $row ) {
123 $module = $this->getModule( $row->md_module
);
125 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
126 $modulesWithDeps[] = $row->md_module
;
130 // Register the absence of a dependency row too
131 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
132 $module = $this->getModule( $name );
134 $this->getModule( $name )->setFileDependencies( $skin, array() );
138 // Get message blob mtimes. Only do this for modules with messages
139 $modulesWithMessages = array();
140 foreach ( $modules as $name ) {
141 $module = $this->getModule( $name );
142 if ( $module && count( $module->getMessages() ) ) {
143 $modulesWithMessages[] = $name;
146 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
147 if ( count( $modulesWithMessages ) ) {
148 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
149 'mr_resource' => $modulesWithMessages,
153 foreach ( $res as $row ) {
154 $module = $this->getModule( $row->mr_resource
);
156 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
157 unset( $modulesWithoutMessages[$row->mr_resource
] );
161 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
162 $module = $this->getModule( $name );
164 $module->setMsgBlobMtime( $lang, 1 );
170 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
172 * Available filters are:
174 * - minify-js \see JavaScriptMinifier::minify
175 * - minify-css \see CSSMin::minify
177 * If $data is empty, only contains whitespace or the filter was unknown,
178 * $data is returned unmodified.
180 * @param string $filter Name of filter to run
181 * @param string $data Text to filter, such as JavaScript or CSS text
182 * @param array $options For back-compat, can also be the boolean value for "cacheReport". Keys:
183 * - (bool) cache: Whether to allow caching this data. Default: true.
184 * - (bool) cacheReport: Whether to include the "cache key" report comment. Default: false.
185 * @return string Filtered data, or a comment containing an error message
187 public function filter( $filter, $data, $options = array() ) {
189 if ( is_bool( $options ) ) {
190 $options = array( 'cacheReport' => $options );
193 $options +
= array( 'cache' => true, 'cacheReport' => false );
194 $stats = RequestContext
::getMain()->getStats();
196 // Don't filter empty content
197 if ( trim( $data ) === '' ) {
201 if ( !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
202 $this->logger
->warning( 'Invalid filter {filter}', array(
208 if ( !$options['cache'] ) {
209 $result = self
::applyFilter( $filter, $data, $this->config
);
211 $key = wfGlobalCacheKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
212 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL
: CACHE_ANYTHING
);
213 $cacheEntry = $cache->get( $key );
214 if ( is_string( $cacheEntry ) ) {
215 $stats->increment( "resourceloader_cache.$filter.hit" );
220 $statStart = microtime( true );
221 $result = self
::applyFilter( $filter, $data, $this->config
);
222 $statTiming = microtime( true ) - $statStart;
223 $stats->increment( "resourceloader_cache.$filter.miss" );
224 $stats->timing( "resourceloader_cache.$filter.timing", 1000 * $statTiming );
225 if ( $options['cacheReport'] ) {
226 $result .= "\n/* cache key: $key */";
228 // Set a TTL since HHVM's APC doesn't have any limitation or eviction logic.
229 $cache->set( $key, $result, 24 * 3600 );
230 } catch ( Exception
$e ) {
231 MWExceptionHandler
::logException( $e );
232 $this->logger
->warning( 'Minification failed: {exception}', array(
235 $this->errors
[] = self
::formatExceptionNoComment( $e );
242 private static function applyFilter( $filter, $data, Config
$config ) {
245 return JavaScriptMinifier
::minify( $data,
246 $config->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
247 $config->get( 'ResourceLoaderMinifierMaxLineLength' )
250 return CSSMin
::minify( $data );
259 * Register core modules and runs registration hooks.
260 * @param Config|null $config
262 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
266 $logger = new NullLogger();
268 $this->setLogger( $logger );
271 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
272 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
274 $this->config
= $config;
276 // Add 'local' source first
277 $this->addSource( 'local', wfScript( 'load' ) );
280 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
282 // Register core modules
283 $this->register( include "$IP/resources/Resources.php" );
284 $this->register( include "$IP/resources/ResourcesOOUI.php" );
285 // Register extension modules
286 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
287 $this->register( $config->get( 'ResourceModules' ) );
289 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
290 $this->registerTestModules();
293 $this->setMessageBlobStore( new MessageBlobStore() );
299 public function getConfig() {
300 return $this->config
;
303 public function setLogger( LoggerInterface
$logger ) {
304 $this->logger
= $logger;
309 * @return MessageBlobStore
311 public function getMessageBlobStore() {
312 return $this->blobStore
;
317 * @param MessageBlobStore $blobStore
319 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
320 $this->blobStore
= $blobStore;
324 * Register a module with the ResourceLoader system.
326 * @param mixed $name Name of module as a string or List of name/object pairs as an array
327 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
328 * this may also be a ResourceLoaderModule object. Optional when using
329 * multiple-registration calling style.
330 * @throws MWException If a duplicate module registration is attempted
331 * @throws MWException If a module name contains illegal characters (pipes or commas)
332 * @throws MWException If something other than a ResourceLoaderModule is being registered
333 * @return bool False if there were any errors, in which case one or more modules were
336 public function register( $name, $info = null ) {
338 // Allow multiple modules to be registered in one call
339 $registrations = is_array( $name ) ?
$name : array( $name => $info );
340 foreach ( $registrations as $name => $info ) {
341 // Disallow duplicate registrations
342 if ( isset( $this->moduleInfos
[$name] ) ) {
343 // A module has already been registered by this name
344 throw new MWException(
345 'ResourceLoader duplicate registration error. ' .
346 'Another module has already been registered as ' . $name
350 // Check $name for validity
351 if ( !self
::isValidModuleName( $name ) ) {
352 throw new MWException( "ResourceLoader module name '$name' is invalid, "
353 . "see ResourceLoader::isValidModuleName()" );
357 if ( $info instanceof ResourceLoaderModule
) {
358 $this->moduleInfos
[$name] = array( 'object' => $info );
359 $info->setName( $name );
360 $this->modules
[$name] = $info;
361 } elseif ( is_array( $info ) ) {
362 // New calling convention
363 $this->moduleInfos
[$name] = $info;
365 throw new MWException(
366 'ResourceLoader module info type error for module \'' . $name .
367 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
371 // Last-minute changes
373 // Apply custom skin-defined styles to existing modules.
374 if ( $this->isFileModule( $name ) ) {
375 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
376 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
377 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
381 // If $name is preceded with a '+', the defined style files will be added to 'default'
382 // skinStyles, otherwise 'default' will be ignored as it normally would be.
383 if ( isset( $skinStyles[$name] ) ) {
384 $paths = (array)$skinStyles[$name];
385 $styleFiles = array();
386 } elseif ( isset( $skinStyles['+' . $name] ) ) {
387 $paths = (array)$skinStyles['+' . $name];
388 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
389 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
395 // Add new file paths, remapping them to refer to our directories and not use settings
396 // from the module we're modifying, which come from the base definition.
397 list( $localBasePath, $remoteBasePath ) =
398 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
400 foreach ( $paths as $path ) {
401 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
404 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
413 public function registerTestModules() {
416 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
417 throw new MWException( 'Attempt to register JavaScript test modules '
418 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
419 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
422 // Get core test suites
423 $testModules = array();
424 $testModules['qunit'] = array();
425 // Get other test suites (e.g. from extensions)
426 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
428 // Add the testrunner (which configures QUnit) to the dependencies.
429 // Since it must be ready before any of the test suites are executed.
430 foreach ( $testModules['qunit'] as &$module ) {
431 // Make sure all test modules are top-loading so that when QUnit starts
432 // on document-ready, it will run once and finish. If some tests arrive
433 // later (possibly after QUnit has already finished) they will be ignored.
434 $module['position'] = 'top';
435 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
438 $testModules['qunit'] =
439 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
441 foreach ( $testModules as $id => $names ) {
442 // Register test modules
443 $this->register( $testModules[$id] );
445 // Keep track of their names so that they can be loaded together
446 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
452 * Add a foreign source of modules.
454 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
455 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
456 * backwards-compatibility.
457 * @throws MWException
459 public function addSource( $id, $loadUrl = null ) {
460 // Allow multiple sources to be registered in one call
461 if ( is_array( $id ) ) {
462 foreach ( $id as $key => $value ) {
463 $this->addSource( $key, $value );
468 // Disallow duplicates
469 if ( isset( $this->sources
[$id] ) ) {
470 throw new MWException(
471 'ResourceLoader duplicate source addition error. ' .
472 'Another source has already been registered as ' . $id
476 // Pre 1.24 backwards-compatibility
477 if ( is_array( $loadUrl ) ) {
478 if ( !isset( $loadUrl['loadScript'] ) ) {
479 throw new MWException(
480 __METHOD__
. ' was passed an array with no "loadScript" key.'
484 $loadUrl = $loadUrl['loadScript'];
487 $this->sources
[$id] = $loadUrl;
491 * Get a list of module names.
493 * @return array List of module names
495 public function getModuleNames() {
496 return array_keys( $this->moduleInfos
);
500 * Get a list of test module names for one (or all) frameworks.
502 * If the given framework id is unknkown, or if the in-object variable is not an array,
503 * then it will return an empty array.
505 * @param string $framework Get only the test module names for one
506 * particular framework (optional)
509 public function getTestModuleNames( $framework = 'all' ) {
510 /** @todo api siteinfo prop testmodulenames modulenames */
511 if ( $framework == 'all' ) {
512 return $this->testModuleNames
;
513 } elseif ( isset( $this->testModuleNames
[$framework] )
514 && is_array( $this->testModuleNames
[$framework] )
516 return $this->testModuleNames
[$framework];
523 * Check whether a ResourceLoader module is registered
526 * @param string $name
529 public function isModuleRegistered( $name ) {
530 return isset( $this->moduleInfos
[$name] );
534 * Get the ResourceLoaderModule object for a given module name.
536 * If an array of module parameters exists but a ResourceLoaderModule object has not
537 * yet been instantiated, this method will instantiate and cache that object such that
538 * subsequent calls simply return the same object.
540 * @param string $name Module name
541 * @return ResourceLoaderModule|null If module has been registered, return a
542 * ResourceLoaderModule instance. Otherwise, return null.
544 public function getModule( $name ) {
545 if ( !isset( $this->modules
[$name] ) ) {
546 if ( !isset( $this->moduleInfos
[$name] ) ) {
550 // Construct the requested object
551 $info = $this->moduleInfos
[$name];
552 /** @var ResourceLoaderModule $object */
553 if ( isset( $info['object'] ) ) {
554 // Object given in info array
555 $object = $info['object'];
557 if ( !isset( $info['class'] ) ) {
558 $class = 'ResourceLoaderFileModule';
560 $class = $info['class'];
562 /** @var ResourceLoaderModule $object */
563 $object = new $class( $info );
564 $object->setConfig( $this->getConfig() );
566 $object->setName( $name );
567 $this->modules
[$name] = $object;
570 return $this->modules
[$name];
574 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
576 * @param string $name Module name
579 protected function isFileModule( $name ) {
580 if ( !isset( $this->moduleInfos
[$name] ) ) {
583 $info = $this->moduleInfos
[$name];
584 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
591 * Get the list of sources.
593 * @return array Like array( id => load.php url, .. )
595 public function getSources() {
596 return $this->sources
;
600 * Get the URL to the load.php endpoint for the given
601 * ResourceLoader source
604 * @param string $source
605 * @throws MWException On an invalid $source name
608 public function getLoadScript( $source ) {
609 if ( !isset( $this->sources
[$source] ) ) {
610 throw new MWException( "The $source source was never registered in ResourceLoader." );
612 return $this->sources
[$source];
617 * @param string $value
618 * @return string Hash
620 public static function makeHash( $value ) {
621 // Use base64 to output more entropy in a more compact string (default hex is only base16).
622 // The first 8 chars of a base64 encoded digest represent the same binary as
623 // the first 12 chars of a hex encoded digest.
624 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
628 * Helper method to get and combine versions of multiple modules.
631 * @param ResourceLoaderContext $context
632 * @param array $modules List of ResourceLoaderModule objects
633 * @return string Hash
635 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
639 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
640 // http://php.net/functions.anonymous
642 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
643 return $rl->getModule( $module )->getVersionHash( $context );
645 return self
::makeHash( implode( $hashes ) );
649 * Output a response to a load request, including the content-type header.
651 * @param ResourceLoaderContext $context Context in which a response should be formed
653 public function respond( ResourceLoaderContext
$context ) {
654 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
655 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
656 // is used: ob_clean() will clear the GZIP header in that case and it won't come
657 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
658 // the whole thing in our own output buffer to be sure the active buffer
659 // doesn't use ob_gzhandler.
660 // See http://bugs.php.net/bug.php?id=36514
663 // Find out which modules are missing and instantiate the others
666 foreach ( $context->getModules() as $name ) {
667 $module = $this->getModule( $name );
669 // Do not allow private modules to be loaded from the web.
670 // This is a security issue, see bug 34907.
671 if ( $module->getGroup() === 'private' ) {
672 $this->logger
->debug( "Request for private module '$name' denied" );
673 $this->errors
[] = "Cannot show private module \"$name\"";
676 $modules[$name] = $module;
683 // Preload for getCombinedVersion()
684 $this->preloadModuleInfo( array_keys( $modules ), $context );
685 } catch ( Exception
$e ) {
686 MWExceptionHandler
::logException( $e );
687 $this->logger
->warning( 'Preloading module info failed: {exception}', array(
690 $this->errors
[] = self
::formatExceptionNoComment( $e );
693 // Combine versions to propagate cache invalidation
696 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
697 } catch ( Exception
$e ) {
698 MWExceptionHandler
::logException( $e );
699 $this->logger
->warning( 'Calculating version hash failed: {exception}', array(
702 $this->errors
[] = self
::formatExceptionNoComment( $e );
705 // See RFC 2616 § 3.11 Entity Tags
706 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
707 $etag = 'W/"' . $versionHash . '"';
709 // Try the client-side cache first
710 if ( $this->tryRespondNotModified( $context, $etag ) ) {
711 return; // output handled (buffers cleared)
714 // Use file cache if enabled and available...
715 if ( $this->config
->get( 'UseFileCache' ) ) {
716 $fileCache = ResourceFileCache
::newFromContext( $context );
717 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
718 return; // output handled
722 // Generate a response
723 $response = $this->makeModuleResponse( $context, $modules, $missing );
725 // Capture any PHP warnings from the output buffer and append them to the
726 // error list if we're in debug mode.
727 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
728 $this->errors
[] = $warnings;
731 // Save response to file cache unless there are errors
732 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
733 // Cache single modules and images...and other requests if there are enough hits
734 if ( ResourceFileCache
::useFileCache( $context ) ) {
735 if ( $fileCache->isCacheWorthy() ) {
736 $fileCache->saveText( $response );
738 $fileCache->incrMissesRecent( $context->getRequest() );
743 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
745 // Remove the output buffer and output the response
748 if ( $context->getImageObj() && $this->errors
) {
749 // We can't show both the error messages and the response when it's an image.
751 foreach ( $this->errors
as $error ) {
752 $errorText .= $error . "\n";
754 $response = $errorText;
755 } elseif ( $this->errors
) {
756 // Prepend comments indicating errors
758 foreach ( $this->errors
as $error ) {
759 $errorText .= self
::makeComment( $error );
761 $response = $errorText . $response;
764 $this->errors
= array();
770 * Send main response headers to the client.
772 * Deals with Content-Type, CORS (for stylesheets), and caching.
774 * @param ResourceLoaderContext $context
775 * @param string $etag ETag header value
776 * @param bool $errors Whether there are errors in the response
779 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
780 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
781 // If a version wasn't specified we need a shorter expiry time for updates
782 // to propagate to clients quickly
783 // If there were errors, we also need a shorter expiry time so we can recover quickly
784 if ( is_null( $context->getVersion() ) ||
$errors ) {
785 $maxage = $rlMaxage['unversioned']['client'];
786 $smaxage = $rlMaxage['unversioned']['server'];
787 // If a version was specified we can use a longer expiry time since changing
788 // version numbers causes cache misses
790 $maxage = $rlMaxage['versioned']['client'];
791 $smaxage = $rlMaxage['versioned']['server'];
793 if ( $context->getImageObj() ) {
794 // Output different headers if we're outputting textual errors.
796 header( 'Content-Type: text/plain; charset=utf-8' );
798 $context->getImageObj()->sendResponseHeaders( $context );
800 } elseif ( $context->getOnly() === 'styles' ) {
801 header( 'Content-Type: text/css; charset=utf-8' );
802 header( 'Access-Control-Allow-Origin: *' );
804 header( 'Content-Type: text/javascript; charset=utf-8' );
806 // See RFC 2616 § 14.19 ETag
807 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
808 header( 'ETag: ' . $etag );
809 if ( $context->getDebug() ) {
810 // Do not cache debug responses
811 header( 'Cache-Control: private, no-cache, must-revalidate' );
812 header( 'Pragma: no-cache' );
814 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
815 $exp = min( $maxage, $smaxage );
816 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
819 // Send the current time expressed as fractional seconds since epoch,
820 // with microsecond precision. This helps distinguish hits from misses
822 header( 'MediaWiki-Timestamp: ' . microtime( true ) );
826 * Respond with HTTP 304 Not Modified if appropiate.
828 * If there's an If-None-Match header, respond with a 304 appropriately
829 * and clear out the output buffer. If the client cache is too old then do nothing.
831 * @param ResourceLoaderContext $context
832 * @param string $etag ETag header value
833 * @return bool True if HTTP 304 was sent and output handled
835 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
836 // See RFC 2616 § 14.26 If-None-Match
837 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
838 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
839 // Never send 304s in debug mode
840 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
841 // There's another bug in ob_gzhandler (see also the comment at
842 // the top of this function) that causes it to gzip even empty
843 // responses, meaning it's impossible to produce a truly empty
844 // response (because the gzip header is always there). This is
845 // a problem because 304 responses have to be completely empty
846 // per the HTTP spec, and Firefox behaves buggily when they're not.
847 // See also http://bugs.php.net/bug.php?id=51579
848 // To work around this, we tear down all output buffering before
850 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
852 HttpStatus
::header( 304 );
854 $this->sendResponseHeaders( $context, $etag, false );
861 * Send out code for a response from file cache if possible.
863 * @param ResourceFileCache $fileCache Cache object for this request URL
864 * @param ResourceLoaderContext $context Context in which to generate a response
865 * @param string $etag ETag header value
866 * @return bool If this found a cache file and handled the response
868 protected function tryRespondFromFileCache(
869 ResourceFileCache
$fileCache,
870 ResourceLoaderContext
$context,
873 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
874 // Buffer output to catch warnings.
876 // Get the maximum age the cache can be
877 $maxage = is_null( $context->getVersion() )
878 ?
$rlMaxage['unversioned']['server']
879 : $rlMaxage['versioned']['server'];
880 // Minimum timestamp the cache file must have
881 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
883 try { // RL always hits the DB on file cache miss...
885 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
886 $good = $fileCache->isCacheGood(); // cache existence check
890 $ts = $fileCache->cacheTimestamp();
891 // Send content type and cache headers
892 $this->sendResponseHeaders( $context, $etag, false );
893 $response = $fileCache->fetchText();
894 // Capture any PHP warnings from the output buffer and append them to the
895 // response in a comment if we're in debug mode.
896 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
897 $response = self
::makeComment( $warnings ) . $response;
899 // Remove the output buffer and output the response
901 echo $response . "\n/* Cached {$ts} */";
902 return true; // cache hit
907 return false; // cache miss
911 * Generate a CSS or JS comment block.
913 * Only use this for public data, not error message details.
915 * @param string $text
918 public static function makeComment( $text ) {
919 $encText = str_replace( '*/', '* /', $text );
920 return "/*\n$encText\n*/\n";
924 * Handle exception display.
926 * @param Exception $e Exception to be shown to the user
927 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
929 public static function formatException( $e ) {
930 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
934 * Handle exception display.
937 * @param Exception $e Exception to be shown to the user
938 * @return string Sanitized text that can be returned to the user
940 protected static function formatExceptionNoComment( $e ) {
941 global $wgShowExceptionDetails;
943 if ( !$wgShowExceptionDetails ) {
944 return 'Internal error';
947 return $e->__toString();
951 * Generate code for a response.
953 * @param ResourceLoaderContext $context Context in which to generate a response
954 * @param array $modules List of module objects keyed by module name
955 * @param array $missing List of requested module names that are unregistered (optional)
956 * @return string Response data
958 public function makeModuleResponse( ResourceLoaderContext
$context,
959 array $modules, array $missing = array()
964 if ( !count( $modules ) && !count( $missing ) ) {
966 /* This file is the Web entry point for MediaWiki's ResourceLoader:
967 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
968 no modules were requested. Max made me put this here. */
972 $image = $context->getImageObj();
974 $data = $image->getImageData( $context );
975 if ( $data === false ) {
977 $this->errors
[] = 'Image generation failed';
983 if ( $context->shouldIncludeMessages() ) {
985 $this->blobStore
->get( $this, $modules, $context->getLanguage() );
986 } catch ( Exception
$e ) {
987 MWExceptionHandler
::logException( $e );
988 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
991 $this->errors
[] = self
::formatExceptionNoComment( $e );
995 foreach ( $missing as $name ) {
996 $states[$name] = 'missing';
1001 foreach ( $modules as $name => $module ) {
1003 $content = $module->getModuleContent( $context );
1006 switch ( $context->getOnly() ) {
1008 $scripts = $content['scripts'];
1009 if ( is_string( $scripts ) ) {
1010 // Load scripts raw...
1012 } elseif ( is_array( $scripts ) ) {
1013 // ...except when $scripts is an array of URLs
1014 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1018 $styles = $content['styles'];
1019 // We no longer seperate into media, they are all combined now with
1020 // custom media type groups into @media .. {} sections as part of the css string.
1021 // Module returns either an empty array or a numerical array with css strings.
1022 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1025 $out .= self
::makeLoaderImplementScript(
1027 isset( $content['scripts'] ) ?
$content['scripts'] : '',
1028 isset( $content['styles'] ) ?
$content['styles'] : array(),
1029 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : array(),
1030 isset( $content['templates'] ) ?
$content['templates'] : array()
1034 } catch ( Exception
$e ) {
1035 MWExceptionHandler
::logException( $e );
1036 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1039 $this->errors
[] = self
::formatExceptionNoComment( $e );
1041 // Respond to client with error-state instead of module implementation
1042 $states[$name] = 'error';
1043 unset( $modules[$name] );
1045 $isRaw |
= $module->isRaw();
1048 // Update module states
1049 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1050 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1051 // Set the state of modules loaded as only scripts to ready as
1052 // they don't have an mw.loader.implement wrapper that sets the state
1053 foreach ( $modules as $name => $module ) {
1054 $states[$name] = 'ready';
1058 // Set the state of modules we didn't respond to with mw.loader.implement
1059 if ( count( $states ) ) {
1060 $out .= self
::makeLoaderStateScript( $states );
1063 if ( count( $states ) ) {
1064 $this->errors
[] = 'Problematic modules: ' .
1065 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1069 $enableFilterCache = true;
1070 if ( count( $modules ) === 1 && reset( $modules ) instanceof ResourceLoaderUserTokensModule
) {
1071 // If we're building the embedded user.tokens, don't cache (T84960)
1072 $enableFilterCache = false;
1075 if ( !$context->getDebug() ) {
1076 if ( $context->getOnly() === 'styles' ) {
1077 $out = $this->filter( 'minify-css', $out );
1079 $out = $this->filter( 'minify-js', $out, array(
1080 'cache' => $enableFilterCache
1088 /* Static Methods */
1091 * Return JS code that calls mw.loader.implement with given module properties.
1093 * @param string $name Module name
1094 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1095 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1096 * to CSS files keyed by media type
1097 * @param mixed $messages List of messages associated with this module. May either be an
1098 * associative array mapping message key to value, or a JSON-encoded message blob containing
1099 * the same data, wrapped in an XmlJsCode object.
1100 * @param array $templates Keys are name of templates and values are the source of
1102 * @throws MWException
1105 public static function makeLoaderImplementScript(
1106 $name, $scripts, $styles, $messages, $templates
1108 if ( is_string( $scripts ) ) {
1109 // Site and user module are a legacy scripts that run in the global scope (no closure).
1110 // Transportation as string instructs mw.loader.implement to use globalEval.
1111 if ( $name === 'site' ||
$name === 'user' ) {
1112 // Minify manually because the general makeModuleResponse() minification won't be
1113 // effective here due to the script being a string instead of a function. (T107377)
1114 if ( !ResourceLoader
::inDebugMode() ) {
1115 $scripts = self
::applyFilter( 'minify-js', $scripts,
1116 ConfigFactory
::getDefaultInstance()->makeConfig( 'main' ) );
1119 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1121 } elseif ( !is_array( $scripts ) ) {
1122 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1124 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1125 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1126 // of "{}". Force them to objects.
1134 self
::trimArray( $module );
1136 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1140 * Returns JS code which, when called, will register a given list of messages.
1142 * @param mixed $messages Either an associative array mapping message key to value, or a
1143 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1146 public static function makeMessageSetScript( $messages ) {
1147 return Xml
::encodeJsCall(
1149 array( (object)$messages ),
1150 ResourceLoader
::inDebugMode()
1155 * Combines an associative array mapping media type to CSS into a
1156 * single stylesheet with "@media" blocks.
1158 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1161 public static function makeCombinedStyles( array $stylePairs ) {
1163 foreach ( $stylePairs as $media => $styles ) {
1164 // ResourceLoaderFileModule::getStyle can return the styles
1165 // as a string or an array of strings. This is to allow separation in
1167 $styles = (array)$styles;
1168 foreach ( $styles as $style ) {
1169 $style = trim( $style );
1170 // Don't output an empty "@media print { }" block (bug 40498)
1171 if ( $style !== '' ) {
1172 // Transform the media type based on request params and config
1173 // The way that this relies on $wgRequest to propagate request params is slightly evil
1174 $media = OutputPage
::transformCssMedia( $media );
1176 if ( $media === '' ||
$media == 'all' ) {
1178 } elseif ( is_string( $media ) ) {
1179 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1189 * Returns a JS call to mw.loader.state, which sets the state of a
1190 * module or modules to a given value. Has two calling conventions:
1192 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1193 * Set the state of a single module called $name to $state
1195 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1196 * Set the state of modules with the given names to the given states
1198 * @param string $name
1199 * @param string $state
1202 public static function makeLoaderStateScript( $name, $state = null ) {
1203 if ( is_array( $name ) ) {
1204 return Xml
::encodeJsCall(
1207 ResourceLoader
::inDebugMode()
1210 return Xml
::encodeJsCall(
1212 array( $name, $state ),
1213 ResourceLoader
::inDebugMode()
1219 * Returns JS code which calls the script given by $script. The script will
1220 * be called with local variables name, version, dependencies and group,
1221 * which will have values corresponding to $name, $version, $dependencies
1222 * and $group as supplied.
1224 * @param string $name Module name
1225 * @param string $version Module version hash
1226 * @param array $dependencies List of module names on which this module depends
1227 * @param string $group Group which the module is in.
1228 * @param string $source Source of the module, or 'local' if not foreign.
1229 * @param string $script JavaScript code
1232 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1233 $group, $source, $script
1235 $script = str_replace( "\n", "\n\t", trim( $script ) );
1236 return Xml
::encodeJsCall(
1237 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1238 array( $name, $version, $dependencies, $group, $source ),
1239 ResourceLoader
::inDebugMode()
1243 private static function isEmptyObject( stdClass
$obj ) {
1244 foreach ( $obj as $key => &$value ) {
1251 * Remove empty values from the end of an array.
1253 * Values considered empty:
1257 * - new XmlJsCode( '{}' )
1258 * - new stdClass() // (object) array()
1260 * @param Array $array
1262 private static function trimArray( Array &$array ) {
1263 $i = count( $array );
1265 if ( $array[$i] === null
1266 ||
$array[$i] === array()
1267 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1268 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1270 unset( $array[$i] );
1278 * Returns JS code which calls mw.loader.register with the given
1279 * parameters. Has three calling conventions:
1281 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1282 * $dependencies, $group, $source, $skip
1284 * Register a single module.
1286 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1287 * Register modules with the given names.
1289 * - ResourceLoader::makeLoaderRegisterScript( array(
1290 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1291 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1294 * Registers modules with the given names and parameters.
1296 * @param string $name Module name
1297 * @param string $version Module version hash
1298 * @param array $dependencies List of module names on which this module depends
1299 * @param string $group Group which the module is in
1300 * @param string $source Source of the module, or 'local' if not foreign
1301 * @param string $skip Script body of the skip function
1304 public static function makeLoaderRegisterScript( $name, $version = null,
1305 $dependencies = null, $group = null, $source = null, $skip = null
1307 if ( is_array( $name ) ) {
1308 // Build module name index
1310 foreach ( $name as $i => &$module ) {
1311 $index[$module[0]] = $i;
1314 // Transform dependency names into indexes when possible, they will be resolved by
1315 // mw.loader.register on the other end
1316 foreach ( $name as &$module ) {
1317 if ( isset( $module[2] ) ) {
1318 foreach ( $module[2] as &$dependency ) {
1319 if ( isset( $index[$dependency] ) ) {
1320 $dependency = $index[$dependency];
1326 array_walk( $name, array( 'self', 'trimArray' ) );
1328 return Xml
::encodeJsCall(
1329 'mw.loader.register',
1331 ResourceLoader
::inDebugMode()
1334 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1335 self
::trimArray( $registration );
1336 return Xml
::encodeJsCall(
1337 'mw.loader.register',
1339 ResourceLoader
::inDebugMode()
1345 * Returns JS code which calls mw.loader.addSource() with the given
1346 * parameters. Has two calling conventions:
1348 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1349 * Register a single source
1351 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1352 * Register sources with the given IDs and properties.
1354 * @param string $id Source ID
1355 * @param array $properties Source properties (see addSource())
1358 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1359 if ( is_array( $id ) ) {
1360 return Xml
::encodeJsCall(
1361 'mw.loader.addSource',
1363 ResourceLoader
::inDebugMode()
1366 return Xml
::encodeJsCall(
1367 'mw.loader.addSource',
1368 array( $id, $properties ),
1369 ResourceLoader
::inDebugMode()
1375 * Returns JS code which runs given JS code if the client-side framework is
1378 * @deprecated since 1.25; use makeInlineScript instead
1379 * @param string $script JavaScript code
1382 public static function makeLoaderConditionalScript( $script ) {
1383 return "window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n" . trim( $script ) . "\n} );";
1387 * Construct an inline script tag with given JS code.
1389 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1390 * only if the client has adequate support for MediaWiki JavaScript code.
1392 * @param string $script JavaScript code
1393 * @return WrappedString HTML
1395 public static function makeInlineScript( $script ) {
1396 $js = self
::makeLoaderConditionalScript( $script );
1397 return new WrappedString(
1398 Html
::inlineScript( $js ),
1399 "<script>window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n",
1405 * Returns JS code which will set the MediaWiki configuration array to
1408 * @param array $configuration List of configuration values keyed by variable name
1411 public static function makeConfigSetScript( array $configuration ) {
1412 if ( ResourceLoader
::inDebugMode() ) {
1413 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ), true );
1416 $config = RequestContext
::getMain()->getConfig();
1417 $js = Xml
::encodeJsCall( 'mw.config.set', array( $configuration ), false );
1418 return self
::applyFilter( 'minify-js', $js, $config );
1422 * Convert an array of module names to a packed query string.
1424 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1425 * becomes 'foo.bar,baz|bar.baz,quux'
1426 * @param array $modules List of module names (strings)
1427 * @return string Packed query string
1429 public static function makePackedModulesString( $modules ) {
1430 $groups = array(); // array( prefix => array( suffixes ) )
1431 foreach ( $modules as $module ) {
1432 $pos = strrpos( $module, '.' );
1433 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1434 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1435 $groups[$prefix][] = $suffix;
1439 foreach ( $groups as $prefix => $suffixes ) {
1440 $p = $prefix === '' ?
'' : $prefix . '.';
1441 $arr[] = $p . implode( ',', $suffixes );
1443 $str = implode( '|', $arr );
1448 * Determine whether debug mode was requested
1449 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1452 public static function inDebugMode() {
1453 if ( self
::$debugMode === null ) {
1454 global $wgRequest, $wgResourceLoaderDebug;
1455 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1456 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1459 return self
::$debugMode;
1463 * Reset static members used for caching.
1465 * Global state and $wgRequest are evil, but we're using it right
1466 * now and sometimes we need to be able to force ResourceLoader to
1467 * re-evaluate the context because it has changed (e.g. in the test suite).
1469 public static function clearCache() {
1470 self
::$debugMode = null;
1474 * Build a load.php URL
1477 * @param string $source Name of the ResourceLoader source
1478 * @param ResourceLoaderContext $context
1479 * @param array $extraQuery
1480 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1482 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1483 $extraQuery = array()
1485 $query = self
::createLoaderQuery( $context, $extraQuery );
1486 $script = $this->getLoadScript( $source );
1488 return wfAppendQuery( $script, $query );
1492 * Build a load.php URL
1493 * @deprecated since 1.24 Use createLoaderURL() instead
1494 * @param array $modules Array of module names (strings)
1495 * @param string $lang Language code
1496 * @param string $skin Skin name
1497 * @param string|null $user User name. If null, the &user= parameter is omitted
1498 * @param string|null $version Versioning timestamp
1499 * @param bool $debug Whether the request should be in debug mode
1500 * @param string|null $only &only= parameter
1501 * @param bool $printable Printable mode
1502 * @param bool $handheld Handheld mode
1503 * @param array $extraQuery Extra query parameters to add
1504 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1506 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1507 $version = null, $debug = false, $only = null, $printable = false,
1508 $handheld = false, $extraQuery = array()
1510 global $wgLoadScript;
1512 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1513 $only, $printable, $handheld, $extraQuery
1516 return wfAppendQuery( $wgLoadScript, $query );
1520 * Helper for createLoaderURL()
1523 * @see makeLoaderQuery
1524 * @param ResourceLoaderContext $context
1525 * @param array $extraQuery
1528 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1529 return self
::makeLoaderQuery(
1530 $context->getModules(),
1531 $context->getLanguage(),
1532 $context->getSkin(),
1533 $context->getUser(),
1534 $context->getVersion(),
1535 $context->getDebug(),
1536 $context->getOnly(),
1537 $context->getRequest()->getBool( 'printable' ),
1538 $context->getRequest()->getBool( 'handheld' ),
1544 * Build a query array (array representation of query string) for load.php. Helper
1545 * function for makeLoaderURL().
1547 * @param array $modules
1548 * @param string $lang
1549 * @param string $skin
1550 * @param string $user
1551 * @param string $version
1552 * @param bool $debug
1553 * @param string $only
1554 * @param bool $printable
1555 * @param bool $handheld
1556 * @param array $extraQuery
1560 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1561 $version = null, $debug = false, $only = null, $printable = false,
1562 $handheld = false, $extraQuery = array()
1565 'modules' => self
::makePackedModulesString( $modules ),
1568 'debug' => $debug ?
'true' : 'false',
1570 if ( $user !== null ) {
1571 $query['user'] = $user;
1573 if ( $version !== null ) {
1574 $query['version'] = $version;
1576 if ( $only !== null ) {
1577 $query['only'] = $only;
1580 $query['printable'] = 1;
1583 $query['handheld'] = 1;
1585 $query +
= $extraQuery;
1587 // Make queries uniform in order
1593 * Check a module name for validity.
1595 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1596 * at most 255 bytes.
1598 * @param string $moduleName Module name to check
1599 * @return bool Whether $moduleName is a valid module name
1601 public static function isValidModuleName( $moduleName ) {
1602 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1606 * Returns LESS compiler set up for use with MediaWiki
1608 * @param Config $config
1609 * @throws MWException
1613 public static function getLessCompiler( Config
$config ) {
1614 // When called from the installer, it is possible that a required PHP extension
1615 // is missing (at least for now; see bug 47564). If this is the case, throw an
1616 // exception (caught by the installer) to prevent a fatal error later on.
1617 if ( !class_exists( 'lessc' ) ) {
1618 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1620 if ( !function_exists( 'ctype_digit' ) ) {
1621 throw new MWException( 'lessc requires the Ctype extension' );
1624 $less = new lessc();
1625 $less->setPreserveComments( true );
1626 $less->setVariables( self
::getLessVars( $config ) );
1627 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1632 * Get global LESS variables.
1634 * @param Config $config
1636 * @return array Map of variable names to string CSS values.
1638 public static function getLessVars( Config
$config ) {
1639 if ( !self
::$lessVars ) {
1640 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1641 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1642 // Sort by key to ensure consistent hashing for cache lookups.
1644 self
::$lessVars = $lessVars;
1646 return self
::$lessVars;