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 protected $hasErrors = false;
70 * Load information stored in the database about modules.
72 * This method grabs modules dependencies from the database and updates modules
75 * This is not inside the module code because it is much faster to
76 * request all of the information at once than it is to have each module
77 * requests its own information. This sacrifice of modularity yields a substantial
78 * performance improvement.
80 * @param array $modules List of module names to preload information for
81 * @param ResourceLoaderContext $context Context to load the information within
83 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
84 if ( !count( $modules ) ) {
85 // Or else Database*::select() will explode, plus it's cheaper!
88 $dbr = wfGetDB( DB_SLAVE
);
89 $skin = $context->getSkin();
90 $lang = $context->getLanguage();
92 // Get file dependency information
93 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
94 'md_module' => $modules,
99 // Set modules' dependencies
100 $modulesWithDeps = array();
101 foreach ( $res as $row ) {
102 $module = $this->getModule( $row->md_module
);
104 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
105 $modulesWithDeps[] = $row->md_module
;
109 // Register the absence of a dependency row too
110 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
111 $module = $this->getModule( $name );
113 $this->getModule( $name )->setFileDependencies( $skin, array() );
117 // Get message blob mtimes. Only do this for modules with messages
118 $modulesWithMessages = array();
119 foreach ( $modules as $name ) {
120 $module = $this->getModule( $name );
121 if ( $module && count( $module->getMessages() ) ) {
122 $modulesWithMessages[] = $name;
125 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
126 if ( count( $modulesWithMessages ) ) {
127 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
128 'mr_resource' => $modulesWithMessages,
132 foreach ( $res as $row ) {
133 $module = $this->getModule( $row->mr_resource
);
135 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
136 unset( $modulesWithoutMessages[$row->mr_resource
] );
140 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
141 $module = $this->getModule( $name );
143 $module->setMsgBlobMtime( $lang, 1 );
149 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
151 * Available filters are:
153 * - minify-js \see JavaScriptMinifier::minify
154 * - minify-css \see CSSMin::minify
156 * If $data is empty, only contains whitespace or the filter was unknown,
157 * $data is returned unmodified.
159 * @param string $filter Name of filter to run
160 * @param string $data Text to filter, such as JavaScript or CSS text
161 * @param string $cacheReport Whether to include the cache key report
162 * @return string Filtered data, or a comment containing an error message
164 public function filter( $filter, $data, $cacheReport = true ) {
165 wfProfileIn( __METHOD__
);
167 // For empty/whitespace-only data or for unknown filters, don't perform
168 // any caching or processing
169 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
170 wfProfileOut( __METHOD__
);
175 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
176 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
177 $cache = wfGetCache( CACHE_ANYTHING
);
178 $cacheEntry = $cache->get( $key );
179 if ( is_string( $cacheEntry ) ) {
180 wfIncrStats( "rl-$filter-cache-hits" );
181 wfProfileOut( __METHOD__
);
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->hasErrors
= true;
213 // Return exception as a comment
214 $result = self
::formatException( $e );
217 wfProfileOut( __METHOD__
);
225 * Register core modules and runs registration hooks.
226 * @param Config|null $config
228 public function __construct( Config
$config = null ) {
231 wfProfileIn( __METHOD__
);
233 if ( $config === null ) {
234 wfDebug( __METHOD__
. ' was called without providing a Config instance' );
235 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
238 $this->config
= $config;
240 // Add 'local' source first
241 $this->addSource( 'local', wfScript( 'load' ) );
244 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
246 // Register core modules
247 $this->register( include "$IP/resources/Resources.php" );
248 // Register extension modules
249 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
250 $this->register( $config->get( 'ResourceModules' ) );
252 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
253 $this->registerTestModules();
256 wfProfileOut( __METHOD__
);
262 public function getConfig() {
263 return $this->config
;
267 * Register a module with the ResourceLoader system.
269 * @param mixed $name Name of module as a string or List of name/object pairs as an array
270 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
271 * this may also be a ResourceLoaderModule object. Optional when using
272 * multiple-registration calling style.
273 * @throws MWException If a duplicate module registration is attempted
274 * @throws MWException If a module name contains illegal characters (pipes or commas)
275 * @throws MWException If something other than a ResourceLoaderModule is being registered
276 * @return bool False if there were any errors, in which case one or more modules were
279 public function register( $name, $info = null ) {
280 wfProfileIn( __METHOD__
);
282 // Allow multiple modules to be registered in one call
283 $registrations = is_array( $name ) ?
$name : array( $name => $info );
284 foreach ( $registrations as $name => $info ) {
285 // Disallow duplicate registrations
286 if ( isset( $this->moduleInfos
[$name] ) ) {
287 wfProfileOut( __METHOD__
);
288 // A module has already been registered by this name
289 throw new MWException(
290 'ResourceLoader duplicate registration error. ' .
291 'Another module has already been registered as ' . $name
295 // Check $name for validity
296 if ( !self
::isValidModuleName( $name ) ) {
297 wfProfileOut( __METHOD__
);
298 throw new MWException( "ResourceLoader module name '$name' is invalid, "
299 . "see ResourceLoader::isValidModuleName()" );
303 if ( $info instanceof ResourceLoaderModule
) {
304 $this->moduleInfos
[$name] = array( 'object' => $info );
305 $info->setName( $name );
306 $this->modules
[$name] = $info;
307 } elseif ( is_array( $info ) ) {
308 // New calling convention
309 $this->moduleInfos
[$name] = $info;
311 wfProfileOut( __METHOD__
);
312 throw new MWException(
313 'ResourceLoader module info type error for module \'' . $name .
314 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
318 // Last-minute changes
320 // Apply custom skin-defined styles to existing modules.
321 if ( $this->isFileModule( $name ) ) {
322 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
323 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
324 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
328 // If $name is preceded with a '+', the defined style files will be added to 'default'
329 // skinStyles, otherwise 'default' will be ignored as it normally would be.
330 if ( isset( $skinStyles[$name] ) ) {
331 $paths = (array)$skinStyles[$name];
332 $styleFiles = array();
333 } elseif ( isset( $skinStyles['+' . $name] ) ) {
334 $paths = (array)$skinStyles['+' . $name];
335 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
336 $this->moduleInfos
[$name]['skinStyles']['default'] :
342 // Add new file paths, remapping them to refer to our directories and not use settings
343 // from the module we're modifying. These can come from the base definition or be defined
345 list( $localBasePath, $remoteBasePath ) =
346 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
347 list( $localBasePath, $remoteBasePath ) =
348 ResourceLoaderFileModule
::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
350 foreach ( $paths as $path ) {
351 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
354 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
359 wfProfileOut( __METHOD__
);
364 public function registerTestModules() {
367 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
368 throw new MWException( 'Attempt to register JavaScript test modules '
369 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
370 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
373 wfProfileIn( __METHOD__
);
375 // Get core test suites
376 $testModules = array();
377 $testModules['qunit'] = array();
378 // Get other test suites (e.g. from extensions)
379 wfRunHooks( '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] );
402 wfProfileOut( __METHOD__
);
406 * Add a foreign source of modules.
408 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
409 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
410 * backwards-compatibility.
411 * @throws MWException
413 public function addSource( $id, $loadUrl = null ) {
414 // Allow multiple sources to be registered in one call
415 if ( is_array( $id ) ) {
416 foreach ( $id as $key => $value ) {
417 $this->addSource( $key, $value );
422 // Disallow duplicates
423 if ( isset( $this->sources
[$id] ) ) {
424 throw new MWException(
425 'ResourceLoader duplicate source addition error. ' .
426 'Another source has already been registered as ' . $id
430 // Pre 1.24 backwards-compatibility
431 if ( is_array( $loadUrl ) ) {
432 if ( !isset( $loadUrl['loadScript'] ) ) {
433 throw new MWException(
434 __METHOD__
. ' was passed an array with no "loadScript" key.'
438 $loadUrl = $loadUrl['loadScript'];
441 $this->sources
[$id] = $loadUrl;
445 * Get a list of module names.
447 * @return array List of module names
449 public function getModuleNames() {
450 return array_keys( $this->moduleInfos
);
454 * Get a list of test module names for one (or all) frameworks.
456 * If the given framework id is unknkown, or if the in-object variable is not an array,
457 * then it will return an empty array.
459 * @param string $framework Get only the test module names for one
460 * particular framework (optional)
463 public function getTestModuleNames( $framework = 'all' ) {
464 /** @todo api siteinfo prop testmodulenames modulenames */
465 if ( $framework == 'all' ) {
466 return $this->testModuleNames
;
467 } elseif ( isset( $this->testModuleNames
[$framework] )
468 && is_array( $this->testModuleNames
[$framework] )
470 return $this->testModuleNames
[$framework];
477 * Get the ResourceLoaderModule object for a given module name.
479 * If an array of module parameters exists but a ResourceLoaderModule object has not
480 * yet been instantiated, this method will instantiate and cache that object such that
481 * subsequent calls simply return the same object.
483 * @param string $name Module name
484 * @return ResourceLoaderModule|null If module has been registered, return a
485 * ResourceLoaderModule instance. Otherwise, return null.
487 public function getModule( $name ) {
488 if ( !isset( $this->modules
[$name] ) ) {
489 if ( !isset( $this->moduleInfos
[$name] ) ) {
493 // Construct the requested object
494 $info = $this->moduleInfos
[$name];
495 /** @var ResourceLoaderModule $object */
496 if ( isset( $info['object'] ) ) {
497 // Object given in info array
498 $object = $info['object'];
500 if ( !isset( $info['class'] ) ) {
501 $class = 'ResourceLoaderFileModule';
503 $class = $info['class'];
505 /** @var ResourceLoaderModule $object */
506 $object = new $class( $info );
507 $object->setConfig( $this->getConfig() );
509 $object->setName( $name );
510 $this->modules
[$name] = $object;
513 return $this->modules
[$name];
517 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
519 * @param string $name Module name
522 protected function isFileModule( $name ) {
523 if ( !isset( $this->moduleInfos
[$name] ) ) {
526 $info = $this->moduleInfos
[$name];
527 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
534 * Get the list of sources.
536 * @return array Like array( id => load.php url, .. )
538 public function getSources() {
539 return $this->sources
;
543 * Get the URL to the load.php endpoint for the given
544 * ResourceLoader source
547 * @param string $source
548 * @throws MWException On an invalid $source name
551 public function getLoadScript( $source ) {
552 if ( !isset( $this->sources
[$source] ) ) {
553 throw new MWException( "The $source source was never registered in ResourceLoader." );
555 return $this->sources
[$source];
559 * Output a response to a load request, including the content-type header.
561 * @param ResourceLoaderContext $context Context in which a response should be formed
563 public function respond( ResourceLoaderContext
$context ) {
564 // Use file cache if enabled and available...
565 if ( $this->config
->get( 'UseFileCache' ) ) {
566 $fileCache = ResourceFileCache
::newFromContext( $context );
567 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
568 return; // output handled
572 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
573 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
574 // is used: ob_clean() will clear the GZIP header in that case and it won't come
575 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
576 // the whole thing in our own output buffer to be sure the active buffer
577 // doesn't use ob_gzhandler.
578 // See http://bugs.php.net/bug.php?id=36514
581 wfProfileIn( __METHOD__
);
584 // Find out which modules are missing and instantiate the others
587 foreach ( $context->getModules() as $name ) {
588 $module = $this->getModule( $name );
590 // Do not allow private modules to be loaded from the web.
591 // This is a security issue, see bug 34907.
592 if ( $module->getGroup() === 'private' ) {
593 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
594 $this->hasErrors
= true;
595 // Add exception to the output as a comment
596 $errors .= self
::makeComment( "Cannot show private module \"$name\"" );
600 $modules[$name] = $module;
606 // Preload information needed to the mtime calculation below
608 $this->preloadModuleInfo( array_keys( $modules ), $context );
609 } catch ( Exception
$e ) {
610 MWExceptionHandler
::logException( $e );
611 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
612 $this->hasErrors
= true;
613 // Add exception to the output as a comment
614 $errors .= self
::formatException( $e );
617 wfProfileIn( __METHOD__
. '-getModifiedTime' );
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->hasErrors
= true;
633 // Add exception to the output as a comment
634 $errors .= self
::formatException( $e );
638 wfProfileOut( __METHOD__
. '-getModifiedTime' );
640 // If there's an If-Modified-Since header, respond with a 304 appropriately
641 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
642 wfProfileOut( __METHOD__
);
643 return; // output handled (buffers cleared)
646 // Generate a response
647 $response = $this->makeModuleResponse( $context, $modules, $missing );
649 // Capture any PHP warnings from the output buffer and append them to the
650 // error list if we're in debug mode.
651 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
652 $errors .= self
::makeComment( $warnings );
653 $this->hasErrors
= true;
656 if ( $context->getImageObj() && !$response ) {
657 $errors .= self
::makeComment( "Image generation failed." );
658 $this->hasErrors
= true;
661 if ( $this->hasErrors
) {
662 if ( $context->getImageObj() ) {
663 // Bail, we can't show both the error messages and the response when it's not CSS or JS.
664 // sendResponseHeaders() will handle this sensibly.
667 // Prepend comments indicating exceptions
668 $response = $errors . $response;
672 // Save response to file cache unless there are errors
673 if ( isset( $fileCache ) && !$this->hasErrors
&& !count( $missing ) ) {
674 // Cache single modules and images...and other requests if there are enough hits
675 if ( ResourceFileCache
::useFileCache( $context ) ) {
676 if ( $fileCache->isCacheWorthy() ) {
677 $fileCache->saveText( $response );
679 $fileCache->incrMissesRecent( $context->getRequest() );
684 // Send content type and cache related headers
685 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
687 // Remove the output buffer and output the response
691 wfProfileOut( __METHOD__
);
695 * Send content type and last modified headers to the client.
696 * @param ResourceLoaderContext $context
697 * @param string $mtime TS_MW timestamp to use for last-modified
698 * @param bool $errors Whether there are commented-out errors in the response
701 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
702 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
703 // If a version wasn't specified we need a shorter expiry time for updates
704 // to propagate to clients quickly
705 // If there were errors, we also need a shorter expiry time so we can recover quickly
706 if ( is_null( $context->getVersion() ) ||
$errors ) {
707 $maxage = $rlMaxage['unversioned']['client'];
708 $smaxage = $rlMaxage['unversioned']['server'];
709 // If a version was specified we can use a longer expiry time since changing
710 // version numbers causes cache misses
712 $maxage = $rlMaxage['versioned']['client'];
713 $smaxage = $rlMaxage['versioned']['server'];
715 if ( $context->getImageObj() ) {
717 header( 'Content-Type: text/plain; charset=utf-8' );
719 $context->getImageObj()->sendResponseHeaders( $context );
721 } elseif ( $context->getOnly() === 'styles' ) {
722 header( 'Content-Type: text/css; charset=utf-8' );
723 header( 'Access-Control-Allow-Origin: *' );
725 header( 'Content-Type: text/javascript; charset=utf-8' );
727 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
728 if ( $context->getDebug() ) {
729 // Do not cache debug responses
730 header( 'Cache-Control: private, no-cache, must-revalidate' );
731 header( 'Pragma: no-cache' );
733 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
734 $exp = min( $maxage, $smaxage );
735 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
740 * Respond with 304 Last Modified if appropiate.
742 * If there's an If-Modified-Since header, respond with a 304 appropriately
743 * and clear out the output buffer. If the client cache is too old then do nothing.
745 * @param ResourceLoaderContext $context
746 * @param string $mtime The TS_MW timestamp to check the header against
747 * @return bool True if 304 header sent and output handled
749 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
750 // If there's an If-Modified-Since header, respond with a 304 appropriately
751 // Some clients send "timestamp;length=123". Strip the part after the first ';'
752 // so we get a valid timestamp.
753 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
754 // Never send 304s in debug mode
755 if ( $ims !== false && !$context->getDebug() ) {
756 $imsTS = strtok( $ims, ';' );
757 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
758 // There's another bug in ob_gzhandler (see also the comment at
759 // the top of this function) that causes it to gzip even empty
760 // responses, meaning it's impossible to produce a truly empty
761 // response (because the gzip header is always there). This is
762 // a problem because 304 responses have to be completely empty
763 // per the HTTP spec, and Firefox behaves buggily when they're not.
764 // See also http://bugs.php.net/bug.php?id=51579
765 // To work around this, we tear down all output buffering before
767 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
769 header( 'HTTP/1.0 304 Not Modified' );
770 header( 'Status: 304 Not Modified' );
778 * Send out code for a response from file cache if possible.
780 * @param ResourceFileCache $fileCache Cache object for this request URL
781 * @param ResourceLoaderContext $context Context in which to generate a response
782 * @return bool If this found a cache file and handled the response
784 protected function tryRespondFromFileCache(
785 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
787 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
788 // Buffer output to catch warnings.
790 // Get the maximum age the cache can be
791 $maxage = is_null( $context->getVersion() )
792 ?
$rlMaxage['unversioned']['server']
793 : $rlMaxage['versioned']['server'];
794 // Minimum timestamp the cache file must have
795 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
797 try { // RL always hits the DB on file cache miss...
799 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
800 $good = $fileCache->isCacheGood(); // cache existence check
804 $ts = $fileCache->cacheTimestamp();
805 // Send content type and cache headers
806 $this->sendResponseHeaders( $context, $ts, false );
807 // If there's an If-Modified-Since header, respond with a 304 appropriately
808 if ( $this->tryRespondLastModified( $context, $ts ) ) {
809 return false; // output handled (buffers cleared)
811 $response = $fileCache->fetchText();
812 // Capture any PHP warnings from the output buffer and append them to the
813 // response in a comment if we're in debug mode.
814 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
815 $response = "/*\n$warnings\n*/\n" . $response;
817 // Remove the output buffer and output the response
819 echo $response . "\n/* Cached {$ts} */";
820 return true; // cache hit
825 return false; // cache miss
829 * Generate a CSS or JS comment block.
831 * Only use this for public data, not error message details.
833 * @param string $text
836 public static function makeComment( $text ) {
837 $encText = str_replace( '*/', '* /', $text );
838 return "/*\n$encText\n*/\n";
842 * Handle exception display.
844 * @param Exception $e Exception to be shown to the user
845 * @return string Sanitized text that can be returned to the user
847 public static function formatException( $e ) {
848 global $wgShowExceptionDetails;
850 if ( $wgShowExceptionDetails ) {
851 return self
::makeComment( $e->__toString() );
853 return self
::makeComment( wfMessage( 'internalerror' )->text() );
858 * Generate code for a response.
860 * @param ResourceLoaderContext $context Context in which to generate a response
861 * @param array $modules List of module objects keyed by module name
862 * @param array $missing List of requested module names that are unregistered (optional)
863 * @return string Response data
865 public function makeModuleResponse( ResourceLoaderContext
$context,
866 array $modules, array $missing = array()
872 if ( !count( $modules ) && !count( $missing ) ) {
873 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
874 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
875 no modules were requested. Max made me put this here. */";
878 wfProfileIn( __METHOD__
);
880 $image = $context->getImageObj();
882 $data = $image->getImageData( $context );
883 wfProfileOut( __METHOD__
);
888 if ( $context->shouldIncludeMessages() ) {
890 $blobs = MessageBlobStore
::getInstance()->get( $this, $modules, $context->getLanguage() );
891 } catch ( Exception
$e ) {
892 MWExceptionHandler
::logException( $e );
895 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
897 $this->hasErrors
= true;
898 // Add exception to the output as a comment
899 $exceptions .= self
::formatException( $e );
905 foreach ( $missing as $name ) {
906 $states[$name] = 'missing';
911 foreach ( $modules as $name => $module ) {
913 * @var $module ResourceLoaderModule
916 wfProfileIn( __METHOD__
. '-' . $name );
919 if ( $context->shouldIncludeScripts() ) {
920 // If we are in debug mode, we'll want to return an array of URLs if possible
921 // However, we can't do this if the module doesn't support it
922 // We also can't do this if there is an only= parameter, because we have to give
923 // the module a way to return a load.php URL without causing an infinite loop
924 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
925 $scripts = $module->getScriptURLsForDebug( $context );
927 $scripts = $module->getScript( $context );
928 // rtrim() because there are usually a few line breaks
929 // after the last ';'. A new line at EOF, a new line
930 // added by ResourceLoaderFileModule::readScriptFiles, etc.
931 if ( is_string( $scripts )
932 && strlen( $scripts )
933 && substr( rtrim( $scripts ), -1 ) !== ';'
935 // Append semicolon to prevent weird bugs caused by files not
936 // terminating their statements right (bug 27054)
943 if ( $context->shouldIncludeStyles() ) {
944 // Don't create empty stylesheets like array( '' => '' ) for modules
945 // that don't *have* any stylesheets (bug 38024).
946 $stylePairs = $module->getStyles( $context );
947 if ( count( $stylePairs ) ) {
948 // If we are in debug mode without &only= set, we'll want to return an array of URLs
949 // See comment near shouldIncludeScripts() for more details
950 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
952 'url' => $module->getStyleURLsForDebug( $context )
955 // Minify CSS before embedding in mw.loader.implement call
956 // (unless in debug mode)
957 if ( !$context->getDebug() ) {
958 foreach ( $stylePairs as $media => $style ) {
959 // Can be either a string or an array of strings.
960 if ( is_array( $style ) ) {
961 $stylePairs[$media] = array();
962 foreach ( $style as $cssText ) {
963 if ( is_string( $cssText ) ) {
964 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
967 } elseif ( is_string( $style ) ) {
968 $stylePairs[$media] = $this->filter( 'minify-css', $style );
972 // Wrap styles into @media groups as needed and flatten into a numerical array
974 'css' => self
::makeCombinedStyles( $stylePairs )
981 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
984 switch ( $context->getOnly() ) {
986 if ( is_string( $scripts ) ) {
987 // Load scripts raw...
989 } elseif ( is_array( $scripts ) ) {
990 // ...except when $scripts is an array of URLs
991 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
995 // We no longer seperate into media, they are all combined now with
996 // custom media type groups into @media .. {} sections as part of the css string.
997 // Module returns either an empty array or a numerical array with css strings.
998 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1001 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
1004 $out .= Xml
::encodeJsCall(
1006 array( $name, (object)$module->getTemplates() ),
1007 ResourceLoader
::inDebugMode()
1011 $out .= self
::makeLoaderImplementScript(
1015 new XmlJsCode( $messagesBlob ),
1016 $module->getTemplates()
1020 } catch ( Exception
$e ) {
1021 MWExceptionHandler
::logException( $e );
1022 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
1023 $this->hasErrors
= true;
1024 // Add exception to the output as a comment
1025 $exceptions .= self
::formatException( $e );
1027 // Respond to client with error-state instead of module implementation
1028 $states[$name] = 'error';
1029 unset( $modules[$name] );
1031 $isRaw |
= $module->isRaw();
1032 wfProfileOut( __METHOD__
. '-' . $name );
1035 // Update module states
1036 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1037 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1038 // Set the state of modules loaded as only scripts to ready as
1039 // they don't have an mw.loader.implement wrapper that sets the state
1040 foreach ( $modules as $name => $module ) {
1041 $states[$name] = 'ready';
1045 // Set the state of modules we didn't respond to with mw.loader.implement
1046 if ( count( $states ) ) {
1047 $out .= self
::makeLoaderStateScript( $states );
1050 if ( count( $states ) ) {
1051 $exceptions .= self
::makeComment(
1052 'Problematic modules: ' . FormatJson
::encode( $states, ResourceLoader
::inDebugMode() )
1057 if ( !$context->getDebug() ) {
1058 if ( $context->getOnly() === 'styles' ) {
1059 $out = $this->filter( 'minify-css', $out );
1061 $out = $this->filter( 'minify-js', $out );
1065 wfProfileOut( __METHOD__
);
1066 return $exceptions . $out;
1069 /* Static Methods */
1072 * Return JS code that calls mw.loader.implement with given module properties.
1074 * @param string $name Module name
1075 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1076 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1077 * to CSS files keyed by media type
1078 * @param mixed $messages List of messages associated with this module. May either be an
1079 * associative array mapping message key to value, or a JSON-encoded message blob containing
1080 * the same data, wrapped in an XmlJsCode object.
1081 * @param array $templates Keys are name of templates and values are the source of
1083 * @throws MWException
1086 public static function makeLoaderImplementScript( $name, $scripts, $styles,
1087 $messages, $templates
1089 if ( is_string( $scripts ) ) {
1090 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1091 } elseif ( !is_array( $scripts ) ) {
1092 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1095 return Xml
::encodeJsCall(
1096 'mw.loader.implement',
1100 // Force objects. mw.loader.implement requires them to be javascript objects.
1101 // Although these variables are associative arrays, which become javascript
1102 // objects through json_encode. In many cases they will be empty arrays, and
1103 // PHP/json_encode() consider empty arrays to be numerical arrays and
1104 // output javascript "[]" instead of "{}". This fixes that.
1109 ResourceLoader
::inDebugMode()
1114 * Returns JS code which, when called, will register a given list of messages.
1116 * @param mixed $messages Either an associative array mapping message key to value, or a
1117 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1120 public static function makeMessageSetScript( $messages ) {
1121 return Xml
::encodeJsCall(
1123 array( (object)$messages ),
1124 ResourceLoader
::inDebugMode()
1129 * Combines an associative array mapping media type to CSS into a
1130 * single stylesheet with "@media" blocks.
1132 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1135 public static function makeCombinedStyles( array $stylePairs ) {
1137 foreach ( $stylePairs as $media => $styles ) {
1138 // ResourceLoaderFileModule::getStyle can return the styles
1139 // as a string or an array of strings. This is to allow separation in
1141 $styles = (array)$styles;
1142 foreach ( $styles as $style ) {
1143 $style = trim( $style );
1144 // Don't output an empty "@media print { }" block (bug 40498)
1145 if ( $style !== '' ) {
1146 // Transform the media type based on request params and config
1147 // The way that this relies on $wgRequest to propagate request params is slightly evil
1148 $media = OutputPage
::transformCssMedia( $media );
1150 if ( $media === '' ||
$media == 'all' ) {
1152 } elseif ( is_string( $media ) ) {
1153 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1163 * Returns a JS call to mw.loader.state, which sets the state of a
1164 * module or modules to a given value. Has two calling conventions:
1166 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1167 * Set the state of a single module called $name to $state
1169 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1170 * Set the state of modules with the given names to the given states
1172 * @param string $name
1173 * @param string $state
1176 public static function makeLoaderStateScript( $name, $state = null ) {
1177 if ( is_array( $name ) ) {
1178 return Xml
::encodeJsCall(
1181 ResourceLoader
::inDebugMode()
1184 return Xml
::encodeJsCall(
1186 array( $name, $state ),
1187 ResourceLoader
::inDebugMode()
1193 * Returns JS code which calls the script given by $script. The script will
1194 * be called with local variables name, version, dependencies and group,
1195 * which will have values corresponding to $name, $version, $dependencies
1196 * and $group as supplied.
1198 * @param string $name Module name
1199 * @param int $version Module version number as a timestamp
1200 * @param array $dependencies List of module names on which this module depends
1201 * @param string $group Group which the module is in.
1202 * @param string $source Source of the module, or 'local' if not foreign.
1203 * @param string $script JavaScript code
1206 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1207 $group, $source, $script
1209 $script = str_replace( "\n", "\n\t", trim( $script ) );
1210 return Xml
::encodeJsCall(
1211 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1212 array( $name, $version, $dependencies, $group, $source ),
1213 ResourceLoader
::inDebugMode()
1218 * Remove empty values from the end of an array.
1220 * Values considered empty:
1225 * @param Array $array
1227 private static function trimArray( Array &$array ) {
1228 $i = count( $array );
1230 if ( $array[$i] === null ||
$array[$i] === array() ) {
1231 unset( $array[$i] );
1239 * Returns JS code which calls mw.loader.register with the given
1240 * parameters. Has three calling conventions:
1242 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1243 * $dependencies, $group, $source, $skip
1245 * Register a single module.
1247 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1248 * Register modules with the given names.
1250 * - ResourceLoader::makeLoaderRegisterScript( array(
1251 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1252 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1255 * Registers modules with the given names and parameters.
1257 * @param string $name Module name
1258 * @param int $version Module version number as a timestamp
1259 * @param array $dependencies List of module names on which this module depends
1260 * @param string $group Group which the module is in
1261 * @param string $source Source of the module, or 'local' if not foreign
1262 * @param string $skip Script body of the skip function
1265 public static function makeLoaderRegisterScript( $name, $version = null,
1266 $dependencies = null, $group = null, $source = null, $skip = null
1268 if ( is_array( $name ) ) {
1269 // Build module name index
1271 foreach ( $name as $i => &$module ) {
1272 $index[$module[0]] = $i;
1275 // Transform dependency names into indexes when possible, they will be resolved by
1276 // mw.loader.register on the other end
1277 foreach ( $name as &$module ) {
1278 if ( isset( $module[2] ) ) {
1279 foreach ( $module[2] as &$dependency ) {
1280 if ( isset( $index[$dependency] ) ) {
1281 $dependency = $index[$dependency];
1287 array_walk( $name, array( 'self', 'trimArray' ) );
1289 return Xml
::encodeJsCall(
1290 'mw.loader.register',
1292 ResourceLoader
::inDebugMode()
1295 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1296 self
::trimArray( $registration );
1297 return Xml
::encodeJsCall(
1298 'mw.loader.register',
1300 ResourceLoader
::inDebugMode()
1306 * Returns JS code which calls mw.loader.addSource() with the given
1307 * parameters. Has two calling conventions:
1309 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1310 * Register a single source
1312 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1313 * Register sources with the given IDs and properties.
1315 * @param string $id Source ID
1316 * @param array $properties Source properties (see addSource())
1319 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1320 if ( is_array( $id ) ) {
1321 return Xml
::encodeJsCall(
1322 'mw.loader.addSource',
1324 ResourceLoader
::inDebugMode()
1327 return Xml
::encodeJsCall(
1328 'mw.loader.addSource',
1329 array( $id, $properties ),
1330 ResourceLoader
::inDebugMode()
1336 * Returns JS code which runs given JS code if the client-side framework is
1339 * @param string $script JavaScript code
1342 public static function makeLoaderConditionalScript( $script ) {
1343 return "if(window.mw){\n" . trim( $script ) . "\n}";
1347 * Returns JS code which will set the MediaWiki configuration array to
1350 * @param array $configuration List of configuration values keyed by variable name
1353 public static function makeConfigSetScript( array $configuration ) {
1354 return Xml
::encodeJsCall(
1356 array( $configuration ),
1357 ResourceLoader
::inDebugMode()
1362 * Convert an array of module names to a packed query string.
1364 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1365 * becomes 'foo.bar,baz|bar.baz,quux'
1366 * @param array $modules List of module names (strings)
1367 * @return string Packed query string
1369 public static function makePackedModulesString( $modules ) {
1370 $groups = array(); // array( prefix => array( suffixes ) )
1371 foreach ( $modules as $module ) {
1372 $pos = strrpos( $module, '.' );
1373 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1374 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1375 $groups[$prefix][] = $suffix;
1379 foreach ( $groups as $prefix => $suffixes ) {
1380 $p = $prefix === '' ?
'' : $prefix . '.';
1381 $arr[] = $p . implode( ',', $suffixes );
1383 $str = implode( '|', $arr );
1388 * Determine whether debug mode was requested
1389 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1392 public static function inDebugMode() {
1393 if ( self
::$debugMode === null ) {
1394 global $wgRequest, $wgResourceLoaderDebug;
1395 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1396 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1399 return self
::$debugMode;
1403 * Reset static members used for caching.
1405 * Global state and $wgRequest are evil, but we're using it right
1406 * now and sometimes we need to be able to force ResourceLoader to
1407 * re-evaluate the context because it has changed (e.g. in the test suite).
1409 public static function clearCache() {
1410 self
::$debugMode = null;
1414 * Build a load.php URL
1417 * @param string $source Name of the ResourceLoader source
1418 * @param ResourceLoaderContext $context
1419 * @param array $extraQuery
1420 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1422 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1423 $extraQuery = array()
1425 $query = self
::createLoaderQuery( $context, $extraQuery );
1426 $script = $this->getLoadScript( $source );
1428 // Prevent the IE6 extension check from being triggered (bug 28840)
1429 // by appending a character that's invalid in Windows extensions ('*')
1430 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1434 * Build a load.php URL
1435 * @deprecated since 1.24, use createLoaderURL instead
1436 * @param array $modules Array of module names (strings)
1437 * @param string $lang Language code
1438 * @param string $skin Skin name
1439 * @param string|null $user User name. If null, the &user= parameter is omitted
1440 * @param string|null $version Versioning timestamp
1441 * @param bool $debug Whether the request should be in debug mode
1442 * @param string|null $only &only= parameter
1443 * @param bool $printable Printable mode
1444 * @param bool $handheld Handheld mode
1445 * @param array $extraQuery Extra query parameters to add
1446 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1448 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1449 $version = null, $debug = false, $only = null, $printable = false,
1450 $handheld = false, $extraQuery = array()
1452 global $wgLoadScript;
1454 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1455 $only, $printable, $handheld, $extraQuery
1458 // Prevent the IE6 extension check from being triggered (bug 28840)
1459 // by appending a character that's invalid in Windows extensions ('*')
1460 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1464 * Helper for createLoaderURL()
1467 * @see makeLoaderQuery
1468 * @param ResourceLoaderContext $context
1469 * @param array $extraQuery
1472 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1473 return self
::makeLoaderQuery(
1474 $context->getModules(),
1475 $context->getLanguage(),
1476 $context->getSkin(),
1477 $context->getUser(),
1478 $context->getVersion(),
1479 $context->getDebug(),
1480 $context->getOnly(),
1481 $context->getRequest()->getBool( 'printable' ),
1482 $context->getRequest()->getBool( 'handheld' ),
1488 * Build a query array (array representation of query string) for load.php. Helper
1489 * function for makeLoaderURL().
1491 * @param array $modules
1492 * @param string $lang
1493 * @param string $skin
1494 * @param string $user
1495 * @param string $version
1496 * @param bool $debug
1497 * @param string $only
1498 * @param bool $printable
1499 * @param bool $handheld
1500 * @param array $extraQuery
1504 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1505 $version = null, $debug = false, $only = null, $printable = false,
1506 $handheld = false, $extraQuery = array()
1509 'modules' => self
::makePackedModulesString( $modules ),
1512 'debug' => $debug ?
'true' : 'false',
1514 if ( $user !== null ) {
1515 $query['user'] = $user;
1517 if ( $version !== null ) {
1518 $query['version'] = $version;
1520 if ( $only !== null ) {
1521 $query['only'] = $only;
1524 $query['printable'] = 1;
1527 $query['handheld'] = 1;
1529 $query +
= $extraQuery;
1531 // Make queries uniform in order
1537 * Check a module name for validity.
1539 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1540 * at most 255 bytes.
1542 * @param string $moduleName Module name to check
1543 * @return bool Whether $moduleName is a valid module name
1545 public static function isValidModuleName( $moduleName ) {
1546 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1550 * Returns LESS compiler set up for use with MediaWiki
1552 * @param Config $config
1553 * @throws MWException
1557 public static function getLessCompiler( Config
$config ) {
1558 // When called from the installer, it is possible that a required PHP extension
1559 // is missing (at least for now; see bug 47564). If this is the case, throw an
1560 // exception (caught by the installer) to prevent a fatal error later on.
1561 if ( !class_exists( 'lessc' ) ) {
1562 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1564 if ( !function_exists( 'ctype_digit' ) ) {
1565 throw new MWException( 'lessc requires the Ctype extension' );
1568 $less = new lessc();
1569 $less->setPreserveComments( true );
1570 $less->setVariables( self
::getLessVars( $config ) );
1571 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1572 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1573 $less->registerFunction( $name, $func );
1579 * Get global LESS variables.
1581 * @param Config $config
1583 * @return array Map of variable names to string CSS values.
1585 public static function getLessVars( Config
$config ) {
1586 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1587 // Sort by key to ensure consistent hashing for cache lookups.