12c452afbc33c24b537e64129879e31767ab24c7
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
{
36 protected static $filterCacheVersion = 7;
40 protected static $requiredSourceProperties = array( 'loadScript' );
43 * @var array Module name/ResourceLoaderModule object pairs
45 protected $modules = array();
48 * @var array Associative array mapping module name to info associative array
50 protected $moduleInfos = array();
53 * @var array Associative array mapping framework ids to a list of names of test suite modules
54 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
56 protected $testModuleNames = array();
59 * @var array e.g. array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) )
61 protected $sources = array();
66 protected $hasErrors = false;
69 * Load information stored in the database about modules.
71 * This method grabs modules dependencies from the database and updates modules
74 * This is not inside the module code because it is much faster to
75 * request all of the information at once than it is to have each module
76 * requests its own information. This sacrifice of modularity yields a substantial
77 * performance improvement.
79 * @param array $modules List of module names to preload information for
80 * @param ResourceLoaderContext $context Context to load the information within
82 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
83 if ( !count( $modules ) ) {
84 // Or else Database*::select() will explode, plus it's cheaper!
87 $dbr = wfGetDB( DB_SLAVE
);
88 $skin = $context->getSkin();
89 $lang = $context->getLanguage();
91 // Get file dependency information
92 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
93 'md_module' => $modules,
98 // Set modules' dependencies
99 $modulesWithDeps = array();
100 foreach ( $res as $row ) {
101 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
102 FormatJson
::decode( $row->md_deps
, true )
104 $modulesWithDeps[] = $row->md_module
;
107 // Register the absence of a dependency row too
108 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
109 $this->getModule( $name )->setFileDependencies( $skin, array() );
112 // Get message blob mtimes. Only do this for modules with messages
113 $modulesWithMessages = array();
114 foreach ( $modules as $name ) {
115 if ( count( $this->getModule( $name )->getMessages() ) ) {
116 $modulesWithMessages[] = $name;
119 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
120 if ( count( $modulesWithMessages ) ) {
121 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
122 'mr_resource' => $modulesWithMessages,
126 foreach ( $res as $row ) {
127 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
128 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
129 unset( $modulesWithoutMessages[$row->mr_resource
] );
132 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
133 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
138 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
140 * Available filters are:
142 * - minify-js \see JavaScriptMinifier::minify
143 * - minify-css \see CSSMin::minify
145 * If $data is empty, only contains whitespace or the filter was unknown,
146 * $data is returned unmodified.
148 * @param string $filter Name of filter to run
149 * @param string $data Text to filter, such as JavaScript or CSS text
150 * @return string Filtered data, or a comment containing an error message
152 protected function filter( $filter, $data ) {
153 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
154 wfProfileIn( __METHOD__
);
156 // For empty/whitespace-only data or for unknown filters, don't perform
157 // any caching or processing
158 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
159 wfProfileOut( __METHOD__
);
164 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
165 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
166 $cache = wfGetCache( CACHE_ANYTHING
);
167 $cacheEntry = $cache->get( $key );
168 if ( is_string( $cacheEntry ) ) {
169 wfIncrStats( "rl-$filter-cache-hits" );
170 wfProfileOut( __METHOD__
);
175 // Run the filter - we've already verified one of these will work
177 wfIncrStats( "rl-$filter-cache-misses" );
180 $result = JavaScriptMinifier
::minify( $data,
181 $wgResourceLoaderMinifierStatementsOnOwnLine,
182 $wgResourceLoaderMinifierMaxLineLength
184 $result .= "\n/* cache key: $key */";
187 $result = CSSMin
::minify( $data );
188 $result .= "\n/* cache key: $key */";
192 // Save filtered text to Memcached
193 $cache->set( $key, $result );
194 } catch ( Exception
$e ) {
195 MWExceptionHandler
::logException( $e );
196 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
197 $this->hasErrors
= true;
198 // Return exception as a comment
199 $result = self
::formatException( $e );
202 wfProfileOut( __METHOD__
);
210 * Register core modules and runs registration hooks.
212 public function __construct() {
213 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
215 wfProfileIn( __METHOD__
);
217 // Add 'local' source first
218 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
221 $this->addSource( $wgResourceLoaderSources );
223 // Register core modules
224 $this->register( include "$IP/resources/Resources.php" );
225 // Register extension modules
226 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
227 $this->register( $wgResourceModules );
229 if ( $wgEnableJavaScriptTest === true ) {
230 $this->registerTestModules();
233 wfProfileOut( __METHOD__
);
237 * Register a module with the ResourceLoader system.
239 * @param mixed $name Name of module as a string or List of name/object pairs as an array
240 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
241 * this may also be a ResourceLoaderModule object. Optional when using
242 * multiple-registration calling style.
243 * @throws MWException: If a duplicate module registration is attempted
244 * @throws MWException: If a module name contains illegal characters (pipes or commas)
245 * @throws MWException: If something other than a ResourceLoaderModule is being registered
246 * @return boolean False if there were any errors, in which case one or more modules were
249 public function register( $name, $info = null ) {
250 wfProfileIn( __METHOD__
);
252 // Allow multiple modules to be registered in one call
253 $registrations = is_array( $name ) ?
$name : array( $name => $info );
254 foreach ( $registrations as $name => $info ) {
255 // Disallow duplicate registrations
256 if ( isset( $this->moduleInfos
[$name] ) ) {
257 wfProfileOut( __METHOD__
);
258 // A module has already been registered by this name
259 throw new MWException(
260 'ResourceLoader duplicate registration error. ' .
261 'Another module has already been registered as ' . $name
265 // Check $name for validity
266 if ( !self
::isValidModuleName( $name ) ) {
267 wfProfileOut( __METHOD__
);
268 throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" );
272 if ( is_object( $info ) ) {
273 // Old calling convention
274 // Validate the input
275 if ( !( $info instanceof ResourceLoaderModule
) ) {
276 wfProfileOut( __METHOD__
);
277 throw new MWException( 'ResourceLoader invalid module error. ' .
278 'Instances of ResourceLoaderModule expected.' );
281 $this->moduleInfos
[$name] = array( 'object' => $info );
282 $info->setName( $name );
283 $this->modules
[$name] = $info;
285 // New calling convention
286 $this->moduleInfos
[$name] = $info;
290 wfProfileOut( __METHOD__
);
295 public function registerTestModules() {
296 global $IP, $wgEnableJavaScriptTest;
298 if ( $wgEnableJavaScriptTest !== true ) {
299 throw new MWException( 'Attempt to register JavaScript test modules but <code>$wgEnableJavaScriptTest</code> is false. Edit your <code>LocalSettings.php</code> to enable it.' );
302 wfProfileIn( __METHOD__
);
304 // Get core test suites
305 $testModules = array();
306 $testModules['qunit'] = array();
307 // Get other test suites (e.g. from extensions)
308 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
310 // Add the testrunner (which configures QUnit) to the dependencies.
311 // Since it must be ready before any of the test suites are executed.
312 foreach ( $testModules['qunit'] as &$module ) {
313 // Make sure all test modules are top-loading so that when QUnit starts
314 // on document-ready, it will run once and finish. If some tests arrive
315 // later (possibly after QUnit has already finished) they will be ignored.
316 $module['position'] = 'top';
317 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
320 $testModules['qunit'] = ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
322 foreach ( $testModules as $id => $names ) {
323 // Register test modules
324 $this->register( $testModules[$id] );
326 // Keep track of their names so that they can be loaded together
327 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
330 wfProfileOut( __METHOD__
);
334 * Add a foreign source of modules.
337 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
339 * @param mixed $id Source ID (string), or array( id1 => props1, id2 => props2, ... )
340 * @param array $properties Source properties
341 * @throws MWException
343 public function addSource( $id, $properties = null ) {
344 // Allow multiple sources to be registered in one call
345 if ( is_array( $id ) ) {
346 foreach ( $id as $key => $value ) {
347 $this->addSource( $key, $value );
352 // Disallow duplicates
353 if ( isset( $this->sources
[$id] ) ) {
354 throw new MWException(
355 'ResourceLoader duplicate source addition error. ' .
356 'Another source has already been registered as ' . $id
360 // Validate properties
361 foreach ( self
::$requiredSourceProperties as $prop ) {
362 if ( !isset( $properties[$prop] ) ) {
363 throw new MWException( "Required property $prop missing from source ID $id" );
367 $this->sources
[$id] = $properties;
371 * Get a list of module names.
373 * @return array List of module names
375 public function getModuleNames() {
376 return array_keys( $this->moduleInfos
);
380 * Get a list of test module names for one (or all) frameworks.
382 * If the given framework id is unknkown, or if the in-object variable is not an array,
383 * then it will return an empty array.
385 * @param string $framework Get only the test module names for one
386 * particular framework (optional)
389 public function getTestModuleNames( $framework = 'all' ) {
390 /// @todo api siteinfo prop testmodulenames modulenames
391 if ( $framework == 'all' ) {
392 return $this->testModuleNames
;
393 } elseif ( isset( $this->testModuleNames
[$framework] ) && is_array( $this->testModuleNames
[$framework] ) ) {
394 return $this->testModuleNames
[$framework];
401 * Get the ResourceLoaderModule object for a given module name.
403 * @param string $name Module name
404 * @return ResourceLoaderModule if module has been registered, null otherwise
406 public function getModule( $name ) {
407 if ( !isset( $this->modules
[$name] ) ) {
408 if ( !isset( $this->moduleInfos
[$name] ) ) {
412 // Construct the requested object
413 $info = $this->moduleInfos
[$name];
414 /** @var ResourceLoaderModule $object */
415 if ( isset( $info['object'] ) ) {
416 // Object given in info array
417 $object = $info['object'];
419 if ( !isset( $info['class'] ) ) {
420 $class = 'ResourceLoaderFileModule';
422 $class = $info['class'];
424 $object = new $class( $info );
426 $object->setName( $name );
427 $this->modules
[$name] = $object;
430 return $this->modules
[$name];
434 * Get the list of sources.
436 * @return array Like array( id => array of properties, .. )
438 public function getSources() {
439 return $this->sources
;
443 * Output a response to a load request, including the content-type header.
445 * @param ResourceLoaderContext $context Context in which a response should be formed
447 public function respond( ResourceLoaderContext
$context ) {
448 global $wgCacheEpoch, $wgUseFileCache;
450 // Use file cache if enabled and available...
451 if ( $wgUseFileCache ) {
452 $fileCache = ResourceFileCache
::newFromContext( $context );
453 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
454 return; // output handled
458 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
459 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
460 // is used: ob_clean() will clear the GZIP header in that case and it won't come
461 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
462 // the whole thing in our own output buffer to be sure the active buffer
463 // doesn't use ob_gzhandler.
464 // See http://bugs.php.net/bug.php?id=36514
467 wfProfileIn( __METHOD__
);
470 // Find out which modules are missing and instantiate the others
473 foreach ( $context->getModules() as $name ) {
474 if ( isset( $this->moduleInfos
[$name] ) ) {
475 $module = $this->getModule( $name );
476 // Do not allow private modules to be loaded from the web.
477 // This is a security issue, see bug 34907.
478 if ( $module->getGroup() === 'private' ) {
479 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
480 $this->hasErrors
= true;
481 // Add exception to the output as a comment
482 $errors .= self
::makeComment( "Cannot show private module \"$name\"" );
486 $modules[$name] = $module;
492 // Preload information needed to the mtime calculation below
494 $this->preloadModuleInfo( array_keys( $modules ), $context );
495 } catch ( Exception
$e ) {
496 MWExceptionHandler
::logException( $e );
497 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
498 $this->hasErrors
= true;
499 // Add exception to the output as a comment
500 $errors .= self
::formatException( $e );
503 wfProfileIn( __METHOD__
. '-getModifiedTime' );
505 // To send Last-Modified and support If-Modified-Since, we need to detect
506 // the last modified time
507 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
508 foreach ( $modules as $module ) {
510 * @var $module ResourceLoaderModule
513 // Calculate maximum modified time
514 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
515 } catch ( Exception
$e ) {
516 MWExceptionHandler
::logException( $e );
517 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
518 $this->hasErrors
= true;
519 // Add exception to the output as a comment
520 $errors .= self
::formatException( $e );
524 wfProfileOut( __METHOD__
. '-getModifiedTime' );
526 // If there's an If-Modified-Since header, respond with a 304 appropriately
527 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
528 wfProfileOut( __METHOD__
);
529 return; // output handled (buffers cleared)
532 // Generate a response
533 $response = $this->makeModuleResponse( $context, $modules, $missing );
535 // Prepend comments indicating exceptions
536 $response = $errors . $response;
538 // Capture any PHP warnings from the output buffer and append them to the
539 // response in a comment if we're in debug mode.
540 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
541 $response = self
::makeComment( $warnings ) . $response;
542 $this->hasErrors
= true;
545 // Save response to file cache unless there are errors
546 if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
547 // Cache single modules...and other requests if there are enough hits
548 if ( ResourceFileCache
::useFileCache( $context ) ) {
549 if ( $fileCache->isCacheWorthy() ) {
550 $fileCache->saveText( $response );
552 $fileCache->incrMissesRecent( $context->getRequest() );
557 // Send content type and cache related headers
558 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
560 // Remove the output buffer and output the response
564 wfProfileOut( __METHOD__
);
568 * Send content type and last modified headers to the client.
569 * @param ResourceLoaderContext $context
570 * @param string $mtime TS_MW timestamp to use for last-modified
571 * @param bool $errors Whether there are commented-out errors in the response
574 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
575 global $wgResourceLoaderMaxage;
576 // If a version wasn't specified we need a shorter expiry time for updates
577 // to propagate to clients quickly
578 // If there were errors, we also need a shorter expiry time so we can recover quickly
579 if ( is_null( $context->getVersion() ) ||
$errors ) {
580 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
581 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
582 // If a version was specified we can use a longer expiry time since changing
583 // version numbers causes cache misses
585 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
586 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
588 if ( $context->getOnly() === 'styles' ) {
589 header( 'Content-Type: text/css; charset=utf-8' );
590 header( 'Access-Control-Allow-Origin: *' );
592 header( 'Content-Type: text/javascript; charset=utf-8' );
594 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
595 if ( $context->getDebug() ) {
596 // Do not cache debug responses
597 header( 'Cache-Control: private, no-cache, must-revalidate' );
598 header( 'Pragma: no-cache' );
600 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
601 $exp = min( $maxage, $smaxage );
602 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
607 * Respond with 304 Last Modified if appropiate.
609 * If there's an If-Modified-Since header, respond with a 304 appropriately
610 * and clear out the output buffer. If the client cache is too old then do nothing.
612 * @param $context ResourceLoaderContext
613 * @param string $mtime The TS_MW timestamp to check the header against
614 * @return bool True if 304 header sent and output handled
616 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
617 // If there's an If-Modified-Since header, respond with a 304 appropriately
618 // Some clients send "timestamp;length=123". Strip the part after the first ';'
619 // so we get a valid timestamp.
620 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
621 // Never send 304s in debug mode
622 if ( $ims !== false && !$context->getDebug() ) {
623 $imsTS = strtok( $ims, ';' );
624 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
625 // There's another bug in ob_gzhandler (see also the comment at
626 // the top of this function) that causes it to gzip even empty
627 // responses, meaning it's impossible to produce a truly empty
628 // response (because the gzip header is always there). This is
629 // a problem because 304 responses have to be completely empty
630 // per the HTTP spec, and Firefox behaves buggily when they're not.
631 // See also http://bugs.php.net/bug.php?id=51579
632 // To work around this, we tear down all output buffering before
634 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
636 header( 'HTTP/1.0 304 Not Modified' );
637 header( 'Status: 304 Not Modified' );
645 * Send out code for a response from file cache if possible.
647 * @param ResourceFileCache $fileCache Cache object for this request URL
648 * @param ResourceLoaderContext $context Context in which to generate a response
649 * @return bool If this found a cache file and handled the response
651 protected function tryRespondFromFileCache(
652 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
654 global $wgResourceLoaderMaxage;
655 // Buffer output to catch warnings.
657 // Get the maximum age the cache can be
658 $maxage = is_null( $context->getVersion() )
659 ?
$wgResourceLoaderMaxage['unversioned']['server']
660 : $wgResourceLoaderMaxage['versioned']['server'];
661 // Minimum timestamp the cache file must have
662 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
664 try { // RL always hits the DB on file cache miss...
666 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
667 $good = $fileCache->isCacheGood(); // cache existence check
671 $ts = $fileCache->cacheTimestamp();
672 // Send content type and cache headers
673 $this->sendResponseHeaders( $context, $ts, false );
674 // If there's an If-Modified-Since header, respond with a 304 appropriately
675 if ( $this->tryRespondLastModified( $context, $ts ) ) {
676 return false; // output handled (buffers cleared)
678 $response = $fileCache->fetchText();
679 // Capture any PHP warnings from the output buffer and append them to the
680 // response in a comment if we're in debug mode.
681 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
682 $response = "/*\n$warnings\n*/\n" . $response;
684 // Remove the output buffer and output the response
686 echo $response . "\n/* Cached {$ts} */";
687 return true; // cache hit
692 return false; // cache miss
696 * Generate a CSS or JS comment block.
698 * Only use this for public data, not error message details.
700 * @param string $text
703 public static function makeComment( $text ) {
704 $encText = str_replace( '*/', '* /', $text );
705 return "/*\n$encText\n*/\n";
709 * Handle exception display.
711 * @param Exception $e to be shown to the user
712 * @return string sanitized text that can be returned to the user
714 public static function formatException( $e ) {
715 global $wgShowExceptionDetails;
717 if ( $wgShowExceptionDetails ) {
718 return self
::makeComment( $e->__toString() );
720 return self
::makeComment( wfMessage( 'internalerror' )->text() );
725 * Generate code for a response.
727 * @param $context ResourceLoaderContext Context in which to generate a response
728 * @param array $modules List of module objects keyed by module name
729 * @param array $missing List of requested module names that are unregistered (optional)
730 * @return string Response data
732 public function makeModuleResponse( ResourceLoaderContext
$context,
733 array $modules, array $missing = array()
739 if ( !count( $modules ) && !count( $missing ) ) {
740 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
741 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
742 no modules were requested. Max made me put this here. */";
745 wfProfileIn( __METHOD__
);
748 if ( $context->shouldIncludeMessages() ) {
750 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
751 } catch ( Exception
$e ) {
752 MWExceptionHandler
::logException( $e );
753 wfDebugLog( 'resourceloader', __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e" );
754 $this->hasErrors
= true;
755 // Add exception to the output as a comment
756 $exceptions .= self
::formatException( $e );
762 foreach ( $missing as $name ) {
763 $states[$name] = 'missing';
768 foreach ( $modules as $name => $module ) {
770 * @var $module ResourceLoaderModule
773 wfProfileIn( __METHOD__
. '-' . $name );
776 if ( $context->shouldIncludeScripts() ) {
777 // If we are in debug mode, we'll want to return an array of URLs if possible
778 // However, we can't do this if the module doesn't support it
779 // We also can't do this if there is an only= parameter, because we have to give
780 // the module a way to return a load.php URL without causing an infinite loop
781 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
782 $scripts = $module->getScriptURLsForDebug( $context );
784 $scripts = $module->getScript( $context );
785 if ( is_string( $scripts ) && strlen( $scripts ) && substr( $scripts, -1 ) !== ';' ) {
786 // bug 27054: Append semicolon to prevent weird bugs
787 // caused by files not terminating their statements right
794 if ( $context->shouldIncludeStyles() ) {
795 // Don't create empty stylesheets like array( '' => '' ) for modules
796 // that don't *have* any stylesheets (bug 38024).
797 $stylePairs = $module->getStyles( $context );
798 if ( count ( $stylePairs ) ) {
799 // If we are in debug mode without &only= set, we'll want to return an array of URLs
800 // See comment near shouldIncludeScripts() for more details
801 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
803 'url' => $module->getStyleURLsForDebug( $context )
806 // Minify CSS before embedding in mw.loader.implement call
807 // (unless in debug mode)
808 if ( !$context->getDebug() ) {
809 foreach ( $stylePairs as $media => $style ) {
810 // Can be either a string or an array of strings.
811 if ( is_array( $style ) ) {
812 $stylePairs[$media] = array();
813 foreach ( $style as $cssText ) {
814 if ( is_string( $cssText ) ) {
815 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
818 } elseif ( is_string( $style ) ) {
819 $stylePairs[$media] = $this->filter( 'minify-css', $style );
823 // Wrap styles into @media groups as needed and flatten into a numerical array
825 'css' => self
::makeCombinedStyles( $stylePairs )
832 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
835 switch ( $context->getOnly() ) {
837 if ( is_string( $scripts ) ) {
838 // Load scripts raw...
840 } elseif ( is_array( $scripts ) ) {
841 // ...except when $scripts is an array of URLs
842 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
846 // We no longer seperate into media, they are all combined now with
847 // custom media type groups into @media .. {} sections as part of the css string.
848 // Module returns either an empty array or a numerical array with css strings.
849 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
852 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
855 $out .= self
::makeLoaderImplementScript(
859 new XmlJsCode( $messagesBlob )
863 } catch ( Exception
$e ) {
864 MWExceptionHandler
::logException( $e );
865 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
866 $this->hasErrors
= true;
867 // Add exception to the output as a comment
868 $exceptions .= self
::formatException( $e );
870 // Respond to client with error-state instead of module implementation
871 $states[$name] = 'error';
872 unset( $modules[$name] );
874 $isRaw |
= $module->isRaw();
875 wfProfileOut( __METHOD__
. '-' . $name );
878 // Update module states
879 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
880 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
881 // Set the state of modules loaded as only scripts to ready as
882 // they don't have an mw.loader.implement wrapper that sets the state
883 foreach ( $modules as $name => $module ) {
884 $states[$name] = 'ready';
888 // Set the state of modules we didn't respond to with mw.loader.implement
889 if ( count( $states ) ) {
890 $out .= self
::makeLoaderStateScript( $states );
894 if ( !$context->getDebug() ) {
895 if ( $context->getOnly() === 'styles' ) {
896 $out = $this->filter( 'minify-css', $out );
898 $out = $this->filter( 'minify-js', $out );
902 wfProfileOut( __METHOD__
);
903 return $exceptions . $out;
909 * Return JS code that calls mw.loader.implement with given module properties.
911 * @param string $name Module name
912 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
913 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
914 * to CSS files keyed by media type
915 * @param mixed $messages List of messages associated with this module. May either be an
916 * associative array mapping message key to value, or a JSON-encoded message blob containing
917 * the same data, wrapped in an XmlJsCode object.
918 * @throws MWException
921 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
922 if ( is_string( $scripts ) ) {
923 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
924 } elseif ( !is_array( $scripts ) ) {
925 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
927 return Xml
::encodeJsCall(
928 'mw.loader.implement',
932 // Force objects. mw.loader.implement requires them to be javascript objects.
933 // Although these variables are associative arrays, which become javascript
934 // objects through json_encode. In many cases they will be empty arrays, and
935 // PHP/json_encode() consider empty arrays to be numerical arrays and
936 // output javascript "[]" instead of "{}". This fixes that.
940 ResourceLoader
::inDebugMode()
945 * Returns JS code which, when called, will register a given list of messages.
947 * @param mixed $messages Either an associative array mapping message key to value, or a
948 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
951 public static function makeMessageSetScript( $messages ) {
952 return Xml
::encodeJsCall(
954 array( (object)$messages ),
955 ResourceLoader
::inDebugMode()
960 * Combines an associative array mapping media type to CSS into a
961 * single stylesheet with "@media" blocks.
963 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
966 private static function makeCombinedStyles( array $stylePairs ) {
968 foreach ( $stylePairs as $media => $styles ) {
969 // ResourceLoaderFileModule::getStyle can return the styles
970 // as a string or an array of strings. This is to allow separation in
972 $styles = (array)$styles;
973 foreach ( $styles as $style ) {
974 $style = trim( $style );
975 // Don't output an empty "@media print { }" block (bug 40498)
976 if ( $style !== '' ) {
977 // Transform the media type based on request params and config
978 // The way that this relies on $wgRequest to propagate request params is slightly evil
979 $media = OutputPage
::transformCssMedia( $media );
981 if ( $media === '' ||
$media == 'all' ) {
983 } elseif ( is_string( $media ) ) {
984 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
994 * Returns a JS call to mw.loader.state, which sets the state of a
995 * module or modules to a given value. Has two calling conventions:
997 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
998 * Set the state of a single module called $name to $state
1000 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1001 * Set the state of modules with the given names to the given states
1003 * @param string $name
1007 public static function makeLoaderStateScript( $name, $state = null ) {
1008 if ( is_array( $name ) ) {
1009 return Xml
::encodeJsCall(
1012 ResourceLoader
::inDebugMode()
1015 return Xml
::encodeJsCall(
1017 array( $name, $state ),
1018 ResourceLoader
::inDebugMode()
1024 * Returns JS code which calls the script given by $script. The script will
1025 * be called with local variables name, version, dependencies and group,
1026 * which will have values corresponding to $name, $version, $dependencies
1027 * and $group as supplied.
1029 * @param string $name Module name
1030 * @param int $version Module version number as a timestamp
1031 * @param array $dependencies List of module names on which this module depends
1032 * @param string $group Group which the module is in.
1033 * @param string $source Source of the module, or 'local' if not foreign.
1034 * @param string $script JavaScript code
1037 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
1038 $script = str_replace( "\n", "\n\t", trim( $script ) );
1039 return Xml
::encodeJsCall(
1040 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1041 array( $name, $version, $dependencies, $group, $source ),
1042 ResourceLoader
::inDebugMode()
1047 * Returns JS code which calls mw.loader.register with the given
1048 * parameters. Has three calling conventions:
1050 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
1051 * Register a single module.
1053 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1054 * Register modules with the given names.
1056 * - ResourceLoader::makeLoaderRegisterScript( array(
1057 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
1058 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
1061 * Registers modules with the given names and parameters.
1063 * @param string $name Module name
1064 * @param int $version Module version number as a timestamp
1065 * @param array $dependencies List of module names on which this module depends
1066 * @param string $group Group which the module is in
1067 * @param string $source Source of the module, or 'local' if not foreign
1070 public static function makeLoaderRegisterScript( $name, $version = null,
1071 $dependencies = null, $group = null, $source = null
1073 if ( is_array( $name ) ) {
1074 return Xml
::encodeJsCall(
1075 'mw.loader.register',
1077 ResourceLoader
::inDebugMode()
1080 $version = (int)$version > 1 ?
(int)$version : 1;
1081 return Xml
::encodeJsCall(
1082 'mw.loader.register',
1083 array( $name, $version, $dependencies, $group, $source ),
1084 ResourceLoader
::inDebugMode()
1090 * Returns JS code which calls mw.loader.addSource() with the given
1091 * parameters. Has two calling conventions:
1093 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1094 * Register a single source
1096 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1097 * Register sources with the given IDs and properties.
1099 * @param string $id source ID
1100 * @param array $properties source properties (see addSource())
1103 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1104 if ( is_array( $id ) ) {
1105 return Xml
::encodeJsCall(
1106 'mw.loader.addSource',
1108 ResourceLoader
::inDebugMode()
1111 return Xml
::encodeJsCall(
1112 'mw.loader.addSource',
1113 array( $id, $properties ),
1114 ResourceLoader
::inDebugMode()
1120 * Returns JS code which runs given JS code if the client-side framework is
1123 * @param string $script JavaScript code
1126 public static function makeLoaderConditionalScript( $script ) {
1127 return "if(window.mw){\n" . trim( $script ) . "\n}";
1131 * Returns JS code which will set the MediaWiki configuration array to
1134 * @param array $configuration List of configuration values keyed by variable name
1137 public static function makeConfigSetScript( array $configuration ) {
1138 return Xml
::encodeJsCall(
1140 array( $configuration ),
1141 ResourceLoader
::inDebugMode()
1146 * Convert an array of module names to a packed query string.
1148 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1149 * becomes 'foo.bar,baz|bar.baz,quux'
1150 * @param array $modules List of module names (strings)
1151 * @return string Packed query string
1153 public static function makePackedModulesString( $modules ) {
1154 $groups = array(); // array( prefix => array( suffixes ) )
1155 foreach ( $modules as $module ) {
1156 $pos = strrpos( $module, '.' );
1157 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1158 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1159 $groups[$prefix][] = $suffix;
1163 foreach ( $groups as $prefix => $suffixes ) {
1164 $p = $prefix === '' ?
'' : $prefix . '.';
1165 $arr[] = $p . implode( ',', $suffixes );
1167 $str = implode( '|', $arr );
1172 * Determine whether debug mode was requested
1173 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1176 public static function inDebugMode() {
1177 global $wgRequest, $wgResourceLoaderDebug;
1178 static $retval = null;
1179 if ( is_null( $retval ) ) {
1180 $retval = $wgRequest->getFuzzyBool( 'debug',
1181 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1187 * Build a load.php URL
1188 * @param array $modules of module names (strings)
1189 * @param string $lang Language code
1190 * @param string $skin Skin name
1191 * @param string|null $user User name. If null, the &user= parameter is omitted
1192 * @param string|null $version Versioning timestamp
1193 * @param bool $debug Whether the request should be in debug mode
1194 * @param string|null $only &only= parameter
1195 * @param bool $printable Printable mode
1196 * @param bool $handheld Handheld mode
1197 * @param array $extraQuery Extra query parameters to add
1198 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1200 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1201 $printable = false, $handheld = false, $extraQuery = array() ) {
1202 global $wgLoadScript;
1203 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1204 $only, $printable, $handheld, $extraQuery
1207 // Prevent the IE6 extension check from being triggered (bug 28840)
1208 // by appending a character that's invalid in Windows extensions ('*')
1209 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1213 * Build a query array (array representation of query string) for load.php. Helper
1214 * function for makeLoaderURL().
1216 * @param array $modules
1217 * @param string $lang
1218 * @param string $skin
1219 * @param string $user
1220 * @param string $version
1221 * @param bool $debug
1222 * @param string $only
1223 * @param bool $printable
1224 * @param bool $handheld
1225 * @param array $extraQuery
1229 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1230 $printable = false, $handheld = false, $extraQuery = array() ) {
1232 'modules' => self
::makePackedModulesString( $modules ),
1235 'debug' => $debug ?
'true' : 'false',
1237 if ( $user !== null ) {
1238 $query['user'] = $user;
1240 if ( $version !== null ) {
1241 $query['version'] = $version;
1243 if ( $only !== null ) {
1244 $query['only'] = $only;
1247 $query['printable'] = 1;
1250 $query['handheld'] = 1;
1252 $query +
= $extraQuery;
1254 // Make queries uniform in order
1260 * Check a module name for validity.
1262 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1263 * at most 255 bytes.
1265 * @param string $moduleName Module name to check
1266 * @return bool Whether $moduleName is a valid module name
1268 public static function isValidModuleName( $moduleName ) {
1269 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1273 * Returns LESS compiler set up for use with MediaWiki
1278 public static function getLessCompiler() {
1279 global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths;
1281 // When called from the installer, it is possible that a required PHP extension
1282 // is missing (at least for now; see bug 47564). If this is the case, throw an
1283 // exception (caught by the installer) to prevent a fatal error later on.
1284 if ( !function_exists( 'ctype_digit' ) ) {
1285 throw new MWException( 'lessc requires the Ctype extension' );
1288 $less = new lessc();
1289 $less->setPreserveComments( true );
1290 $less->setVariables( self
::getLESSVars() );
1291 $less->setImportDir( $wgResourceLoaderLESSImportPaths );
1292 foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) {
1293 $less->registerFunction( $name, $func );
1299 * Get global LESS variables.
1302 * @return array: Map of variable names to string CSS values.
1304 public static function getLESSVars() {
1305 global $wgResourceLoaderLESSVars;
1307 static $lessVars = null;
1308 if ( $lessVars === null ) {
1309 $lessVars = $wgResourceLoaderLESSVars;
1310 // Sort by key to ensure consistent hashing for cache lookups.