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 * Module name/ResourceLoaderModule object pairs
42 protected $modules = array();
45 * Associative array mapping module name to info associative array
48 protected $moduleInfos = array();
50 /** @var Config $config */
54 * Associative array mapping framework ids to a list of names of test suite modules
55 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
58 protected $testModuleNames = array();
61 * E.g. array( 'source-id' => 'http://.../load.php' )
64 protected $sources = array();
67 * Errors accumulated during current respond() call.
70 protected $errors = array();
73 * Load information stored in the database about modules.
75 * This method grabs modules dependencies from the database and updates modules
78 * This is not inside the module code because it is much faster to
79 * request all of the information at once than it is to have each module
80 * requests its own information. This sacrifice of modularity yields a substantial
81 * performance improvement.
83 * @param array $modules List of module names to preload information for
84 * @param ResourceLoaderContext $context Context to load the information within
86 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
87 if ( !count( $modules ) ) {
88 // Or else Database*::select() will explode, plus it's cheaper!
91 $dbr = wfGetDB( DB_SLAVE
);
92 $skin = $context->getSkin();
93 $lang = $context->getLanguage();
95 // Get file dependency information
96 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
97 'md_module' => $modules,
102 // Set modules' dependencies
103 $modulesWithDeps = array();
104 foreach ( $res as $row ) {
105 $module = $this->getModule( $row->md_module
);
107 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
108 $modulesWithDeps[] = $row->md_module
;
112 // Register the absence of a dependency row too
113 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
114 $module = $this->getModule( $name );
116 $this->getModule( $name )->setFileDependencies( $skin, array() );
120 // Get message blob mtimes. Only do this for modules with messages
121 $modulesWithMessages = array();
122 foreach ( $modules as $name ) {
123 $module = $this->getModule( $name );
124 if ( $module && count( $module->getMessages() ) ) {
125 $modulesWithMessages[] = $name;
128 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
129 if ( count( $modulesWithMessages ) ) {
130 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
131 'mr_resource' => $modulesWithMessages,
135 foreach ( $res as $row ) {
136 $module = $this->getModule( $row->mr_resource
);
138 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
139 unset( $modulesWithoutMessages[$row->mr_resource
] );
143 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
144 $module = $this->getModule( $name );
146 $module->setMsgBlobMtime( $lang, 1 );
152 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
154 * Available filters are:
156 * - minify-js \see JavaScriptMinifier::minify
157 * - minify-css \see CSSMin::minify
159 * If $data is empty, only contains whitespace or the filter was unknown,
160 * $data is returned unmodified.
162 * @param string $filter Name of filter to run
163 * @param string $data Text to filter, such as JavaScript or CSS text
164 * @param string $cacheReport Whether to include the cache key report
165 * @return string Filtered data, or a comment containing an error message
167 public function filter( $filter, $data, $cacheReport = true ) {
169 // For empty/whitespace-only data or for unknown filters, don't perform
170 // any caching or processing
171 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
176 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
177 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
178 $cache = wfGetCache( CACHE_ANYTHING
);
179 $cacheEntry = $cache->get( $key );
180 if ( is_string( $cacheEntry ) ) {
181 wfIncrStats( "rl-$filter-cache-hits" );
186 // Run the filter - we've already verified one of these will work
188 wfIncrStats( "rl-$filter-cache-misses" );
191 $result = JavaScriptMinifier
::minify( $data,
192 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
193 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
195 if ( $cacheReport ) {
196 $result .= "\n/* cache key: $key */";
200 $result = CSSMin
::minify( $data );
201 if ( $cacheReport ) {
202 $result .= "\n/* cache key: $key */";
207 // Save filtered text to Memcached
208 $cache->set( $key, $result );
209 } catch ( Exception
$e ) {
210 MWExceptionHandler
::logException( $e );
211 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
212 $this->errors
[] = self
::formatExceptionNoComment( $e );
221 * Register core modules and runs registration hooks.
222 * @param Config|null $config
224 public function __construct( Config
$config = null ) {
227 if ( $config === null ) {
228 wfDebug( __METHOD__
. ' was called without providing a Config instance' );
229 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
232 $this->config
= $config;
234 // Add 'local' source first
235 $this->addSource( 'local', wfScript( 'load' ) );
238 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
240 // Register core modules
241 $this->register( include "$IP/resources/Resources.php" );
242 // Register extension modules
243 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
244 $this->register( $config->get( 'ResourceModules' ) );
246 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
247 $this->registerTestModules();
255 public function getConfig() {
256 return $this->config
;
260 * Register a module with the ResourceLoader system.
262 * @param mixed $name Name of module as a string or List of name/object pairs as an array
263 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
264 * this may also be a ResourceLoaderModule object. Optional when using
265 * multiple-registration calling style.
266 * @throws MWException If a duplicate module registration is attempted
267 * @throws MWException If a module name contains illegal characters (pipes or commas)
268 * @throws MWException If something other than a ResourceLoaderModule is being registered
269 * @return bool False if there were any errors, in which case one or more modules were
272 public function register( $name, $info = null ) {
274 // Allow multiple modules to be registered in one call
275 $registrations = is_array( $name ) ?
$name : array( $name => $info );
276 foreach ( $registrations as $name => $info ) {
277 // Disallow duplicate registrations
278 if ( isset( $this->moduleInfos
[$name] ) ) {
279 // A module has already been registered by this name
280 throw new MWException(
281 'ResourceLoader duplicate registration error. ' .
282 'Another module has already been registered as ' . $name
286 // Check $name for validity
287 if ( !self
::isValidModuleName( $name ) ) {
288 throw new MWException( "ResourceLoader module name '$name' is invalid, "
289 . "see ResourceLoader::isValidModuleName()" );
293 if ( $info instanceof ResourceLoaderModule
) {
294 $this->moduleInfos
[$name] = array( 'object' => $info );
295 $info->setName( $name );
296 $this->modules
[$name] = $info;
297 } elseif ( is_array( $info ) ) {
298 // New calling convention
299 $this->moduleInfos
[$name] = $info;
301 throw new MWException(
302 'ResourceLoader module info type error for module \'' . $name .
303 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
307 // Last-minute changes
309 // Apply custom skin-defined styles to existing modules.
310 if ( $this->isFileModule( $name ) ) {
311 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
312 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
313 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
317 // If $name is preceded with a '+', the defined style files will be added to 'default'
318 // skinStyles, otherwise 'default' will be ignored as it normally would be.
319 if ( isset( $skinStyles[$name] ) ) {
320 $paths = (array)$skinStyles[$name];
321 $styleFiles = array();
322 } elseif ( isset( $skinStyles['+' . $name] ) ) {
323 $paths = (array)$skinStyles['+' . $name];
324 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
325 $this->moduleInfos
[$name]['skinStyles']['default'] :
331 // Add new file paths, remapping them to refer to our directories and not use settings
332 // from the module we're modifying. These can come from the base definition or be defined
334 list( $localBasePath, $remoteBasePath ) =
335 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
336 list( $localBasePath, $remoteBasePath ) =
337 ResourceLoaderFileModule
::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
339 foreach ( $paths as $path ) {
340 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
343 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
352 public function registerTestModules() {
355 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
356 throw new MWException( 'Attempt to register JavaScript test modules '
357 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
358 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
361 // Get core test suites
362 $testModules = array();
363 $testModules['qunit'] = array();
364 // Get other test suites (e.g. from extensions)
365 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
367 // Add the testrunner (which configures QUnit) to the dependencies.
368 // Since it must be ready before any of the test suites are executed.
369 foreach ( $testModules['qunit'] as &$module ) {
370 // Make sure all test modules are top-loading so that when QUnit starts
371 // on document-ready, it will run once and finish. If some tests arrive
372 // later (possibly after QUnit has already finished) they will be ignored.
373 $module['position'] = 'top';
374 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
377 $testModules['qunit'] =
378 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
380 foreach ( $testModules as $id => $names ) {
381 // Register test modules
382 $this->register( $testModules[$id] );
384 // Keep track of their names so that they can be loaded together
385 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
391 * Add a foreign source of modules.
393 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
394 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
395 * backwards-compatibility.
396 * @throws MWException
398 public function addSource( $id, $loadUrl = null ) {
399 // Allow multiple sources to be registered in one call
400 if ( is_array( $id ) ) {
401 foreach ( $id as $key => $value ) {
402 $this->addSource( $key, $value );
407 // Disallow duplicates
408 if ( isset( $this->sources
[$id] ) ) {
409 throw new MWException(
410 'ResourceLoader duplicate source addition error. ' .
411 'Another source has already been registered as ' . $id
415 // Pre 1.24 backwards-compatibility
416 if ( is_array( $loadUrl ) ) {
417 if ( !isset( $loadUrl['loadScript'] ) ) {
418 throw new MWException(
419 __METHOD__
. ' was passed an array with no "loadScript" key.'
423 $loadUrl = $loadUrl['loadScript'];
426 $this->sources
[$id] = $loadUrl;
430 * Get a list of module names.
432 * @return array List of module names
434 public function getModuleNames() {
435 return array_keys( $this->moduleInfos
);
439 * Get a list of test module names for one (or all) frameworks.
441 * If the given framework id is unknkown, or if the in-object variable is not an array,
442 * then it will return an empty array.
444 * @param string $framework Get only the test module names for one
445 * particular framework (optional)
448 public function getTestModuleNames( $framework = 'all' ) {
449 /** @todo api siteinfo prop testmodulenames modulenames */
450 if ( $framework == 'all' ) {
451 return $this->testModuleNames
;
452 } elseif ( isset( $this->testModuleNames
[$framework] )
453 && is_array( $this->testModuleNames
[$framework] )
455 return $this->testModuleNames
[$framework];
462 * Get the ResourceLoaderModule object for a given module name.
464 * If an array of module parameters exists but a ResourceLoaderModule object has not
465 * yet been instantiated, this method will instantiate and cache that object such that
466 * subsequent calls simply return the same object.
468 * @param string $name Module name
469 * @return ResourceLoaderModule|null If module has been registered, return a
470 * ResourceLoaderModule instance. Otherwise, return null.
472 public function getModule( $name ) {
473 if ( !isset( $this->modules
[$name] ) ) {
474 if ( !isset( $this->moduleInfos
[$name] ) ) {
478 // Construct the requested object
479 $info = $this->moduleInfos
[$name];
480 /** @var ResourceLoaderModule $object */
481 if ( isset( $info['object'] ) ) {
482 // Object given in info array
483 $object = $info['object'];
485 if ( !isset( $info['class'] ) ) {
486 $class = 'ResourceLoaderFileModule';
488 $class = $info['class'];
490 /** @var ResourceLoaderModule $object */
491 $object = new $class( $info );
492 $object->setConfig( $this->getConfig() );
494 $object->setName( $name );
495 $this->modules
[$name] = $object;
498 return $this->modules
[$name];
502 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
504 * @param string $name Module name
507 protected function isFileModule( $name ) {
508 if ( !isset( $this->moduleInfos
[$name] ) ) {
511 $info = $this->moduleInfos
[$name];
512 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
519 * Get the list of sources.
521 * @return array Like array( id => load.php url, .. )
523 public function getSources() {
524 return $this->sources
;
528 * Get the URL to the load.php endpoint for the given
529 * ResourceLoader source
532 * @param string $source
533 * @throws MWException On an invalid $source name
536 public function getLoadScript( $source ) {
537 if ( !isset( $this->sources
[$source] ) ) {
538 throw new MWException( "The $source source was never registered in ResourceLoader." );
540 return $this->sources
[$source];
544 * Output a response to a load request, including the content-type header.
546 * @param ResourceLoaderContext $context Context in which a response should be formed
548 public function respond( ResourceLoaderContext
$context ) {
549 // Use file cache if enabled and available...
550 if ( $this->config
->get( 'UseFileCache' ) ) {
551 $fileCache = ResourceFileCache
::newFromContext( $context );
552 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
553 return; // output handled
557 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
558 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
559 // is used: ob_clean() will clear the GZIP header in that case and it won't come
560 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
561 // the whole thing in our own output buffer to be sure the active buffer
562 // doesn't use ob_gzhandler.
563 // See http://bugs.php.net/bug.php?id=36514
566 // Find out which modules are missing and instantiate the others
569 foreach ( $context->getModules() as $name ) {
570 $module = $this->getModule( $name );
572 // Do not allow private modules to be loaded from the web.
573 // This is a security issue, see bug 34907.
574 if ( $module->getGroup() === 'private' ) {
575 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
576 $this->errors
[] = "Cannot show private module \"$name\"";
579 $modules[$name] = $module;
585 // Preload information needed to the mtime calculation below
587 $this->preloadModuleInfo( array_keys( $modules ), $context );
588 } catch ( Exception
$e ) {
589 MWExceptionHandler
::logException( $e );
590 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
591 $this->errors
[] = self
::formatExceptionNoComment( $e );
594 // To send Last-Modified and support If-Modified-Since, we need to detect
595 // the last modified time
596 $mtime = wfTimestamp( TS_UNIX
, $this->config
->get( 'CacheEpoch' ) );
597 foreach ( $modules as $module ) {
599 * @var $module ResourceLoaderModule
602 // Calculate maximum modified time
603 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
604 } catch ( Exception
$e ) {
605 MWExceptionHandler
::logException( $e );
606 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
607 $this->errors
[] = self
::formatExceptionNoComment( $e );
611 // If there's an If-Modified-Since header, respond with a 304 appropriately
612 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
613 return; // output handled (buffers cleared)
616 // Generate a response
617 $response = $this->makeModuleResponse( $context, $modules, $missing );
619 // Capture any PHP warnings from the output buffer and append them to the
620 // error list if we're in debug mode.
621 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
622 $this->errors
[] = $warnings;
625 // Save response to file cache unless there are errors
626 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
627 // Cache single modules and images...and other requests if there are enough hits
628 if ( ResourceFileCache
::useFileCache( $context ) ) {
629 if ( $fileCache->isCacheWorthy() ) {
630 $fileCache->saveText( $response );
632 $fileCache->incrMissesRecent( $context->getRequest() );
637 // Send content type and cache related headers
638 $this->sendResponseHeaders( $context, $mtime, (bool)$this->errors
);
640 // Remove the output buffer and output the response
643 if ( $context->getImageObj() && $this->errors
) {
644 // We can't show both the error messages and the response when it's an image.
646 foreach ( $this->errors
as $error ) {
647 $errorText .= $error . "\n";
649 $response = $errorText;
650 } elseif ( $this->errors
) {
651 // Prepend comments indicating errors
653 foreach ( $this->errors
as $error ) {
654 $errorText .= self
::makeComment( $error );
656 $response = $errorText . $response;
659 $this->errors
= array();
665 * Send content type and last modified headers to the client.
666 * @param ResourceLoaderContext $context
667 * @param string $mtime TS_MW timestamp to use for last-modified
668 * @param bool $errors Whether there are errors in the response
671 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
672 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
673 // If a version wasn't specified we need a shorter expiry time for updates
674 // to propagate to clients quickly
675 // If there were errors, we also need a shorter expiry time so we can recover quickly
676 if ( is_null( $context->getVersion() ) ||
$errors ) {
677 $maxage = $rlMaxage['unversioned']['client'];
678 $smaxage = $rlMaxage['unversioned']['server'];
679 // If a version was specified we can use a longer expiry time since changing
680 // version numbers causes cache misses
682 $maxage = $rlMaxage['versioned']['client'];
683 $smaxage = $rlMaxage['versioned']['server'];
685 if ( $context->getImageObj() ) {
686 // Output different headers if we're outputting textual errors.
688 header( 'Content-Type: text/plain; charset=utf-8' );
690 $context->getImageObj()->sendResponseHeaders( $context );
692 } elseif ( $context->getOnly() === 'styles' ) {
693 header( 'Content-Type: text/css; charset=utf-8' );
694 header( 'Access-Control-Allow-Origin: *' );
696 header( 'Content-Type: text/javascript; charset=utf-8' );
698 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
699 if ( $context->getDebug() ) {
700 // Do not cache debug responses
701 header( 'Cache-Control: private, no-cache, must-revalidate' );
702 header( 'Pragma: no-cache' );
704 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
705 $exp = min( $maxage, $smaxage );
706 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
711 * Respond with 304 Last Modified if appropiate.
713 * If there's an If-Modified-Since header, respond with a 304 appropriately
714 * and clear out the output buffer. If the client cache is too old then do nothing.
716 * @param ResourceLoaderContext $context
717 * @param string $mtime The TS_MW timestamp to check the header against
718 * @return bool True if 304 header sent and output handled
720 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
721 // If there's an If-Modified-Since header, respond with a 304 appropriately
722 // Some clients send "timestamp;length=123". Strip the part after the first ';'
723 // so we get a valid timestamp.
724 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
725 // Never send 304s in debug mode
726 if ( $ims !== false && !$context->getDebug() ) {
727 $imsTS = strtok( $ims, ';' );
728 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
729 // There's another bug in ob_gzhandler (see also the comment at
730 // the top of this function) that causes it to gzip even empty
731 // responses, meaning it's impossible to produce a truly empty
732 // response (because the gzip header is always there). This is
733 // a problem because 304 responses have to be completely empty
734 // per the HTTP spec, and Firefox behaves buggily when they're not.
735 // See also http://bugs.php.net/bug.php?id=51579
736 // To work around this, we tear down all output buffering before
738 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
740 header( 'HTTP/1.0 304 Not Modified' );
741 header( 'Status: 304 Not Modified' );
749 * Send out code for a response from file cache if possible.
751 * @param ResourceFileCache $fileCache Cache object for this request URL
752 * @param ResourceLoaderContext $context Context in which to generate a response
753 * @return bool If this found a cache file and handled the response
755 protected function tryRespondFromFileCache(
756 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
758 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
759 // Buffer output to catch warnings.
761 // Get the maximum age the cache can be
762 $maxage = is_null( $context->getVersion() )
763 ?
$rlMaxage['unversioned']['server']
764 : $rlMaxage['versioned']['server'];
765 // Minimum timestamp the cache file must have
766 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
768 try { // RL always hits the DB on file cache miss...
770 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
771 $good = $fileCache->isCacheGood(); // cache existence check
775 $ts = $fileCache->cacheTimestamp();
776 // Send content type and cache headers
777 $this->sendResponseHeaders( $context, $ts, false );
778 // If there's an If-Modified-Since header, respond with a 304 appropriately
779 if ( $this->tryRespondLastModified( $context, $ts ) ) {
780 return false; // output handled (buffers cleared)
782 $response = $fileCache->fetchText();
783 // Capture any PHP warnings from the output buffer and append them to the
784 // response in a comment if we're in debug mode.
785 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
786 $response = "/*\n$warnings\n*/\n" . $response;
788 // Remove the output buffer and output the response
790 echo $response . "\n/* Cached {$ts} */";
791 return true; // cache hit
796 return false; // cache miss
800 * Generate a CSS or JS comment block.
802 * Only use this for public data, not error message details.
804 * @param string $text
807 public static function makeComment( $text ) {
808 $encText = str_replace( '*/', '* /', $text );
809 return "/*\n$encText\n*/\n";
813 * Handle exception display.
815 * @param Exception $e Exception to be shown to the user
816 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
818 public static function formatException( $e ) {
819 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
823 * Handle exception display.
826 * @param Exception $e Exception to be shown to the user
827 * @return string Sanitized text that can be returned to the user
829 protected static function formatExceptionNoComment( $e ) {
830 global $wgShowExceptionDetails;
832 if ( $wgShowExceptionDetails ) {
833 return $e->__toString();
835 return wfMessage( 'internalerror' )->text();
840 * Generate code for a response.
842 * @param ResourceLoaderContext $context Context in which to generate a response
843 * @param array $modules List of module objects keyed by module name
844 * @param array $missing List of requested module names that are unregistered (optional)
845 * @return string Response data
847 public function makeModuleResponse( ResourceLoaderContext
$context,
848 array $modules, array $missing = array()
853 if ( !count( $modules ) && !count( $missing ) ) {
854 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
855 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
856 no modules were requested. Max made me put this here. */";
859 $image = $context->getImageObj();
861 $data = $image->getImageData( $context );
862 if ( $data === false ) {
864 $this->errors
[] = 'Image generation failed';
870 if ( $context->shouldIncludeMessages() ) {
872 $blobs = MessageBlobStore
::getInstance()->get( $this, $modules, $context->getLanguage() );
873 } catch ( Exception
$e ) {
874 MWExceptionHandler
::logException( $e );
877 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
879 $this->errors
[] = self
::formatExceptionNoComment( $e );
885 foreach ( $missing as $name ) {
886 $states[$name] = 'missing';
891 foreach ( $modules as $name => $module ) {
893 * @var $module ResourceLoaderModule
898 if ( $context->shouldIncludeScripts() ) {
899 // If we are in debug mode, we'll want to return an array of URLs if possible
900 // However, we can't do this if the module doesn't support it
901 // We also can't do this if there is an only= parameter, because we have to give
902 // the module a way to return a load.php URL without causing an infinite loop
903 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
904 $scripts = $module->getScriptURLsForDebug( $context );
906 $scripts = $module->getScript( $context );
907 // rtrim() because there are usually a few line breaks
908 // after the last ';'. A new line at EOF, a new line
909 // added by ResourceLoaderFileModule::readScriptFiles, etc.
910 if ( is_string( $scripts )
911 && strlen( $scripts )
912 && substr( rtrim( $scripts ), -1 ) !== ';'
914 // Append semicolon to prevent weird bugs caused by files not
915 // terminating their statements right (bug 27054)
922 if ( $context->shouldIncludeStyles() ) {
923 // Don't create empty stylesheets like array( '' => '' ) for modules
924 // that don't *have* any stylesheets (bug 38024).
925 $stylePairs = $module->getStyles( $context );
926 if ( count( $stylePairs ) ) {
927 // If we are in debug mode without &only= set, we'll want to return an array of URLs
928 // See comment near shouldIncludeScripts() for more details
929 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
931 'url' => $module->getStyleURLsForDebug( $context )
934 // Minify CSS before embedding in mw.loader.implement call
935 // (unless in debug mode)
936 if ( !$context->getDebug() ) {
937 foreach ( $stylePairs as $media => $style ) {
938 // Can be either a string or an array of strings.
939 if ( is_array( $style ) ) {
940 $stylePairs[$media] = array();
941 foreach ( $style as $cssText ) {
942 if ( is_string( $cssText ) ) {
943 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
946 } elseif ( is_string( $style ) ) {
947 $stylePairs[$media] = $this->filter( 'minify-css', $style );
951 // Wrap styles into @media groups as needed and flatten into a numerical array
953 'css' => self
::makeCombinedStyles( $stylePairs )
960 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
963 switch ( $context->getOnly() ) {
965 if ( is_string( $scripts ) ) {
966 // Load scripts raw...
968 } elseif ( is_array( $scripts ) ) {
969 // ...except when $scripts is an array of URLs
970 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
974 // We no longer seperate into media, they are all combined now with
975 // custom media type groups into @media .. {} sections as part of the css string.
976 // Module returns either an empty array or a numerical array with css strings.
977 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
980 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
983 $out .= Xml
::encodeJsCall(
985 array( $name, (object)$module->getTemplates() ),
986 ResourceLoader
::inDebugMode()
990 $out .= self
::makeLoaderImplementScript(
994 new XmlJsCode( $messagesBlob ),
995 $module->getTemplates()
999 } catch ( Exception
$e ) {
1000 MWExceptionHandler
::logException( $e );
1001 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
1002 $this->errors
[] = self
::formatExceptionNoComment( $e );
1004 // Respond to client with error-state instead of module implementation
1005 $states[$name] = 'error';
1006 unset( $modules[$name] );
1008 $isRaw |
= $module->isRaw();
1011 // Update module states
1012 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1013 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1014 // Set the state of modules loaded as only scripts to ready as
1015 // they don't have an mw.loader.implement wrapper that sets the state
1016 foreach ( $modules as $name => $module ) {
1017 $states[$name] = 'ready';
1021 // Set the state of modules we didn't respond to with mw.loader.implement
1022 if ( count( $states ) ) {
1023 $out .= self
::makeLoaderStateScript( $states );
1026 if ( count( $states ) ) {
1027 $this->errors
[] = 'Problematic modules: ' .
1028 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1032 if ( !$context->getDebug() ) {
1033 if ( $context->getOnly() === 'styles' ) {
1034 $out = $this->filter( 'minify-css', $out );
1036 $out = $this->filter( 'minify-js', $out );
1043 /* Static Methods */
1046 * Return JS code that calls mw.loader.implement with given module properties.
1048 * @param string $name Module name
1049 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1050 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1051 * to CSS files keyed by media type
1052 * @param mixed $messages List of messages associated with this module. May either be an
1053 * associative array mapping message key to value, or a JSON-encoded message blob containing
1054 * the same data, wrapped in an XmlJsCode object.
1055 * @param array $templates Keys are name of templates and values are the source of
1057 * @throws MWException
1060 public static function makeLoaderImplementScript( $name, $scripts, $styles,
1061 $messages, $templates
1063 if ( is_string( $scripts ) ) {
1064 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1065 } elseif ( !is_array( $scripts ) ) {
1066 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1069 return Xml
::encodeJsCall(
1070 'mw.loader.implement',
1074 // Force objects. mw.loader.implement requires them to be javascript objects.
1075 // Although these variables are associative arrays, which become javascript
1076 // objects through json_encode. In many cases they will be empty arrays, and
1077 // PHP/json_encode() consider empty arrays to be numerical arrays and
1078 // output javascript "[]" instead of "{}". This fixes that.
1083 ResourceLoader
::inDebugMode()
1088 * Returns JS code which, when called, will register a given list of messages.
1090 * @param mixed $messages Either an associative array mapping message key to value, or a
1091 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1094 public static function makeMessageSetScript( $messages ) {
1095 return Xml
::encodeJsCall(
1097 array( (object)$messages ),
1098 ResourceLoader
::inDebugMode()
1103 * Combines an associative array mapping media type to CSS into a
1104 * single stylesheet with "@media" blocks.
1106 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1109 public static function makeCombinedStyles( array $stylePairs ) {
1111 foreach ( $stylePairs as $media => $styles ) {
1112 // ResourceLoaderFileModule::getStyle can return the styles
1113 // as a string or an array of strings. This is to allow separation in
1115 $styles = (array)$styles;
1116 foreach ( $styles as $style ) {
1117 $style = trim( $style );
1118 // Don't output an empty "@media print { }" block (bug 40498)
1119 if ( $style !== '' ) {
1120 // Transform the media type based on request params and config
1121 // The way that this relies on $wgRequest to propagate request params is slightly evil
1122 $media = OutputPage
::transformCssMedia( $media );
1124 if ( $media === '' ||
$media == 'all' ) {
1126 } elseif ( is_string( $media ) ) {
1127 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1137 * Returns a JS call to mw.loader.state, which sets the state of a
1138 * module or modules to a given value. Has two calling conventions:
1140 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1141 * Set the state of a single module called $name to $state
1143 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1144 * Set the state of modules with the given names to the given states
1146 * @param string $name
1147 * @param string $state
1150 public static function makeLoaderStateScript( $name, $state = null ) {
1151 if ( is_array( $name ) ) {
1152 return Xml
::encodeJsCall(
1155 ResourceLoader
::inDebugMode()
1158 return Xml
::encodeJsCall(
1160 array( $name, $state ),
1161 ResourceLoader
::inDebugMode()
1167 * Returns JS code which calls the script given by $script. The script will
1168 * be called with local variables name, version, dependencies and group,
1169 * which will have values corresponding to $name, $version, $dependencies
1170 * and $group as supplied.
1172 * @param string $name Module name
1173 * @param int $version Module version number as a timestamp
1174 * @param array $dependencies List of module names on which this module depends
1175 * @param string $group Group which the module is in.
1176 * @param string $source Source of the module, or 'local' if not foreign.
1177 * @param string $script JavaScript code
1180 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1181 $group, $source, $script
1183 $script = str_replace( "\n", "\n\t", trim( $script ) );
1184 return Xml
::encodeJsCall(
1185 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1186 array( $name, $version, $dependencies, $group, $source ),
1187 ResourceLoader
::inDebugMode()
1192 * Remove empty values from the end of an array.
1194 * Values considered empty:
1199 * @param Array $array
1201 private static function trimArray( Array &$array ) {
1202 $i = count( $array );
1204 if ( $array[$i] === null ||
$array[$i] === array() ) {
1205 unset( $array[$i] );
1213 * Returns JS code which calls mw.loader.register with the given
1214 * parameters. Has three calling conventions:
1216 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1217 * $dependencies, $group, $source, $skip
1219 * Register a single module.
1221 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1222 * Register modules with the given names.
1224 * - ResourceLoader::makeLoaderRegisterScript( array(
1225 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1226 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1229 * Registers modules with the given names and parameters.
1231 * @param string $name Module name
1232 * @param int $version Module version number as a timestamp
1233 * @param array $dependencies List of module names on which this module depends
1234 * @param string $group Group which the module is in
1235 * @param string $source Source of the module, or 'local' if not foreign
1236 * @param string $skip Script body of the skip function
1239 public static function makeLoaderRegisterScript( $name, $version = null,
1240 $dependencies = null, $group = null, $source = null, $skip = null
1242 if ( is_array( $name ) ) {
1243 // Build module name index
1245 foreach ( $name as $i => &$module ) {
1246 $index[$module[0]] = $i;
1249 // Transform dependency names into indexes when possible, they will be resolved by
1250 // mw.loader.register on the other end
1251 foreach ( $name as &$module ) {
1252 if ( isset( $module[2] ) ) {
1253 foreach ( $module[2] as &$dependency ) {
1254 if ( isset( $index[$dependency] ) ) {
1255 $dependency = $index[$dependency];
1261 array_walk( $name, array( 'self', 'trimArray' ) );
1263 return Xml
::encodeJsCall(
1264 'mw.loader.register',
1266 ResourceLoader
::inDebugMode()
1269 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1270 self
::trimArray( $registration );
1271 return Xml
::encodeJsCall(
1272 'mw.loader.register',
1274 ResourceLoader
::inDebugMode()
1280 * Returns JS code which calls mw.loader.addSource() with the given
1281 * parameters. Has two calling conventions:
1283 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1284 * Register a single source
1286 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1287 * Register sources with the given IDs and properties.
1289 * @param string $id Source ID
1290 * @param array $properties Source properties (see addSource())
1293 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1294 if ( is_array( $id ) ) {
1295 return Xml
::encodeJsCall(
1296 'mw.loader.addSource',
1298 ResourceLoader
::inDebugMode()
1301 return Xml
::encodeJsCall(
1302 'mw.loader.addSource',
1303 array( $id, $properties ),
1304 ResourceLoader
::inDebugMode()
1310 * Returns JS code which runs given JS code if the client-side framework is
1313 * @param string $script JavaScript code
1316 public static function makeLoaderConditionalScript( $script ) {
1317 return "if(window.mw){\n" . trim( $script ) . "\n}";
1321 * Returns JS code which will set the MediaWiki configuration array to
1324 * @param array $configuration List of configuration values keyed by variable name
1327 public static function makeConfigSetScript( array $configuration ) {
1328 return Xml
::encodeJsCall(
1330 array( $configuration ),
1331 ResourceLoader
::inDebugMode()
1336 * Convert an array of module names to a packed query string.
1338 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1339 * becomes 'foo.bar,baz|bar.baz,quux'
1340 * @param array $modules List of module names (strings)
1341 * @return string Packed query string
1343 public static function makePackedModulesString( $modules ) {
1344 $groups = array(); // array( prefix => array( suffixes ) )
1345 foreach ( $modules as $module ) {
1346 $pos = strrpos( $module, '.' );
1347 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1348 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1349 $groups[$prefix][] = $suffix;
1353 foreach ( $groups as $prefix => $suffixes ) {
1354 $p = $prefix === '' ?
'' : $prefix . '.';
1355 $arr[] = $p . implode( ',', $suffixes );
1357 $str = implode( '|', $arr );
1362 * Determine whether debug mode was requested
1363 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1366 public static function inDebugMode() {
1367 if ( self
::$debugMode === null ) {
1368 global $wgRequest, $wgResourceLoaderDebug;
1369 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1370 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1373 return self
::$debugMode;
1377 * Reset static members used for caching.
1379 * Global state and $wgRequest are evil, but we're using it right
1380 * now and sometimes we need to be able to force ResourceLoader to
1381 * re-evaluate the context because it has changed (e.g. in the test suite).
1383 public static function clearCache() {
1384 self
::$debugMode = null;
1388 * Build a load.php URL
1391 * @param string $source Name of the ResourceLoader source
1392 * @param ResourceLoaderContext $context
1393 * @param array $extraQuery
1394 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1396 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1397 $extraQuery = array()
1399 $query = self
::createLoaderQuery( $context, $extraQuery );
1400 $script = $this->getLoadScript( $source );
1402 // Prevent the IE6 extension check from being triggered (bug 28840)
1403 // by appending a character that's invalid in Windows extensions ('*')
1404 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1408 * Build a load.php URL
1409 * @deprecated since 1.24, use createLoaderURL instead
1410 * @param array $modules Array of module names (strings)
1411 * @param string $lang Language code
1412 * @param string $skin Skin name
1413 * @param string|null $user User name. If null, the &user= parameter is omitted
1414 * @param string|null $version Versioning timestamp
1415 * @param bool $debug Whether the request should be in debug mode
1416 * @param string|null $only &only= parameter
1417 * @param bool $printable Printable mode
1418 * @param bool $handheld Handheld mode
1419 * @param array $extraQuery Extra query parameters to add
1420 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1422 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1423 $version = null, $debug = false, $only = null, $printable = false,
1424 $handheld = false, $extraQuery = array()
1426 global $wgLoadScript;
1428 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1429 $only, $printable, $handheld, $extraQuery
1432 // Prevent the IE6 extension check from being triggered (bug 28840)
1433 // by appending a character that's invalid in Windows extensions ('*')
1434 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1438 * Helper for createLoaderURL()
1441 * @see makeLoaderQuery
1442 * @param ResourceLoaderContext $context
1443 * @param array $extraQuery
1446 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1447 return self
::makeLoaderQuery(
1448 $context->getModules(),
1449 $context->getLanguage(),
1450 $context->getSkin(),
1451 $context->getUser(),
1452 $context->getVersion(),
1453 $context->getDebug(),
1454 $context->getOnly(),
1455 $context->getRequest()->getBool( 'printable' ),
1456 $context->getRequest()->getBool( 'handheld' ),
1462 * Build a query array (array representation of query string) for load.php. Helper
1463 * function for makeLoaderURL().
1465 * @param array $modules
1466 * @param string $lang
1467 * @param string $skin
1468 * @param string $user
1469 * @param string $version
1470 * @param bool $debug
1471 * @param string $only
1472 * @param bool $printable
1473 * @param bool $handheld
1474 * @param array $extraQuery
1478 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1479 $version = null, $debug = false, $only = null, $printable = false,
1480 $handheld = false, $extraQuery = array()
1483 'modules' => self
::makePackedModulesString( $modules ),
1486 'debug' => $debug ?
'true' : 'false',
1488 if ( $user !== null ) {
1489 $query['user'] = $user;
1491 if ( $version !== null ) {
1492 $query['version'] = $version;
1494 if ( $only !== null ) {
1495 $query['only'] = $only;
1498 $query['printable'] = 1;
1501 $query['handheld'] = 1;
1503 $query +
= $extraQuery;
1505 // Make queries uniform in order
1511 * Check a module name for validity.
1513 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1514 * at most 255 bytes.
1516 * @param string $moduleName Module name to check
1517 * @return bool Whether $moduleName is a valid module name
1519 public static function isValidModuleName( $moduleName ) {
1520 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1524 * Returns LESS compiler set up for use with MediaWiki
1526 * @param Config $config
1527 * @throws MWException
1531 public static function getLessCompiler( Config
$config ) {
1532 // When called from the installer, it is possible that a required PHP extension
1533 // is missing (at least for now; see bug 47564). If this is the case, throw an
1534 // exception (caught by the installer) to prevent a fatal error later on.
1535 if ( !class_exists( 'lessc' ) ) {
1536 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1538 if ( !function_exists( 'ctype_digit' ) ) {
1539 throw new MWException( 'lessc requires the Ctype extension' );
1542 $less = new lessc();
1543 $less->setPreserveComments( true );
1544 $less->setVariables( self
::getLessVars( $config ) );
1545 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1546 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1547 $less->registerFunction( $name, $func );
1553 * Get global LESS variables.
1555 * @param Config $config
1557 * @return array Map of variable names to string CSS values.
1559 public static function getLessVars( Config
$config ) {
1560 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1561 // Sort by key to ensure consistent hashing for cache lookups.