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 $requiredSourceProperties = array( 'loadScript' );
39 protected static $debugMode = null;
41 /** @var array Module name/ResourceLoaderModule object pairs */
42 protected $modules = array();
44 /** @var array Associative array mapping module name to info associative array */
45 protected $moduleInfos = array();
47 /** @var Config $config */
51 * @var array Associative array mapping framework ids to a list of names of test suite modules
52 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
54 protected $testModuleNames = array();
56 /** @var array E.g. array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) */
57 protected $sources = array();
60 protected $hasErrors = false;
63 * Load information stored in the database about modules.
65 * This method grabs modules dependencies from the database and updates modules
68 * This is not inside the module code because it is much faster to
69 * request all of the information at once than it is to have each module
70 * requests its own information. This sacrifice of modularity yields a substantial
71 * performance improvement.
73 * @param array $modules List of module names to preload information for
74 * @param ResourceLoaderContext $context Context to load the information within
76 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
77 if ( !count( $modules ) ) {
78 // Or else Database*::select() will explode, plus it's cheaper!
81 $dbr = wfGetDB( DB_SLAVE
);
82 $skin = $context->getSkin();
83 $lang = $context->getLanguage();
85 // Get file dependency information
86 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
87 'md_module' => $modules,
92 // Set modules' dependencies
93 $modulesWithDeps = array();
94 foreach ( $res as $row ) {
95 $module = $this->getModule( $row->md_module
);
97 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
98 $modulesWithDeps[] = $row->md_module
;
102 // Register the absence of a dependency row too
103 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
104 $module = $this->getModule( $name );
106 $this->getModule( $name )->setFileDependencies( $skin, array() );
110 // Get message blob mtimes. Only do this for modules with messages
111 $modulesWithMessages = array();
112 foreach ( $modules as $name ) {
113 $module = $this->getModule( $name );
114 if ( $module && count( $module->getMessages() ) ) {
115 $modulesWithMessages[] = $name;
118 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
119 if ( count( $modulesWithMessages ) ) {
120 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
121 'mr_resource' => $modulesWithMessages,
125 foreach ( $res as $row ) {
126 $module = $this->getModule( $row->mr_resource
);
128 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
129 unset( $modulesWithoutMessages[$row->mr_resource
] );
133 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
134 $module = $this->getModule( $name );
136 $module->setMsgBlobMtime( $lang, 0 );
142 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
144 * Available filters are:
146 * - minify-js \see JavaScriptMinifier::minify
147 * - minify-css \see CSSMin::minify
149 * If $data is empty, only contains whitespace or the filter was unknown,
150 * $data is returned unmodified.
152 * @param string $filter Name of filter to run
153 * @param string $data Text to filter, such as JavaScript or CSS text
154 * @param string $cacheReport Whether to include the cache key report
155 * @return string Filtered data, or a comment containing an error message
157 public function filter( $filter, $data, $cacheReport = true ) {
158 wfProfileIn( __METHOD__
);
160 // For empty/whitespace-only data or for unknown filters, don't perform
161 // any caching or processing
162 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
163 wfProfileOut( __METHOD__
);
168 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
169 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
170 $cache = wfGetCache( CACHE_ANYTHING
);
171 $cacheEntry = $cache->get( $key );
172 if ( is_string( $cacheEntry ) ) {
173 wfIncrStats( "rl-$filter-cache-hits" );
174 wfProfileOut( __METHOD__
);
179 // Run the filter - we've already verified one of these will work
181 wfIncrStats( "rl-$filter-cache-misses" );
184 $result = JavaScriptMinifier
::minify( $data,
185 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
186 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
188 if ( $cacheReport ) {
189 $result .= "\n/* cache key: $key */";
193 $result = CSSMin
::minify( $data );
194 if ( $cacheReport ) {
195 $result .= "\n/* cache key: $key */";
200 // Save filtered text to Memcached
201 $cache->set( $key, $result );
202 } catch ( Exception
$e ) {
203 MWExceptionHandler
::logException( $e );
204 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
205 $this->hasErrors
= true;
206 // Return exception as a comment
207 $result = self
::formatException( $e );
210 wfProfileOut( __METHOD__
);
218 * Register core modules and runs registration hooks.
219 * @param Config|null $config
221 public function __construct( Config
$config = null ) {
224 wfProfileIn( __METHOD__
);
226 if ( $config === null ) {
227 wfDebug( __METHOD__
. ' was called without providing a Config instance' );
228 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
231 $this->config
= $config;
233 // Add 'local' source first
236 array( 'loadScript' => wfScript( 'load' ), 'apiScript' => wfScript( 'api' ) )
240 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
242 // Register core modules
243 $this->register( include "$IP/resources/Resources.php" );
244 // Register extension modules
245 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
246 $this->register( $config->get( 'ResourceModules' ) );
248 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
249 $this->registerTestModules();
252 wfProfileOut( __METHOD__
);
258 public function getConfig() {
259 return $this->config
;
263 * Register a module with the ResourceLoader system.
265 * @param mixed $name Name of module as a string or List of name/object pairs as an array
266 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
267 * this may also be a ResourceLoaderModule object. Optional when using
268 * multiple-registration calling style.
269 * @throws MWException If a duplicate module registration is attempted
270 * @throws MWException If a module name contains illegal characters (pipes or commas)
271 * @throws MWException If something other than a ResourceLoaderModule is being registered
272 * @return bool False if there were any errors, in which case one or more modules were
275 public function register( $name, $info = null ) {
276 wfProfileIn( __METHOD__
);
278 // Allow multiple modules to be registered in one call
279 $registrations = is_array( $name ) ?
$name : array( $name => $info );
280 foreach ( $registrations as $name => $info ) {
281 // Disallow duplicate registrations
282 if ( isset( $this->moduleInfos
[$name] ) ) {
283 wfProfileOut( __METHOD__
);
284 // A module has already been registered by this name
285 throw new MWException(
286 'ResourceLoader duplicate registration error. ' .
287 'Another module has already been registered as ' . $name
291 // Check $name for validity
292 if ( !self
::isValidModuleName( $name ) ) {
293 wfProfileOut( __METHOD__
);
294 throw new MWException( "ResourceLoader module name '$name' is invalid, "
295 . "see ResourceLoader::isValidModuleName()" );
299 if ( $info instanceof ResourceLoaderModule
) {
300 $this->moduleInfos
[$name] = array( 'object' => $info );
301 $info->setName( $name );
302 $this->modules
[$name] = $info;
303 } elseif ( is_array( $info ) ) {
304 // New calling convention
305 $this->moduleInfos
[$name] = $info;
307 wfProfileOut( __METHOD__
);
308 throw new MWException(
309 'ResourceLoader module info type error for module \'' . $name .
310 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
314 // Last-minute changes
316 // Apply custom skin-defined styles to existing modules.
317 if ( $this->isFileModule( $name ) ) {
318 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
319 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
320 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
324 // If $name is preceded with a '+', the defined style files will be added to 'default'
325 // skinStyles, otherwise 'default' will be ignored as it normally would be.
326 if ( isset( $skinStyles[$name] ) ) {
327 $paths = (array)$skinStyles[$name];
328 $styleFiles = array();
329 } elseif ( isset( $skinStyles['+' . $name] ) ) {
330 $paths = (array)$skinStyles['+' . $name];
331 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
332 $this->moduleInfos
[$name]['skinStyles']['default'] :
338 // Add new file paths, remapping them to refer to our directories and not use settings
339 // from the module we're modifying. These can come from the base definition or be defined
341 list( $localBasePath, $remoteBasePath ) =
342 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
343 list( $localBasePath, $remoteBasePath ) =
344 ResourceLoaderFileModule
::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
346 foreach ( $paths as $path ) {
347 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
350 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
355 wfProfileOut( __METHOD__
);
360 public function registerTestModules() {
363 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
364 throw new MWException( 'Attempt to register JavaScript test modules '
365 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
366 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
369 wfProfileIn( __METHOD__
);
371 // Get core test suites
372 $testModules = array();
373 $testModules['qunit'] = array();
374 // Get other test suites (e.g. from extensions)
375 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
377 // Add the testrunner (which configures QUnit) to the dependencies.
378 // Since it must be ready before any of the test suites are executed.
379 foreach ( $testModules['qunit'] as &$module ) {
380 // Make sure all test modules are top-loading so that when QUnit starts
381 // on document-ready, it will run once and finish. If some tests arrive
382 // later (possibly after QUnit has already finished) they will be ignored.
383 $module['position'] = 'top';
384 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
387 $testModules['qunit'] =
388 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
390 foreach ( $testModules as $id => $names ) {
391 // Register test modules
392 $this->register( $testModules[$id] );
394 // Keep track of their names so that they can be loaded together
395 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
398 wfProfileOut( __METHOD__
);
402 * Add a foreign source of modules.
405 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
407 * @param mixed $id Source ID (string), or array( id1 => props1, id2 => props2, ... )
408 * @param array $properties Source properties
409 * @throws MWException
411 public function addSource( $id, $properties = null ) {
412 // Allow multiple sources to be registered in one call
413 if ( is_array( $id ) ) {
414 foreach ( $id as $key => $value ) {
415 $this->addSource( $key, $value );
420 // Disallow duplicates
421 if ( isset( $this->sources
[$id] ) ) {
422 throw new MWException(
423 'ResourceLoader duplicate source addition error. ' .
424 'Another source has already been registered as ' . $id
428 // Validate properties
429 foreach ( self
::$requiredSourceProperties as $prop ) {
430 if ( !isset( $properties[$prop] ) ) {
431 throw new MWException( "Required property $prop missing from source ID $id" );
435 $this->sources
[$id] = $properties;
439 * Get a list of module names.
441 * @return array List of module names
443 public function getModuleNames() {
444 return array_keys( $this->moduleInfos
);
448 * Get a list of test module names for one (or all) frameworks.
450 * If the given framework id is unknkown, or if the in-object variable is not an array,
451 * then it will return an empty array.
453 * @param string $framework Get only the test module names for one
454 * particular framework (optional)
457 public function getTestModuleNames( $framework = 'all' ) {
458 /** @todo api siteinfo prop testmodulenames modulenames */
459 if ( $framework == 'all' ) {
460 return $this->testModuleNames
;
461 } elseif ( isset( $this->testModuleNames
[$framework] )
462 && is_array( $this->testModuleNames
[$framework] )
464 return $this->testModuleNames
[$framework];
471 * Get the ResourceLoaderModule object for a given module name.
473 * If an array of module parameters exists but a ResourceLoaderModule object has not
474 * yet been instantiated, this method will instantiate and cache that object such that
475 * subsequent calls simply return the same object.
477 * @param string $name Module name
478 * @return ResourceLoaderModule|null If module has been registered, return a
479 * ResourceLoaderModule instance. Otherwise, return null.
481 public function getModule( $name ) {
482 if ( !isset( $this->modules
[$name] ) ) {
483 if ( !isset( $this->moduleInfos
[$name] ) ) {
487 // Construct the requested object
488 $info = $this->moduleInfos
[$name];
489 /** @var ResourceLoaderModule $object */
490 if ( isset( $info['object'] ) ) {
491 // Object given in info array
492 $object = $info['object'];
494 if ( !isset( $info['class'] ) ) {
495 $class = 'ResourceLoaderFileModule';
497 $class = $info['class'];
499 /** @var ResourceLoaderModule $object */
500 $object = new $class( $info );
501 $object->setConfig( $this->getConfig() );
503 $object->setName( $name );
504 $this->modules
[$name] = $object;
507 return $this->modules
[$name];
511 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
513 * @param string $name Module name
516 protected function isFileModule( $name ) {
517 if ( !isset( $this->moduleInfos
[$name] ) ) {
520 $info = $this->moduleInfos
[$name];
521 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
528 * Get the list of sources.
530 * @return array Like array( id => array of properties, .. )
532 public function getSources() {
533 return $this->sources
;
537 * Get the URL to the load.php endpoint for the given
538 * ResourceLoader source
541 * @param string $source
542 * @throws MWException On an invalid $source name
545 public function getLoadScript( $source ) {
546 if ( !isset( $this->sources
[$source] ) ) {
547 throw new MWException( "The $source source was never registered in ResourceLoader." );
549 return $this->sources
[$source]['loadScript'];
553 * Output a response to a load request, including the content-type header.
555 * @param ResourceLoaderContext $context Context in which a response should be formed
557 public function respond( ResourceLoaderContext
$context ) {
558 // Use file cache if enabled and available...
559 if ( $this->config
->get( 'UseFileCache' ) ) {
560 $fileCache = ResourceFileCache
::newFromContext( $context );
561 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
562 return; // output handled
566 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
567 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
568 // is used: ob_clean() will clear the GZIP header in that case and it won't come
569 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
570 // the whole thing in our own output buffer to be sure the active buffer
571 // doesn't use ob_gzhandler.
572 // See http://bugs.php.net/bug.php?id=36514
575 wfProfileIn( __METHOD__
);
578 // Find out which modules are missing and instantiate the others
581 foreach ( $context->getModules() as $name ) {
582 $module = $this->getModule( $name );
584 // Do not allow private modules to be loaded from the web.
585 // This is a security issue, see bug 34907.
586 if ( $module->getGroup() === 'private' ) {
587 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
588 $this->hasErrors
= true;
589 // Add exception to the output as a comment
590 $errors .= self
::makeComment( "Cannot show private module \"$name\"" );
594 $modules[$name] = $module;
600 // Preload information needed to the mtime calculation below
602 $this->preloadModuleInfo( array_keys( $modules ), $context );
603 } catch ( Exception
$e ) {
604 MWExceptionHandler
::logException( $e );
605 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
606 $this->hasErrors
= true;
607 // Add exception to the output as a comment
608 $errors .= self
::formatException( $e );
611 wfProfileIn( __METHOD__
. '-getModifiedTime' );
613 // To send Last-Modified and support If-Modified-Since, we need to detect
614 // the last modified time
615 $mtime = wfTimestamp( TS_UNIX
, $this->config
->get( 'CacheEpoch' ) );
616 foreach ( $modules as $module ) {
618 * @var $module ResourceLoaderModule
621 // Calculate maximum modified time
622 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
623 } catch ( Exception
$e ) {
624 MWExceptionHandler
::logException( $e );
625 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
626 $this->hasErrors
= true;
627 // Add exception to the output as a comment
628 $errors .= self
::formatException( $e );
632 wfProfileOut( __METHOD__
. '-getModifiedTime' );
634 // If there's an If-Modified-Since header, respond with a 304 appropriately
635 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
636 wfProfileOut( __METHOD__
);
637 return; // output handled (buffers cleared)
640 // Generate a response
641 $response = $this->makeModuleResponse( $context, $modules, $missing );
643 // Prepend comments indicating exceptions
644 $response = $errors . $response;
646 // Capture any PHP warnings from the output buffer and append them to the
647 // response in a comment if we're in debug mode.
648 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
649 $response = self
::makeComment( $warnings ) . $response;
650 $this->hasErrors
= true;
653 // Save response to file cache unless there are errors
654 if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
655 // Cache single modules...and other requests if there are enough hits
656 if ( ResourceFileCache
::useFileCache( $context ) ) {
657 if ( $fileCache->isCacheWorthy() ) {
658 $fileCache->saveText( $response );
660 $fileCache->incrMissesRecent( $context->getRequest() );
665 // Send content type and cache related headers
666 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
668 // Remove the output buffer and output the response
672 wfProfileOut( __METHOD__
);
676 * Send content type and last modified headers to the client.
677 * @param ResourceLoaderContext $context
678 * @param string $mtime TS_MW timestamp to use for last-modified
679 * @param bool $errors Whether there are commented-out errors in the response
682 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
683 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
684 // If a version wasn't specified we need a shorter expiry time for updates
685 // to propagate to clients quickly
686 // If there were errors, we also need a shorter expiry time so we can recover quickly
687 if ( is_null( $context->getVersion() ) ||
$errors ) {
688 $maxage = $rlMaxage['unversioned']['client'];
689 $smaxage = $rlMaxage['unversioned']['server'];
690 // If a version was specified we can use a longer expiry time since changing
691 // version numbers causes cache misses
693 $maxage = $rlMaxage['versioned']['client'];
694 $smaxage = $rlMaxage['versioned']['server'];
696 if ( $context->getOnly() === 'styles' ) {
697 header( 'Content-Type: text/css; charset=utf-8' );
698 header( 'Access-Control-Allow-Origin: *' );
700 header( 'Content-Type: text/javascript; charset=utf-8' );
702 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
703 if ( $context->getDebug() ) {
704 // Do not cache debug responses
705 header( 'Cache-Control: private, no-cache, must-revalidate' );
706 header( 'Pragma: no-cache' );
708 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
709 $exp = min( $maxage, $smaxage );
710 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
715 * Respond with 304 Last Modified if appropiate.
717 * If there's an If-Modified-Since header, respond with a 304 appropriately
718 * and clear out the output buffer. If the client cache is too old then do nothing.
720 * @param ResourceLoaderContext $context
721 * @param string $mtime The TS_MW timestamp to check the header against
722 * @return bool True if 304 header sent and output handled
724 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
725 // If there's an If-Modified-Since header, respond with a 304 appropriately
726 // Some clients send "timestamp;length=123". Strip the part after the first ';'
727 // so we get a valid timestamp.
728 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
729 // Never send 304s in debug mode
730 if ( $ims !== false && !$context->getDebug() ) {
731 $imsTS = strtok( $ims, ';' );
732 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
733 // There's another bug in ob_gzhandler (see also the comment at
734 // the top of this function) that causes it to gzip even empty
735 // responses, meaning it's impossible to produce a truly empty
736 // response (because the gzip header is always there). This is
737 // a problem because 304 responses have to be completely empty
738 // per the HTTP spec, and Firefox behaves buggily when they're not.
739 // See also http://bugs.php.net/bug.php?id=51579
740 // To work around this, we tear down all output buffering before
742 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
744 header( 'HTTP/1.0 304 Not Modified' );
745 header( 'Status: 304 Not Modified' );
753 * Send out code for a response from file cache if possible.
755 * @param ResourceFileCache $fileCache Cache object for this request URL
756 * @param ResourceLoaderContext $context Context in which to generate a response
757 * @return bool If this found a cache file and handled the response
759 protected function tryRespondFromFileCache(
760 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
762 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
763 // Buffer output to catch warnings.
765 // Get the maximum age the cache can be
766 $maxage = is_null( $context->getVersion() )
767 ?
$rlMaxage['unversioned']['server']
768 : $rlMaxage['versioned']['server'];
769 // Minimum timestamp the cache file must have
770 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
772 try { // RL always hits the DB on file cache miss...
774 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
775 $good = $fileCache->isCacheGood(); // cache existence check
779 $ts = $fileCache->cacheTimestamp();
780 // Send content type and cache headers
781 $this->sendResponseHeaders( $context, $ts, false );
782 // If there's an If-Modified-Since header, respond with a 304 appropriately
783 if ( $this->tryRespondLastModified( $context, $ts ) ) {
784 return false; // output handled (buffers cleared)
786 $response = $fileCache->fetchText();
787 // Capture any PHP warnings from the output buffer and append them to the
788 // response in a comment if we're in debug mode.
789 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
790 $response = "/*\n$warnings\n*/\n" . $response;
792 // Remove the output buffer and output the response
794 echo $response . "\n/* Cached {$ts} */";
795 return true; // cache hit
800 return false; // cache miss
804 * Generate a CSS or JS comment block.
806 * Only use this for public data, not error message details.
808 * @param string $text
811 public static function makeComment( $text ) {
812 $encText = str_replace( '*/', '* /', $text );
813 return "/*\n$encText\n*/\n";
817 * Handle exception display.
819 * @param Exception $e Exception to be shown to the user
820 * @return string Sanitized text that can be returned to the user
822 public static function formatException( $e ) {
823 global $wgShowExceptionDetails;
825 if ( $wgShowExceptionDetails ) {
826 return self
::makeComment( $e->__toString() );
828 return self
::makeComment( wfMessage( 'internalerror' )->text() );
833 * Generate code for a response.
835 * @param ResourceLoaderContext $context Context in which to generate a response
836 * @param array $modules List of module objects keyed by module name
837 * @param array $missing List of requested module names that are unregistered (optional)
838 * @return string Response data
840 public function makeModuleResponse( ResourceLoaderContext
$context,
841 array $modules, array $missing = array()
847 if ( !count( $modules ) && !count( $missing ) ) {
848 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
849 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
850 no modules were requested. Max made me put this here. */";
853 wfProfileIn( __METHOD__
);
856 if ( $context->shouldIncludeMessages() ) {
858 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
859 } catch ( Exception
$e ) {
860 MWExceptionHandler
::logException( $e );
863 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
865 $this->hasErrors
= true;
866 // Add exception to the output as a comment
867 $exceptions .= self
::formatException( $e );
873 foreach ( $missing as $name ) {
874 $states[$name] = 'missing';
879 foreach ( $modules as $name => $module ) {
881 * @var $module ResourceLoaderModule
884 wfProfileIn( __METHOD__
. '-' . $name );
887 if ( $context->shouldIncludeScripts() ) {
888 // If we are in debug mode, we'll want to return an array of URLs if possible
889 // However, we can't do this if the module doesn't support it
890 // We also can't do this if there is an only= parameter, because we have to give
891 // the module a way to return a load.php URL without causing an infinite loop
892 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
893 $scripts = $module->getScriptURLsForDebug( $context );
895 $scripts = $module->getScript( $context );
896 // rtrim() because there are usually a few line breaks
897 // after the last ';'. A new line at EOF, a new line
898 // added by ResourceLoaderFileModule::readScriptFiles, etc.
899 if ( is_string( $scripts )
900 && strlen( $scripts )
901 && substr( rtrim( $scripts ), -1 ) !== ';'
903 // Append semicolon to prevent weird bugs caused by files not
904 // terminating their statements right (bug 27054)
911 if ( $context->shouldIncludeStyles() ) {
912 // Don't create empty stylesheets like array( '' => '' ) for modules
913 // that don't *have* any stylesheets (bug 38024).
914 $stylePairs = $module->getStyles( $context );
915 if ( count( $stylePairs ) ) {
916 // If we are in debug mode without &only= set, we'll want to return an array of URLs
917 // See comment near shouldIncludeScripts() for more details
918 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
920 'url' => $module->getStyleURLsForDebug( $context )
923 // Minify CSS before embedding in mw.loader.implement call
924 // (unless in debug mode)
925 if ( !$context->getDebug() ) {
926 foreach ( $stylePairs as $media => $style ) {
927 // Can be either a string or an array of strings.
928 if ( is_array( $style ) ) {
929 $stylePairs[$media] = array();
930 foreach ( $style as $cssText ) {
931 if ( is_string( $cssText ) ) {
932 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
935 } elseif ( is_string( $style ) ) {
936 $stylePairs[$media] = $this->filter( 'minify-css', $style );
940 // Wrap styles into @media groups as needed and flatten into a numerical array
942 'css' => self
::makeCombinedStyles( $stylePairs )
949 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
952 switch ( $context->getOnly() ) {
954 if ( is_string( $scripts ) ) {
955 // Load scripts raw...
957 } elseif ( is_array( $scripts ) ) {
958 // ...except when $scripts is an array of URLs
959 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
963 // We no longer seperate into media, they are all combined now with
964 // custom media type groups into @media .. {} sections as part of the css string.
965 // Module returns either an empty array or a numerical array with css strings.
966 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
969 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
972 $out .= self
::makeLoaderImplementScript(
976 new XmlJsCode( $messagesBlob )
980 } catch ( Exception
$e ) {
981 MWExceptionHandler
::logException( $e );
982 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
983 $this->hasErrors
= true;
984 // Add exception to the output as a comment
985 $exceptions .= self
::formatException( $e );
987 // Respond to client with error-state instead of module implementation
988 $states[$name] = 'error';
989 unset( $modules[$name] );
991 $isRaw |
= $module->isRaw();
992 wfProfileOut( __METHOD__
. '-' . $name );
995 // Update module states
996 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
997 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
998 // Set the state of modules loaded as only scripts to ready as
999 // they don't have an mw.loader.implement wrapper that sets the state
1000 foreach ( $modules as $name => $module ) {
1001 $states[$name] = 'ready';
1005 // Set the state of modules we didn't respond to with mw.loader.implement
1006 if ( count( $states ) ) {
1007 $out .= self
::makeLoaderStateScript( $states );
1010 if ( $context->getOnly() === 'scripts' ) {
1011 // In only=script requests for modules that are not raw (e.g. not the startup module)
1012 // ensure the execution is conditional to avoid situations where browsers with an
1013 // unsupported environment do unconditionally execute a module's scripts. Otherwise users
1014 // will get things like "ReferenceError: mw is undefined" or "jQuery is undefined" from
1015 // legacy scripts loaded with only=scripts (such as the 'site' module).
1016 $out = self
::makeLoaderConditionalScript( $out );
1019 if ( count( $states ) ) {
1020 $exceptions .= self
::makeComment(
1021 'Problematic modules: ' . FormatJson
::encode( $states, ResourceLoader
::inDebugMode() )
1026 if ( !$context->getDebug() ) {
1027 if ( $context->getOnly() === 'styles' ) {
1028 $out = $this->filter( 'minify-css', $out );
1030 $out = $this->filter( 'minify-js', $out );
1034 wfProfileOut( __METHOD__
);
1035 return $exceptions . $out;
1038 /* Static Methods */
1041 * Return JS code that calls mw.loader.implement with given module properties.
1043 * @param string $name Module name
1044 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1045 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1046 * to CSS files keyed by media type
1047 * @param mixed $messages List of messages associated with this module. May either be an
1048 * associative array mapping message key to value, or a JSON-encoded message blob containing
1049 * the same data, wrapped in an XmlJsCode object.
1050 * @throws MWException
1053 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
1054 if ( is_string( $scripts ) ) {
1055 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1056 } elseif ( !is_array( $scripts ) ) {
1057 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1059 return Xml
::encodeJsCall(
1060 'mw.loader.implement',
1064 // Force objects. mw.loader.implement requires them to be javascript objects.
1065 // Although these variables are associative arrays, which become javascript
1066 // objects through json_encode. In many cases they will be empty arrays, and
1067 // PHP/json_encode() consider empty arrays to be numerical arrays and
1068 // output javascript "[]" instead of "{}". This fixes that.
1072 ResourceLoader
::inDebugMode()
1077 * Returns JS code which, when called, will register a given list of messages.
1079 * @param mixed $messages Either an associative array mapping message key to value, or a
1080 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1083 public static function makeMessageSetScript( $messages ) {
1084 return Xml
::encodeJsCall(
1086 array( (object)$messages ),
1087 ResourceLoader
::inDebugMode()
1092 * Combines an associative array mapping media type to CSS into a
1093 * single stylesheet with "@media" blocks.
1095 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1098 public static function makeCombinedStyles( array $stylePairs ) {
1100 foreach ( $stylePairs as $media => $styles ) {
1101 // ResourceLoaderFileModule::getStyle can return the styles
1102 // as a string or an array of strings. This is to allow separation in
1104 $styles = (array)$styles;
1105 foreach ( $styles as $style ) {
1106 $style = trim( $style );
1107 // Don't output an empty "@media print { }" block (bug 40498)
1108 if ( $style !== '' ) {
1109 // Transform the media type based on request params and config
1110 // The way that this relies on $wgRequest to propagate request params is slightly evil
1111 $media = OutputPage
::transformCssMedia( $media );
1113 if ( $media === '' ||
$media == 'all' ) {
1115 } elseif ( is_string( $media ) ) {
1116 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1126 * Returns a JS call to mw.loader.state, which sets the state of a
1127 * module or modules to a given value. Has two calling conventions:
1129 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1130 * Set the state of a single module called $name to $state
1132 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1133 * Set the state of modules with the given names to the given states
1135 * @param string $name
1136 * @param string $state
1139 public static function makeLoaderStateScript( $name, $state = null ) {
1140 if ( is_array( $name ) ) {
1141 return Xml
::encodeJsCall(
1144 ResourceLoader
::inDebugMode()
1147 return Xml
::encodeJsCall(
1149 array( $name, $state ),
1150 ResourceLoader
::inDebugMode()
1156 * Returns JS code which calls the script given by $script. The script will
1157 * be called with local variables name, version, dependencies and group,
1158 * which will have values corresponding to $name, $version, $dependencies
1159 * and $group as supplied.
1161 * @param string $name Module name
1162 * @param int $version Module version number as a timestamp
1163 * @param array $dependencies List of module names on which this module depends
1164 * @param string $group Group which the module is in.
1165 * @param string $source Source of the module, or 'local' if not foreign.
1166 * @param string $script JavaScript code
1169 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1170 $group, $source, $script
1172 $script = str_replace( "\n", "\n\t", trim( $script ) );
1173 return Xml
::encodeJsCall(
1174 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1175 array( $name, $version, $dependencies, $group, $source ),
1176 ResourceLoader
::inDebugMode()
1181 * Returns JS code which calls mw.loader.register with the given
1182 * parameters. Has three calling conventions:
1184 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source, $skip ):
1185 * Register a single module.
1187 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1188 * Register modules with the given names.
1190 * - ResourceLoader::makeLoaderRegisterScript( array(
1191 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1192 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1195 * Registers modules with the given names and parameters.
1197 * @param string $name Module name
1198 * @param int $version Module version number as a timestamp
1199 * @param array $dependencies List of module names on which this module depends
1200 * @param string $group Group which the module is in
1201 * @param string $source Source of the module, or 'local' if not foreign
1202 * @param string $skip Script body of the skip function
1205 public static function makeLoaderRegisterScript( $name, $version = null,
1206 $dependencies = null, $group = null, $source = null, $skip = null
1208 if ( is_array( $name ) ) {
1209 return Xml
::encodeJsCall(
1210 'mw.loader.register',
1212 ResourceLoader
::inDebugMode()
1215 $version = (int)$version > 1 ?
(int)$version : 1;
1216 return Xml
::encodeJsCall(
1217 'mw.loader.register',
1218 array( $name, $version, $dependencies, $group, $source, $skip ),
1219 ResourceLoader
::inDebugMode()
1225 * Returns JS code which calls mw.loader.addSource() with the given
1226 * parameters. Has two calling conventions:
1228 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1229 * Register a single source
1231 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1232 * Register sources with the given IDs and properties.
1234 * @param string $id Source ID
1235 * @param array $properties Source properties (see addSource())
1238 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1239 if ( is_array( $id ) ) {
1240 return Xml
::encodeJsCall(
1241 'mw.loader.addSource',
1243 ResourceLoader
::inDebugMode()
1246 return Xml
::encodeJsCall(
1247 'mw.loader.addSource',
1248 array( $id, $properties ),
1249 ResourceLoader
::inDebugMode()
1255 * Returns JS code which runs given JS code if the client-side framework is
1258 * @param string $script JavaScript code
1261 public static function makeLoaderConditionalScript( $script ) {
1262 return "if(window.mw){\n" . trim( $script ) . "\n}";
1266 * Returns JS code which will set the MediaWiki configuration array to
1269 * @param array $configuration List of configuration values keyed by variable name
1272 public static function makeConfigSetScript( array $configuration ) {
1273 return Xml
::encodeJsCall(
1275 array( $configuration ),
1276 ResourceLoader
::inDebugMode()
1281 * Convert an array of module names to a packed query string.
1283 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1284 * becomes 'foo.bar,baz|bar.baz,quux'
1285 * @param array $modules List of module names (strings)
1286 * @return string Packed query string
1288 public static function makePackedModulesString( $modules ) {
1289 $groups = array(); // array( prefix => array( suffixes ) )
1290 foreach ( $modules as $module ) {
1291 $pos = strrpos( $module, '.' );
1292 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1293 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1294 $groups[$prefix][] = $suffix;
1298 foreach ( $groups as $prefix => $suffixes ) {
1299 $p = $prefix === '' ?
'' : $prefix . '.';
1300 $arr[] = $p . implode( ',', $suffixes );
1302 $str = implode( '|', $arr );
1307 * Determine whether debug mode was requested
1308 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1311 public static function inDebugMode() {
1312 if ( self
::$debugMode === null ) {
1313 global $wgRequest, $wgResourceLoaderDebug;
1314 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1315 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1318 return self
::$debugMode;
1322 * Reset static members used for caching.
1324 * Global state and $wgRequest are evil, but we're using it right
1325 * now and sometimes we need to be able to force ResourceLoader to
1326 * re-evaluate the context because it has changed (e.g. in the test suite).
1328 public static function clearCache() {
1329 self
::$debugMode = null;
1333 * Build a load.php URL
1336 * @param string $source Name of the ResourceLoader source
1337 * @param ResourceLoaderContext $context
1338 * @param array $extraQuery
1339 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1341 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1342 $extraQuery = array()
1344 $query = self
::createLoaderQuery( $context, $extraQuery );
1345 $script = $this->getLoadScript( $source );
1347 // Prevent the IE6 extension check from being triggered (bug 28840)
1348 // by appending a character that's invalid in Windows extensions ('*')
1349 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1353 * Build a load.php URL
1354 * @deprecated since 1.24, use createLoaderURL instead
1355 * @param array $modules Array of module names (strings)
1356 * @param string $lang Language code
1357 * @param string $skin Skin name
1358 * @param string|null $user User name. If null, the &user= parameter is omitted
1359 * @param string|null $version Versioning timestamp
1360 * @param bool $debug Whether the request should be in debug mode
1361 * @param string|null $only &only= parameter
1362 * @param bool $printable Printable mode
1363 * @param bool $handheld Handheld mode
1364 * @param array $extraQuery Extra query parameters to add
1365 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1367 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1368 $version = null, $debug = false, $only = null, $printable = false,
1369 $handheld = false, $extraQuery = array()
1371 global $wgLoadScript;
1373 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1374 $only, $printable, $handheld, $extraQuery
1377 // Prevent the IE6 extension check from being triggered (bug 28840)
1378 // by appending a character that's invalid in Windows extensions ('*')
1379 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1383 * Helper for createLoaderURL()
1386 * @see makeLoaderQuery
1387 * @param ResourceLoaderContext $context
1388 * @param array $extraQuery
1391 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1392 return self
::makeLoaderQuery(
1393 $context->getModules(),
1394 $context->getLanguage(),
1395 $context->getSkin(),
1396 $context->getUser(),
1397 $context->getVersion(),
1398 $context->getDebug(),
1399 $context->getOnly(),
1400 $context->getRequest()->getBool( 'printable' ),
1401 $context->getRequest()->getBool( 'handheld' ),
1407 * Build a query array (array representation of query string) for load.php. Helper
1408 * function for makeLoaderURL().
1410 * @param array $modules
1411 * @param string $lang
1412 * @param string $skin
1413 * @param string $user
1414 * @param string $version
1415 * @param bool $debug
1416 * @param string $only
1417 * @param bool $printable
1418 * @param bool $handheld
1419 * @param array $extraQuery
1423 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1424 $version = null, $debug = false, $only = null, $printable = false,
1425 $handheld = false, $extraQuery = array()
1428 'modules' => self
::makePackedModulesString( $modules ),
1431 'debug' => $debug ?
'true' : 'false',
1433 if ( $user !== null ) {
1434 $query['user'] = $user;
1436 if ( $version !== null ) {
1437 $query['version'] = $version;
1439 if ( $only !== null ) {
1440 $query['only'] = $only;
1443 $query['printable'] = 1;
1446 $query['handheld'] = 1;
1448 $query +
= $extraQuery;
1450 // Make queries uniform in order
1456 * Check a module name for validity.
1458 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1459 * at most 255 bytes.
1461 * @param string $moduleName Module name to check
1462 * @return bool Whether $moduleName is a valid module name
1464 public static function isValidModuleName( $moduleName ) {
1465 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1469 * Returns LESS compiler set up for use with MediaWiki
1471 * @param Config $config
1472 * @throws MWException
1476 public static function getLessCompiler( Config
$config ) {
1477 // When called from the installer, it is possible that a required PHP extension
1478 // is missing (at least for now; see bug 47564). If this is the case, throw an
1479 // exception (caught by the installer) to prevent a fatal error later on.
1480 if ( !function_exists( 'ctype_digit' ) ) {
1481 throw new MWException( 'lessc requires the Ctype extension' );
1484 $less = new lessc();
1485 $less->setPreserveComments( true );
1486 $less->setVariables( self
::getLessVars( $config ) );
1487 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1488 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1489 $less->registerFunction( $name, $func );
1495 * Get global LESS variables.
1497 * @param Config $config
1499 * @return array Map of variable names to string CSS values.
1501 public static function getLessVars( Config
$config ) {
1502 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1503 // Sort by key to ensure consistent hashing for cache lookups.