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 ) . ')'
298 wfProfileOut( __METHOD__
);
303 public function registerTestModules() {
304 global $IP, $wgEnableJavaScriptTest;
306 if ( $wgEnableJavaScriptTest !== true ) {
307 throw new MWException( 'Attempt to register JavaScript test modules '
308 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
309 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
312 wfProfileIn( __METHOD__
);
314 // Get core test suites
315 $testModules = array();
316 $testModules['qunit'] = array();
317 // Get other test suites (e.g. from extensions)
318 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
320 // Add the testrunner (which configures QUnit) to the dependencies.
321 // Since it must be ready before any of the test suites are executed.
322 foreach ( $testModules['qunit'] as &$module ) {
323 // Make sure all test modules are top-loading so that when QUnit starts
324 // on document-ready, it will run once and finish. If some tests arrive
325 // later (possibly after QUnit has already finished) they will be ignored.
326 $module['position'] = 'top';
327 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
330 $testModules['qunit'] =
331 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
333 foreach ( $testModules as $id => $names ) {
334 // Register test modules
335 $this->register( $testModules[$id] );
337 // Keep track of their names so that they can be loaded together
338 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
341 wfProfileOut( __METHOD__
);
345 * Add a foreign source of modules.
348 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
350 * @param mixed $id Source ID (string), or array( id1 => props1, id2 => props2, ... )
351 * @param array $properties Source properties
352 * @throws MWException
354 public function addSource( $id, $properties = null ) {
355 // Allow multiple sources to be registered in one call
356 if ( is_array( $id ) ) {
357 foreach ( $id as $key => $value ) {
358 $this->addSource( $key, $value );
363 // Disallow duplicates
364 if ( isset( $this->sources
[$id] ) ) {
365 throw new MWException(
366 'ResourceLoader duplicate source addition error. ' .
367 'Another source has already been registered as ' . $id
371 // Validate properties
372 foreach ( self
::$requiredSourceProperties as $prop ) {
373 if ( !isset( $properties[$prop] ) ) {
374 throw new MWException( "Required property $prop missing from source ID $id" );
378 $this->sources
[$id] = $properties;
382 * Get a list of module names.
384 * @return array List of module names
386 public function getModuleNames() {
387 return array_keys( $this->moduleInfos
);
391 * Get a list of test module names for one (or all) frameworks.
393 * If the given framework id is unknkown, or if the in-object variable is not an array,
394 * then it will return an empty array.
396 * @param string $framework Get only the test module names for one
397 * particular framework (optional)
400 public function getTestModuleNames( $framework = 'all' ) {
401 /** @todo api siteinfo prop testmodulenames modulenames */
402 if ( $framework == 'all' ) {
403 return $this->testModuleNames
;
404 } elseif ( isset( $this->testModuleNames
[$framework] )
405 && is_array( $this->testModuleNames
[$framework] )
407 return $this->testModuleNames
[$framework];
414 * Get the ResourceLoaderModule object for a given module name.
416 * If an array of module parameters exists but a ResourceLoaderModule object has not
417 * yet been instantiated, this method will instantiate and cache that object such that
418 * subsequent calls simply return the same object.
420 * @param string $name Module name
421 * @return ResourceLoaderModule|null If module has been registered, return a
422 * ResourceLoaderModule instance. Otherwise, return null.
424 public function getModule( $name ) {
425 if ( !isset( $this->modules
[$name] ) ) {
426 if ( !isset( $this->moduleInfos
[$name] ) ) {
430 // Construct the requested object
431 $info = $this->moduleInfos
[$name];
432 /** @var ResourceLoaderModule $object */
433 if ( isset( $info['object'] ) ) {
434 // Object given in info array
435 $object = $info['object'];
437 if ( !isset( $info['class'] ) ) {
438 $class = 'ResourceLoaderFileModule';
440 $class = $info['class'];
442 $object = new $class( $info );
444 $object->setName( $name );
445 $this->modules
[$name] = $object;
448 return $this->modules
[$name];
452 * Get the list of sources.
454 * @return array Like array( id => array of properties, .. )
456 public function getSources() {
457 return $this->sources
;
461 * Get the URL to the load.php endpoint for the given
462 * ResourceLoader source
465 * @param string $source
466 * @throws MWException on an invalid $source name
469 public function getLoadScript( $source ) {
470 if ( !isset( $this->sources
[$source] ) ) {
471 throw new MWException( "The $source source was never registered in ResourceLoader." );
473 return $this->sources
[$source]['loadScript'];
477 * Output a response to a load request, including the content-type header.
479 * @param ResourceLoaderContext $context Context in which a response should be formed
481 public function respond( ResourceLoaderContext
$context ) {
482 global $wgCacheEpoch, $wgUseFileCache;
484 // Use file cache if enabled and available...
485 if ( $wgUseFileCache ) {
486 $fileCache = ResourceFileCache
::newFromContext( $context );
487 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
488 return; // output handled
492 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
493 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
494 // is used: ob_clean() will clear the GZIP header in that case and it won't come
495 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
496 // the whole thing in our own output buffer to be sure the active buffer
497 // doesn't use ob_gzhandler.
498 // See http://bugs.php.net/bug.php?id=36514
501 wfProfileIn( __METHOD__
);
504 // Find out which modules are missing and instantiate the others
507 foreach ( $context->getModules() as $name ) {
508 $module = $this->getModule( $name );
510 // Do not allow private modules to be loaded from the web.
511 // This is a security issue, see bug 34907.
512 if ( $module->getGroup() === 'private' ) {
513 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
514 $this->hasErrors
= true;
515 // Add exception to the output as a comment
516 $errors .= self
::makeComment( "Cannot show private module \"$name\"" );
520 $modules[$name] = $module;
526 // Preload information needed to the mtime calculation below
528 $this->preloadModuleInfo( array_keys( $modules ), $context );
529 } catch ( Exception
$e ) {
530 MWExceptionHandler
::logException( $e );
531 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
532 $this->hasErrors
= true;
533 // Add exception to the output as a comment
534 $errors .= self
::formatException( $e );
537 wfProfileIn( __METHOD__
. '-getModifiedTime' );
539 // To send Last-Modified and support If-Modified-Since, we need to detect
540 // the last modified time
541 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
542 foreach ( $modules as $module ) {
544 * @var $module ResourceLoaderModule
547 // Calculate maximum modified time
548 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
549 } catch ( Exception
$e ) {
550 MWExceptionHandler
::logException( $e );
551 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
552 $this->hasErrors
= true;
553 // Add exception to the output as a comment
554 $errors .= self
::formatException( $e );
558 wfProfileOut( __METHOD__
. '-getModifiedTime' );
560 // If there's an If-Modified-Since header, respond with a 304 appropriately
561 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
562 wfProfileOut( __METHOD__
);
563 return; // output handled (buffers cleared)
566 // Generate a response
567 $response = $this->makeModuleResponse( $context, $modules, $missing );
569 // Prepend comments indicating exceptions
570 $response = $errors . $response;
572 // Capture any PHP warnings from the output buffer and append them to the
573 // response in a comment if we're in debug mode.
574 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
575 $response = self
::makeComment( $warnings ) . $response;
576 $this->hasErrors
= true;
579 // Save response to file cache unless there are errors
580 if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
581 // Cache single modules...and other requests if there are enough hits
582 if ( ResourceFileCache
::useFileCache( $context ) ) {
583 if ( $fileCache->isCacheWorthy() ) {
584 $fileCache->saveText( $response );
586 $fileCache->incrMissesRecent( $context->getRequest() );
591 // Send content type and cache related headers
592 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
594 // Remove the output buffer and output the response
598 wfProfileOut( __METHOD__
);
602 * Send content type and last modified headers to the client.
603 * @param ResourceLoaderContext $context
604 * @param string $mtime TS_MW timestamp to use for last-modified
605 * @param bool $errors Whether there are commented-out errors in the response
608 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
609 global $wgResourceLoaderMaxage;
610 // If a version wasn't specified we need a shorter expiry time for updates
611 // to propagate to clients quickly
612 // If there were errors, we also need a shorter expiry time so we can recover quickly
613 if ( is_null( $context->getVersion() ) ||
$errors ) {
614 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
615 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
616 // If a version was specified we can use a longer expiry time since changing
617 // version numbers causes cache misses
619 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
620 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
622 if ( $context->getOnly() === 'styles' ) {
623 header( 'Content-Type: text/css; charset=utf-8' );
624 header( 'Access-Control-Allow-Origin: *' );
626 header( 'Content-Type: text/javascript; charset=utf-8' );
628 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
629 if ( $context->getDebug() ) {
630 // Do not cache debug responses
631 header( 'Cache-Control: private, no-cache, must-revalidate' );
632 header( 'Pragma: no-cache' );
634 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
635 $exp = min( $maxage, $smaxage );
636 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
641 * Respond with 304 Last Modified if appropiate.
643 * If there's an If-Modified-Since header, respond with a 304 appropriately
644 * and clear out the output buffer. If the client cache is too old then do nothing.
646 * @param ResourceLoaderContext $context
647 * @param string $mtime The TS_MW timestamp to check the header against
648 * @return bool True if 304 header sent and output handled
650 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
651 // If there's an If-Modified-Since header, respond with a 304 appropriately
652 // Some clients send "timestamp;length=123". Strip the part after the first ';'
653 // so we get a valid timestamp.
654 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
655 // Never send 304s in debug mode
656 if ( $ims !== false && !$context->getDebug() ) {
657 $imsTS = strtok( $ims, ';' );
658 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
659 // There's another bug in ob_gzhandler (see also the comment at
660 // the top of this function) that causes it to gzip even empty
661 // responses, meaning it's impossible to produce a truly empty
662 // response (because the gzip header is always there). This is
663 // a problem because 304 responses have to be completely empty
664 // per the HTTP spec, and Firefox behaves buggily when they're not.
665 // See also http://bugs.php.net/bug.php?id=51579
666 // To work around this, we tear down all output buffering before
668 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
670 header( 'HTTP/1.0 304 Not Modified' );
671 header( 'Status: 304 Not Modified' );
679 * Send out code for a response from file cache if possible.
681 * @param ResourceFileCache $fileCache Cache object for this request URL
682 * @param ResourceLoaderContext $context Context in which to generate a response
683 * @return bool If this found a cache file and handled the response
685 protected function tryRespondFromFileCache(
686 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
688 global $wgResourceLoaderMaxage;
689 // Buffer output to catch warnings.
691 // Get the maximum age the cache can be
692 $maxage = is_null( $context->getVersion() )
693 ?
$wgResourceLoaderMaxage['unversioned']['server']
694 : $wgResourceLoaderMaxage['versioned']['server'];
695 // Minimum timestamp the cache file must have
696 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
698 try { // RL always hits the DB on file cache miss...
700 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
701 $good = $fileCache->isCacheGood(); // cache existence check
705 $ts = $fileCache->cacheTimestamp();
706 // Send content type and cache headers
707 $this->sendResponseHeaders( $context, $ts, false );
708 // If there's an If-Modified-Since header, respond with a 304 appropriately
709 if ( $this->tryRespondLastModified( $context, $ts ) ) {
710 return false; // output handled (buffers cleared)
712 $response = $fileCache->fetchText();
713 // Capture any PHP warnings from the output buffer and append them to the
714 // response in a comment if we're in debug mode.
715 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
716 $response = "/*\n$warnings\n*/\n" . $response;
718 // Remove the output buffer and output the response
720 echo $response . "\n/* Cached {$ts} */";
721 return true; // cache hit
726 return false; // cache miss
730 * Generate a CSS or JS comment block.
732 * Only use this for public data, not error message details.
734 * @param string $text
737 public static function makeComment( $text ) {
738 $encText = str_replace( '*/', '* /', $text );
739 return "/*\n$encText\n*/\n";
743 * Handle exception display.
745 * @param Exception $e Exception to be shown to the user
746 * @return string Sanitized text that can be returned to the user
748 public static function formatException( $e ) {
749 global $wgShowExceptionDetails;
751 if ( $wgShowExceptionDetails ) {
752 return self
::makeComment( $e->__toString() );
754 return self
::makeComment( wfMessage( 'internalerror' )->text() );
759 * Generate code for a response.
761 * @param ResourceLoaderContext $context Context in which to generate a response
762 * @param array $modules List of module objects keyed by module name
763 * @param array $missing List of requested module names that are unregistered (optional)
764 * @return string Response data
766 public function makeModuleResponse( ResourceLoaderContext
$context,
767 array $modules, array $missing = array()
773 if ( !count( $modules ) && !count( $missing ) ) {
774 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
775 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
776 no modules were requested. Max made me put this here. */";
779 wfProfileIn( __METHOD__
);
782 if ( $context->shouldIncludeMessages() ) {
784 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
785 } catch ( Exception
$e ) {
786 MWExceptionHandler
::logException( $e );
789 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
791 $this->hasErrors
= true;
792 // Add exception to the output as a comment
793 $exceptions .= self
::formatException( $e );
799 foreach ( $missing as $name ) {
800 $states[$name] = 'missing';
805 foreach ( $modules as $name => $module ) {
807 * @var $module ResourceLoaderModule
810 wfProfileIn( __METHOD__
. '-' . $name );
813 if ( $context->shouldIncludeScripts() ) {
814 // If we are in debug mode, we'll want to return an array of URLs if possible
815 // However, we can't do this if the module doesn't support it
816 // We also can't do this if there is an only= parameter, because we have to give
817 // the module a way to return a load.php URL without causing an infinite loop
818 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
819 $scripts = $module->getScriptURLsForDebug( $context );
821 $scripts = $module->getScript( $context );
822 // rtrim() because there are usually a few line breaks
823 // after the last ';'. A new line at EOF, a new line
824 // added by ResourceLoaderFileModule::readScriptFiles, etc.
825 if ( is_string( $scripts )
826 && strlen( $scripts )
827 && substr( rtrim( $scripts ), -1 ) !== ';'
829 // Append semicolon to prevent weird bugs caused by files not
830 // terminating their statements right (bug 27054)
837 if ( $context->shouldIncludeStyles() ) {
838 // Don't create empty stylesheets like array( '' => '' ) for modules
839 // that don't *have* any stylesheets (bug 38024).
840 $stylePairs = $module->getStyles( $context );
841 if ( count( $stylePairs ) ) {
842 // If we are in debug mode without &only= set, we'll want to return an array of URLs
843 // See comment near shouldIncludeScripts() for more details
844 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
846 'url' => $module->getStyleURLsForDebug( $context )
849 // Minify CSS before embedding in mw.loader.implement call
850 // (unless in debug mode)
851 if ( !$context->getDebug() ) {
852 foreach ( $stylePairs as $media => $style ) {
853 // Can be either a string or an array of strings.
854 if ( is_array( $style ) ) {
855 $stylePairs[$media] = array();
856 foreach ( $style as $cssText ) {
857 if ( is_string( $cssText ) ) {
858 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
861 } elseif ( is_string( $style ) ) {
862 $stylePairs[$media] = $this->filter( 'minify-css', $style );
866 // Wrap styles into @media groups as needed and flatten into a numerical array
868 'css' => self
::makeCombinedStyles( $stylePairs )
875 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
878 switch ( $context->getOnly() ) {
880 if ( is_string( $scripts ) ) {
881 // Load scripts raw...
883 } elseif ( is_array( $scripts ) ) {
884 // ...except when $scripts is an array of URLs
885 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
889 // We no longer seperate into media, they are all combined now with
890 // custom media type groups into @media .. {} sections as part of the css string.
891 // Module returns either an empty array or a numerical array with css strings.
892 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
895 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
898 $out .= self
::makeLoaderImplementScript(
902 new XmlJsCode( $messagesBlob )
906 } catch ( Exception
$e ) {
907 MWExceptionHandler
::logException( $e );
908 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
909 $this->hasErrors
= true;
910 // Add exception to the output as a comment
911 $exceptions .= self
::formatException( $e );
913 // Respond to client with error-state instead of module implementation
914 $states[$name] = 'error';
915 unset( $modules[$name] );
917 $isRaw |
= $module->isRaw();
918 wfProfileOut( __METHOD__
. '-' . $name );
921 // Update module states
922 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
923 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
924 // Set the state of modules loaded as only scripts to ready as
925 // they don't have an mw.loader.implement wrapper that sets the state
926 foreach ( $modules as $name => $module ) {
927 $states[$name] = 'ready';
931 // Set the state of modules we didn't respond to with mw.loader.implement
932 if ( count( $states ) ) {
933 $out .= self
::makeLoaderStateScript( $states );
936 if ( count( $states ) ) {
937 $exceptions .= self
::makeComment(
938 'Problematic modules: ' . FormatJson
::encode( $states, ResourceLoader
::inDebugMode() )
943 if ( !$context->getDebug() ) {
944 if ( $context->getOnly() === 'styles' ) {
945 $out = $this->filter( 'minify-css', $out );
947 $out = $this->filter( 'minify-js', $out );
951 wfProfileOut( __METHOD__
);
952 return $exceptions . $out;
958 * Return JS code that calls mw.loader.implement with given module properties.
960 * @param string $name Module name
961 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
962 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
963 * to CSS files keyed by media type
964 * @param mixed $messages List of messages associated with this module. May either be an
965 * associative array mapping message key to value, or a JSON-encoded message blob containing
966 * the same data, wrapped in an XmlJsCode object.
967 * @throws MWException
970 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
971 if ( is_string( $scripts ) ) {
972 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
973 } elseif ( !is_array( $scripts ) ) {
974 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
976 return Xml
::encodeJsCall(
977 'mw.loader.implement',
981 // Force objects. mw.loader.implement requires them to be javascript objects.
982 // Although these variables are associative arrays, which become javascript
983 // objects through json_encode. In many cases they will be empty arrays, and
984 // PHP/json_encode() consider empty arrays to be numerical arrays and
985 // output javascript "[]" instead of "{}". This fixes that.
989 ResourceLoader
::inDebugMode()
994 * Returns JS code which, when called, will register a given list of messages.
996 * @param mixed $messages Either an associative array mapping message key to value, or a
997 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1000 public static function makeMessageSetScript( $messages ) {
1001 return Xml
::encodeJsCall(
1003 array( (object)$messages ),
1004 ResourceLoader
::inDebugMode()
1009 * Combines an associative array mapping media type to CSS into a
1010 * single stylesheet with "@media" blocks.
1012 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1015 public static function makeCombinedStyles( array $stylePairs ) {
1017 foreach ( $stylePairs as $media => $styles ) {
1018 // ResourceLoaderFileModule::getStyle can return the styles
1019 // as a string or an array of strings. This is to allow separation in
1021 $styles = (array)$styles;
1022 foreach ( $styles as $style ) {
1023 $style = trim( $style );
1024 // Don't output an empty "@media print { }" block (bug 40498)
1025 if ( $style !== '' ) {
1026 // Transform the media type based on request params and config
1027 // The way that this relies on $wgRequest to propagate request params is slightly evil
1028 $media = OutputPage
::transformCssMedia( $media );
1030 if ( $media === '' ||
$media == 'all' ) {
1032 } elseif ( is_string( $media ) ) {
1033 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1043 * Returns a JS call to mw.loader.state, which sets the state of a
1044 * module or modules to a given value. Has two calling conventions:
1046 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1047 * Set the state of a single module called $name to $state
1049 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1050 * Set the state of modules with the given names to the given states
1052 * @param string $name
1053 * @param string $state
1056 public static function makeLoaderStateScript( $name, $state = null ) {
1057 if ( is_array( $name ) ) {
1058 return Xml
::encodeJsCall(
1061 ResourceLoader
::inDebugMode()
1064 return Xml
::encodeJsCall(
1066 array( $name, $state ),
1067 ResourceLoader
::inDebugMode()
1073 * Returns JS code which calls the script given by $script. The script will
1074 * be called with local variables name, version, dependencies and group,
1075 * which will have values corresponding to $name, $version, $dependencies
1076 * and $group as supplied.
1078 * @param string $name Module name
1079 * @param int $version Module version number as a timestamp
1080 * @param array $dependencies List of module names on which this module depends
1081 * @param string $group Group which the module is in.
1082 * @param string $source Source of the module, or 'local' if not foreign.
1083 * @param string $script JavaScript code
1086 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1087 $group, $source, $script
1089 $script = str_replace( "\n", "\n\t", trim( $script ) );
1090 return Xml
::encodeJsCall(
1091 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1092 array( $name, $version, $dependencies, $group, $source ),
1093 ResourceLoader
::inDebugMode()
1098 * Returns JS code which calls mw.loader.register with the given
1099 * parameters. Has three calling conventions:
1101 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source, $skip ):
1102 * Register a single module.
1104 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1105 * Register modules with the given names.
1107 * - ResourceLoader::makeLoaderRegisterScript( array(
1108 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1109 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1112 * Registers modules with the given names and parameters.
1114 * @param string $name Module name
1115 * @param int $version Module version number as a timestamp
1116 * @param array $dependencies List of module names on which this module depends
1117 * @param string $group Group which the module is in
1118 * @param string $source Source of the module, or 'local' if not foreign
1119 * @param string $skip Script body of the skip function
1122 public static function makeLoaderRegisterScript( $name, $version = null,
1123 $dependencies = null, $group = null, $source = null, $skip = null
1125 if ( is_array( $name ) ) {
1126 return Xml
::encodeJsCall(
1127 'mw.loader.register',
1129 ResourceLoader
::inDebugMode()
1132 $version = (int)$version > 1 ?
(int)$version : 1;
1133 return Xml
::encodeJsCall(
1134 'mw.loader.register',
1135 array( $name, $version, $dependencies, $group, $source, $skip ),
1136 ResourceLoader
::inDebugMode()
1142 * Returns JS code which calls mw.loader.addSource() with the given
1143 * parameters. Has two calling conventions:
1145 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1146 * Register a single source
1148 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1149 * Register sources with the given IDs and properties.
1151 * @param string $id Source ID
1152 * @param array $properties Source properties (see addSource())
1155 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1156 if ( is_array( $id ) ) {
1157 return Xml
::encodeJsCall(
1158 'mw.loader.addSource',
1160 ResourceLoader
::inDebugMode()
1163 return Xml
::encodeJsCall(
1164 'mw.loader.addSource',
1165 array( $id, $properties ),
1166 ResourceLoader
::inDebugMode()
1172 * Returns JS code which runs given JS code if the client-side framework is
1175 * @param string $script JavaScript code
1178 public static function makeLoaderConditionalScript( $script ) {
1179 return "if(window.mw){\n" . trim( $script ) . "\n}";
1183 * Returns JS code which will set the MediaWiki configuration array to
1186 * @param array $configuration List of configuration values keyed by variable name
1189 public static function makeConfigSetScript( array $configuration ) {
1190 return Xml
::encodeJsCall(
1192 array( $configuration ),
1193 ResourceLoader
::inDebugMode()
1198 * Convert an array of module names to a packed query string.
1200 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1201 * becomes 'foo.bar,baz|bar.baz,quux'
1202 * @param array $modules List of module names (strings)
1203 * @return string Packed query string
1205 public static function makePackedModulesString( $modules ) {
1206 $groups = array(); // array( prefix => array( suffixes ) )
1207 foreach ( $modules as $module ) {
1208 $pos = strrpos( $module, '.' );
1209 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1210 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1211 $groups[$prefix][] = $suffix;
1215 foreach ( $groups as $prefix => $suffixes ) {
1216 $p = $prefix === '' ?
'' : $prefix . '.';
1217 $arr[] = $p . implode( ',', $suffixes );
1219 $str = implode( '|', $arr );
1224 * Determine whether debug mode was requested
1225 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1228 public static function inDebugMode() {
1229 if ( self
::$debugMode === null ) {
1230 global $wgRequest, $wgResourceLoaderDebug;
1231 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1232 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1235 return self
::$debugMode;
1239 * Reset static members used for caching.
1241 * Global state and $wgRequest are evil, but we're using it right
1242 * now and sometimes we need to be able to force ResourceLoader to
1243 * re-evaluate the context because it has changed (e.g. in the test suite).
1245 public static function clearCache() {
1246 self
::$debugMode = null;
1250 * Build a load.php URL
1253 * @param string $source name of the ResourceLoader source
1254 * @param ResourceLoaderContext $context
1255 * @param array $extraQuery
1256 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1258 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1259 $extraQuery = array()
1261 $query = self
::createLoaderQuery( $context, $extraQuery );
1262 $script = $this->getLoadScript( $source );
1264 // Prevent the IE6 extension check from being triggered (bug 28840)
1265 // by appending a character that's invalid in Windows extensions ('*')
1266 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1270 * Build a load.php URL
1271 * @deprecated since 1.24, use createLoaderURL instead
1272 * @param array $modules Array of module names (strings)
1273 * @param string $lang Language code
1274 * @param string $skin Skin name
1275 * @param string|null $user User name. If null, the &user= parameter is omitted
1276 * @param string|null $version Versioning timestamp
1277 * @param bool $debug Whether the request should be in debug mode
1278 * @param string|null $only &only= parameter
1279 * @param bool $printable Printable mode
1280 * @param bool $handheld Handheld mode
1281 * @param array $extraQuery Extra query parameters to add
1282 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1284 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1285 $version = null, $debug = false, $only = null, $printable = false,
1286 $handheld = false, $extraQuery = array()
1288 global $wgLoadScript;
1290 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1291 $only, $printable, $handheld, $extraQuery
1294 // Prevent the IE6 extension check from being triggered (bug 28840)
1295 // by appending a character that's invalid in Windows extensions ('*')
1296 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1300 * Helper for createLoaderURL()
1303 * @see makeLoaderQuery
1304 * @param ResourceLoaderContext $context
1305 * @param array $extraQuery
1308 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1309 return self
::makeLoaderQuery(
1310 $context->getModules(),
1311 $context->getLanguage(),
1312 $context->getSkin(),
1313 $context->getUser(),
1314 $context->getVersion(),
1315 $context->getDebug(),
1316 $context->getOnly(),
1317 $context->getRequest()->getBool( 'printable' ),
1318 $context->getRequest()->getBool( 'handheld' ),
1324 * Build a query array (array representation of query string) for load.php. Helper
1325 * function for makeLoaderURL().
1327 * @param array $modules
1328 * @param string $lang
1329 * @param string $skin
1330 * @param string $user
1331 * @param string $version
1332 * @param bool $debug
1333 * @param string $only
1334 * @param bool $printable
1335 * @param bool $handheld
1336 * @param array $extraQuery
1340 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1341 $version = null, $debug = false, $only = null, $printable = false,
1342 $handheld = false, $extraQuery = array()
1345 'modules' => self
::makePackedModulesString( $modules ),
1348 'debug' => $debug ?
'true' : 'false',
1350 if ( $user !== null ) {
1351 $query['user'] = $user;
1353 if ( $version !== null ) {
1354 $query['version'] = $version;
1356 if ( $only !== null ) {
1357 $query['only'] = $only;
1360 $query['printable'] = 1;
1363 $query['handheld'] = 1;
1365 $query +
= $extraQuery;
1367 // Make queries uniform in order
1373 * Check a module name for validity.
1375 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1376 * at most 255 bytes.
1378 * @param string $moduleName Module name to check
1379 * @return bool Whether $moduleName is a valid module name
1381 public static function isValidModuleName( $moduleName ) {
1382 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1386 * Returns LESS compiler set up for use with MediaWiki
1391 public static function getLessCompiler() {
1392 global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths;
1394 // When called from the installer, it is possible that a required PHP extension
1395 // is missing (at least for now; see bug 47564). If this is the case, throw an
1396 // exception (caught by the installer) to prevent a fatal error later on.
1397 if ( !function_exists( 'ctype_digit' ) ) {
1398 throw new MWException( 'lessc requires the Ctype extension' );
1401 $less = new lessc();
1402 $less->setPreserveComments( true );
1403 $less->setVariables( self
::getLESSVars() );
1404 $less->setImportDir( $wgResourceLoaderLESSImportPaths );
1405 foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) {
1406 $less->registerFunction( $name, $func );
1412 * Get global LESS variables.
1415 * @return array Map of variable names to string CSS values.
1417 public static function getLESSVars() {
1418 global $wgResourceLoaderLESSVars;
1420 $lessVars = $wgResourceLoaderLESSVars;
1421 // Sort by key to ensure consistent hashing for cache lookups.