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
;
30 * Dynamic JavaScript and CSS resource loading system.
32 * Most of the documentation is on the MediaWiki documentation wiki starting at:
33 * https://www.mediawiki.org/wiki/ResourceLoader
35 class ResourceLoader
implements LoggerAwareInterface
{
37 protected static $filterCacheVersion = 7;
40 protected static $debugMode = null;
43 private static $lessVars = null;
46 * Module name/ResourceLoaderModule object pairs
49 protected $modules = array();
52 * Associative array mapping module name to info associative array
55 protected $moduleInfos = array();
57 /** @var Config $config */
61 * Associative array mapping framework ids to a list of names of test suite modules
62 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
65 protected $testModuleNames = array();
68 * E.g. array( 'source-id' => 'http://.../load.php' )
71 protected $sources = array();
74 * Errors accumulated during current respond() call.
77 protected $errors = array();
80 * @var MessageBlobStore
85 * @var LoggerInterface
90 * Load information stored in the database about modules.
92 * This method grabs modules dependencies from the database and updates modules
95 * This is not inside the module code because it is much faster to
96 * request all of the information at once than it is to have each module
97 * requests its own information. This sacrifice of modularity yields a substantial
98 * performance improvement.
100 * @param array $modules List of module names to preload information for
101 * @param ResourceLoaderContext $context Context to load the information within
103 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
104 if ( !count( $modules ) ) {
105 // Or else Database*::select() will explode, plus it's cheaper!
108 $dbr = wfGetDB( DB_SLAVE
);
109 $skin = $context->getSkin();
110 $lang = $context->getLanguage();
112 // Get file dependency information
113 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
114 'md_module' => $modules,
119 // Set modules' dependencies
120 $modulesWithDeps = array();
121 foreach ( $res as $row ) {
122 $module = $this->getModule( $row->md_module
);
124 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
125 $modulesWithDeps[] = $row->md_module
;
129 // Register the absence of a dependency row too
130 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
131 $module = $this->getModule( $name );
133 $this->getModule( $name )->setFileDependencies( $skin, array() );
137 // Get message blob mtimes. Only do this for modules with messages
138 $modulesWithMessages = array();
139 foreach ( $modules as $name ) {
140 $module = $this->getModule( $name );
141 if ( $module && count( $module->getMessages() ) ) {
142 $modulesWithMessages[] = $name;
145 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
146 if ( count( $modulesWithMessages ) ) {
147 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
148 'mr_resource' => $modulesWithMessages,
152 foreach ( $res as $row ) {
153 $module = $this->getModule( $row->mr_resource
);
155 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
156 unset( $modulesWithoutMessages[$row->mr_resource
] );
160 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
161 $module = $this->getModule( $name );
163 $module->setMsgBlobMtime( $lang, 1 );
169 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
171 * Available filters are:
173 * - minify-js \see JavaScriptMinifier::minify
174 * - minify-css \see CSSMin::minify
176 * If $data is empty, only contains whitespace or the filter was unknown,
177 * $data is returned unmodified.
179 * @param string $filter Name of filter to run
180 * @param string $data Text to filter, such as JavaScript or CSS text
181 * @param array $options For back-compat, can also be the boolean value for "cacheReport". Keys:
182 * - (bool) cache: Whether to allow caching this data. Default: true.
183 * - (bool) cacheReport: Whether to include the "cache key" report comment. Default: true.
184 * @return string Filtered data, or a comment containing an error message
186 public function filter( $filter, $data, $options = array() ) {
188 if ( is_bool( $options ) ) {
189 $options = array( 'cacheReport' => $options );
192 $options +
= array( 'cache' => true, 'cacheReport' => true );
194 // Don't filter empty content
195 if ( trim( $data ) === '' ) {
199 if ( !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
200 $this->logger
->warning( 'Invalid filter {filter}', array(
206 if ( !$options['cache'] ) {
207 $result = $this->applyFilter( $filter, $data );
209 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
210 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL
: CACHE_ANYTHING
);
211 $cacheEntry = $cache->get( $key );
212 if ( is_string( $cacheEntry ) ) {
213 wfIncrStats( "resourceloader_cache.$filter.hit" );
218 $stats = RequestContext
::getMain()->getStats();
219 $statStart = microtime( true );
221 $result = $this->applyFilter( $filter, $data );
223 $stats->timing( "resourceloader_cache.$filter.miss", microtime( true ) - $statStart );
224 if ( $options['cacheReport'] ) {
225 $result .= "\n/* cache key: $key */";
227 $cache->set( $key, $result );
228 } catch ( Exception
$e ) {
229 MWExceptionHandler
::logException( $e );
230 $this->logger
->warning( 'Minification failed: {exception}', array(
233 $this->errors
[] = self
::formatExceptionNoComment( $e );
240 private function applyFilter( $filter, $data ) {
243 return JavaScriptMinifier
::minify( $data,
244 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
245 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
248 return CSSMin
::minify( $data );
257 * Register core modules and runs registration hooks.
258 * @param Config|null $config
260 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
264 $logger = new NullLogger();
266 $this->setLogger( $logger );
269 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
270 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
272 $this->config
= $config;
274 // Add 'local' source first
275 $this->addSource( 'local', wfScript( 'load' ) );
278 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
280 // Register core modules
281 $this->register( include "$IP/resources/Resources.php" );
282 $this->register( include "$IP/resources/ResourcesOOUI.php" );
283 // Register extension modules
284 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
285 $this->register( $config->get( 'ResourceModules' ) );
287 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
288 $this->registerTestModules();
291 $this->setMessageBlobStore( new MessageBlobStore() );
297 public function getConfig() {
298 return $this->config
;
301 public function setLogger( LoggerInterface
$logger ) {
302 $this->logger
= $logger;
307 * @return MessageBlobStore
309 public function getMessageBlobStore() {
310 return $this->blobStore
;
315 * @param MessageBlobStore $blobStore
317 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
318 $this->blobStore
= $blobStore;
322 * Register a module with the ResourceLoader system.
324 * @param mixed $name Name of module as a string or List of name/object pairs as an array
325 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
326 * this may also be a ResourceLoaderModule object. Optional when using
327 * multiple-registration calling style.
328 * @throws MWException If a duplicate module registration is attempted
329 * @throws MWException If a module name contains illegal characters (pipes or commas)
330 * @throws MWException If something other than a ResourceLoaderModule is being registered
331 * @return bool False if there were any errors, in which case one or more modules were
334 public function register( $name, $info = null ) {
336 // Allow multiple modules to be registered in one call
337 $registrations = is_array( $name ) ?
$name : array( $name => $info );
338 foreach ( $registrations as $name => $info ) {
339 // Disallow duplicate registrations
340 if ( isset( $this->moduleInfos
[$name] ) ) {
341 // A module has already been registered by this name
342 throw new MWException(
343 'ResourceLoader duplicate registration error. ' .
344 'Another module has already been registered as ' . $name
348 // Check $name for validity
349 if ( !self
::isValidModuleName( $name ) ) {
350 throw new MWException( "ResourceLoader module name '$name' is invalid, "
351 . "see ResourceLoader::isValidModuleName()" );
355 if ( $info instanceof ResourceLoaderModule
) {
356 $this->moduleInfos
[$name] = array( 'object' => $info );
357 $info->setName( $name );
358 $this->modules
[$name] = $info;
359 } elseif ( is_array( $info ) ) {
360 // New calling convention
361 $this->moduleInfos
[$name] = $info;
363 throw new MWException(
364 'ResourceLoader module info type error for module \'' . $name .
365 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
369 // Last-minute changes
371 // Apply custom skin-defined styles to existing modules.
372 if ( $this->isFileModule( $name ) ) {
373 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
374 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
375 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
379 // If $name is preceded with a '+', the defined style files will be added to 'default'
380 // skinStyles, otherwise 'default' will be ignored as it normally would be.
381 if ( isset( $skinStyles[$name] ) ) {
382 $paths = (array)$skinStyles[$name];
383 $styleFiles = array();
384 } elseif ( isset( $skinStyles['+' . $name] ) ) {
385 $paths = (array)$skinStyles['+' . $name];
386 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
387 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
393 // Add new file paths, remapping them to refer to our directories and not use settings
394 // from the module we're modifying, which come from the base definition.
395 list( $localBasePath, $remoteBasePath ) =
396 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
398 foreach ( $paths as $path ) {
399 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
402 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
411 public function registerTestModules() {
414 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
415 throw new MWException( 'Attempt to register JavaScript test modules '
416 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
417 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
420 // Get core test suites
421 $testModules = array();
422 $testModules['qunit'] = array();
423 // Get other test suites (e.g. from extensions)
424 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
426 // Add the testrunner (which configures QUnit) to the dependencies.
427 // Since it must be ready before any of the test suites are executed.
428 foreach ( $testModules['qunit'] as &$module ) {
429 // Make sure all test modules are top-loading so that when QUnit starts
430 // on document-ready, it will run once and finish. If some tests arrive
431 // later (possibly after QUnit has already finished) they will be ignored.
432 $module['position'] = 'top';
433 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
436 $testModules['qunit'] =
437 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
439 foreach ( $testModules as $id => $names ) {
440 // Register test modules
441 $this->register( $testModules[$id] );
443 // Keep track of their names so that they can be loaded together
444 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
450 * Add a foreign source of modules.
452 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
453 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
454 * backwards-compatibility.
455 * @throws MWException
457 public function addSource( $id, $loadUrl = null ) {
458 // Allow multiple sources to be registered in one call
459 if ( is_array( $id ) ) {
460 foreach ( $id as $key => $value ) {
461 $this->addSource( $key, $value );
466 // Disallow duplicates
467 if ( isset( $this->sources
[$id] ) ) {
468 throw new MWException(
469 'ResourceLoader duplicate source addition error. ' .
470 'Another source has already been registered as ' . $id
474 // Pre 1.24 backwards-compatibility
475 if ( is_array( $loadUrl ) ) {
476 if ( !isset( $loadUrl['loadScript'] ) ) {
477 throw new MWException(
478 __METHOD__
. ' was passed an array with no "loadScript" key.'
482 $loadUrl = $loadUrl['loadScript'];
485 $this->sources
[$id] = $loadUrl;
489 * Get a list of module names.
491 * @return array List of module names
493 public function getModuleNames() {
494 return array_keys( $this->moduleInfos
);
498 * Get a list of test module names for one (or all) frameworks.
500 * If the given framework id is unknkown, or if the in-object variable is not an array,
501 * then it will return an empty array.
503 * @param string $framework Get only the test module names for one
504 * particular framework (optional)
507 public function getTestModuleNames( $framework = 'all' ) {
508 /** @todo api siteinfo prop testmodulenames modulenames */
509 if ( $framework == 'all' ) {
510 return $this->testModuleNames
;
511 } elseif ( isset( $this->testModuleNames
[$framework] )
512 && is_array( $this->testModuleNames
[$framework] )
514 return $this->testModuleNames
[$framework];
521 * Check whether a ResourceLoader module is registered
524 * @param string $name
527 public function isModuleRegistered( $name ) {
528 return isset( $this->moduleInfos
[$name] );
532 * Get the ResourceLoaderModule object for a given module name.
534 * If an array of module parameters exists but a ResourceLoaderModule object has not
535 * yet been instantiated, this method will instantiate and cache that object such that
536 * subsequent calls simply return the same object.
538 * @param string $name Module name
539 * @return ResourceLoaderModule|null If module has been registered, return a
540 * ResourceLoaderModule instance. Otherwise, return null.
542 public function getModule( $name ) {
543 if ( !isset( $this->modules
[$name] ) ) {
544 if ( !isset( $this->moduleInfos
[$name] ) ) {
548 // Construct the requested object
549 $info = $this->moduleInfos
[$name];
550 /** @var ResourceLoaderModule $object */
551 if ( isset( $info['object'] ) ) {
552 // Object given in info array
553 $object = $info['object'];
555 if ( !isset( $info['class'] ) ) {
556 $class = 'ResourceLoaderFileModule';
558 $class = $info['class'];
560 /** @var ResourceLoaderModule $object */
561 $object = new $class( $info );
562 $object->setConfig( $this->getConfig() );
564 $object->setName( $name );
565 $this->modules
[$name] = $object;
568 return $this->modules
[$name];
572 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
574 * @param string $name Module name
577 protected function isFileModule( $name ) {
578 if ( !isset( $this->moduleInfos
[$name] ) ) {
581 $info = $this->moduleInfos
[$name];
582 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
589 * Get the list of sources.
591 * @return array Like array( id => load.php url, .. )
593 public function getSources() {
594 return $this->sources
;
598 * Get the URL to the load.php endpoint for the given
599 * ResourceLoader source
602 * @param string $source
603 * @throws MWException On an invalid $source name
606 public function getLoadScript( $source ) {
607 if ( !isset( $this->sources
[$source] ) ) {
608 throw new MWException( "The $source source was never registered in ResourceLoader." );
610 return $this->sources
[$source];
615 * @param string $value
616 * @return string Hash
618 public static function makeHash( $value ) {
619 // Use base64 to output more entropy in a more compact string (default hex is only base16).
620 // The first 8 chars of a base64 encoded digest represent the same binary as
621 // the first 12 chars of a hex encoded digest.
622 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
626 * Helper method to get and combine versions of multiple modules.
629 * @param ResourceLoaderContext $context
630 * @param array $modules List of ResourceLoaderModule objects
631 * @return string Hash
633 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
637 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
638 // http://php.net/functions.anonymous
640 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
641 return $rl->getModule( $module )->getVersionHash( $context );
643 return self
::makeHash( implode( $hashes ) );
647 * Output a response to a load request, including the content-type header.
649 * @param ResourceLoaderContext $context Context in which a response should be formed
651 public function respond( ResourceLoaderContext
$context ) {
652 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
653 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
654 // is used: ob_clean() will clear the GZIP header in that case and it won't come
655 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
656 // the whole thing in our own output buffer to be sure the active buffer
657 // doesn't use ob_gzhandler.
658 // See http://bugs.php.net/bug.php?id=36514
661 // Find out which modules are missing and instantiate the others
664 foreach ( $context->getModules() as $name ) {
665 $module = $this->getModule( $name );
667 // Do not allow private modules to be loaded from the web.
668 // This is a security issue, see bug 34907.
669 if ( $module->getGroup() === 'private' ) {
670 $this->logger
->debug( "Request for private module '$name' denied" );
671 $this->errors
[] = "Cannot show private module \"$name\"";
674 $modules[$name] = $module;
681 // Preload for getCombinedVersion()
682 $this->preloadModuleInfo( array_keys( $modules ), $context );
683 } catch ( Exception
$e ) {
684 MWExceptionHandler
::logException( $e );
685 $this->logger
->warning( 'Preloading module info failed: {exception}', array(
688 $this->errors
[] = self
::formatExceptionNoComment( $e );
691 // Combine versions to propagate cache invalidation
694 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
695 } catch ( Exception
$e ) {
696 MWExceptionHandler
::logException( $e );
697 $this->logger
->warning( 'Calculating version hash failed: {exception}', array(
700 $this->errors
[] = self
::formatExceptionNoComment( $e );
703 // See RFC 2616 § 3.11 Entity Tags
704 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
705 $etag = 'W/"' . $versionHash . '"';
707 // Try the client-side cache first
708 if ( $this->tryRespondNotModified( $context, $etag ) ) {
709 return; // output handled (buffers cleared)
712 // Use file cache if enabled and available...
713 if ( $this->config
->get( 'UseFileCache' ) ) {
714 $fileCache = ResourceFileCache
::newFromContext( $context );
715 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
716 return; // output handled
720 // Generate a response
721 $response = $this->makeModuleResponse( $context, $modules, $missing );
723 // Capture any PHP warnings from the output buffer and append them to the
724 // error list if we're in debug mode.
725 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
726 $this->errors
[] = $warnings;
729 // Save response to file cache unless there are errors
730 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
731 // Cache single modules and images...and other requests if there are enough hits
732 if ( ResourceFileCache
::useFileCache( $context ) ) {
733 if ( $fileCache->isCacheWorthy() ) {
734 $fileCache->saveText( $response );
736 $fileCache->incrMissesRecent( $context->getRequest() );
741 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
743 // Remove the output buffer and output the response
746 if ( $context->getImageObj() && $this->errors
) {
747 // We can't show both the error messages and the response when it's an image.
749 foreach ( $this->errors
as $error ) {
750 $errorText .= $error . "\n";
752 $response = $errorText;
753 } elseif ( $this->errors
) {
754 // Prepend comments indicating errors
756 foreach ( $this->errors
as $error ) {
757 $errorText .= self
::makeComment( $error );
759 $response = $errorText . $response;
762 $this->errors
= array();
768 * Send main response headers to the client.
770 * Deals with Content-Type, CORS (for stylesheets), and caching.
772 * @param ResourceLoaderContext $context
773 * @param string $etag ETag header value
774 * @param bool $errors Whether there are errors in the response
777 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
778 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
779 // If a version wasn't specified we need a shorter expiry time for updates
780 // to propagate to clients quickly
781 // If there were errors, we also need a shorter expiry time so we can recover quickly
782 if ( is_null( $context->getVersion() ) ||
$errors ) {
783 $maxage = $rlMaxage['unversioned']['client'];
784 $smaxage = $rlMaxage['unversioned']['server'];
785 // If a version was specified we can use a longer expiry time since changing
786 // version numbers causes cache misses
788 $maxage = $rlMaxage['versioned']['client'];
789 $smaxage = $rlMaxage['versioned']['server'];
791 if ( $context->getImageObj() ) {
792 // Output different headers if we're outputting textual errors.
794 header( 'Content-Type: text/plain; charset=utf-8' );
796 $context->getImageObj()->sendResponseHeaders( $context );
798 } elseif ( $context->getOnly() === 'styles' ) {
799 header( 'Content-Type: text/css; charset=utf-8' );
800 header( 'Access-Control-Allow-Origin: *' );
802 header( 'Content-Type: text/javascript; charset=utf-8' );
804 // See RFC 2616 § 14.19 ETag
805 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
806 header( 'ETag: ' . $etag );
807 if ( $context->getDebug() ) {
808 // Do not cache debug responses
809 header( 'Cache-Control: private, no-cache, must-revalidate' );
810 header( 'Pragma: no-cache' );
812 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
813 $exp = min( $maxage, $smaxage );
814 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
819 * Respond with HTTP 304 Not Modified if appropiate.
821 * If there's an If-None-Match header, respond with a 304 appropriately
822 * and clear out the output buffer. If the client cache is too old then do nothing.
824 * @param ResourceLoaderContext $context
825 * @param string $etag ETag header value
826 * @return bool True if HTTP 304 was sent and output handled
828 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
829 // See RFC 2616 § 14.26 If-None-Match
830 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
831 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
832 // Never send 304s in debug mode
833 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
834 // There's another bug in ob_gzhandler (see also the comment at
835 // the top of this function) that causes it to gzip even empty
836 // responses, meaning it's impossible to produce a truly empty
837 // response (because the gzip header is always there). This is
838 // a problem because 304 responses have to be completely empty
839 // per the HTTP spec, and Firefox behaves buggily when they're not.
840 // See also http://bugs.php.net/bug.php?id=51579
841 // To work around this, we tear down all output buffering before
843 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
845 HttpStatus
::header( 304 );
847 $this->sendResponseHeaders( $context, $etag, false );
854 * Send out code for a response from file cache if possible.
856 * @param ResourceFileCache $fileCache Cache object for this request URL
857 * @param ResourceLoaderContext $context Context in which to generate a response
858 * @param string $etag ETag header value
859 * @return bool If this found a cache file and handled the response
861 protected function tryRespondFromFileCache(
862 ResourceFileCache
$fileCache,
863 ResourceLoaderContext
$context,
866 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
867 // Buffer output to catch warnings.
869 // Get the maximum age the cache can be
870 $maxage = is_null( $context->getVersion() )
871 ?
$rlMaxage['unversioned']['server']
872 : $rlMaxage['versioned']['server'];
873 // Minimum timestamp the cache file must have
874 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
876 try { // RL always hits the DB on file cache miss...
878 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
879 $good = $fileCache->isCacheGood(); // cache existence check
883 $ts = $fileCache->cacheTimestamp();
884 // Send content type and cache headers
885 $this->sendResponseHeaders( $context, $etag, false );
886 $response = $fileCache->fetchText();
887 // Capture any PHP warnings from the output buffer and append them to the
888 // response in a comment if we're in debug mode.
889 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
890 $response = self
::makeComment( $warnings ) . $response;
892 // Remove the output buffer and output the response
894 echo $response . "\n/* Cached {$ts} */";
895 return true; // cache hit
900 return false; // cache miss
904 * Generate a CSS or JS comment block.
906 * Only use this for public data, not error message details.
908 * @param string $text
911 public static function makeComment( $text ) {
912 $encText = str_replace( '*/', '* /', $text );
913 return "/*\n$encText\n*/\n";
917 * Handle exception display.
919 * @param Exception $e Exception to be shown to the user
920 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
922 public static function formatException( $e ) {
923 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
927 * Handle exception display.
930 * @param Exception $e Exception to be shown to the user
931 * @return string Sanitized text that can be returned to the user
933 protected static function formatExceptionNoComment( $e ) {
934 global $wgShowExceptionDetails;
936 if ( $wgShowExceptionDetails ) {
937 return $e->__toString();
939 return wfMessage( 'internalerror' )->text();
944 * Generate code for a response.
946 * @param ResourceLoaderContext $context Context in which to generate a response
947 * @param array $modules List of module objects keyed by module name
948 * @param array $missing List of requested module names that are unregistered (optional)
949 * @return string Response data
951 public function makeModuleResponse( ResourceLoaderContext
$context,
952 array $modules, array $missing = array()
957 if ( !count( $modules ) && !count( $missing ) ) {
959 /* This file is the Web entry point for MediaWiki's ResourceLoader:
960 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
961 no modules were requested. Max made me put this here. */
965 $image = $context->getImageObj();
967 $data = $image->getImageData( $context );
968 if ( $data === false ) {
970 $this->errors
[] = 'Image generation failed';
976 if ( $context->shouldIncludeMessages() ) {
978 $this->blobStore
->get( $this, $modules, $context->getLanguage() );
979 } catch ( Exception
$e ) {
980 MWExceptionHandler
::logException( $e );
981 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
984 $this->errors
[] = self
::formatExceptionNoComment( $e );
988 foreach ( $missing as $name ) {
989 $states[$name] = 'missing';
994 foreach ( $modules as $name => $module ) {
996 $content = $module->getModuleContent( $context );
999 switch ( $context->getOnly() ) {
1001 $scripts = $content['scripts'];
1002 if ( is_string( $scripts ) ) {
1003 // Load scripts raw...
1005 } elseif ( is_array( $scripts ) ) {
1006 // ...except when $scripts is an array of URLs
1007 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1011 $styles = $content['styles'];
1012 // We no longer seperate into media, they are all combined now with
1013 // custom media type groups into @media .. {} sections as part of the css string.
1014 // Module returns either an empty array or a numerical array with css strings.
1015 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1018 $out .= self
::makeLoaderImplementScript(
1020 isset( $content['scripts'] ) ?
$content['scripts'] : '',
1021 isset( $content['styles'] ) ?
$content['styles'] : array(),
1022 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : array(),
1023 isset( $content['templates'] ) ?
$content['templates'] : array()
1027 } catch ( Exception
$e ) {
1028 MWExceptionHandler
::logException( $e );
1029 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1032 $this->errors
[] = self
::formatExceptionNoComment( $e );
1034 // Respond to client with error-state instead of module implementation
1035 $states[$name] = 'error';
1036 unset( $modules[$name] );
1038 $isRaw |
= $module->isRaw();
1041 // Update module states
1042 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1043 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1044 // Set the state of modules loaded as only scripts to ready as
1045 // they don't have an mw.loader.implement wrapper that sets the state
1046 foreach ( $modules as $name => $module ) {
1047 $states[$name] = 'ready';
1051 // Set the state of modules we didn't respond to with mw.loader.implement
1052 if ( count( $states ) ) {
1053 $out .= self
::makeLoaderStateScript( $states );
1056 if ( count( $states ) ) {
1057 $this->errors
[] = 'Problematic modules: ' .
1058 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1062 $enableFilterCache = true;
1063 if ( count( $modules ) === 1 && reset( $modules ) instanceof ResourceLoaderUserTokensModule
) {
1064 // If we're building the embedded user.tokens, don't cache (T84960)
1065 $enableFilterCache = false;
1068 if ( !$context->getDebug() ) {
1069 if ( $context->getOnly() === 'styles' ) {
1070 $out = $this->filter( 'minify-css', $out );
1072 $out = $this->filter( 'minify-js', $out, array(
1073 'cache' => $enableFilterCache
1081 /* Static Methods */
1084 * Return JS code that calls mw.loader.implement with given module properties.
1086 * @param string $name Module name
1087 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1088 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1089 * to CSS files keyed by media type
1090 * @param mixed $messages List of messages associated with this module. May either be an
1091 * associative array mapping message key to value, or a JSON-encoded message blob containing
1092 * the same data, wrapped in an XmlJsCode object.
1093 * @param array $templates Keys are name of templates and values are the source of
1095 * @throws MWException
1098 public static function makeLoaderImplementScript(
1099 $name, $scripts, $styles, $messages, $templates
1101 if ( is_string( $scripts ) ) {
1102 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1103 } elseif ( !is_array( $scripts ) ) {
1104 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1106 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1107 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1108 // of "{}". Force them to objects.
1116 self
::trimArray( $module );
1118 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1122 * Returns JS code which, when called, will register a given list of messages.
1124 * @param mixed $messages Either an associative array mapping message key to value, or a
1125 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1128 public static function makeMessageSetScript( $messages ) {
1129 return Xml
::encodeJsCall(
1131 array( (object)$messages ),
1132 ResourceLoader
::inDebugMode()
1137 * Combines an associative array mapping media type to CSS into a
1138 * single stylesheet with "@media" blocks.
1140 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1143 public static function makeCombinedStyles( array $stylePairs ) {
1145 foreach ( $stylePairs as $media => $styles ) {
1146 // ResourceLoaderFileModule::getStyle can return the styles
1147 // as a string or an array of strings. This is to allow separation in
1149 $styles = (array)$styles;
1150 foreach ( $styles as $style ) {
1151 $style = trim( $style );
1152 // Don't output an empty "@media print { }" block (bug 40498)
1153 if ( $style !== '' ) {
1154 // Transform the media type based on request params and config
1155 // The way that this relies on $wgRequest to propagate request params is slightly evil
1156 $media = OutputPage
::transformCssMedia( $media );
1158 if ( $media === '' ||
$media == 'all' ) {
1160 } elseif ( is_string( $media ) ) {
1161 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1171 * Returns a JS call to mw.loader.state, which sets the state of a
1172 * module or modules to a given value. Has two calling conventions:
1174 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1175 * Set the state of a single module called $name to $state
1177 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1178 * Set the state of modules with the given names to the given states
1180 * @param string $name
1181 * @param string $state
1184 public static function makeLoaderStateScript( $name, $state = null ) {
1185 if ( is_array( $name ) ) {
1186 return Xml
::encodeJsCall(
1189 ResourceLoader
::inDebugMode()
1192 return Xml
::encodeJsCall(
1194 array( $name, $state ),
1195 ResourceLoader
::inDebugMode()
1201 * Returns JS code which calls the script given by $script. The script will
1202 * be called with local variables name, version, dependencies and group,
1203 * which will have values corresponding to $name, $version, $dependencies
1204 * and $group as supplied.
1206 * @param string $name Module name
1207 * @param string $version Module version hash
1208 * @param array $dependencies List of module names on which this module depends
1209 * @param string $group Group which the module is in.
1210 * @param string $source Source of the module, or 'local' if not foreign.
1211 * @param string $script JavaScript code
1214 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1215 $group, $source, $script
1217 $script = str_replace( "\n", "\n\t", trim( $script ) );
1218 return Xml
::encodeJsCall(
1219 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1220 array( $name, $version, $dependencies, $group, $source ),
1221 ResourceLoader
::inDebugMode()
1225 private static function isEmptyObject( stdClass
$obj ) {
1226 foreach ( $obj as $key => &$value ) {
1233 * Remove empty values from the end of an array.
1235 * Values considered empty:
1239 * - new XmlJsCode( '{}' )
1240 * - new stdClass() // (object) array()
1242 * @param Array $array
1244 private static function trimArray( Array &$array ) {
1245 $i = count( $array );
1247 if ( $array[$i] === null
1248 ||
$array[$i] === array()
1249 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1250 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1252 unset( $array[$i] );
1260 * Returns JS code which calls mw.loader.register with the given
1261 * parameters. Has three calling conventions:
1263 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1264 * $dependencies, $group, $source, $skip
1266 * Register a single module.
1268 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1269 * Register modules with the given names.
1271 * - ResourceLoader::makeLoaderRegisterScript( array(
1272 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1273 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1276 * Registers modules with the given names and parameters.
1278 * @param string $name Module name
1279 * @param string $version Module version hash
1280 * @param array $dependencies List of module names on which this module depends
1281 * @param string $group Group which the module is in
1282 * @param string $source Source of the module, or 'local' if not foreign
1283 * @param string $skip Script body of the skip function
1286 public static function makeLoaderRegisterScript( $name, $version = null,
1287 $dependencies = null, $group = null, $source = null, $skip = null
1289 if ( is_array( $name ) ) {
1290 // Build module name index
1292 foreach ( $name as $i => &$module ) {
1293 $index[$module[0]] = $i;
1296 // Transform dependency names into indexes when possible, they will be resolved by
1297 // mw.loader.register on the other end
1298 foreach ( $name as &$module ) {
1299 if ( isset( $module[2] ) ) {
1300 foreach ( $module[2] as &$dependency ) {
1301 if ( isset( $index[$dependency] ) ) {
1302 $dependency = $index[$dependency];
1308 array_walk( $name, array( 'self', 'trimArray' ) );
1310 return Xml
::encodeJsCall(
1311 'mw.loader.register',
1313 ResourceLoader
::inDebugMode()
1316 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1317 self
::trimArray( $registration );
1318 return Xml
::encodeJsCall(
1319 'mw.loader.register',
1321 ResourceLoader
::inDebugMode()
1327 * Returns JS code which calls mw.loader.addSource() with the given
1328 * parameters. Has two calling conventions:
1330 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1331 * Register a single source
1333 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1334 * Register sources with the given IDs and properties.
1336 * @param string $id Source ID
1337 * @param array $properties Source properties (see addSource())
1340 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1341 if ( is_array( $id ) ) {
1342 return Xml
::encodeJsCall(
1343 'mw.loader.addSource',
1345 ResourceLoader
::inDebugMode()
1348 return Xml
::encodeJsCall(
1349 'mw.loader.addSource',
1350 array( $id, $properties ),
1351 ResourceLoader
::inDebugMode()
1357 * Returns JS code which runs given JS code if the client-side framework is
1360 * @deprecated since 1.25; use makeInlineScript instead
1361 * @param string $script JavaScript code
1364 public static function makeLoaderConditionalScript( $script ) {
1365 return "if(window.mw){\n" . trim( $script ) . "\n}";
1369 * Construct an inline script tag with given JS code.
1371 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1372 * only if the client has adequate support for MediaWiki JavaScript code.
1374 * @param string $script JavaScript code
1375 * @return string HTML
1377 public static function makeInlineScript( $script ) {
1378 $js = self
::makeLoaderConditionalScript( $script );
1379 return Html
::inlineScript( $js );
1383 * Returns JS code which will set the MediaWiki configuration array to
1386 * @param array $configuration List of configuration values keyed by variable name
1389 public static function makeConfigSetScript( array $configuration ) {
1390 return Xml
::encodeJsCall(
1392 array( $configuration ),
1393 ResourceLoader
::inDebugMode()
1398 * Convert an array of module names to a packed query string.
1400 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1401 * becomes 'foo.bar,baz|bar.baz,quux'
1402 * @param array $modules List of module names (strings)
1403 * @return string Packed query string
1405 public static function makePackedModulesString( $modules ) {
1406 $groups = array(); // array( prefix => array( suffixes ) )
1407 foreach ( $modules as $module ) {
1408 $pos = strrpos( $module, '.' );
1409 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1410 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1411 $groups[$prefix][] = $suffix;
1415 foreach ( $groups as $prefix => $suffixes ) {
1416 $p = $prefix === '' ?
'' : $prefix . '.';
1417 $arr[] = $p . implode( ',', $suffixes );
1419 $str = implode( '|', $arr );
1424 * Determine whether debug mode was requested
1425 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1428 public static function inDebugMode() {
1429 if ( self
::$debugMode === null ) {
1430 global $wgRequest, $wgResourceLoaderDebug;
1431 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1432 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1435 return self
::$debugMode;
1439 * Reset static members used for caching.
1441 * Global state and $wgRequest are evil, but we're using it right
1442 * now and sometimes we need to be able to force ResourceLoader to
1443 * re-evaluate the context because it has changed (e.g. in the test suite).
1445 public static function clearCache() {
1446 self
::$debugMode = null;
1450 * Build a load.php URL
1453 * @param string $source Name of the ResourceLoader source
1454 * @param ResourceLoaderContext $context
1455 * @param array $extraQuery
1456 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1458 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1459 $extraQuery = array()
1461 $query = self
::createLoaderQuery( $context, $extraQuery );
1462 $script = $this->getLoadScript( $source );
1464 // Prevent the IE6 extension check from being triggered (bug 28840)
1465 // by appending a character that's invalid in Windows extensions ('*')
1466 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1470 * Build a load.php URL
1471 * @deprecated since 1.24 Use createLoaderURL() instead
1472 * @param array $modules Array of module names (strings)
1473 * @param string $lang Language code
1474 * @param string $skin Skin name
1475 * @param string|null $user User name. If null, the &user= parameter is omitted
1476 * @param string|null $version Versioning timestamp
1477 * @param bool $debug Whether the request should be in debug mode
1478 * @param string|null $only &only= parameter
1479 * @param bool $printable Printable mode
1480 * @param bool $handheld Handheld mode
1481 * @param array $extraQuery Extra query parameters to add
1482 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1484 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1485 $version = null, $debug = false, $only = null, $printable = false,
1486 $handheld = false, $extraQuery = array()
1488 global $wgLoadScript;
1490 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1491 $only, $printable, $handheld, $extraQuery
1494 // Prevent the IE6 extension check from being triggered (bug 28840)
1495 // by appending a character that's invalid in Windows extensions ('*')
1496 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1500 * Helper for createLoaderURL()
1503 * @see makeLoaderQuery
1504 * @param ResourceLoaderContext $context
1505 * @param array $extraQuery
1508 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1509 return self
::makeLoaderQuery(
1510 $context->getModules(),
1511 $context->getLanguage(),
1512 $context->getSkin(),
1513 $context->getUser(),
1514 $context->getVersion(),
1515 $context->getDebug(),
1516 $context->getOnly(),
1517 $context->getRequest()->getBool( 'printable' ),
1518 $context->getRequest()->getBool( 'handheld' ),
1524 * Build a query array (array representation of query string) for load.php. Helper
1525 * function for makeLoaderURL().
1527 * @param array $modules
1528 * @param string $lang
1529 * @param string $skin
1530 * @param string $user
1531 * @param string $version
1532 * @param bool $debug
1533 * @param string $only
1534 * @param bool $printable
1535 * @param bool $handheld
1536 * @param array $extraQuery
1540 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1541 $version = null, $debug = false, $only = null, $printable = false,
1542 $handheld = false, $extraQuery = array()
1545 'modules' => self
::makePackedModulesString( $modules ),
1548 'debug' => $debug ?
'true' : 'false',
1550 if ( $user !== null ) {
1551 $query['user'] = $user;
1553 if ( $version !== null ) {
1554 $query['version'] = $version;
1556 if ( $only !== null ) {
1557 $query['only'] = $only;
1560 $query['printable'] = 1;
1563 $query['handheld'] = 1;
1565 $query +
= $extraQuery;
1567 // Make queries uniform in order
1573 * Check a module name for validity.
1575 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1576 * at most 255 bytes.
1578 * @param string $moduleName Module name to check
1579 * @return bool Whether $moduleName is a valid module name
1581 public static function isValidModuleName( $moduleName ) {
1582 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1586 * Returns LESS compiler set up for use with MediaWiki
1588 * @param Config $config
1589 * @throws MWException
1593 public static function getLessCompiler( Config
$config ) {
1594 // When called from the installer, it is possible that a required PHP extension
1595 // is missing (at least for now; see bug 47564). If this is the case, throw an
1596 // exception (caught by the installer) to prevent a fatal error later on.
1597 if ( !class_exists( 'lessc' ) ) {
1598 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1600 if ( !function_exists( 'ctype_digit' ) ) {
1601 throw new MWException( 'lessc requires the Ctype extension' );
1604 $less = new lessc();
1605 $less->setPreserveComments( true );
1606 $less->setVariables( self
::getLessVars( $config ) );
1607 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1608 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1609 $less->registerFunction( $name, $func );
1615 * Get global LESS variables.
1617 * @param Config $config
1619 * @return array Map of variable names to string CSS values.
1621 public static function getLessVars( Config
$config ) {
1622 if ( !self
::$lessVars ) {
1623 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1624 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1625 // Sort by key to ensure consistent hashing for cache lookups.
1627 self
::$lessVars = $lessVars;
1629 return self
::$lessVars;