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 wfIncrStats( "resourceloader_cache.$filter.miss" );
219 $result = $this->applyFilter( $filter, $data );
220 if ( $options['cacheReport'] ) {
221 $result .= "\n/* cache key: $key */";
223 $cache->set( $key, $result );
224 } catch ( Exception
$e ) {
225 MWExceptionHandler
::logException( $e );
226 $this->logger
->warning( 'Minification failed: {exception}', array(
229 $this->errors
[] = self
::formatExceptionNoComment( $e );
236 private function applyFilter( $filter, $data ) {
239 return JavaScriptMinifier
::minify( $data,
240 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
241 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
244 return CSSMin
::minify( $data );
252 * Register core modules and runs registration hooks.
253 * @param Config|null $config
255 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
259 $logger = new NullLogger();
261 $this->setLogger( $logger );
264 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
265 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
267 $this->config
= $config;
269 // Add 'local' source first
270 $this->addSource( 'local', wfScript( 'load' ) );
273 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
275 // Register core modules
276 $this->register( include "$IP/resources/Resources.php" );
277 $this->register( include "$IP/resources/ResourcesOOUI.php" );
278 // Register extension modules
279 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
280 $this->register( $config->get( 'ResourceModules' ) );
282 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
283 $this->registerTestModules();
286 $this->setMessageBlobStore( new MessageBlobStore() );
292 public function getConfig() {
293 return $this->config
;
296 public function setLogger( LoggerInterface
$logger ) {
297 $this->logger
= $logger;
302 * @return MessageBlobStore
304 public function getMessageBlobStore() {
305 return $this->blobStore
;
310 * @param MessageBlobStore $blobStore
312 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
313 $this->blobStore
= $blobStore;
317 * Register a module with the ResourceLoader system.
319 * @param mixed $name Name of module as a string or List of name/object pairs as an array
320 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
321 * this may also be a ResourceLoaderModule object. Optional when using
322 * multiple-registration calling style.
323 * @throws MWException If a duplicate module registration is attempted
324 * @throws MWException If a module name contains illegal characters (pipes or commas)
325 * @throws MWException If something other than a ResourceLoaderModule is being registered
326 * @return bool False if there were any errors, in which case one or more modules were
329 public function register( $name, $info = null ) {
331 // Allow multiple modules to be registered in one call
332 $registrations = is_array( $name ) ?
$name : array( $name => $info );
333 foreach ( $registrations as $name => $info ) {
334 // Disallow duplicate registrations
335 if ( isset( $this->moduleInfos
[$name] ) ) {
336 // A module has already been registered by this name
337 throw new MWException(
338 'ResourceLoader duplicate registration error. ' .
339 'Another module has already been registered as ' . $name
343 // Check $name for validity
344 if ( !self
::isValidModuleName( $name ) ) {
345 throw new MWException( "ResourceLoader module name '$name' is invalid, "
346 . "see ResourceLoader::isValidModuleName()" );
350 if ( $info instanceof ResourceLoaderModule
) {
351 $this->moduleInfos
[$name] = array( 'object' => $info );
352 $info->setName( $name );
353 $this->modules
[$name] = $info;
354 } elseif ( is_array( $info ) ) {
355 // New calling convention
356 $this->moduleInfos
[$name] = $info;
358 throw new MWException(
359 'ResourceLoader module info type error for module \'' . $name .
360 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
364 // Last-minute changes
366 // Apply custom skin-defined styles to existing modules.
367 if ( $this->isFileModule( $name ) ) {
368 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
369 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
370 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
374 // If $name is preceded with a '+', the defined style files will be added to 'default'
375 // skinStyles, otherwise 'default' will be ignored as it normally would be.
376 if ( isset( $skinStyles[$name] ) ) {
377 $paths = (array)$skinStyles[$name];
378 $styleFiles = array();
379 } elseif ( isset( $skinStyles['+' . $name] ) ) {
380 $paths = (array)$skinStyles['+' . $name];
381 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
382 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
388 // Add new file paths, remapping them to refer to our directories and not use settings
389 // from the module we're modifying, which come from the base definition.
390 list( $localBasePath, $remoteBasePath ) =
391 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
393 foreach ( $paths as $path ) {
394 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
397 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
406 public function registerTestModules() {
409 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
410 throw new MWException( 'Attempt to register JavaScript test modules '
411 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
412 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
415 // Get core test suites
416 $testModules = array();
417 $testModules['qunit'] = array();
418 // Get other test suites (e.g. from extensions)
419 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
421 // Add the testrunner (which configures QUnit) to the dependencies.
422 // Since it must be ready before any of the test suites are executed.
423 foreach ( $testModules['qunit'] as &$module ) {
424 // Make sure all test modules are top-loading so that when QUnit starts
425 // on document-ready, it will run once and finish. If some tests arrive
426 // later (possibly after QUnit has already finished) they will be ignored.
427 $module['position'] = 'top';
428 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
431 $testModules['qunit'] =
432 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
434 foreach ( $testModules as $id => $names ) {
435 // Register test modules
436 $this->register( $testModules[$id] );
438 // Keep track of their names so that they can be loaded together
439 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
445 * Add a foreign source of modules.
447 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
448 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
449 * backwards-compatibility.
450 * @throws MWException
452 public function addSource( $id, $loadUrl = null ) {
453 // Allow multiple sources to be registered in one call
454 if ( is_array( $id ) ) {
455 foreach ( $id as $key => $value ) {
456 $this->addSource( $key, $value );
461 // Disallow duplicates
462 if ( isset( $this->sources
[$id] ) ) {
463 throw new MWException(
464 'ResourceLoader duplicate source addition error. ' .
465 'Another source has already been registered as ' . $id
469 // Pre 1.24 backwards-compatibility
470 if ( is_array( $loadUrl ) ) {
471 if ( !isset( $loadUrl['loadScript'] ) ) {
472 throw new MWException(
473 __METHOD__
. ' was passed an array with no "loadScript" key.'
477 $loadUrl = $loadUrl['loadScript'];
480 $this->sources
[$id] = $loadUrl;
484 * Get a list of module names.
486 * @return array List of module names
488 public function getModuleNames() {
489 return array_keys( $this->moduleInfos
);
493 * Get a list of test module names for one (or all) frameworks.
495 * If the given framework id is unknkown, or if the in-object variable is not an array,
496 * then it will return an empty array.
498 * @param string $framework Get only the test module names for one
499 * particular framework (optional)
502 public function getTestModuleNames( $framework = 'all' ) {
503 /** @todo api siteinfo prop testmodulenames modulenames */
504 if ( $framework == 'all' ) {
505 return $this->testModuleNames
;
506 } elseif ( isset( $this->testModuleNames
[$framework] )
507 && is_array( $this->testModuleNames
[$framework] )
509 return $this->testModuleNames
[$framework];
516 * Check whether a ResourceLoader module is registered
519 * @param string $name
522 public function isModuleRegistered( $name ) {
523 return isset( $this->moduleInfos
[$name] );
527 * Get the ResourceLoaderModule object for a given module name.
529 * If an array of module parameters exists but a ResourceLoaderModule object has not
530 * yet been instantiated, this method will instantiate and cache that object such that
531 * subsequent calls simply return the same object.
533 * @param string $name Module name
534 * @return ResourceLoaderModule|null If module has been registered, return a
535 * ResourceLoaderModule instance. Otherwise, return null.
537 public function getModule( $name ) {
538 if ( !isset( $this->modules
[$name] ) ) {
539 if ( !isset( $this->moduleInfos
[$name] ) ) {
543 // Construct the requested object
544 $info = $this->moduleInfos
[$name];
545 /** @var ResourceLoaderModule $object */
546 if ( isset( $info['object'] ) ) {
547 // Object given in info array
548 $object = $info['object'];
550 if ( !isset( $info['class'] ) ) {
551 $class = 'ResourceLoaderFileModule';
553 $class = $info['class'];
555 /** @var ResourceLoaderModule $object */
556 $object = new $class( $info );
557 $object->setConfig( $this->getConfig() );
559 $object->setName( $name );
560 $this->modules
[$name] = $object;
563 return $this->modules
[$name];
567 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
569 * @param string $name Module name
572 protected function isFileModule( $name ) {
573 if ( !isset( $this->moduleInfos
[$name] ) ) {
576 $info = $this->moduleInfos
[$name];
577 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
584 * Get the list of sources.
586 * @return array Like array( id => load.php url, .. )
588 public function getSources() {
589 return $this->sources
;
593 * Get the URL to the load.php endpoint for the given
594 * ResourceLoader source
597 * @param string $source
598 * @throws MWException On an invalid $source name
601 public function getLoadScript( $source ) {
602 if ( !isset( $this->sources
[$source] ) ) {
603 throw new MWException( "The $source source was never registered in ResourceLoader." );
605 return $this->sources
[$source];
610 * @param string $value
611 * @return string Hash
613 public static function makeHash( $value ) {
614 // Use base64 to output more entropy in a more compact string (default hex is only base16).
615 // The first 8 chars of a base64 encoded digest represent the same binary as
616 // the first 12 chars of a hex encoded digest.
617 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
621 * Helper method to get and combine versions of multiple modules.
624 * @param ResourceLoaderContext $context
625 * @param array $modules List of ResourceLoaderModule objects
626 * @return string Hash
628 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
632 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
633 // http://php.net/functions.anonymous
635 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
636 return $rl->getModule( $module )->getVersionHash( $context );
638 return self
::makeHash( implode( $hashes ) );
642 * Output a response to a load request, including the content-type header.
644 * @param ResourceLoaderContext $context Context in which a response should be formed
646 public function respond( ResourceLoaderContext
$context ) {
647 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
648 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
649 // is used: ob_clean() will clear the GZIP header in that case and it won't come
650 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
651 // the whole thing in our own output buffer to be sure the active buffer
652 // doesn't use ob_gzhandler.
653 // See http://bugs.php.net/bug.php?id=36514
656 // Find out which modules are missing and instantiate the others
659 foreach ( $context->getModules() as $name ) {
660 $module = $this->getModule( $name );
662 // Do not allow private modules to be loaded from the web.
663 // This is a security issue, see bug 34907.
664 if ( $module->getGroup() === 'private' ) {
665 $this->logger
->debug( "Request for private module '$name' denied" );
666 $this->errors
[] = "Cannot show private module \"$name\"";
669 $modules[$name] = $module;
676 // Preload for getCombinedVersion()
677 $this->preloadModuleInfo( array_keys( $modules ), $context );
678 } catch ( Exception
$e ) {
679 MWExceptionHandler
::logException( $e );
680 $this->logger
->warning( 'Preloading module info failed: {exception}', array(
683 $this->errors
[] = self
::formatExceptionNoComment( $e );
686 // Combine versions to propagate cache invalidation
689 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
690 } catch ( Exception
$e ) {
691 MWExceptionHandler
::logException( $e );
692 $this->logger
->warning( 'Calculating version hash failed: {exception}', array(
695 $this->errors
[] = self
::formatExceptionNoComment( $e );
698 // See RFC 2616 § 3.11 Entity Tags
699 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
700 $etag = 'W/"' . $versionHash . '"';
702 // Try the client-side cache first
703 if ( $this->tryRespondNotModified( $context, $etag ) ) {
704 return; // output handled (buffers cleared)
707 // Use file cache if enabled and available...
708 if ( $this->config
->get( 'UseFileCache' ) ) {
709 $fileCache = ResourceFileCache
::newFromContext( $context );
710 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
711 return; // output handled
715 // Generate a response
716 $response = $this->makeModuleResponse( $context, $modules, $missing );
718 // Capture any PHP warnings from the output buffer and append them to the
719 // error list if we're in debug mode.
720 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
721 $this->errors
[] = $warnings;
724 // Save response to file cache unless there are errors
725 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
726 // Cache single modules and images...and other requests if there are enough hits
727 if ( ResourceFileCache
::useFileCache( $context ) ) {
728 if ( $fileCache->isCacheWorthy() ) {
729 $fileCache->saveText( $response );
731 $fileCache->incrMissesRecent( $context->getRequest() );
736 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
738 // Remove the output buffer and output the response
741 if ( $context->getImageObj() && $this->errors
) {
742 // We can't show both the error messages and the response when it's an image.
744 foreach ( $this->errors
as $error ) {
745 $errorText .= $error . "\n";
747 $response = $errorText;
748 } elseif ( $this->errors
) {
749 // Prepend comments indicating errors
751 foreach ( $this->errors
as $error ) {
752 $errorText .= self
::makeComment( $error );
754 $response = $errorText . $response;
757 $this->errors
= array();
763 * Send main response headers to the client.
765 * Deals with Content-Type, CORS (for stylesheets), and caching.
767 * @param ResourceLoaderContext $context
768 * @param string $etag ETag header value
769 * @param bool $errors Whether there are errors in the response
772 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
773 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
774 // If a version wasn't specified we need a shorter expiry time for updates
775 // to propagate to clients quickly
776 // If there were errors, we also need a shorter expiry time so we can recover quickly
777 if ( is_null( $context->getVersion() ) ||
$errors ) {
778 $maxage = $rlMaxage['unversioned']['client'];
779 $smaxage = $rlMaxage['unversioned']['server'];
780 // If a version was specified we can use a longer expiry time since changing
781 // version numbers causes cache misses
783 $maxage = $rlMaxage['versioned']['client'];
784 $smaxage = $rlMaxage['versioned']['server'];
786 if ( $context->getImageObj() ) {
787 // Output different headers if we're outputting textual errors.
789 header( 'Content-Type: text/plain; charset=utf-8' );
791 $context->getImageObj()->sendResponseHeaders( $context );
793 } elseif ( $context->getOnly() === 'styles' ) {
794 header( 'Content-Type: text/css; charset=utf-8' );
795 header( 'Access-Control-Allow-Origin: *' );
797 header( 'Content-Type: text/javascript; charset=utf-8' );
799 // See RFC 2616 § 14.19 ETag
800 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
801 header( 'ETag: ' . $etag );
802 if ( $context->getDebug() ) {
803 // Do not cache debug responses
804 header( 'Cache-Control: private, no-cache, must-revalidate' );
805 header( 'Pragma: no-cache' );
807 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
808 $exp = min( $maxage, $smaxage );
809 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
814 * Respond with HTTP 304 Not Modified if appropiate.
816 * If there's an If-None-Match header, respond with a 304 appropriately
817 * and clear out the output buffer. If the client cache is too old then do nothing.
819 * @param ResourceLoaderContext $context
820 * @param string $etag ETag header value
821 * @return bool True if HTTP 304 was sent and output handled
823 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
824 // See RFC 2616 § 14.26 If-None-Match
825 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
826 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
827 // Never send 304s in debug mode
828 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
829 // There's another bug in ob_gzhandler (see also the comment at
830 // the top of this function) that causes it to gzip even empty
831 // responses, meaning it's impossible to produce a truly empty
832 // response (because the gzip header is always there). This is
833 // a problem because 304 responses have to be completely empty
834 // per the HTTP spec, and Firefox behaves buggily when they're not.
835 // See also http://bugs.php.net/bug.php?id=51579
836 // To work around this, we tear down all output buffering before
838 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
840 HttpStatus
::header( 304 );
842 $this->sendResponseHeaders( $context, $etag, false );
849 * Send out code for a response from file cache if possible.
851 * @param ResourceFileCache $fileCache Cache object for this request URL
852 * @param ResourceLoaderContext $context Context in which to generate a response
853 * @param string $etag ETag header value
854 * @return bool If this found a cache file and handled the response
856 protected function tryRespondFromFileCache(
857 ResourceFileCache
$fileCache,
858 ResourceLoaderContext
$context,
861 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
862 // Buffer output to catch warnings.
864 // Get the maximum age the cache can be
865 $maxage = is_null( $context->getVersion() )
866 ?
$rlMaxage['unversioned']['server']
867 : $rlMaxage['versioned']['server'];
868 // Minimum timestamp the cache file must have
869 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
871 try { // RL always hits the DB on file cache miss...
873 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
874 $good = $fileCache->isCacheGood(); // cache existence check
878 $ts = $fileCache->cacheTimestamp();
879 // Send content type and cache headers
880 $this->sendResponseHeaders( $context, $etag, false );
881 $response = $fileCache->fetchText();
882 // Capture any PHP warnings from the output buffer and append them to the
883 // response in a comment if we're in debug mode.
884 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
885 $response = self
::makeComment( $warnings ) . $response;
887 // Remove the output buffer and output the response
889 echo $response . "\n/* Cached {$ts} */";
890 return true; // cache hit
895 return false; // cache miss
899 * Generate a CSS or JS comment block.
901 * Only use this for public data, not error message details.
903 * @param string $text
906 public static function makeComment( $text ) {
907 $encText = str_replace( '*/', '* /', $text );
908 return "/*\n$encText\n*/\n";
912 * Handle exception display.
914 * @param Exception $e Exception to be shown to the user
915 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
917 public static function formatException( $e ) {
918 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
922 * Handle exception display.
925 * @param Exception $e Exception to be shown to the user
926 * @return string Sanitized text that can be returned to the user
928 protected static function formatExceptionNoComment( $e ) {
929 global $wgShowExceptionDetails;
931 if ( $wgShowExceptionDetails ) {
932 return $e->__toString();
934 return wfMessage( 'internalerror' )->text();
939 * Generate code for a response.
941 * @param ResourceLoaderContext $context Context in which to generate a response
942 * @param array $modules List of module objects keyed by module name
943 * @param array $missing List of requested module names that are unregistered (optional)
944 * @return string Response data
946 public function makeModuleResponse( ResourceLoaderContext
$context,
947 array $modules, array $missing = array()
952 if ( !count( $modules ) && !count( $missing ) ) {
954 /* This file is the Web entry point for MediaWiki's ResourceLoader:
955 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
956 no modules were requested. Max made me put this here. */
960 $image = $context->getImageObj();
962 $data = $image->getImageData( $context );
963 if ( $data === false ) {
965 $this->errors
[] = 'Image generation failed';
971 if ( $context->shouldIncludeMessages() ) {
973 $this->blobStore
->get( $this, $modules, $context->getLanguage() );
974 } catch ( Exception
$e ) {
975 MWExceptionHandler
::logException( $e );
976 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
979 $this->errors
[] = self
::formatExceptionNoComment( $e );
983 foreach ( $missing as $name ) {
984 $states[$name] = 'missing';
989 foreach ( $modules as $name => $module ) {
991 $content = $module->getModuleContent( $context );
994 switch ( $context->getOnly() ) {
996 $scripts = $content['scripts'];
997 if ( is_string( $scripts ) ) {
998 // Load scripts raw...
1000 } elseif ( is_array( $scripts ) ) {
1001 // ...except when $scripts is an array of URLs
1002 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1006 $styles = $content['styles'];
1007 // We no longer seperate into media, they are all combined now with
1008 // custom media type groups into @media .. {} sections as part of the css string.
1009 // Module returns either an empty array or a numerical array with css strings.
1010 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1013 $out .= self
::makeLoaderImplementScript(
1015 isset( $content['scripts'] ) ?
$content['scripts'] : '',
1016 isset( $content['styles'] ) ?
$content['styles'] : array(),
1017 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : array(),
1018 isset( $content['templates'] ) ?
$content['templates'] : array()
1022 } catch ( Exception
$e ) {
1023 MWExceptionHandler
::logException( $e );
1024 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1027 $this->errors
[] = self
::formatExceptionNoComment( $e );
1029 // Respond to client with error-state instead of module implementation
1030 $states[$name] = 'error';
1031 unset( $modules[$name] );
1033 $isRaw |
= $module->isRaw();
1036 // Update module states
1037 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1038 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1039 // Set the state of modules loaded as only scripts to ready as
1040 // they don't have an mw.loader.implement wrapper that sets the state
1041 foreach ( $modules as $name => $module ) {
1042 $states[$name] = 'ready';
1046 // Set the state of modules we didn't respond to with mw.loader.implement
1047 if ( count( $states ) ) {
1048 $out .= self
::makeLoaderStateScript( $states );
1051 if ( count( $states ) ) {
1052 $this->errors
[] = 'Problematic modules: ' .
1053 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1057 $enableFilterCache = true;
1058 if ( count( $modules ) === 1 && reset( $modules ) instanceof ResourceLoaderUserTokensModule
) {
1059 // If we're building the embedded user.tokens, don't cache (T84960)
1060 $enableFilterCache = false;
1063 if ( !$context->getDebug() ) {
1064 if ( $context->getOnly() === 'styles' ) {
1065 $out = $this->filter( 'minify-css', $out );
1067 $out = $this->filter( 'minify-js', $out, array(
1068 'cache' => $enableFilterCache
1076 /* Static Methods */
1079 * Return JS code that calls mw.loader.implement with given module properties.
1081 * @param string $name Module name
1082 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1083 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1084 * to CSS files keyed by media type
1085 * @param mixed $messages List of messages associated with this module. May either be an
1086 * associative array mapping message key to value, or a JSON-encoded message blob containing
1087 * the same data, wrapped in an XmlJsCode object.
1088 * @param array $templates Keys are name of templates and values are the source of
1090 * @throws MWException
1093 public static function makeLoaderImplementScript(
1094 $name, $scripts, $styles, $messages, $templates
1096 if ( is_string( $scripts ) ) {
1097 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1098 } elseif ( !is_array( $scripts ) ) {
1099 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1101 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1102 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1103 // of "{}". Force them to objects.
1109 (object) $templates,
1111 self
::trimArray( $module );
1113 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1117 * Returns JS code which, when called, will register a given list of messages.
1119 * @param mixed $messages Either an associative array mapping message key to value, or a
1120 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1123 public static function makeMessageSetScript( $messages ) {
1124 return Xml
::encodeJsCall(
1126 array( (object)$messages ),
1127 ResourceLoader
::inDebugMode()
1132 * Combines an associative array mapping media type to CSS into a
1133 * single stylesheet with "@media" blocks.
1135 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1138 public static function makeCombinedStyles( array $stylePairs ) {
1140 foreach ( $stylePairs as $media => $styles ) {
1141 // ResourceLoaderFileModule::getStyle can return the styles
1142 // as a string or an array of strings. This is to allow separation in
1144 $styles = (array)$styles;
1145 foreach ( $styles as $style ) {
1146 $style = trim( $style );
1147 // Don't output an empty "@media print { }" block (bug 40498)
1148 if ( $style !== '' ) {
1149 // Transform the media type based on request params and config
1150 // The way that this relies on $wgRequest to propagate request params is slightly evil
1151 $media = OutputPage
::transformCssMedia( $media );
1153 if ( $media === '' ||
$media == 'all' ) {
1155 } elseif ( is_string( $media ) ) {
1156 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1166 * Returns a JS call to mw.loader.state, which sets the state of a
1167 * module or modules to a given value. Has two calling conventions:
1169 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1170 * Set the state of a single module called $name to $state
1172 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1173 * Set the state of modules with the given names to the given states
1175 * @param string $name
1176 * @param string $state
1179 public static function makeLoaderStateScript( $name, $state = null ) {
1180 if ( is_array( $name ) ) {
1181 return Xml
::encodeJsCall(
1184 ResourceLoader
::inDebugMode()
1187 return Xml
::encodeJsCall(
1189 array( $name, $state ),
1190 ResourceLoader
::inDebugMode()
1196 * Returns JS code which calls the script given by $script. The script will
1197 * be called with local variables name, version, dependencies and group,
1198 * which will have values corresponding to $name, $version, $dependencies
1199 * and $group as supplied.
1201 * @param string $name Module name
1202 * @param string $version Module version hash
1203 * @param array $dependencies List of module names on which this module depends
1204 * @param string $group Group which the module is in.
1205 * @param string $source Source of the module, or 'local' if not foreign.
1206 * @param string $script JavaScript code
1209 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1210 $group, $source, $script
1212 $script = str_replace( "\n", "\n\t", trim( $script ) );
1213 return Xml
::encodeJsCall(
1214 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1215 array( $name, $version, $dependencies, $group, $source ),
1216 ResourceLoader
::inDebugMode()
1220 private static function isEmptyObject( stdClass
$obj ) {
1221 foreach ( $obj as $key => &$value ) {
1228 * Remove empty values from the end of an array.
1230 * Values considered empty:
1234 * - new XmlJsCode( '{}' )
1235 * - new stdClass() // (object) array()
1237 * @param Array $array
1239 private static function trimArray( Array &$array ) {
1240 $i = count( $array );
1242 if ( $array[$i] === null
1243 ||
$array[$i] === array()
1244 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1245 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1247 unset( $array[$i] );
1255 * Returns JS code which calls mw.loader.register with the given
1256 * parameters. Has three calling conventions:
1258 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1259 * $dependencies, $group, $source, $skip
1261 * Register a single module.
1263 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1264 * Register modules with the given names.
1266 * - ResourceLoader::makeLoaderRegisterScript( array(
1267 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1268 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1271 * Registers modules with the given names and parameters.
1273 * @param string $name Module name
1274 * @param string $version Module version hash
1275 * @param array $dependencies List of module names on which this module depends
1276 * @param string $group Group which the module is in
1277 * @param string $source Source of the module, or 'local' if not foreign
1278 * @param string $skip Script body of the skip function
1281 public static function makeLoaderRegisterScript( $name, $version = null,
1282 $dependencies = null, $group = null, $source = null, $skip = null
1284 if ( is_array( $name ) ) {
1285 // Build module name index
1287 foreach ( $name as $i => &$module ) {
1288 $index[$module[0]] = $i;
1291 // Transform dependency names into indexes when possible, they will be resolved by
1292 // mw.loader.register on the other end
1293 foreach ( $name as &$module ) {
1294 if ( isset( $module[2] ) ) {
1295 foreach ( $module[2] as &$dependency ) {
1296 if ( isset( $index[$dependency] ) ) {
1297 $dependency = $index[$dependency];
1303 array_walk( $name, array( 'self', 'trimArray' ) );
1305 return Xml
::encodeJsCall(
1306 'mw.loader.register',
1308 ResourceLoader
::inDebugMode()
1311 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1312 self
::trimArray( $registration );
1313 return Xml
::encodeJsCall(
1314 'mw.loader.register',
1316 ResourceLoader
::inDebugMode()
1322 * Returns JS code which calls mw.loader.addSource() with the given
1323 * parameters. Has two calling conventions:
1325 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1326 * Register a single source
1328 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1329 * Register sources with the given IDs and properties.
1331 * @param string $id Source ID
1332 * @param array $properties Source properties (see addSource())
1335 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1336 if ( is_array( $id ) ) {
1337 return Xml
::encodeJsCall(
1338 'mw.loader.addSource',
1340 ResourceLoader
::inDebugMode()
1343 return Xml
::encodeJsCall(
1344 'mw.loader.addSource',
1345 array( $id, $properties ),
1346 ResourceLoader
::inDebugMode()
1352 * Returns JS code which runs given JS code if the client-side framework is
1355 * @deprecated since 1.25; use makeInlineScript instead
1356 * @param string $script JavaScript code
1359 public static function makeLoaderConditionalScript( $script ) {
1360 return "if(window.mw){\n" . trim( $script ) . "\n}";
1364 * Construct an inline script tag with given JS code.
1366 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1367 * only if the client has adequate support for MediaWiki JavaScript code.
1369 * @param string $script JavaScript code
1370 * @return string HTML
1372 public static function makeInlineScript( $script ) {
1373 $js = self
::makeLoaderConditionalScript( $script );
1374 return Html
::inlineScript( $js );
1378 * Returns JS code which will set the MediaWiki configuration array to
1381 * @param array $configuration List of configuration values keyed by variable name
1384 public static function makeConfigSetScript( array $configuration ) {
1385 return Xml
::encodeJsCall(
1387 array( $configuration ),
1388 ResourceLoader
::inDebugMode()
1393 * Convert an array of module names to a packed query string.
1395 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1396 * becomes 'foo.bar,baz|bar.baz,quux'
1397 * @param array $modules List of module names (strings)
1398 * @return string Packed query string
1400 public static function makePackedModulesString( $modules ) {
1401 $groups = array(); // array( prefix => array( suffixes ) )
1402 foreach ( $modules as $module ) {
1403 $pos = strrpos( $module, '.' );
1404 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1405 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1406 $groups[$prefix][] = $suffix;
1410 foreach ( $groups as $prefix => $suffixes ) {
1411 $p = $prefix === '' ?
'' : $prefix . '.';
1412 $arr[] = $p . implode( ',', $suffixes );
1414 $str = implode( '|', $arr );
1419 * Determine whether debug mode was requested
1420 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1423 public static function inDebugMode() {
1424 if ( self
::$debugMode === null ) {
1425 global $wgRequest, $wgResourceLoaderDebug;
1426 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1427 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1430 return self
::$debugMode;
1434 * Reset static members used for caching.
1436 * Global state and $wgRequest are evil, but we're using it right
1437 * now and sometimes we need to be able to force ResourceLoader to
1438 * re-evaluate the context because it has changed (e.g. in the test suite).
1440 public static function clearCache() {
1441 self
::$debugMode = null;
1445 * Build a load.php URL
1448 * @param string $source Name of the ResourceLoader source
1449 * @param ResourceLoaderContext $context
1450 * @param array $extraQuery
1451 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1453 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1454 $extraQuery = array()
1456 $query = self
::createLoaderQuery( $context, $extraQuery );
1457 $script = $this->getLoadScript( $source );
1459 // Prevent the IE6 extension check from being triggered (bug 28840)
1460 // by appending a character that's invalid in Windows extensions ('*')
1461 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1465 * Build a load.php URL
1466 * @deprecated since 1.24 Use createLoaderURL() instead
1467 * @param array $modules Array of module names (strings)
1468 * @param string $lang Language code
1469 * @param string $skin Skin name
1470 * @param string|null $user User name. If null, the &user= parameter is omitted
1471 * @param string|null $version Versioning timestamp
1472 * @param bool $debug Whether the request should be in debug mode
1473 * @param string|null $only &only= parameter
1474 * @param bool $printable Printable mode
1475 * @param bool $handheld Handheld mode
1476 * @param array $extraQuery Extra query parameters to add
1477 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1479 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1480 $version = null, $debug = false, $only = null, $printable = false,
1481 $handheld = false, $extraQuery = array()
1483 global $wgLoadScript;
1485 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1486 $only, $printable, $handheld, $extraQuery
1489 // Prevent the IE6 extension check from being triggered (bug 28840)
1490 // by appending a character that's invalid in Windows extensions ('*')
1491 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1495 * Helper for createLoaderURL()
1498 * @see makeLoaderQuery
1499 * @param ResourceLoaderContext $context
1500 * @param array $extraQuery
1503 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1504 return self
::makeLoaderQuery(
1505 $context->getModules(),
1506 $context->getLanguage(),
1507 $context->getSkin(),
1508 $context->getUser(),
1509 $context->getVersion(),
1510 $context->getDebug(),
1511 $context->getOnly(),
1512 $context->getRequest()->getBool( 'printable' ),
1513 $context->getRequest()->getBool( 'handheld' ),
1519 * Build a query array (array representation of query string) for load.php. Helper
1520 * function for makeLoaderURL().
1522 * @param array $modules
1523 * @param string $lang
1524 * @param string $skin
1525 * @param string $user
1526 * @param string $version
1527 * @param bool $debug
1528 * @param string $only
1529 * @param bool $printable
1530 * @param bool $handheld
1531 * @param array $extraQuery
1535 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1536 $version = null, $debug = false, $only = null, $printable = false,
1537 $handheld = false, $extraQuery = array()
1540 'modules' => self
::makePackedModulesString( $modules ),
1543 'debug' => $debug ?
'true' : 'false',
1545 if ( $user !== null ) {
1546 $query['user'] = $user;
1548 if ( $version !== null ) {
1549 $query['version'] = $version;
1551 if ( $only !== null ) {
1552 $query['only'] = $only;
1555 $query['printable'] = 1;
1558 $query['handheld'] = 1;
1560 $query +
= $extraQuery;
1562 // Make queries uniform in order
1568 * Check a module name for validity.
1570 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1571 * at most 255 bytes.
1573 * @param string $moduleName Module name to check
1574 * @return bool Whether $moduleName is a valid module name
1576 public static function isValidModuleName( $moduleName ) {
1577 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1581 * Returns LESS compiler set up for use with MediaWiki
1583 * @param Config $config
1584 * @throws MWException
1588 public static function getLessCompiler( Config
$config ) {
1589 // When called from the installer, it is possible that a required PHP extension
1590 // is missing (at least for now; see bug 47564). If this is the case, throw an
1591 // exception (caught by the installer) to prevent a fatal error later on.
1592 if ( !class_exists( 'lessc' ) ) {
1593 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1595 if ( !function_exists( 'ctype_digit' ) ) {
1596 throw new MWException( 'lessc requires the Ctype extension' );
1599 $less = new lessc();
1600 $less->setPreserveComments( true );
1601 $less->setVariables( self
::getLessVars( $config ) );
1602 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1603 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1604 $less->registerFunction( $name, $func );
1610 * Get global LESS variables.
1612 * @param Config $config
1614 * @return array Map of variable names to string CSS values.
1616 public static function getLessVars( Config
$config ) {
1617 if ( !self
::$lessVars ) {
1618 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1619 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1620 // Sort by key to ensure consistent hashing for cache lookups.
1622 self
::$lessVars = $lessVars;
1624 return self
::$lessVars;