3 * Base class for resource loading system.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Roan Kattouw
22 * @author Trevor Parscal
26 * Dynamic JavaScript and CSS resource loading system.
28 * Most of the documentation is on the MediaWiki documentation wiki starting at:
29 * https://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader
{
33 protected static $filterCacheVersion = 7;
36 protected static $debugMode = null;
39 private static $lessVars = null;
42 * Module name/ResourceLoaderModule object pairs
45 protected $modules = array();
48 * Associative array mapping module name to info associative array
51 protected $moduleInfos = array();
53 /** @var Config $config */
57 * Associative array mapping framework ids to a list of names of test suite modules
58 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
61 protected $testModuleNames = array();
64 * E.g. array( 'source-id' => 'http://.../load.php' )
67 protected $sources = array();
70 * Errors accumulated during current respond() call.
73 protected $errors = array();
76 * @var MessageBlobStore
81 * Load information stored in the database about modules.
83 * This method grabs modules dependencies from the database and updates modules
86 * This is not inside the module code because it is much faster to
87 * request all of the information at once than it is to have each module
88 * requests its own information. This sacrifice of modularity yields a substantial
89 * performance improvement.
91 * @param array $modules List of module names to preload information for
92 * @param ResourceLoaderContext $context Context to load the information within
94 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
95 if ( !count( $modules ) ) {
96 // Or else Database*::select() will explode, plus it's cheaper!
99 $dbr = wfGetDB( DB_SLAVE
);
100 $skin = $context->getSkin();
101 $lang = $context->getLanguage();
103 // Get file dependency information
104 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
105 'md_module' => $modules,
110 // Set modules' dependencies
111 $modulesWithDeps = array();
112 foreach ( $res as $row ) {
113 $module = $this->getModule( $row->md_module
);
115 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
116 $modulesWithDeps[] = $row->md_module
;
120 // Register the absence of a dependency row too
121 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
122 $module = $this->getModule( $name );
124 $this->getModule( $name )->setFileDependencies( $skin, array() );
128 // Get message blob mtimes. Only do this for modules with messages
129 $modulesWithMessages = array();
130 foreach ( $modules as $name ) {
131 $module = $this->getModule( $name );
132 if ( $module && count( $module->getMessages() ) ) {
133 $modulesWithMessages[] = $name;
136 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
137 if ( count( $modulesWithMessages ) ) {
138 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
139 'mr_resource' => $modulesWithMessages,
143 foreach ( $res as $row ) {
144 $module = $this->getModule( $row->mr_resource
);
146 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
147 unset( $modulesWithoutMessages[$row->mr_resource
] );
151 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
152 $module = $this->getModule( $name );
154 $module->setMsgBlobMtime( $lang, 1 );
160 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
162 * Available filters are:
164 * - minify-js \see JavaScriptMinifier::minify
165 * - minify-css \see CSSMin::minify
167 * If $data is empty, only contains whitespace or the filter was unknown,
168 * $data is returned unmodified.
170 * @param string $filter Name of filter to run
171 * @param string $data Text to filter, such as JavaScript or CSS text
172 * @param string $cacheReport Whether to include the cache key report
173 * @return string Filtered data, or a comment containing an error message
175 public function filter( $filter, $data, $cacheReport = true ) {
177 // For empty/whitespace-only data or for unknown filters, don't perform
178 // any caching or processing
179 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
184 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
185 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
186 $cache = wfGetCache( CACHE_ANYTHING
);
187 $cacheEntry = $cache->get( $key );
188 if ( is_string( $cacheEntry ) ) {
189 wfIncrStats( "rl-$filter-cache-hits" );
194 // Run the filter - we've already verified one of these will work
196 wfIncrStats( "rl-$filter-cache-misses" );
199 $result = JavaScriptMinifier
::minify( $data,
200 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
201 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
203 if ( $cacheReport ) {
204 $result .= "\n/* cache key: $key */";
208 $result = CSSMin
::minify( $data );
209 if ( $cacheReport ) {
210 $result .= "\n/* cache key: $key */";
215 // Save filtered text to Memcached
216 $cache->set( $key, $result );
217 } catch ( Exception
$e ) {
218 MWExceptionHandler
::logException( $e );
219 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
220 $this->errors
[] = self
::formatExceptionNoComment( $e );
229 * Register core modules and runs registration hooks.
230 * @param Config|null $config
232 public function __construct( Config
$config = null ) {
235 if ( $config === null ) {
236 wfDebug( __METHOD__
. ' was called without providing a Config instance' );
237 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
240 $this->config
= $config;
242 // Add 'local' source first
243 $this->addSource( 'local', wfScript( 'load' ) );
246 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
248 // Register core modules
249 $this->register( include "$IP/resources/Resources.php" );
250 // Register extension modules
251 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
252 $this->register( $config->get( 'ResourceModules' ) );
254 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
255 $this->registerTestModules();
258 $this->setMessageBlobStore( new MessageBlobStore() );
264 public function getConfig() {
265 return $this->config
;
269 * @param MessageBlobStore $blobStore
272 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
273 $this->blobStore
= $blobStore;
277 * Register a module with the ResourceLoader system.
279 * @param mixed $name Name of module as a string or List of name/object pairs as an array
280 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
281 * this may also be a ResourceLoaderModule object. Optional when using
282 * multiple-registration calling style.
283 * @throws MWException If a duplicate module registration is attempted
284 * @throws MWException If a module name contains illegal characters (pipes or commas)
285 * @throws MWException If something other than a ResourceLoaderModule is being registered
286 * @return bool False if there were any errors, in which case one or more modules were
289 public function register( $name, $info = null ) {
291 // Allow multiple modules to be registered in one call
292 $registrations = is_array( $name ) ?
$name : array( $name => $info );
293 foreach ( $registrations as $name => $info ) {
294 // Disallow duplicate registrations
295 if ( isset( $this->moduleInfos
[$name] ) ) {
296 // A module has already been registered by this name
297 throw new MWException(
298 'ResourceLoader duplicate registration error. ' .
299 'Another module has already been registered as ' . $name
303 // Check $name for validity
304 if ( !self
::isValidModuleName( $name ) ) {
305 throw new MWException( "ResourceLoader module name '$name' is invalid, "
306 . "see ResourceLoader::isValidModuleName()" );
310 if ( $info instanceof ResourceLoaderModule
) {
311 $this->moduleInfos
[$name] = array( 'object' => $info );
312 $info->setName( $name );
313 $this->modules
[$name] = $info;
314 } elseif ( is_array( $info ) ) {
315 // New calling convention
316 $this->moduleInfos
[$name] = $info;
318 throw new MWException(
319 'ResourceLoader module info type error for module \'' . $name .
320 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
324 // Last-minute changes
326 // Apply custom skin-defined styles to existing modules.
327 if ( $this->isFileModule( $name ) ) {
328 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
329 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
330 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
334 // If $name is preceded with a '+', the defined style files will be added to 'default'
335 // skinStyles, otherwise 'default' will be ignored as it normally would be.
336 if ( isset( $skinStyles[$name] ) ) {
337 $paths = (array)$skinStyles[$name];
338 $styleFiles = array();
339 } elseif ( isset( $skinStyles['+' . $name] ) ) {
340 $paths = (array)$skinStyles['+' . $name];
341 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
342 $this->moduleInfos
[$name]['skinStyles']['default'] :
348 // Add new file paths, remapping them to refer to our directories and not use settings
349 // from the module we're modifying, which come from the base definition.
350 list( $localBasePath, $remoteBasePath ) =
351 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
353 foreach ( $paths as $path ) {
354 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
357 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
366 public function registerTestModules() {
369 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
370 throw new MWException( 'Attempt to register JavaScript test modules '
371 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
372 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
375 // Get core test suites
376 $testModules = array();
377 $testModules['qunit'] = array();
378 // Get other test suites (e.g. from extensions)
379 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
381 // Add the testrunner (which configures QUnit) to the dependencies.
382 // Since it must be ready before any of the test suites are executed.
383 foreach ( $testModules['qunit'] as &$module ) {
384 // Make sure all test modules are top-loading so that when QUnit starts
385 // on document-ready, it will run once and finish. If some tests arrive
386 // later (possibly after QUnit has already finished) they will be ignored.
387 $module['position'] = 'top';
388 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
391 $testModules['qunit'] =
392 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
394 foreach ( $testModules as $id => $names ) {
395 // Register test modules
396 $this->register( $testModules[$id] );
398 // Keep track of their names so that they can be loaded together
399 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
405 * Add a foreign source of modules.
407 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
408 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
409 * backwards-compatibility.
410 * @throws MWException
412 public function addSource( $id, $loadUrl = null ) {
413 // Allow multiple sources to be registered in one call
414 if ( is_array( $id ) ) {
415 foreach ( $id as $key => $value ) {
416 $this->addSource( $key, $value );
421 // Disallow duplicates
422 if ( isset( $this->sources
[$id] ) ) {
423 throw new MWException(
424 'ResourceLoader duplicate source addition error. ' .
425 'Another source has already been registered as ' . $id
429 // Pre 1.24 backwards-compatibility
430 if ( is_array( $loadUrl ) ) {
431 if ( !isset( $loadUrl['loadScript'] ) ) {
432 throw new MWException(
433 __METHOD__
. ' was passed an array with no "loadScript" key.'
437 $loadUrl = $loadUrl['loadScript'];
440 $this->sources
[$id] = $loadUrl;
444 * Get a list of module names.
446 * @return array List of module names
448 public function getModuleNames() {
449 return array_keys( $this->moduleInfos
);
453 * Get a list of test module names for one (or all) frameworks.
455 * If the given framework id is unknkown, or if the in-object variable is not an array,
456 * then it will return an empty array.
458 * @param string $framework Get only the test module names for one
459 * particular framework (optional)
462 public function getTestModuleNames( $framework = 'all' ) {
463 /** @todo api siteinfo prop testmodulenames modulenames */
464 if ( $framework == 'all' ) {
465 return $this->testModuleNames
;
466 } elseif ( isset( $this->testModuleNames
[$framework] )
467 && is_array( $this->testModuleNames
[$framework] )
469 return $this->testModuleNames
[$framework];
476 * Check whether a ResourceLoader module is registered
479 * @param string $name
482 public function isModuleRegistered( $name ) {
483 return isset( $this->moduleInfos
[$name] );
487 * Get the ResourceLoaderModule object for a given module name.
489 * If an array of module parameters exists but a ResourceLoaderModule object has not
490 * yet been instantiated, this method will instantiate and cache that object such that
491 * subsequent calls simply return the same object.
493 * @param string $name Module name
494 * @return ResourceLoaderModule|null If module has been registered, return a
495 * ResourceLoaderModule instance. Otherwise, return null.
497 public function getModule( $name ) {
498 if ( !isset( $this->modules
[$name] ) ) {
499 if ( !isset( $this->moduleInfos
[$name] ) ) {
503 // Construct the requested object
504 $info = $this->moduleInfos
[$name];
505 /** @var ResourceLoaderModule $object */
506 if ( isset( $info['object'] ) ) {
507 // Object given in info array
508 $object = $info['object'];
510 if ( !isset( $info['class'] ) ) {
511 $class = 'ResourceLoaderFileModule';
513 $class = $info['class'];
515 /** @var ResourceLoaderModule $object */
516 $object = new $class( $info );
517 $object->setConfig( $this->getConfig() );
519 $object->setName( $name );
520 $this->modules
[$name] = $object;
523 return $this->modules
[$name];
527 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
529 * @param string $name Module name
532 protected function isFileModule( $name ) {
533 if ( !isset( $this->moduleInfos
[$name] ) ) {
536 $info = $this->moduleInfos
[$name];
537 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
544 * Get the list of sources.
546 * @return array Like array( id => load.php url, .. )
548 public function getSources() {
549 return $this->sources
;
553 * Get the URL to the load.php endpoint for the given
554 * ResourceLoader source
557 * @param string $source
558 * @throws MWException On an invalid $source name
561 public function getLoadScript( $source ) {
562 if ( !isset( $this->sources
[$source] ) ) {
563 throw new MWException( "The $source source was never registered in ResourceLoader." );
565 return $this->sources
[$source];
569 * Output a response to a load request, including the content-type header.
571 * @param ResourceLoaderContext $context Context in which a response should be formed
573 public function respond( ResourceLoaderContext
$context ) {
574 // Use file cache if enabled and available...
575 if ( $this->config
->get( 'UseFileCache' ) ) {
576 $fileCache = ResourceFileCache
::newFromContext( $context );
577 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
578 return; // output handled
582 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
583 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
584 // is used: ob_clean() will clear the GZIP header in that case and it won't come
585 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
586 // the whole thing in our own output buffer to be sure the active buffer
587 // doesn't use ob_gzhandler.
588 // See http://bugs.php.net/bug.php?id=36514
591 // Find out which modules are missing and instantiate the others
594 foreach ( $context->getModules() as $name ) {
595 $module = $this->getModule( $name );
597 // Do not allow private modules to be loaded from the web.
598 // This is a security issue, see bug 34907.
599 if ( $module->getGroup() === 'private' ) {
600 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
601 $this->errors
[] = "Cannot show private module \"$name\"";
604 $modules[$name] = $module;
610 // Preload information needed to the mtime calculation below
612 $this->preloadModuleInfo( array_keys( $modules ), $context );
613 } catch ( Exception
$e ) {
614 MWExceptionHandler
::logException( $e );
615 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
616 $this->errors
[] = self
::formatExceptionNoComment( $e );
619 // To send Last-Modified and support If-Modified-Since, we need to detect
620 // the last modified time
621 $mtime = wfTimestamp( TS_UNIX
, $this->config
->get( 'CacheEpoch' ) );
622 foreach ( $modules as $module ) {
624 * @var $module ResourceLoaderModule
627 // Calculate maximum modified time
628 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
629 } catch ( Exception
$e ) {
630 MWExceptionHandler
::logException( $e );
631 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
632 $this->errors
[] = self
::formatExceptionNoComment( $e );
636 // If there's an If-Modified-Since header, respond with a 304 appropriately
637 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
638 return; // output handled (buffers cleared)
641 // Generate a response
642 $response = $this->makeModuleResponse( $context, $modules, $missing );
644 // Capture any PHP warnings from the output buffer and append them to the
645 // error list if we're in debug mode.
646 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
647 $this->errors
[] = $warnings;
650 // Save response to file cache unless there are errors
651 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
652 // Cache single modules and images...and other requests if there are enough hits
653 if ( ResourceFileCache
::useFileCache( $context ) ) {
654 if ( $fileCache->isCacheWorthy() ) {
655 $fileCache->saveText( $response );
657 $fileCache->incrMissesRecent( $context->getRequest() );
662 // Send content type and cache related headers
663 $this->sendResponseHeaders( $context, $mtime, (bool)$this->errors
);
665 // Remove the output buffer and output the response
668 if ( $context->getImageObj() && $this->errors
) {
669 // We can't show both the error messages and the response when it's an image.
671 foreach ( $this->errors
as $error ) {
672 $errorText .= $error . "\n";
674 $response = $errorText;
675 } elseif ( $this->errors
) {
676 // Prepend comments indicating errors
678 foreach ( $this->errors
as $error ) {
679 $errorText .= self
::makeComment( $error );
681 $response = $errorText . $response;
684 $this->errors
= array();
690 * Send content type and last modified headers to the client.
691 * @param ResourceLoaderContext $context
692 * @param string $mtime TS_MW timestamp to use for last-modified
693 * @param bool $errors Whether there are errors in the response
696 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
697 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
698 // If a version wasn't specified we need a shorter expiry time for updates
699 // to propagate to clients quickly
700 // If there were errors, we also need a shorter expiry time so we can recover quickly
701 if ( is_null( $context->getVersion() ) ||
$errors ) {
702 $maxage = $rlMaxage['unversioned']['client'];
703 $smaxage = $rlMaxage['unversioned']['server'];
704 // If a version was specified we can use a longer expiry time since changing
705 // version numbers causes cache misses
707 $maxage = $rlMaxage['versioned']['client'];
708 $smaxage = $rlMaxage['versioned']['server'];
710 if ( $context->getImageObj() ) {
711 // Output different headers if we're outputting textual errors.
713 header( 'Content-Type: text/plain; charset=utf-8' );
715 $context->getImageObj()->sendResponseHeaders( $context );
717 } elseif ( $context->getOnly() === 'styles' ) {
718 header( 'Content-Type: text/css; charset=utf-8' );
719 header( 'Access-Control-Allow-Origin: *' );
721 header( 'Content-Type: text/javascript; charset=utf-8' );
723 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
724 if ( $context->getDebug() ) {
725 // Do not cache debug responses
726 header( 'Cache-Control: private, no-cache, must-revalidate' );
727 header( 'Pragma: no-cache' );
729 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
730 $exp = min( $maxage, $smaxage );
731 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
736 * Respond with 304 Last Modified if appropiate.
738 * If there's an If-Modified-Since header, respond with a 304 appropriately
739 * and clear out the output buffer. If the client cache is too old then do nothing.
741 * @param ResourceLoaderContext $context
742 * @param string $mtime The TS_MW timestamp to check the header against
743 * @return bool True if 304 header sent and output handled
745 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
746 // If there's an If-Modified-Since header, respond with a 304 appropriately
747 // Some clients send "timestamp;length=123". Strip the part after the first ';'
748 // so we get a valid timestamp.
749 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
750 // Never send 304s in debug mode
751 if ( $ims !== false && !$context->getDebug() ) {
752 $imsTS = strtok( $ims, ';' );
753 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
754 // There's another bug in ob_gzhandler (see also the comment at
755 // the top of this function) that causes it to gzip even empty
756 // responses, meaning it's impossible to produce a truly empty
757 // response (because the gzip header is always there). This is
758 // a problem because 304 responses have to be completely empty
759 // per the HTTP spec, and Firefox behaves buggily when they're not.
760 // See also http://bugs.php.net/bug.php?id=51579
761 // To work around this, we tear down all output buffering before
763 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
765 header( 'HTTP/1.0 304 Not Modified' );
766 header( 'Status: 304 Not Modified' );
774 * Send out code for a response from file cache if possible.
776 * @param ResourceFileCache $fileCache Cache object for this request URL
777 * @param ResourceLoaderContext $context Context in which to generate a response
778 * @return bool If this found a cache file and handled the response
780 protected function tryRespondFromFileCache(
781 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
783 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
784 // Buffer output to catch warnings.
786 // Get the maximum age the cache can be
787 $maxage = is_null( $context->getVersion() )
788 ?
$rlMaxage['unversioned']['server']
789 : $rlMaxage['versioned']['server'];
790 // Minimum timestamp the cache file must have
791 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
793 try { // RL always hits the DB on file cache miss...
795 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
796 $good = $fileCache->isCacheGood(); // cache existence check
800 $ts = $fileCache->cacheTimestamp();
801 // Send content type and cache headers
802 $this->sendResponseHeaders( $context, $ts, false );
803 // If there's an If-Modified-Since header, respond with a 304 appropriately
804 if ( $this->tryRespondLastModified( $context, $ts ) ) {
805 return false; // output handled (buffers cleared)
807 $response = $fileCache->fetchText();
808 // Capture any PHP warnings from the output buffer and append them to the
809 // response in a comment if we're in debug mode.
810 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
811 $response = "/*\n$warnings\n*/\n" . $response;
813 // Remove the output buffer and output the response
815 echo $response . "\n/* Cached {$ts} */";
816 return true; // cache hit
821 return false; // cache miss
825 * Generate a CSS or JS comment block.
827 * Only use this for public data, not error message details.
829 * @param string $text
832 public static function makeComment( $text ) {
833 $encText = str_replace( '*/', '* /', $text );
834 return "/*\n$encText\n*/\n";
838 * Handle exception display.
840 * @param Exception $e Exception to be shown to the user
841 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
843 public static function formatException( $e ) {
844 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
848 * Handle exception display.
851 * @param Exception $e Exception to be shown to the user
852 * @return string Sanitized text that can be returned to the user
854 protected static function formatExceptionNoComment( $e ) {
855 global $wgShowExceptionDetails;
857 if ( $wgShowExceptionDetails ) {
858 return $e->__toString();
860 return wfMessage( 'internalerror' )->text();
865 * Generate code for a response.
867 * @param ResourceLoaderContext $context Context in which to generate a response
868 * @param array $modules List of module objects keyed by module name
869 * @param array $missing List of requested module names that are unregistered (optional)
870 * @return string Response data
872 public function makeModuleResponse( ResourceLoaderContext
$context,
873 array $modules, array $missing = array()
878 if ( !count( $modules ) && !count( $missing ) ) {
880 /* This file is the Web entry point for MediaWiki's ResourceLoader:
881 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
882 no modules were requested. Max made me put this here. */
886 $image = $context->getImageObj();
888 $data = $image->getImageData( $context );
889 if ( $data === false ) {
891 $this->errors
[] = 'Image generation failed';
897 if ( $context->shouldIncludeMessages() ) {
899 $blobs = $this->blobStore
->get( $this, $modules, $context->getLanguage() );
900 } catch ( Exception
$e ) {
901 MWExceptionHandler
::logException( $e );
904 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
906 $this->errors
[] = self
::formatExceptionNoComment( $e );
912 foreach ( $missing as $name ) {
913 $states[$name] = 'missing';
918 foreach ( $modules as $name => $module ) {
920 * @var $module ResourceLoaderModule
925 if ( $context->shouldIncludeScripts() ) {
926 // If we are in debug mode, we'll want to return an array of URLs if possible
927 // However, we can't do this if the module doesn't support it
928 // We also can't do this if there is an only= parameter, because we have to give
929 // the module a way to return a load.php URL without causing an infinite loop
930 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
931 $scripts = $module->getScriptURLsForDebug( $context );
933 $scripts = $module->getScript( $context );
934 // rtrim() because there are usually a few line breaks
935 // after the last ';'. A new line at EOF, a new line
936 // added by ResourceLoaderFileModule::readScriptFiles, etc.
937 if ( is_string( $scripts )
938 && strlen( $scripts )
939 && substr( rtrim( $scripts ), -1 ) !== ';'
941 // Append semicolon to prevent weird bugs caused by files not
942 // terminating their statements right (bug 27054)
949 if ( $context->shouldIncludeStyles() ) {
950 // Don't create empty stylesheets like array( '' => '' ) for modules
951 // that don't *have* any stylesheets (bug 38024).
952 $stylePairs = $module->getStyles( $context );
953 if ( count( $stylePairs ) ) {
954 // If we are in debug mode without &only= set, we'll want to return an array of URLs
955 // See comment near shouldIncludeScripts() for more details
956 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
958 'url' => $module->getStyleURLsForDebug( $context )
961 // Minify CSS before embedding in mw.loader.implement call
962 // (unless in debug mode)
963 if ( !$context->getDebug() ) {
964 foreach ( $stylePairs as $media => $style ) {
965 // Can be either a string or an array of strings.
966 if ( is_array( $style ) ) {
967 $stylePairs[$media] = array();
968 foreach ( $style as $cssText ) {
969 if ( is_string( $cssText ) ) {
970 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
973 } elseif ( is_string( $style ) ) {
974 $stylePairs[$media] = $this->filter( 'minify-css', $style );
978 // Wrap styles into @media groups as needed and flatten into a numerical array
980 'css' => self
::makeCombinedStyles( $stylePairs )
987 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
990 switch ( $context->getOnly() ) {
992 if ( is_string( $scripts ) ) {
993 // Load scripts raw...
995 } elseif ( is_array( $scripts ) ) {
996 // ...except when $scripts is an array of URLs
997 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1001 // We no longer seperate into media, they are all combined now with
1002 // custom media type groups into @media .. {} sections as part of the css string.
1003 // Module returns either an empty array or a numerical array with css strings.
1004 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1007 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
1010 $out .= Xml
::encodeJsCall(
1012 array( $name, (object)$module->getTemplates() ),
1013 ResourceLoader
::inDebugMode()
1017 $out .= self
::makeLoaderImplementScript(
1021 new XmlJsCode( $messagesBlob ),
1022 $module->getTemplates()
1026 } catch ( Exception
$e ) {
1027 MWExceptionHandler
::logException( $e );
1028 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
1029 $this->errors
[] = self
::formatExceptionNoComment( $e );
1031 // Respond to client with error-state instead of module implementation
1032 $states[$name] = 'error';
1033 unset( $modules[$name] );
1035 $isRaw |
= $module->isRaw();
1038 // Update module states
1039 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1040 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1041 // Set the state of modules loaded as only scripts to ready as
1042 // they don't have an mw.loader.implement wrapper that sets the state
1043 foreach ( $modules as $name => $module ) {
1044 $states[$name] = 'ready';
1048 // Set the state of modules we didn't respond to with mw.loader.implement
1049 if ( count( $states ) ) {
1050 $out .= self
::makeLoaderStateScript( $states );
1053 if ( count( $states ) ) {
1054 $this->errors
[] = 'Problematic modules: ' .
1055 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1059 if ( !$context->getDebug() ) {
1060 if ( $context->getOnly() === 'styles' ) {
1061 $out = $this->filter( 'minify-css', $out );
1063 $out = $this->filter( 'minify-js', $out );
1070 /* Static Methods */
1073 * Return JS code that calls mw.loader.implement with given module properties.
1075 * @param string $name Module name
1076 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1077 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1078 * to CSS files keyed by media type
1079 * @param mixed $messages List of messages associated with this module. May either be an
1080 * associative array mapping message key to value, or a JSON-encoded message blob containing
1081 * the same data, wrapped in an XmlJsCode object.
1082 * @param array $templates Keys are name of templates and values are the source of
1084 * @throws MWException
1087 public static function makeLoaderImplementScript( $name, $scripts, $styles,
1088 $messages, $templates
1090 if ( is_string( $scripts ) ) {
1091 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1092 } elseif ( !is_array( $scripts ) ) {
1093 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1095 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1096 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1097 // of "{}". Force them to objects.
1103 (object) $templates,
1105 self
::trimArray( $module );
1107 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1111 * Returns JS code which, when called, will register a given list of messages.
1113 * @param mixed $messages Either an associative array mapping message key to value, or a
1114 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1117 public static function makeMessageSetScript( $messages ) {
1118 return Xml
::encodeJsCall(
1120 array( (object)$messages ),
1121 ResourceLoader
::inDebugMode()
1126 * Combines an associative array mapping media type to CSS into a
1127 * single stylesheet with "@media" blocks.
1129 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1132 public static function makeCombinedStyles( array $stylePairs ) {
1134 foreach ( $stylePairs as $media => $styles ) {
1135 // ResourceLoaderFileModule::getStyle can return the styles
1136 // as a string or an array of strings. This is to allow separation in
1138 $styles = (array)$styles;
1139 foreach ( $styles as $style ) {
1140 $style = trim( $style );
1141 // Don't output an empty "@media print { }" block (bug 40498)
1142 if ( $style !== '' ) {
1143 // Transform the media type based on request params and config
1144 // The way that this relies on $wgRequest to propagate request params is slightly evil
1145 $media = OutputPage
::transformCssMedia( $media );
1147 if ( $media === '' ||
$media == 'all' ) {
1149 } elseif ( is_string( $media ) ) {
1150 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1160 * Returns a JS call to mw.loader.state, which sets the state of a
1161 * module or modules to a given value. Has two calling conventions:
1163 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1164 * Set the state of a single module called $name to $state
1166 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1167 * Set the state of modules with the given names to the given states
1169 * @param string $name
1170 * @param string $state
1173 public static function makeLoaderStateScript( $name, $state = null ) {
1174 if ( is_array( $name ) ) {
1175 return Xml
::encodeJsCall(
1178 ResourceLoader
::inDebugMode()
1181 return Xml
::encodeJsCall(
1183 array( $name, $state ),
1184 ResourceLoader
::inDebugMode()
1190 * Returns JS code which calls the script given by $script. The script will
1191 * be called with local variables name, version, dependencies and group,
1192 * which will have values corresponding to $name, $version, $dependencies
1193 * and $group as supplied.
1195 * @param string $name Module name
1196 * @param int $version Module version number as a timestamp
1197 * @param array $dependencies List of module names on which this module depends
1198 * @param string $group Group which the module is in.
1199 * @param string $source Source of the module, or 'local' if not foreign.
1200 * @param string $script JavaScript code
1203 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1204 $group, $source, $script
1206 $script = str_replace( "\n", "\n\t", trim( $script ) );
1207 return Xml
::encodeJsCall(
1208 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1209 array( $name, $version, $dependencies, $group, $source ),
1210 ResourceLoader
::inDebugMode()
1214 private static function isEmptyObject( stdClass
$obj ) {
1215 foreach ( $obj as $key => &$value ) {
1222 * Remove empty values from the end of an array.
1224 * Values considered empty:
1228 * - new XmlJsCode( '{}' )
1229 * - new stdClass() // (object) array()
1231 * @param Array $array
1233 private static function trimArray( Array &$array ) {
1234 $i = count( $array );
1236 if ( $array[$i] === null
1237 ||
$array[$i] === array()
1238 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1239 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1241 unset( $array[$i] );
1249 * Returns JS code which calls mw.loader.register with the given
1250 * parameters. Has three calling conventions:
1252 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1253 * $dependencies, $group, $source, $skip
1255 * Register a single module.
1257 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1258 * Register modules with the given names.
1260 * - ResourceLoader::makeLoaderRegisterScript( array(
1261 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1262 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1265 * Registers modules with the given names and parameters.
1267 * @param string $name Module name
1268 * @param int $version Module version number as a timestamp
1269 * @param array $dependencies List of module names on which this module depends
1270 * @param string $group Group which the module is in
1271 * @param string $source Source of the module, or 'local' if not foreign
1272 * @param string $skip Script body of the skip function
1275 public static function makeLoaderRegisterScript( $name, $version = null,
1276 $dependencies = null, $group = null, $source = null, $skip = null
1278 if ( is_array( $name ) ) {
1279 // Build module name index
1281 foreach ( $name as $i => &$module ) {
1282 $index[$module[0]] = $i;
1285 // Transform dependency names into indexes when possible, they will be resolved by
1286 // mw.loader.register on the other end
1287 foreach ( $name as &$module ) {
1288 if ( isset( $module[2] ) ) {
1289 foreach ( $module[2] as &$dependency ) {
1290 if ( isset( $index[$dependency] ) ) {
1291 $dependency = $index[$dependency];
1297 array_walk( $name, array( 'self', 'trimArray' ) );
1299 return Xml
::encodeJsCall(
1300 'mw.loader.register',
1302 ResourceLoader
::inDebugMode()
1305 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1306 self
::trimArray( $registration );
1307 return Xml
::encodeJsCall(
1308 'mw.loader.register',
1310 ResourceLoader
::inDebugMode()
1316 * Returns JS code which calls mw.loader.addSource() with the given
1317 * parameters. Has two calling conventions:
1319 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1320 * Register a single source
1322 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1323 * Register sources with the given IDs and properties.
1325 * @param string $id Source ID
1326 * @param array $properties Source properties (see addSource())
1329 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1330 if ( is_array( $id ) ) {
1331 return Xml
::encodeJsCall(
1332 'mw.loader.addSource',
1334 ResourceLoader
::inDebugMode()
1337 return Xml
::encodeJsCall(
1338 'mw.loader.addSource',
1339 array( $id, $properties ),
1340 ResourceLoader
::inDebugMode()
1346 * Returns JS code which runs given JS code if the client-side framework is
1349 * @param string $script JavaScript code
1352 public static function makeLoaderConditionalScript( $script ) {
1353 return "if(window.mw){\n" . trim( $script ) . "\n}";
1357 * Returns JS code which will set the MediaWiki configuration array to
1360 * @param array $configuration List of configuration values keyed by variable name
1363 public static function makeConfigSetScript( array $configuration ) {
1364 return Xml
::encodeJsCall(
1366 array( $configuration ),
1367 ResourceLoader
::inDebugMode()
1372 * Convert an array of module names to a packed query string.
1374 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1375 * becomes 'foo.bar,baz|bar.baz,quux'
1376 * @param array $modules List of module names (strings)
1377 * @return string Packed query string
1379 public static function makePackedModulesString( $modules ) {
1380 $groups = array(); // array( prefix => array( suffixes ) )
1381 foreach ( $modules as $module ) {
1382 $pos = strrpos( $module, '.' );
1383 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1384 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1385 $groups[$prefix][] = $suffix;
1389 foreach ( $groups as $prefix => $suffixes ) {
1390 $p = $prefix === '' ?
'' : $prefix . '.';
1391 $arr[] = $p . implode( ',', $suffixes );
1393 $str = implode( '|', $arr );
1398 * Determine whether debug mode was requested
1399 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1402 public static function inDebugMode() {
1403 if ( self
::$debugMode === null ) {
1404 global $wgRequest, $wgResourceLoaderDebug;
1405 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1406 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1409 return self
::$debugMode;
1413 * Reset static members used for caching.
1415 * Global state and $wgRequest are evil, but we're using it right
1416 * now and sometimes we need to be able to force ResourceLoader to
1417 * re-evaluate the context because it has changed (e.g. in the test suite).
1419 public static function clearCache() {
1420 self
::$debugMode = null;
1424 * Build a load.php URL
1427 * @param string $source Name of the ResourceLoader source
1428 * @param ResourceLoaderContext $context
1429 * @param array $extraQuery
1430 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1432 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1433 $extraQuery = array()
1435 $query = self
::createLoaderQuery( $context, $extraQuery );
1436 $script = $this->getLoadScript( $source );
1438 // Prevent the IE6 extension check from being triggered (bug 28840)
1439 // by appending a character that's invalid in Windows extensions ('*')
1440 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1444 * Build a load.php URL
1445 * @deprecated since 1.24, use createLoaderURL instead
1446 * @param array $modules Array of module names (strings)
1447 * @param string $lang Language code
1448 * @param string $skin Skin name
1449 * @param string|null $user User name. If null, the &user= parameter is omitted
1450 * @param string|null $version Versioning timestamp
1451 * @param bool $debug Whether the request should be in debug mode
1452 * @param string|null $only &only= parameter
1453 * @param bool $printable Printable mode
1454 * @param bool $handheld Handheld mode
1455 * @param array $extraQuery Extra query parameters to add
1456 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1458 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1459 $version = null, $debug = false, $only = null, $printable = false,
1460 $handheld = false, $extraQuery = array()
1462 global $wgLoadScript;
1464 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1465 $only, $printable, $handheld, $extraQuery
1468 // Prevent the IE6 extension check from being triggered (bug 28840)
1469 // by appending a character that's invalid in Windows extensions ('*')
1470 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1474 * Helper for createLoaderURL()
1477 * @see makeLoaderQuery
1478 * @param ResourceLoaderContext $context
1479 * @param array $extraQuery
1482 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1483 return self
::makeLoaderQuery(
1484 $context->getModules(),
1485 $context->getLanguage(),
1486 $context->getSkin(),
1487 $context->getUser(),
1488 $context->getVersion(),
1489 $context->getDebug(),
1490 $context->getOnly(),
1491 $context->getRequest()->getBool( 'printable' ),
1492 $context->getRequest()->getBool( 'handheld' ),
1498 * Build a query array (array representation of query string) for load.php. Helper
1499 * function for makeLoaderURL().
1501 * @param array $modules
1502 * @param string $lang
1503 * @param string $skin
1504 * @param string $user
1505 * @param string $version
1506 * @param bool $debug
1507 * @param string $only
1508 * @param bool $printable
1509 * @param bool $handheld
1510 * @param array $extraQuery
1514 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1515 $version = null, $debug = false, $only = null, $printable = false,
1516 $handheld = false, $extraQuery = array()
1519 'modules' => self
::makePackedModulesString( $modules ),
1522 'debug' => $debug ?
'true' : 'false',
1524 if ( $user !== null ) {
1525 $query['user'] = $user;
1527 if ( $version !== null ) {
1528 $query['version'] = $version;
1530 if ( $only !== null ) {
1531 $query['only'] = $only;
1534 $query['printable'] = 1;
1537 $query['handheld'] = 1;
1539 $query +
= $extraQuery;
1541 // Make queries uniform in order
1547 * Check a module name for validity.
1549 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1550 * at most 255 bytes.
1552 * @param string $moduleName Module name to check
1553 * @return bool Whether $moduleName is a valid module name
1555 public static function isValidModuleName( $moduleName ) {
1556 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1560 * Returns LESS compiler set up for use with MediaWiki
1562 * @param Config $config
1563 * @throws MWException
1567 public static function getLessCompiler( Config
$config ) {
1568 // When called from the installer, it is possible that a required PHP extension
1569 // is missing (at least for now; see bug 47564). If this is the case, throw an
1570 // exception (caught by the installer) to prevent a fatal error later on.
1571 if ( !class_exists( 'lessc' ) ) {
1572 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1574 if ( !function_exists( 'ctype_digit' ) ) {
1575 throw new MWException( 'lessc requires the Ctype extension' );
1578 $less = new lessc();
1579 $less->setPreserveComments( true );
1580 $less->setVariables( self
::getLessVars( $config ) );
1581 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1582 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1583 $less->registerFunction( $name, $func );
1589 * Get global LESS variables.
1591 * @param Config $config
1593 * @return array Map of variable names to string CSS values.
1595 public static function getLessVars( Config
$config ) {
1596 if ( !self
::$lessVars ) {
1597 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1598 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1599 // Sort by key to ensure consistent hashing for cache lookups.
1601 self
::$lessVars = $lessVars;
1603 return self
::$lessVars;