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();
48 * @var array Associative array mapping framework ids to a list of names of test suite modules
49 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
51 protected $testModuleNames = array();
53 /** @var array E.g. array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) */
54 protected $sources = array();
57 protected $hasErrors = false;
60 * Load information stored in the database about modules.
62 * This method grabs modules dependencies from the database and updates modules
65 * This is not inside the module code because it is much faster to
66 * request all of the information at once than it is to have each module
67 * requests its own information. This sacrifice of modularity yields a substantial
68 * performance improvement.
70 * @param array $modules List of module names to preload information for
71 * @param ResourceLoaderContext $context Context to load the information within
73 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
74 if ( !count( $modules ) ) {
75 // Or else Database*::select() will explode, plus it's cheaper!
78 $dbr = wfGetDB( DB_SLAVE
);
79 $skin = $context->getSkin();
80 $lang = $context->getLanguage();
82 // Get file dependency information
83 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
84 'md_module' => $modules,
89 // Set modules' dependencies
90 $modulesWithDeps = array();
91 foreach ( $res as $row ) {
92 $module = $this->getModule( $row->md_module
);
94 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
95 $modulesWithDeps[] = $row->md_module
;
99 // Register the absence of a dependency row too
100 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
101 $module = $this->getModule( $name );
103 $this->getModule( $name )->setFileDependencies( $skin, array() );
107 // Get message blob mtimes. Only do this for modules with messages
108 $modulesWithMessages = array();
109 foreach ( $modules as $name ) {
110 $module = $this->getModule( $name );
111 if ( $module && count( $module->getMessages() ) ) {
112 $modulesWithMessages[] = $name;
115 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
116 if ( count( $modulesWithMessages ) ) {
117 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
118 'mr_resource' => $modulesWithMessages,
122 foreach ( $res as $row ) {
123 $module = $this->getModule( $row->mr_resource
);
125 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
126 unset( $modulesWithoutMessages[$row->mr_resource
] );
130 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
131 $module = $this->getModule( $name );
133 $module->setMsgBlobMtime( $lang, 0 );
139 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
141 * Available filters are:
143 * - minify-js \see JavaScriptMinifier::minify
144 * - minify-css \see CSSMin::minify
146 * If $data is empty, only contains whitespace or the filter was unknown,
147 * $data is returned unmodified.
149 * @param string $filter Name of filter to run
150 * @param string $data Text to filter, such as JavaScript or CSS text
151 * @param string $cacheReport Whether to include the cache key report
152 * @return string Filtered data, or a comment containing an error message
154 public function filter( $filter, $data, $cacheReport = true ) {
155 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
156 wfProfileIn( __METHOD__
);
158 // For empty/whitespace-only data or for unknown filters, don't perform
159 // any caching or processing
160 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
161 wfProfileOut( __METHOD__
);
166 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
167 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
168 $cache = wfGetCache( CACHE_ANYTHING
);
169 $cacheEntry = $cache->get( $key );
170 if ( is_string( $cacheEntry ) ) {
171 wfIncrStats( "rl-$filter-cache-hits" );
172 wfProfileOut( __METHOD__
);
177 // Run the filter - we've already verified one of these will work
179 wfIncrStats( "rl-$filter-cache-misses" );
182 $result = JavaScriptMinifier
::minify( $data,
183 $wgResourceLoaderMinifierStatementsOnOwnLine,
184 $wgResourceLoaderMinifierMaxLineLength
186 if ( $cacheReport ) {
187 $result .= "\n/* cache key: $key */";
191 $result = CSSMin
::minify( $data );
192 if ( $cacheReport ) {
193 $result .= "\n/* cache key: $key */";
198 // Save filtered text to Memcached
199 $cache->set( $key, $result );
200 } catch ( Exception
$e ) {
201 MWExceptionHandler
::logException( $e );
202 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
203 $this->hasErrors
= true;
204 // Return exception as a comment
205 $result = self
::formatException( $e );
208 wfProfileOut( __METHOD__
);
216 * Register core modules and runs registration hooks.
218 public function __construct() {
219 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
221 wfProfileIn( __METHOD__
);
223 // Add 'local' source first
226 array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) )
230 $this->addSource( $wgResourceLoaderSources );
232 // Register core modules
233 $this->register( include "$IP/resources/Resources.php" );
234 // Register extension modules
235 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
236 $this->register( $wgResourceModules );
238 if ( $wgEnableJavaScriptTest === true ) {
239 $this->registerTestModules();
242 wfProfileOut( __METHOD__
);
246 * Register a module with the ResourceLoader system.
248 * @param mixed $name Name of module as a string or List of name/object pairs as an array
249 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
250 * this may also be a ResourceLoaderModule object. Optional when using
251 * multiple-registration calling style.
252 * @throws MWException If a duplicate module registration is attempted
253 * @throws MWException If a module name contains illegal characters (pipes or commas)
254 * @throws MWException If something other than a ResourceLoaderModule is being registered
255 * @return bool False if there were any errors, in which case one or more modules were
258 public function register( $name, $info = null ) {
259 wfProfileIn( __METHOD__
);
261 // Allow multiple modules to be registered in one call
262 $registrations = is_array( $name ) ?
$name : array( $name => $info );
263 foreach ( $registrations as $name => $info ) {
264 // Disallow duplicate registrations
265 if ( isset( $this->moduleInfos
[$name] ) ) {
266 wfProfileOut( __METHOD__
);
267 // A module has already been registered by this name
268 throw new MWException(
269 'ResourceLoader duplicate registration error. ' .
270 'Another module has already been registered as ' . $name
274 // Check $name for validity
275 if ( !self
::isValidModuleName( $name ) ) {
276 wfProfileOut( __METHOD__
);
277 throw new MWException( "ResourceLoader module name '$name' is invalid, "
278 . "see ResourceLoader::isValidModuleName()" );
282 if ( $info instanceof ResourceLoaderModule
) {
283 $this->moduleInfos
[$name] = array( 'object' => $info );
284 $info->setName( $name );
285 $this->modules
[$name] = $info;
286 } elseif ( is_array( $info ) ) {
287 // New calling convention
288 $this->moduleInfos
[$name] = $info;
290 wfProfileOut( __METHOD__
);
291 throw new MWException(
292 'ResourceLoader module info type error for module \'' . $name .
293 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
297 // Last-minute changes
299 // Apply custom skin-defined styles to existing modules.
300 if ( $this->isFileModule( $name ) ) {
301 global $wgResourceModuleSkinStyles;
302 foreach ( $wgResourceModuleSkinStyles as $skinName => $skinStyles ) {
303 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
304 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
308 // If $name is preceded with a '+', the defined style files will be added to 'default'
309 // skinStyles, otherwise 'default' will be ignored as it normally would be.
310 if ( isset( $skinStyles[$name] ) ) {
311 $paths = (array)$skinStyles[$name];
312 $styleFiles = array();
313 } elseif ( isset( $skinStyles['+' . $name] ) ) {
314 $paths = (array)$skinStyles['+' . $name];
315 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
316 $this->moduleInfos
[$name]['skinStyles']['default'] :
322 // Add new file paths, remapping them to refer to our directories and not use settings
323 // from the module we're modifying. These can come from the base definition or be defined
325 list( $localBasePath, $remoteBasePath ) =
326 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
327 list( $localBasePath, $remoteBasePath ) =
328 ResourceLoaderFileModule
::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
330 foreach ( $paths as $path ) {
331 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
334 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
339 wfProfileOut( __METHOD__
);
344 public function registerTestModules() {
345 global $IP, $wgEnableJavaScriptTest;
347 if ( $wgEnableJavaScriptTest !== true ) {
348 throw new MWException( 'Attempt to register JavaScript test modules '
349 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
350 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
353 wfProfileIn( __METHOD__
);
355 // Get core test suites
356 $testModules = array();
357 $testModules['qunit'] = array();
358 // Get other test suites (e.g. from extensions)
359 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
361 // Add the testrunner (which configures QUnit) to the dependencies.
362 // Since it must be ready before any of the test suites are executed.
363 foreach ( $testModules['qunit'] as &$module ) {
364 // Make sure all test modules are top-loading so that when QUnit starts
365 // on document-ready, it will run once and finish. If some tests arrive
366 // later (possibly after QUnit has already finished) they will be ignored.
367 $module['position'] = 'top';
368 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
371 $testModules['qunit'] =
372 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
374 foreach ( $testModules as $id => $names ) {
375 // Register test modules
376 $this->register( $testModules[$id] );
378 // Keep track of their names so that they can be loaded together
379 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
382 wfProfileOut( __METHOD__
);
386 * Add a foreign source of modules.
389 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
391 * @param mixed $id Source ID (string), or array( id1 => props1, id2 => props2, ... )
392 * @param array $properties Source properties
393 * @throws MWException
395 public function addSource( $id, $properties = null ) {
396 // Allow multiple sources to be registered in one call
397 if ( is_array( $id ) ) {
398 foreach ( $id as $key => $value ) {
399 $this->addSource( $key, $value );
404 // Disallow duplicates
405 if ( isset( $this->sources
[$id] ) ) {
406 throw new MWException(
407 'ResourceLoader duplicate source addition error. ' .
408 'Another source has already been registered as ' . $id
412 // Validate properties
413 foreach ( self
::$requiredSourceProperties as $prop ) {
414 if ( !isset( $properties[$prop] ) ) {
415 throw new MWException( "Required property $prop missing from source ID $id" );
419 $this->sources
[$id] = $properties;
423 * Get a list of module names.
425 * @return array List of module names
427 public function getModuleNames() {
428 return array_keys( $this->moduleInfos
);
432 * Get a list of test module names for one (or all) frameworks.
434 * If the given framework id is unknkown, or if the in-object variable is not an array,
435 * then it will return an empty array.
437 * @param string $framework Get only the test module names for one
438 * particular framework (optional)
441 public function getTestModuleNames( $framework = 'all' ) {
442 /** @todo api siteinfo prop testmodulenames modulenames */
443 if ( $framework == 'all' ) {
444 return $this->testModuleNames
;
445 } elseif ( isset( $this->testModuleNames
[$framework] )
446 && is_array( $this->testModuleNames
[$framework] )
448 return $this->testModuleNames
[$framework];
455 * Get the ResourceLoaderModule object for a given module name.
457 * If an array of module parameters exists but a ResourceLoaderModule object has not
458 * yet been instantiated, this method will instantiate and cache that object such that
459 * subsequent calls simply return the same object.
461 * @param string $name Module name
462 * @return ResourceLoaderModule|null If module has been registered, return a
463 * ResourceLoaderModule instance. Otherwise, return null.
465 public function getModule( $name ) {
466 if ( !isset( $this->modules
[$name] ) ) {
467 if ( !isset( $this->moduleInfos
[$name] ) ) {
471 // Construct the requested object
472 $info = $this->moduleInfos
[$name];
473 /** @var ResourceLoaderModule $object */
474 if ( isset( $info['object'] ) ) {
475 // Object given in info array
476 $object = $info['object'];
478 if ( !isset( $info['class'] ) ) {
479 $class = 'ResourceLoaderFileModule';
481 $class = $info['class'];
483 $object = new $class( $info );
485 $object->setName( $name );
486 $this->modules
[$name] = $object;
489 return $this->modules
[$name];
493 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
495 * @param string $name Module name
498 protected function isFileModule( $name ) {
499 if ( !isset( $this->moduleInfos
[$name] ) ) {
502 $info = $this->moduleInfos
[$name];
503 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
510 * Get the list of sources.
512 * @return array Like array( id => array of properties, .. )
514 public function getSources() {
515 return $this->sources
;
519 * Get the URL to the load.php endpoint for the given
520 * ResourceLoader source
523 * @param string $source
524 * @throws MWException On an invalid $source name
527 public function getLoadScript( $source ) {
528 if ( !isset( $this->sources
[$source] ) ) {
529 throw new MWException( "The $source source was never registered in ResourceLoader." );
531 return $this->sources
[$source]['loadScript'];
535 * Output a response to a load request, including the content-type header.
537 * @param ResourceLoaderContext $context Context in which a response should be formed
539 public function respond( ResourceLoaderContext
$context ) {
540 global $wgCacheEpoch, $wgUseFileCache;
542 // Use file cache if enabled and available...
543 if ( $wgUseFileCache ) {
544 $fileCache = ResourceFileCache
::newFromContext( $context );
545 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
546 return; // output handled
550 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
551 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
552 // is used: ob_clean() will clear the GZIP header in that case and it won't come
553 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
554 // the whole thing in our own output buffer to be sure the active buffer
555 // doesn't use ob_gzhandler.
556 // See http://bugs.php.net/bug.php?id=36514
559 wfProfileIn( __METHOD__
);
562 // Find out which modules are missing and instantiate the others
565 foreach ( $context->getModules() as $name ) {
566 $module = $this->getModule( $name );
568 // Do not allow private modules to be loaded from the web.
569 // This is a security issue, see bug 34907.
570 if ( $module->getGroup() === 'private' ) {
571 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
572 $this->hasErrors
= true;
573 // Add exception to the output as a comment
574 $errors .= self
::makeComment( "Cannot show private module \"$name\"" );
578 $modules[$name] = $module;
584 // Preload information needed to the mtime calculation below
586 $this->preloadModuleInfo( array_keys( $modules ), $context );
587 } catch ( Exception
$e ) {
588 MWExceptionHandler
::logException( $e );
589 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
590 $this->hasErrors
= true;
591 // Add exception to the output as a comment
592 $errors .= self
::formatException( $e );
595 wfProfileIn( __METHOD__
. '-getModifiedTime' );
597 // To send Last-Modified and support If-Modified-Since, we need to detect
598 // the last modified time
599 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
600 foreach ( $modules as $module ) {
602 * @var $module ResourceLoaderModule
605 // Calculate maximum modified time
606 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
607 } catch ( Exception
$e ) {
608 MWExceptionHandler
::logException( $e );
609 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
610 $this->hasErrors
= true;
611 // Add exception to the output as a comment
612 $errors .= self
::formatException( $e );
616 wfProfileOut( __METHOD__
. '-getModifiedTime' );
618 // If there's an If-Modified-Since header, respond with a 304 appropriately
619 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
620 wfProfileOut( __METHOD__
);
621 return; // output handled (buffers cleared)
624 // Generate a response
625 $response = $this->makeModuleResponse( $context, $modules, $missing );
627 // Prepend comments indicating exceptions
628 $response = $errors . $response;
630 // Capture any PHP warnings from the output buffer and append them to the
631 // response in a comment if we're in debug mode.
632 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
633 $response = self
::makeComment( $warnings ) . $response;
634 $this->hasErrors
= true;
637 // Save response to file cache unless there are errors
638 if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
639 // Cache single modules...and other requests if there are enough hits
640 if ( ResourceFileCache
::useFileCache( $context ) ) {
641 if ( $fileCache->isCacheWorthy() ) {
642 $fileCache->saveText( $response );
644 $fileCache->incrMissesRecent( $context->getRequest() );
649 // Send content type and cache related headers
650 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
652 // Remove the output buffer and output the response
656 wfProfileOut( __METHOD__
);
660 * Send content type and last modified headers to the client.
661 * @param ResourceLoaderContext $context
662 * @param string $mtime TS_MW timestamp to use for last-modified
663 * @param bool $errors Whether there are commented-out errors in the response
666 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
667 global $wgResourceLoaderMaxage;
668 // If a version wasn't specified we need a shorter expiry time for updates
669 // to propagate to clients quickly
670 // If there were errors, we also need a shorter expiry time so we can recover quickly
671 if ( is_null( $context->getVersion() ) ||
$errors ) {
672 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
673 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
674 // If a version was specified we can use a longer expiry time since changing
675 // version numbers causes cache misses
677 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
678 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
680 if ( $context->getOnly() === 'styles' ) {
681 header( 'Content-Type: text/css; charset=utf-8' );
682 header( 'Access-Control-Allow-Origin: *' );
684 header( 'Content-Type: text/javascript; charset=utf-8' );
686 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
687 if ( $context->getDebug() ) {
688 // Do not cache debug responses
689 header( 'Cache-Control: private, no-cache, must-revalidate' );
690 header( 'Pragma: no-cache' );
692 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
693 $exp = min( $maxage, $smaxage );
694 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
699 * Respond with 304 Last Modified if appropiate.
701 * If there's an If-Modified-Since header, respond with a 304 appropriately
702 * and clear out the output buffer. If the client cache is too old then do nothing.
704 * @param ResourceLoaderContext $context
705 * @param string $mtime The TS_MW timestamp to check the header against
706 * @return bool True if 304 header sent and output handled
708 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
709 // If there's an If-Modified-Since header, respond with a 304 appropriately
710 // Some clients send "timestamp;length=123". Strip the part after the first ';'
711 // so we get a valid timestamp.
712 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
713 // Never send 304s in debug mode
714 if ( $ims !== false && !$context->getDebug() ) {
715 $imsTS = strtok( $ims, ';' );
716 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
717 // There's another bug in ob_gzhandler (see also the comment at
718 // the top of this function) that causes it to gzip even empty
719 // responses, meaning it's impossible to produce a truly empty
720 // response (because the gzip header is always there). This is
721 // a problem because 304 responses have to be completely empty
722 // per the HTTP spec, and Firefox behaves buggily when they're not.
723 // See also http://bugs.php.net/bug.php?id=51579
724 // To work around this, we tear down all output buffering before
726 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
728 header( 'HTTP/1.0 304 Not Modified' );
729 header( 'Status: 304 Not Modified' );
737 * Send out code for a response from file cache if possible.
739 * @param ResourceFileCache $fileCache Cache object for this request URL
740 * @param ResourceLoaderContext $context Context in which to generate a response
741 * @return bool If this found a cache file and handled the response
743 protected function tryRespondFromFileCache(
744 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
746 global $wgResourceLoaderMaxage;
747 // Buffer output to catch warnings.
749 // Get the maximum age the cache can be
750 $maxage = is_null( $context->getVersion() )
751 ?
$wgResourceLoaderMaxage['unversioned']['server']
752 : $wgResourceLoaderMaxage['versioned']['server'];
753 // Minimum timestamp the cache file must have
754 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
756 try { // RL always hits the DB on file cache miss...
758 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
759 $good = $fileCache->isCacheGood(); // cache existence check
763 $ts = $fileCache->cacheTimestamp();
764 // Send content type and cache headers
765 $this->sendResponseHeaders( $context, $ts, false );
766 // If there's an If-Modified-Since header, respond with a 304 appropriately
767 if ( $this->tryRespondLastModified( $context, $ts ) ) {
768 return false; // output handled (buffers cleared)
770 $response = $fileCache->fetchText();
771 // Capture any PHP warnings from the output buffer and append them to the
772 // response in a comment if we're in debug mode.
773 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
774 $response = "/*\n$warnings\n*/\n" . $response;
776 // Remove the output buffer and output the response
778 echo $response . "\n/* Cached {$ts} */";
779 return true; // cache hit
784 return false; // cache miss
788 * Generate a CSS or JS comment block.
790 * Only use this for public data, not error message details.
792 * @param string $text
795 public static function makeComment( $text ) {
796 $encText = str_replace( '*/', '* /', $text );
797 return "/*\n$encText\n*/\n";
801 * Handle exception display.
803 * @param Exception $e Exception to be shown to the user
804 * @return string Sanitized text that can be returned to the user
806 public static function formatException( $e ) {
807 global $wgShowExceptionDetails;
809 if ( $wgShowExceptionDetails ) {
810 return self
::makeComment( $e->__toString() );
812 return self
::makeComment( wfMessage( 'internalerror' )->text() );
817 * Generate code for a response.
819 * @param ResourceLoaderContext $context Context in which to generate a response
820 * @param array $modules List of module objects keyed by module name
821 * @param array $missing List of requested module names that are unregistered (optional)
822 * @return string Response data
824 public function makeModuleResponse( ResourceLoaderContext
$context,
825 array $modules, array $missing = array()
831 if ( !count( $modules ) && !count( $missing ) ) {
832 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
833 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
834 no modules were requested. Max made me put this here. */";
837 wfProfileIn( __METHOD__
);
840 if ( $context->shouldIncludeMessages() ) {
842 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
843 } catch ( Exception
$e ) {
844 MWExceptionHandler
::logException( $e );
847 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
849 $this->hasErrors
= true;
850 // Add exception to the output as a comment
851 $exceptions .= self
::formatException( $e );
857 foreach ( $missing as $name ) {
858 $states[$name] = 'missing';
863 foreach ( $modules as $name => $module ) {
865 * @var $module ResourceLoaderModule
868 wfProfileIn( __METHOD__
. '-' . $name );
871 if ( $context->shouldIncludeScripts() ) {
872 // If we are in debug mode, we'll want to return an array of URLs if possible
873 // However, we can't do this if the module doesn't support it
874 // We also can't do this if there is an only= parameter, because we have to give
875 // the module a way to return a load.php URL without causing an infinite loop
876 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
877 $scripts = $module->getScriptURLsForDebug( $context );
879 $scripts = $module->getScript( $context );
880 // rtrim() because there are usually a few line breaks
881 // after the last ';'. A new line at EOF, a new line
882 // added by ResourceLoaderFileModule::readScriptFiles, etc.
883 if ( is_string( $scripts )
884 && strlen( $scripts )
885 && substr( rtrim( $scripts ), -1 ) !== ';'
887 // Append semicolon to prevent weird bugs caused by files not
888 // terminating their statements right (bug 27054)
895 if ( $context->shouldIncludeStyles() ) {
896 // Don't create empty stylesheets like array( '' => '' ) for modules
897 // that don't *have* any stylesheets (bug 38024).
898 $stylePairs = $module->getStyles( $context );
899 if ( count( $stylePairs ) ) {
900 // If we are in debug mode without &only= set, we'll want to return an array of URLs
901 // See comment near shouldIncludeScripts() for more details
902 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
904 'url' => $module->getStyleURLsForDebug( $context )
907 // Minify CSS before embedding in mw.loader.implement call
908 // (unless in debug mode)
909 if ( !$context->getDebug() ) {
910 foreach ( $stylePairs as $media => $style ) {
911 // Can be either a string or an array of strings.
912 if ( is_array( $style ) ) {
913 $stylePairs[$media] = array();
914 foreach ( $style as $cssText ) {
915 if ( is_string( $cssText ) ) {
916 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
919 } elseif ( is_string( $style ) ) {
920 $stylePairs[$media] = $this->filter( 'minify-css', $style );
924 // Wrap styles into @media groups as needed and flatten into a numerical array
926 'css' => self
::makeCombinedStyles( $stylePairs )
933 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
936 switch ( $context->getOnly() ) {
938 if ( is_string( $scripts ) ) {
939 // Load scripts raw...
941 } elseif ( is_array( $scripts ) ) {
942 // ...except when $scripts is an array of URLs
943 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
947 // We no longer seperate into media, they are all combined now with
948 // custom media type groups into @media .. {} sections as part of the css string.
949 // Module returns either an empty array or a numerical array with css strings.
950 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
953 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
956 $out .= self
::makeLoaderImplementScript(
960 new XmlJsCode( $messagesBlob )
964 } catch ( Exception
$e ) {
965 MWExceptionHandler
::logException( $e );
966 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
967 $this->hasErrors
= true;
968 // Add exception to the output as a comment
969 $exceptions .= self
::formatException( $e );
971 // Respond to client with error-state instead of module implementation
972 $states[$name] = 'error';
973 unset( $modules[$name] );
975 $isRaw |
= $module->isRaw();
976 wfProfileOut( __METHOD__
. '-' . $name );
979 // Update module states
980 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
981 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
982 // Set the state of modules loaded as only scripts to ready as
983 // they don't have an mw.loader.implement wrapper that sets the state
984 foreach ( $modules as $name => $module ) {
985 $states[$name] = 'ready';
989 // Set the state of modules we didn't respond to with mw.loader.implement
990 if ( count( $states ) ) {
991 $out .= self
::makeLoaderStateScript( $states );
994 if ( count( $states ) ) {
995 $exceptions .= self
::makeComment(
996 'Problematic modules: ' . FormatJson
::encode( $states, ResourceLoader
::inDebugMode() )
1001 if ( !$context->getDebug() ) {
1002 if ( $context->getOnly() === 'styles' ) {
1003 $out = $this->filter( 'minify-css', $out );
1005 $out = $this->filter( 'minify-js', $out );
1009 wfProfileOut( __METHOD__
);
1010 return $exceptions . $out;
1013 /* Static Methods */
1016 * Return JS code that calls mw.loader.implement with given module properties.
1018 * @param string $name Module name
1019 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1020 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1021 * to CSS files keyed by media type
1022 * @param mixed $messages List of messages associated with this module. May either be an
1023 * associative array mapping message key to value, or a JSON-encoded message blob containing
1024 * the same data, wrapped in an XmlJsCode object.
1025 * @throws MWException
1028 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
1029 if ( is_string( $scripts ) ) {
1030 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1031 } elseif ( !is_array( $scripts ) ) {
1032 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1034 return Xml
::encodeJsCall(
1035 'mw.loader.implement',
1039 // Force objects. mw.loader.implement requires them to be javascript objects.
1040 // Although these variables are associative arrays, which become javascript
1041 // objects through json_encode. In many cases they will be empty arrays, and
1042 // PHP/json_encode() consider empty arrays to be numerical arrays and
1043 // output javascript "[]" instead of "{}". This fixes that.
1047 ResourceLoader
::inDebugMode()
1052 * Returns JS code which, when called, will register a given list of messages.
1054 * @param mixed $messages Either an associative array mapping message key to value, or a
1055 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1058 public static function makeMessageSetScript( $messages ) {
1059 return Xml
::encodeJsCall(
1061 array( (object)$messages ),
1062 ResourceLoader
::inDebugMode()
1067 * Combines an associative array mapping media type to CSS into a
1068 * single stylesheet with "@media" blocks.
1070 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1073 public static function makeCombinedStyles( array $stylePairs ) {
1075 foreach ( $stylePairs as $media => $styles ) {
1076 // ResourceLoaderFileModule::getStyle can return the styles
1077 // as a string or an array of strings. This is to allow separation in
1079 $styles = (array)$styles;
1080 foreach ( $styles as $style ) {
1081 $style = trim( $style );
1082 // Don't output an empty "@media print { }" block (bug 40498)
1083 if ( $style !== '' ) {
1084 // Transform the media type based on request params and config
1085 // The way that this relies on $wgRequest to propagate request params is slightly evil
1086 $media = OutputPage
::transformCssMedia( $media );
1088 if ( $media === '' ||
$media == 'all' ) {
1090 } elseif ( is_string( $media ) ) {
1091 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1101 * Returns a JS call to mw.loader.state, which sets the state of a
1102 * module or modules to a given value. Has two calling conventions:
1104 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1105 * Set the state of a single module called $name to $state
1107 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1108 * Set the state of modules with the given names to the given states
1110 * @param string $name
1111 * @param string $state
1114 public static function makeLoaderStateScript( $name, $state = null ) {
1115 if ( is_array( $name ) ) {
1116 return Xml
::encodeJsCall(
1119 ResourceLoader
::inDebugMode()
1122 return Xml
::encodeJsCall(
1124 array( $name, $state ),
1125 ResourceLoader
::inDebugMode()
1131 * Returns JS code which calls the script given by $script. The script will
1132 * be called with local variables name, version, dependencies and group,
1133 * which will have values corresponding to $name, $version, $dependencies
1134 * and $group as supplied.
1136 * @param string $name Module name
1137 * @param int $version Module version number as a timestamp
1138 * @param array $dependencies List of module names on which this module depends
1139 * @param string $group Group which the module is in.
1140 * @param string $source Source of the module, or 'local' if not foreign.
1141 * @param string $script JavaScript code
1144 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1145 $group, $source, $script
1147 $script = str_replace( "\n", "\n\t", trim( $script ) );
1148 return Xml
::encodeJsCall(
1149 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1150 array( $name, $version, $dependencies, $group, $source ),
1151 ResourceLoader
::inDebugMode()
1156 * Returns JS code which calls mw.loader.register with the given
1157 * parameters. Has three calling conventions:
1159 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source, $skip ):
1160 * Register a single module.
1162 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1163 * Register modules with the given names.
1165 * - ResourceLoader::makeLoaderRegisterScript( array(
1166 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1167 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1170 * Registers modules with the given names and parameters.
1172 * @param string $name Module name
1173 * @param int $version Module version number as a timestamp
1174 * @param array $dependencies List of module names on which this module depends
1175 * @param string $group Group which the module is in
1176 * @param string $source Source of the module, or 'local' if not foreign
1177 * @param string $skip Script body of the skip function
1180 public static function makeLoaderRegisterScript( $name, $version = null,
1181 $dependencies = null, $group = null, $source = null, $skip = null
1183 if ( is_array( $name ) ) {
1184 return Xml
::encodeJsCall(
1185 'mw.loader.register',
1187 ResourceLoader
::inDebugMode()
1190 $version = (int)$version > 1 ?
(int)$version : 1;
1191 return Xml
::encodeJsCall(
1192 'mw.loader.register',
1193 array( $name, $version, $dependencies, $group, $source, $skip ),
1194 ResourceLoader
::inDebugMode()
1200 * Returns JS code which calls mw.loader.addSource() with the given
1201 * parameters. Has two calling conventions:
1203 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1204 * Register a single source
1206 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1207 * Register sources with the given IDs and properties.
1209 * @param string $id Source ID
1210 * @param array $properties Source properties (see addSource())
1213 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1214 if ( is_array( $id ) ) {
1215 return Xml
::encodeJsCall(
1216 'mw.loader.addSource',
1218 ResourceLoader
::inDebugMode()
1221 return Xml
::encodeJsCall(
1222 'mw.loader.addSource',
1223 array( $id, $properties ),
1224 ResourceLoader
::inDebugMode()
1230 * Returns JS code which runs given JS code if the client-side framework is
1233 * @param string $script JavaScript code
1236 public static function makeLoaderConditionalScript( $script ) {
1237 return "if(window.mw){\n" . trim( $script ) . "\n}";
1241 * Returns JS code which will set the MediaWiki configuration array to
1244 * @param array $configuration List of configuration values keyed by variable name
1247 public static function makeConfigSetScript( array $configuration ) {
1248 return Xml
::encodeJsCall(
1250 array( $configuration ),
1251 ResourceLoader
::inDebugMode()
1256 * Convert an array of module names to a packed query string.
1258 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1259 * becomes 'foo.bar,baz|bar.baz,quux'
1260 * @param array $modules List of module names (strings)
1261 * @return string Packed query string
1263 public static function makePackedModulesString( $modules ) {
1264 $groups = array(); // array( prefix => array( suffixes ) )
1265 foreach ( $modules as $module ) {
1266 $pos = strrpos( $module, '.' );
1267 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1268 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1269 $groups[$prefix][] = $suffix;
1273 foreach ( $groups as $prefix => $suffixes ) {
1274 $p = $prefix === '' ?
'' : $prefix . '.';
1275 $arr[] = $p . implode( ',', $suffixes );
1277 $str = implode( '|', $arr );
1282 * Determine whether debug mode was requested
1283 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1286 public static function inDebugMode() {
1287 if ( self
::$debugMode === null ) {
1288 global $wgRequest, $wgResourceLoaderDebug;
1289 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1290 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1293 return self
::$debugMode;
1297 * Reset static members used for caching.
1299 * Global state and $wgRequest are evil, but we're using it right
1300 * now and sometimes we need to be able to force ResourceLoader to
1301 * re-evaluate the context because it has changed (e.g. in the test suite).
1303 public static function clearCache() {
1304 self
::$debugMode = null;
1308 * Build a load.php URL
1311 * @param string $source Name of the ResourceLoader source
1312 * @param ResourceLoaderContext $context
1313 * @param array $extraQuery
1314 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1316 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1317 $extraQuery = array()
1319 $query = self
::createLoaderQuery( $context, $extraQuery );
1320 $script = $this->getLoadScript( $source );
1322 // Prevent the IE6 extension check from being triggered (bug 28840)
1323 // by appending a character that's invalid in Windows extensions ('*')
1324 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1328 * Build a load.php URL
1329 * @deprecated since 1.24, use createLoaderURL instead
1330 * @param array $modules Array of module names (strings)
1331 * @param string $lang Language code
1332 * @param string $skin Skin name
1333 * @param string|null $user User name. If null, the &user= parameter is omitted
1334 * @param string|null $version Versioning timestamp
1335 * @param bool $debug Whether the request should be in debug mode
1336 * @param string|null $only &only= parameter
1337 * @param bool $printable Printable mode
1338 * @param bool $handheld Handheld mode
1339 * @param array $extraQuery Extra query parameters to add
1340 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1342 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1343 $version = null, $debug = false, $only = null, $printable = false,
1344 $handheld = false, $extraQuery = array()
1346 global $wgLoadScript;
1348 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1349 $only, $printable, $handheld, $extraQuery
1352 // Prevent the IE6 extension check from being triggered (bug 28840)
1353 // by appending a character that's invalid in Windows extensions ('*')
1354 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1358 * Helper for createLoaderURL()
1361 * @see makeLoaderQuery
1362 * @param ResourceLoaderContext $context
1363 * @param array $extraQuery
1366 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1367 return self
::makeLoaderQuery(
1368 $context->getModules(),
1369 $context->getLanguage(),
1370 $context->getSkin(),
1371 $context->getUser(),
1372 $context->getVersion(),
1373 $context->getDebug(),
1374 $context->getOnly(),
1375 $context->getRequest()->getBool( 'printable' ),
1376 $context->getRequest()->getBool( 'handheld' ),
1382 * Build a query array (array representation of query string) for load.php. Helper
1383 * function for makeLoaderURL().
1385 * @param array $modules
1386 * @param string $lang
1387 * @param string $skin
1388 * @param string $user
1389 * @param string $version
1390 * @param bool $debug
1391 * @param string $only
1392 * @param bool $printable
1393 * @param bool $handheld
1394 * @param array $extraQuery
1398 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1399 $version = null, $debug = false, $only = null, $printable = false,
1400 $handheld = false, $extraQuery = array()
1403 'modules' => self
::makePackedModulesString( $modules ),
1406 'debug' => $debug ?
'true' : 'false',
1408 if ( $user !== null ) {
1409 $query['user'] = $user;
1411 if ( $version !== null ) {
1412 $query['version'] = $version;
1414 if ( $only !== null ) {
1415 $query['only'] = $only;
1418 $query['printable'] = 1;
1421 $query['handheld'] = 1;
1423 $query +
= $extraQuery;
1425 // Make queries uniform in order
1431 * Check a module name for validity.
1433 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1434 * at most 255 bytes.
1436 * @param string $moduleName Module name to check
1437 * @return bool Whether $moduleName is a valid module name
1439 public static function isValidModuleName( $moduleName ) {
1440 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1444 * Returns LESS compiler set up for use with MediaWiki
1449 public static function getLessCompiler() {
1450 global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths;
1452 // When called from the installer, it is possible that a required PHP extension
1453 // is missing (at least for now; see bug 47564). If this is the case, throw an
1454 // exception (caught by the installer) to prevent a fatal error later on.
1455 if ( !function_exists( 'ctype_digit' ) ) {
1456 throw new MWException( 'lessc requires the Ctype extension' );
1459 $less = new lessc();
1460 $less->setPreserveComments( true );
1461 $less->setVariables( self
::getLESSVars() );
1462 $less->setImportDir( $wgResourceLoaderLESSImportPaths );
1463 foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) {
1464 $less->registerFunction( $name, $func );
1470 * Get global LESS variables.
1473 * @return array Map of variable names to string CSS values.
1475 public static function getLESSVars() {
1476 global $wgResourceLoaderLESSVars;
1478 $lessVars = $wgResourceLoaderLESSVars;
1479 // Sort by key to ensure consistent hashing for cache lookups.