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 ) {
168 wfProfileIn( __METHOD__
);
170 // For empty/whitespace-only data or for unknown filters, don't perform
171 // any caching or processing
172 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
173 wfProfileOut( __METHOD__
);
178 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
179 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
180 $cache = wfGetCache( CACHE_ANYTHING
);
181 $cacheEntry = $cache->get( $key );
182 if ( is_string( $cacheEntry ) ) {
183 wfIncrStats( "rl-$filter-cache-hits" );
184 wfProfileOut( __METHOD__
);
189 // Run the filter - we've already verified one of these will work
191 wfIncrStats( "rl-$filter-cache-misses" );
194 $result = JavaScriptMinifier
::minify( $data,
195 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
196 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
198 if ( $cacheReport ) {
199 $result .= "\n/* cache key: $key */";
203 $result = CSSMin
::minify( $data );
204 if ( $cacheReport ) {
205 $result .= "\n/* cache key: $key */";
210 // Save filtered text to Memcached
211 $cache->set( $key, $result );
212 } catch ( Exception
$e ) {
213 MWExceptionHandler
::logException( $e );
214 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
215 $this->errors
[] = self
::formatExceptionNoComment( $e );
218 wfProfileOut( __METHOD__
);
226 * Register core modules and runs registration hooks.
227 * @param Config|null $config
229 public function __construct( Config
$config = null ) {
232 wfProfileIn( __METHOD__
);
234 if ( $config === null ) {
235 wfDebug( __METHOD__
. ' was called without providing a Config instance' );
236 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
239 $this->config
= $config;
241 // Add 'local' source first
242 $this->addSource( 'local', wfScript( 'load' ) );
245 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
247 // Register core modules
248 $this->register( include "$IP/resources/Resources.php" );
249 // Register extension modules
250 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
251 $this->register( $config->get( 'ResourceModules' ) );
253 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
254 $this->registerTestModules();
257 wfProfileOut( __METHOD__
);
263 public function getConfig() {
264 return $this->config
;
268 * Register a module with the ResourceLoader system.
270 * @param mixed $name Name of module as a string or List of name/object pairs as an array
271 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
272 * this may also be a ResourceLoaderModule object. Optional when using
273 * multiple-registration calling style.
274 * @throws MWException If a duplicate module registration is attempted
275 * @throws MWException If a module name contains illegal characters (pipes or commas)
276 * @throws MWException If something other than a ResourceLoaderModule is being registered
277 * @return bool False if there were any errors, in which case one or more modules were
280 public function register( $name, $info = null ) {
281 wfProfileIn( __METHOD__
);
283 // Allow multiple modules to be registered in one call
284 $registrations = is_array( $name ) ?
$name : array( $name => $info );
285 foreach ( $registrations as $name => $info ) {
286 // Disallow duplicate registrations
287 if ( isset( $this->moduleInfos
[$name] ) ) {
288 wfProfileOut( __METHOD__
);
289 // A module has already been registered by this name
290 throw new MWException(
291 'ResourceLoader duplicate registration error. ' .
292 'Another module has already been registered as ' . $name
296 // Check $name for validity
297 if ( !self
::isValidModuleName( $name ) ) {
298 wfProfileOut( __METHOD__
);
299 throw new MWException( "ResourceLoader module name '$name' is invalid, "
300 . "see ResourceLoader::isValidModuleName()" );
304 if ( $info instanceof ResourceLoaderModule
) {
305 $this->moduleInfos
[$name] = array( 'object' => $info );
306 $info->setName( $name );
307 $this->modules
[$name] = $info;
308 } elseif ( is_array( $info ) ) {
309 // New calling convention
310 $this->moduleInfos
[$name] = $info;
312 wfProfileOut( __METHOD__
);
313 throw new MWException(
314 'ResourceLoader module info type error for module \'' . $name .
315 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
319 // Last-minute changes
321 // Apply custom skin-defined styles to existing modules.
322 if ( $this->isFileModule( $name ) ) {
323 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
324 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
325 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
329 // If $name is preceded with a '+', the defined style files will be added to 'default'
330 // skinStyles, otherwise 'default' will be ignored as it normally would be.
331 if ( isset( $skinStyles[$name] ) ) {
332 $paths = (array)$skinStyles[$name];
333 $styleFiles = array();
334 } elseif ( isset( $skinStyles['+' . $name] ) ) {
335 $paths = (array)$skinStyles['+' . $name];
336 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
337 $this->moduleInfos
[$name]['skinStyles']['default'] :
343 // Add new file paths, remapping them to refer to our directories and not use settings
344 // from the module we're modifying. These can come from the base definition or be defined
346 list( $localBasePath, $remoteBasePath ) =
347 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
348 list( $localBasePath, $remoteBasePath ) =
349 ResourceLoaderFileModule
::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
351 foreach ( $paths as $path ) {
352 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
355 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
360 wfProfileOut( __METHOD__
);
365 public function registerTestModules() {
368 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
369 throw new MWException( 'Attempt to register JavaScript test modules '
370 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
371 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
374 wfProfileIn( __METHOD__
);
376 // Get core test suites
377 $testModules = array();
378 $testModules['qunit'] = array();
379 // Get other test suites (e.g. from extensions)
380 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
382 // Add the testrunner (which configures QUnit) to the dependencies.
383 // Since it must be ready before any of the test suites are executed.
384 foreach ( $testModules['qunit'] as &$module ) {
385 // Make sure all test modules are top-loading so that when QUnit starts
386 // on document-ready, it will run once and finish. If some tests arrive
387 // later (possibly after QUnit has already finished) they will be ignored.
388 $module['position'] = 'top';
389 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
392 $testModules['qunit'] =
393 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
395 foreach ( $testModules as $id => $names ) {
396 // Register test modules
397 $this->register( $testModules[$id] );
399 // Keep track of their names so that they can be loaded together
400 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
403 wfProfileOut( __METHOD__
);
407 * Add a foreign source of modules.
409 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
410 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
411 * backwards-compatibility.
412 * @throws MWException
414 public function addSource( $id, $loadUrl = null ) {
415 // Allow multiple sources to be registered in one call
416 if ( is_array( $id ) ) {
417 foreach ( $id as $key => $value ) {
418 $this->addSource( $key, $value );
423 // Disallow duplicates
424 if ( isset( $this->sources
[$id] ) ) {
425 throw new MWException(
426 'ResourceLoader duplicate source addition error. ' .
427 'Another source has already been registered as ' . $id
431 // Pre 1.24 backwards-compatibility
432 if ( is_array( $loadUrl ) ) {
433 if ( !isset( $loadUrl['loadScript'] ) ) {
434 throw new MWException(
435 __METHOD__
. ' was passed an array with no "loadScript" key.'
439 $loadUrl = $loadUrl['loadScript'];
442 $this->sources
[$id] = $loadUrl;
446 * Get a list of module names.
448 * @return array List of module names
450 public function getModuleNames() {
451 return array_keys( $this->moduleInfos
);
455 * Get a list of test module names for one (or all) frameworks.
457 * If the given framework id is unknkown, or if the in-object variable is not an array,
458 * then it will return an empty array.
460 * @param string $framework Get only the test module names for one
461 * particular framework (optional)
464 public function getTestModuleNames( $framework = 'all' ) {
465 /** @todo api siteinfo prop testmodulenames modulenames */
466 if ( $framework == 'all' ) {
467 return $this->testModuleNames
;
468 } elseif ( isset( $this->testModuleNames
[$framework] )
469 && is_array( $this->testModuleNames
[$framework] )
471 return $this->testModuleNames
[$framework];
478 * Get the ResourceLoaderModule object for a given module name.
480 * If an array of module parameters exists but a ResourceLoaderModule object has not
481 * yet been instantiated, this method will instantiate and cache that object such that
482 * subsequent calls simply return the same object.
484 * @param string $name Module name
485 * @return ResourceLoaderModule|null If module has been registered, return a
486 * ResourceLoaderModule instance. Otherwise, return null.
488 public function getModule( $name ) {
489 if ( !isset( $this->modules
[$name] ) ) {
490 if ( !isset( $this->moduleInfos
[$name] ) ) {
494 // Construct the requested object
495 $info = $this->moduleInfos
[$name];
496 /** @var ResourceLoaderModule $object */
497 if ( isset( $info['object'] ) ) {
498 // Object given in info array
499 $object = $info['object'];
501 if ( !isset( $info['class'] ) ) {
502 $class = 'ResourceLoaderFileModule';
504 $class = $info['class'];
506 /** @var ResourceLoaderModule $object */
507 $object = new $class( $info );
508 $object->setConfig( $this->getConfig() );
510 $object->setName( $name );
511 $this->modules
[$name] = $object;
514 return $this->modules
[$name];
518 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
520 * @param string $name Module name
523 protected function isFileModule( $name ) {
524 if ( !isset( $this->moduleInfos
[$name] ) ) {
527 $info = $this->moduleInfos
[$name];
528 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
535 * Get the list of sources.
537 * @return array Like array( id => load.php url, .. )
539 public function getSources() {
540 return $this->sources
;
544 * Get the URL to the load.php endpoint for the given
545 * ResourceLoader source
548 * @param string $source
549 * @throws MWException On an invalid $source name
552 public function getLoadScript( $source ) {
553 if ( !isset( $this->sources
[$source] ) ) {
554 throw new MWException( "The $source source was never registered in ResourceLoader." );
556 return $this->sources
[$source];
560 * Output a response to a load request, including the content-type header.
562 * @param ResourceLoaderContext $context Context in which a response should be formed
564 public function respond( ResourceLoaderContext
$context ) {
565 // Use file cache if enabled and available...
566 if ( $this->config
->get( 'UseFileCache' ) ) {
567 $fileCache = ResourceFileCache
::newFromContext( $context );
568 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
569 return; // output handled
573 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
574 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
575 // is used: ob_clean() will clear the GZIP header in that case and it won't come
576 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
577 // the whole thing in our own output buffer to be sure the active buffer
578 // doesn't use ob_gzhandler.
579 // See http://bugs.php.net/bug.php?id=36514
582 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->errors
[] = "Cannot show private module \"$name\"";
597 $modules[$name] = $module;
603 // Preload information needed to the mtime calculation below
605 $this->preloadModuleInfo( array_keys( $modules ), $context );
606 } catch ( Exception
$e ) {
607 MWExceptionHandler
::logException( $e );
608 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
609 $this->errors
[] = self
::formatExceptionNoComment( $e );
612 wfProfileIn( __METHOD__
. '-getModifiedTime' );
614 // To send Last-Modified and support If-Modified-Since, we need to detect
615 // the last modified time
616 $mtime = wfTimestamp( TS_UNIX
, $this->config
->get( 'CacheEpoch' ) );
617 foreach ( $modules as $module ) {
619 * @var $module ResourceLoaderModule
622 // Calculate maximum modified time
623 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
624 } catch ( Exception
$e ) {
625 MWExceptionHandler
::logException( $e );
626 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
627 $this->errors
[] = self
::formatExceptionNoComment( $e );
631 wfProfileOut( __METHOD__
. '-getModifiedTime' );
633 // If there's an If-Modified-Since header, respond with a 304 appropriately
634 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
635 wfProfileOut( __METHOD__
);
636 return; // output handled (buffers cleared)
639 // Generate a response
640 $response = $this->makeModuleResponse( $context, $modules, $missing );
642 // Capture any PHP warnings from the output buffer and append them to the
643 // error list if we're in debug mode.
644 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
645 $this->errors
[] = $warnings;
648 // Save response to file cache unless there are errors
649 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
650 // Cache single modules and images...and other requests if there are enough hits
651 if ( ResourceFileCache
::useFileCache( $context ) ) {
652 if ( $fileCache->isCacheWorthy() ) {
653 $fileCache->saveText( $response );
655 $fileCache->incrMissesRecent( $context->getRequest() );
660 // Send content type and cache related headers
661 $this->sendResponseHeaders( $context, $mtime, (bool)$this->errors
);
663 // Remove the output buffer and output the response
666 if ( $context->getImageObj() && $this->errors
) {
667 // We can't show both the error messages and the response when it's an image.
669 foreach ( $this->errors
as $error ) {
670 $errorText .= $error . "\n";
672 $response = $errorText;
673 } elseif ( $this->errors
) {
674 // Prepend comments indicating errors
676 foreach ( $this->errors
as $error ) {
677 $errorText .= self
::makeComment( $error );
679 $response = $errorText . $response;
682 $this->errors
= array();
685 wfProfileOut( __METHOD__
);
689 * Send content type and last modified headers to the client.
690 * @param ResourceLoaderContext $context
691 * @param string $mtime TS_MW timestamp to use for last-modified
692 * @param bool $errors Whether there are errors in the response
695 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
696 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
697 // If a version wasn't specified we need a shorter expiry time for updates
698 // to propagate to clients quickly
699 // If there were errors, we also need a shorter expiry time so we can recover quickly
700 if ( is_null( $context->getVersion() ) ||
$errors ) {
701 $maxage = $rlMaxage['unversioned']['client'];
702 $smaxage = $rlMaxage['unversioned']['server'];
703 // If a version was specified we can use a longer expiry time since changing
704 // version numbers causes cache misses
706 $maxage = $rlMaxage['versioned']['client'];
707 $smaxage = $rlMaxage['versioned']['server'];
709 if ( $context->getImageObj() ) {
710 // Output different headers if we're outputting textual errors.
712 header( 'Content-Type: text/plain; charset=utf-8' );
714 $context->getImageObj()->sendResponseHeaders( $context );
716 } elseif ( $context->getOnly() === 'styles' ) {
717 header( 'Content-Type: text/css; charset=utf-8' );
718 header( 'Access-Control-Allow-Origin: *' );
720 header( 'Content-Type: text/javascript; charset=utf-8' );
722 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
723 if ( $context->getDebug() ) {
724 // Do not cache debug responses
725 header( 'Cache-Control: private, no-cache, must-revalidate' );
726 header( 'Pragma: no-cache' );
728 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
729 $exp = min( $maxage, $smaxage );
730 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
735 * Respond with 304 Last Modified if appropiate.
737 * If there's an If-Modified-Since header, respond with a 304 appropriately
738 * and clear out the output buffer. If the client cache is too old then do nothing.
740 * @param ResourceLoaderContext $context
741 * @param string $mtime The TS_MW timestamp to check the header against
742 * @return bool True if 304 header sent and output handled
744 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
745 // If there's an If-Modified-Since header, respond with a 304 appropriately
746 // Some clients send "timestamp;length=123". Strip the part after the first ';'
747 // so we get a valid timestamp.
748 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
749 // Never send 304s in debug mode
750 if ( $ims !== false && !$context->getDebug() ) {
751 $imsTS = strtok( $ims, ';' );
752 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
753 // There's another bug in ob_gzhandler (see also the comment at
754 // the top of this function) that causes it to gzip even empty
755 // responses, meaning it's impossible to produce a truly empty
756 // response (because the gzip header is always there). This is
757 // a problem because 304 responses have to be completely empty
758 // per the HTTP spec, and Firefox behaves buggily when they're not.
759 // See also http://bugs.php.net/bug.php?id=51579
760 // To work around this, we tear down all output buffering before
762 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
764 header( 'HTTP/1.0 304 Not Modified' );
765 header( 'Status: 304 Not Modified' );
773 * Send out code for a response from file cache if possible.
775 * @param ResourceFileCache $fileCache Cache object for this request URL
776 * @param ResourceLoaderContext $context Context in which to generate a response
777 * @return bool If this found a cache file and handled the response
779 protected function tryRespondFromFileCache(
780 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
782 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
783 // Buffer output to catch warnings.
785 // Get the maximum age the cache can be
786 $maxage = is_null( $context->getVersion() )
787 ?
$rlMaxage['unversioned']['server']
788 : $rlMaxage['versioned']['server'];
789 // Minimum timestamp the cache file must have
790 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
792 try { // RL always hits the DB on file cache miss...
794 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
795 $good = $fileCache->isCacheGood(); // cache existence check
799 $ts = $fileCache->cacheTimestamp();
800 // Send content type and cache headers
801 $this->sendResponseHeaders( $context, $ts, false );
802 // If there's an If-Modified-Since header, respond with a 304 appropriately
803 if ( $this->tryRespondLastModified( $context, $ts ) ) {
804 return false; // output handled (buffers cleared)
806 $response = $fileCache->fetchText();
807 // Capture any PHP warnings from the output buffer and append them to the
808 // response in a comment if we're in debug mode.
809 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
810 $response = "/*\n$warnings\n*/\n" . $response;
812 // Remove the output buffer and output the response
814 echo $response . "\n/* Cached {$ts} */";
815 return true; // cache hit
820 return false; // cache miss
824 * Generate a CSS or JS comment block.
826 * Only use this for public data, not error message details.
828 * @param string $text
831 public static function makeComment( $text ) {
832 $encText = str_replace( '*/', '* /', $text );
833 return "/*\n$encText\n*/\n";
837 * Handle exception display.
839 * @param Exception $e Exception to be shown to the user
840 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
842 public static function formatException( $e ) {
843 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
847 * Handle exception display.
850 * @param Exception $e Exception to be shown to the user
851 * @return string Sanitized text that can be returned to the user
853 protected static function formatExceptionNoComment( $e ) {
854 global $wgShowExceptionDetails;
856 if ( $wgShowExceptionDetails ) {
857 return $e->__toString();
859 return wfMessage( 'internalerror' )->text();
864 * Generate code for a response.
866 * @param ResourceLoaderContext $context Context in which to generate a response
867 * @param array $modules List of module objects keyed by module name
868 * @param array $missing List of requested module names that are unregistered (optional)
869 * @return string Response data
871 public function makeModuleResponse( ResourceLoaderContext
$context,
872 array $modules, array $missing = array()
877 if ( !count( $modules ) && !count( $missing ) ) {
878 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
879 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
880 no modules were requested. Max made me put this here. */";
883 wfProfileIn( __METHOD__
);
885 $image = $context->getImageObj();
887 $data = $image->getImageData( $context );
888 if ( $data === false ) {
890 $this->errors
[] = 'Image generation failed';
892 wfProfileOut( __METHOD__
);
897 if ( $context->shouldIncludeMessages() ) {
899 $blobs = MessageBlobStore
::getInstance()->get( $this, $modules, $context->getLanguage() );
900 } catch ( Exception
$e ) {
901 MWExceptionHandler
::logException( $e );
904 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
906 $this->errors
[] = self
::formatExceptionNoComment( $e );
912 foreach ( $missing as $name ) {
913 $states[$name] = 'missing';
918 foreach ( $modules as $name => $module ) {
920 * @var $module ResourceLoaderModule
923 wfProfileIn( __METHOD__
. '-' . $name );
926 if ( $context->shouldIncludeScripts() ) {
927 // If we are in debug mode, we'll want to return an array of URLs if possible
928 // However, we can't do this if the module doesn't support it
929 // We also can't do this if there is an only= parameter, because we have to give
930 // the module a way to return a load.php URL without causing an infinite loop
931 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
932 $scripts = $module->getScriptURLsForDebug( $context );
934 $scripts = $module->getScript( $context );
935 // rtrim() because there are usually a few line breaks
936 // after the last ';'. A new line at EOF, a new line
937 // added by ResourceLoaderFileModule::readScriptFiles, etc.
938 if ( is_string( $scripts )
939 && strlen( $scripts )
940 && substr( rtrim( $scripts ), -1 ) !== ';'
942 // Append semicolon to prevent weird bugs caused by files not
943 // terminating their statements right (bug 27054)
950 if ( $context->shouldIncludeStyles() ) {
951 // Don't create empty stylesheets like array( '' => '' ) for modules
952 // that don't *have* any stylesheets (bug 38024).
953 $stylePairs = $module->getStyles( $context );
954 if ( count( $stylePairs ) ) {
955 // If we are in debug mode without &only= set, we'll want to return an array of URLs
956 // See comment near shouldIncludeScripts() for more details
957 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
959 'url' => $module->getStyleURLsForDebug( $context )
962 // Minify CSS before embedding in mw.loader.implement call
963 // (unless in debug mode)
964 if ( !$context->getDebug() ) {
965 foreach ( $stylePairs as $media => $style ) {
966 // Can be either a string or an array of strings.
967 if ( is_array( $style ) ) {
968 $stylePairs[$media] = array();
969 foreach ( $style as $cssText ) {
970 if ( is_string( $cssText ) ) {
971 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
974 } elseif ( is_string( $style ) ) {
975 $stylePairs[$media] = $this->filter( 'minify-css', $style );
979 // Wrap styles into @media groups as needed and flatten into a numerical array
981 'css' => self
::makeCombinedStyles( $stylePairs )
988 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
991 switch ( $context->getOnly() ) {
993 if ( is_string( $scripts ) ) {
994 // Load scripts raw...
996 } elseif ( is_array( $scripts ) ) {
997 // ...except when $scripts is an array of URLs
998 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1002 // We no longer seperate into media, they are all combined now with
1003 // custom media type groups into @media .. {} sections as part of the css string.
1004 // Module returns either an empty array or a numerical array with css strings.
1005 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1008 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
1011 $out .= Xml
::encodeJsCall(
1013 array( $name, (object)$module->getTemplates() ),
1014 ResourceLoader
::inDebugMode()
1018 $out .= self
::makeLoaderImplementScript(
1022 new XmlJsCode( $messagesBlob ),
1023 $module->getTemplates()
1027 } catch ( Exception
$e ) {
1028 MWExceptionHandler
::logException( $e );
1029 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
1030 $this->errors
[] = self
::formatExceptionNoComment( $e );
1032 // Respond to client with error-state instead of module implementation
1033 $states[$name] = 'error';
1034 unset( $modules[$name] );
1036 $isRaw |
= $module->isRaw();
1037 wfProfileOut( __METHOD__
. '-' . $name );
1040 // Update module states
1041 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1042 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1043 // Set the state of modules loaded as only scripts to ready as
1044 // they don't have an mw.loader.implement wrapper that sets the state
1045 foreach ( $modules as $name => $module ) {
1046 $states[$name] = 'ready';
1050 // Set the state of modules we didn't respond to with mw.loader.implement
1051 if ( count( $states ) ) {
1052 $out .= self
::makeLoaderStateScript( $states );
1055 if ( count( $states ) ) {
1056 $this->errors
[] = 'Problematic modules: ' .
1057 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1061 if ( !$context->getDebug() ) {
1062 if ( $context->getOnly() === 'styles' ) {
1063 $out = $this->filter( 'minify-css', $out );
1065 $out = $this->filter( 'minify-js', $out );
1069 wfProfileOut( __METHOD__
);
1073 /* Static Methods */
1076 * Return JS code that calls mw.loader.implement with given module properties.
1078 * @param string $name Module name
1079 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1080 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1081 * to CSS files keyed by media type
1082 * @param mixed $messages List of messages associated with this module. May either be an
1083 * associative array mapping message key to value, or a JSON-encoded message blob containing
1084 * the same data, wrapped in an XmlJsCode object.
1085 * @param array $templates Keys are name of templates and values are the source of
1087 * @throws MWException
1090 public static function makeLoaderImplementScript( $name, $scripts, $styles,
1091 $messages, $templates
1093 if ( is_string( $scripts ) ) {
1094 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1095 } elseif ( !is_array( $scripts ) ) {
1096 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1099 return Xml
::encodeJsCall(
1100 'mw.loader.implement',
1104 // Force objects. mw.loader.implement requires them to be javascript objects.
1105 // Although these variables are associative arrays, which become javascript
1106 // objects through json_encode. In many cases they will be empty arrays, and
1107 // PHP/json_encode() consider empty arrays to be numerical arrays and
1108 // output javascript "[]" instead of "{}". This fixes that.
1113 ResourceLoader
::inDebugMode()
1118 * Returns JS code which, when called, will register a given list of messages.
1120 * @param mixed $messages Either an associative array mapping message key to value, or a
1121 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1124 public static function makeMessageSetScript( $messages ) {
1125 return Xml
::encodeJsCall(
1127 array( (object)$messages ),
1128 ResourceLoader
::inDebugMode()
1133 * Combines an associative array mapping media type to CSS into a
1134 * single stylesheet with "@media" blocks.
1136 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1139 public static function makeCombinedStyles( array $stylePairs ) {
1141 foreach ( $stylePairs as $media => $styles ) {
1142 // ResourceLoaderFileModule::getStyle can return the styles
1143 // as a string or an array of strings. This is to allow separation in
1145 $styles = (array)$styles;
1146 foreach ( $styles as $style ) {
1147 $style = trim( $style );
1148 // Don't output an empty "@media print { }" block (bug 40498)
1149 if ( $style !== '' ) {
1150 // Transform the media type based on request params and config
1151 // The way that this relies on $wgRequest to propagate request params is slightly evil
1152 $media = OutputPage
::transformCssMedia( $media );
1154 if ( $media === '' ||
$media == 'all' ) {
1156 } elseif ( is_string( $media ) ) {
1157 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1167 * Returns a JS call to mw.loader.state, which sets the state of a
1168 * module or modules to a given value. Has two calling conventions:
1170 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1171 * Set the state of a single module called $name to $state
1173 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1174 * Set the state of modules with the given names to the given states
1176 * @param string $name
1177 * @param string $state
1180 public static function makeLoaderStateScript( $name, $state = null ) {
1181 if ( is_array( $name ) ) {
1182 return Xml
::encodeJsCall(
1185 ResourceLoader
::inDebugMode()
1188 return Xml
::encodeJsCall(
1190 array( $name, $state ),
1191 ResourceLoader
::inDebugMode()
1197 * Returns JS code which calls the script given by $script. The script will
1198 * be called with local variables name, version, dependencies and group,
1199 * which will have values corresponding to $name, $version, $dependencies
1200 * and $group as supplied.
1202 * @param string $name Module name
1203 * @param int $version Module version number as a timestamp
1204 * @param array $dependencies List of module names on which this module depends
1205 * @param string $group Group which the module is in.
1206 * @param string $source Source of the module, or 'local' if not foreign.
1207 * @param string $script JavaScript code
1210 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1211 $group, $source, $script
1213 $script = str_replace( "\n", "\n\t", trim( $script ) );
1214 return Xml
::encodeJsCall(
1215 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1216 array( $name, $version, $dependencies, $group, $source ),
1217 ResourceLoader
::inDebugMode()
1222 * Remove empty values from the end of an array.
1224 * Values considered empty:
1229 * @param Array $array
1231 private static function trimArray( Array &$array ) {
1232 $i = count( $array );
1234 if ( $array[$i] === null ||
$array[$i] === array() ) {
1235 unset( $array[$i] );
1243 * Returns JS code which calls mw.loader.register with the given
1244 * parameters. Has three calling conventions:
1246 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1247 * $dependencies, $group, $source, $skip
1249 * Register a single module.
1251 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1252 * Register modules with the given names.
1254 * - ResourceLoader::makeLoaderRegisterScript( array(
1255 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1256 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1259 * Registers modules with the given names and parameters.
1261 * @param string $name Module name
1262 * @param int $version Module version number as a timestamp
1263 * @param array $dependencies List of module names on which this module depends
1264 * @param string $group Group which the module is in
1265 * @param string $source Source of the module, or 'local' if not foreign
1266 * @param string $skip Script body of the skip function
1269 public static function makeLoaderRegisterScript( $name, $version = null,
1270 $dependencies = null, $group = null, $source = null, $skip = null
1272 if ( is_array( $name ) ) {
1273 // Build module name index
1275 foreach ( $name as $i => &$module ) {
1276 $index[$module[0]] = $i;
1279 // Transform dependency names into indexes when possible, they will be resolved by
1280 // mw.loader.register on the other end
1281 foreach ( $name as &$module ) {
1282 if ( isset( $module[2] ) ) {
1283 foreach ( $module[2] as &$dependency ) {
1284 if ( isset( $index[$dependency] ) ) {
1285 $dependency = $index[$dependency];
1291 array_walk( $name, array( 'self', 'trimArray' ) );
1293 return Xml
::encodeJsCall(
1294 'mw.loader.register',
1296 ResourceLoader
::inDebugMode()
1299 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1300 self
::trimArray( $registration );
1301 return Xml
::encodeJsCall(
1302 'mw.loader.register',
1304 ResourceLoader
::inDebugMode()
1310 * Returns JS code which calls mw.loader.addSource() with the given
1311 * parameters. Has two calling conventions:
1313 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1314 * Register a single source
1316 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1317 * Register sources with the given IDs and properties.
1319 * @param string $id Source ID
1320 * @param array $properties Source properties (see addSource())
1323 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1324 if ( is_array( $id ) ) {
1325 return Xml
::encodeJsCall(
1326 'mw.loader.addSource',
1328 ResourceLoader
::inDebugMode()
1331 return Xml
::encodeJsCall(
1332 'mw.loader.addSource',
1333 array( $id, $properties ),
1334 ResourceLoader
::inDebugMode()
1340 * Returns JS code which runs given JS code if the client-side framework is
1343 * @param string $script JavaScript code
1346 public static function makeLoaderConditionalScript( $script ) {
1347 return "if(window.mw){\n" . trim( $script ) . "\n}";
1351 * Returns JS code which will set the MediaWiki configuration array to
1354 * @param array $configuration List of configuration values keyed by variable name
1357 public static function makeConfigSetScript( array $configuration ) {
1358 return Xml
::encodeJsCall(
1360 array( $configuration ),
1361 ResourceLoader
::inDebugMode()
1366 * Convert an array of module names to a packed query string.
1368 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1369 * becomes 'foo.bar,baz|bar.baz,quux'
1370 * @param array $modules List of module names (strings)
1371 * @return string Packed query string
1373 public static function makePackedModulesString( $modules ) {
1374 $groups = array(); // array( prefix => array( suffixes ) )
1375 foreach ( $modules as $module ) {
1376 $pos = strrpos( $module, '.' );
1377 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1378 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1379 $groups[$prefix][] = $suffix;
1383 foreach ( $groups as $prefix => $suffixes ) {
1384 $p = $prefix === '' ?
'' : $prefix . '.';
1385 $arr[] = $p . implode( ',', $suffixes );
1387 $str = implode( '|', $arr );
1392 * Determine whether debug mode was requested
1393 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1396 public static function inDebugMode() {
1397 if ( self
::$debugMode === null ) {
1398 global $wgRequest, $wgResourceLoaderDebug;
1399 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1400 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1403 return self
::$debugMode;
1407 * Reset static members used for caching.
1409 * Global state and $wgRequest are evil, but we're using it right
1410 * now and sometimes we need to be able to force ResourceLoader to
1411 * re-evaluate the context because it has changed (e.g. in the test suite).
1413 public static function clearCache() {
1414 self
::$debugMode = null;
1418 * Build a load.php URL
1421 * @param string $source Name of the ResourceLoader source
1422 * @param ResourceLoaderContext $context
1423 * @param array $extraQuery
1424 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1426 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1427 $extraQuery = array()
1429 $query = self
::createLoaderQuery( $context, $extraQuery );
1430 $script = $this->getLoadScript( $source );
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( $script, $query ) . '&*', PROTO_RELATIVE
);
1438 * Build a load.php URL
1439 * @deprecated since 1.24, use createLoaderURL instead
1440 * @param array $modules Array of module names (strings)
1441 * @param string $lang Language code
1442 * @param string $skin Skin name
1443 * @param string|null $user User name. If null, the &user= parameter is omitted
1444 * @param string|null $version Versioning timestamp
1445 * @param bool $debug Whether the request should be in debug mode
1446 * @param string|null $only &only= parameter
1447 * @param bool $printable Printable mode
1448 * @param bool $handheld Handheld mode
1449 * @param array $extraQuery Extra query parameters to add
1450 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1452 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1453 $version = null, $debug = false, $only = null, $printable = false,
1454 $handheld = false, $extraQuery = array()
1456 global $wgLoadScript;
1458 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1459 $only, $printable, $handheld, $extraQuery
1462 // Prevent the IE6 extension check from being triggered (bug 28840)
1463 // by appending a character that's invalid in Windows extensions ('*')
1464 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1468 * Helper for createLoaderURL()
1471 * @see makeLoaderQuery
1472 * @param ResourceLoaderContext $context
1473 * @param array $extraQuery
1476 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1477 return self
::makeLoaderQuery(
1478 $context->getModules(),
1479 $context->getLanguage(),
1480 $context->getSkin(),
1481 $context->getUser(),
1482 $context->getVersion(),
1483 $context->getDebug(),
1484 $context->getOnly(),
1485 $context->getRequest()->getBool( 'printable' ),
1486 $context->getRequest()->getBool( 'handheld' ),
1492 * Build a query array (array representation of query string) for load.php. Helper
1493 * function for makeLoaderURL().
1495 * @param array $modules
1496 * @param string $lang
1497 * @param string $skin
1498 * @param string $user
1499 * @param string $version
1500 * @param bool $debug
1501 * @param string $only
1502 * @param bool $printable
1503 * @param bool $handheld
1504 * @param array $extraQuery
1508 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1509 $version = null, $debug = false, $only = null, $printable = false,
1510 $handheld = false, $extraQuery = array()
1513 'modules' => self
::makePackedModulesString( $modules ),
1516 'debug' => $debug ?
'true' : 'false',
1518 if ( $user !== null ) {
1519 $query['user'] = $user;
1521 if ( $version !== null ) {
1522 $query['version'] = $version;
1524 if ( $only !== null ) {
1525 $query['only'] = $only;
1528 $query['printable'] = 1;
1531 $query['handheld'] = 1;
1533 $query +
= $extraQuery;
1535 // Make queries uniform in order
1541 * Check a module name for validity.
1543 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1544 * at most 255 bytes.
1546 * @param string $moduleName Module name to check
1547 * @return bool Whether $moduleName is a valid module name
1549 public static function isValidModuleName( $moduleName ) {
1550 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1554 * Returns LESS compiler set up for use with MediaWiki
1556 * @param Config $config
1557 * @throws MWException
1561 public static function getLessCompiler( Config
$config ) {
1562 // When called from the installer, it is possible that a required PHP extension
1563 // is missing (at least for now; see bug 47564). If this is the case, throw an
1564 // exception (caught by the installer) to prevent a fatal error later on.
1565 if ( !class_exists( 'lessc' ) ) {
1566 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1568 if ( !function_exists( 'ctype_digit' ) ) {
1569 throw new MWException( 'lessc requires the Ctype extension' );
1572 $less = new lessc();
1573 $less->setPreserveComments( true );
1574 $less->setVariables( self
::getLessVars( $config ) );
1575 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1576 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1577 $less->registerFunction( $name, $func );
1583 * Get global LESS variables.
1585 * @param Config $config
1587 * @return array Map of variable names to string CSS values.
1589 public static function getLessVars( Config
$config ) {
1590 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1591 // Sort by key to ensure consistent hashing for cache lookups.