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 documention is on the MediaWiki documentation wiki starting at:
29 * http://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader
{
33 /* Protected Static Members */
34 protected static $filterCacheVersion = 7;
35 protected static $requiredSourceProperties = array( 'loadScript' );
37 /** Array: List of module name/ResourceLoaderModule object pairs */
38 protected $modules = array();
40 /** Associative array mapping module name to info associative array */
41 protected $moduleInfos = array();
43 /** Associative array mapping framework ids to a list of names of test suite modules */
44 /** like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. ) */
45 protected $testModuleNames = array();
47 /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
48 protected $sources = array();
51 protected $hasErrors = false;
53 /* Protected Methods */
56 * Loads information stored in the database about modules.
58 * This method grabs modules dependencies from the database and updates modules
61 * This is not inside the module code because it is much faster to
62 * request all of the information at once than it is to have each module
63 * requests its own information. This sacrifice of modularity yields a substantial
64 * performance improvement.
66 * @param array $modules List of module names to preload information for
67 * @param $context ResourceLoaderContext: Context to load the information within
69 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
70 if ( !count( $modules ) ) {
71 // Or else Database*::select() will explode, plus it's cheaper!
74 $dbr = wfGetDB( DB_SLAVE
);
75 $skin = $context->getSkin();
76 $lang = $context->getLanguage();
78 // Get file dependency information
79 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
80 'md_module' => $modules,
85 // Set modules' dependencies
86 $modulesWithDeps = array();
87 foreach ( $res as $row ) {
88 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
89 FormatJson
::decode( $row->md_deps
, true )
91 $modulesWithDeps[] = $row->md_module
;
94 // Register the absence of a dependency row too
95 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
96 $this->getModule( $name )->setFileDependencies( $skin, array() );
99 // Get message blob mtimes. Only do this for modules with messages
100 $modulesWithMessages = array();
101 foreach ( $modules as $name ) {
102 if ( count( $this->getModule( $name )->getMessages() ) ) {
103 $modulesWithMessages[] = $name;
106 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
107 if ( count( $modulesWithMessages ) ) {
108 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
109 'mr_resource' => $modulesWithMessages,
113 foreach ( $res as $row ) {
114 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
115 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
116 unset( $modulesWithoutMessages[$row->mr_resource
] );
119 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
120 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
125 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
127 * Available filters are:
128 * - minify-js \see JavaScriptMinifier::minify
129 * - minify-css \see CSSMin::minify
131 * If $data is empty, only contains whitespace or the filter was unknown,
132 * $data is returned unmodified.
134 * @param string $filter Name of filter to run
135 * @param string $data Text to filter, such as JavaScript or CSS text
136 * @return String: Filtered data, or a comment containing an error message
138 protected function filter( $filter, $data ) {
139 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
140 wfProfileIn( __METHOD__
);
142 // For empty/whitespace-only data or for unknown filters, don't perform
143 // any caching or processing
144 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
145 wfProfileOut( __METHOD__
);
150 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
151 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
152 $cache = wfGetCache( CACHE_ANYTHING
);
153 $cacheEntry = $cache->get( $key );
154 if ( is_string( $cacheEntry ) ) {
155 wfIncrStats( "rl-$filter-cache-hits" );
156 wfProfileOut( __METHOD__
);
161 // Run the filter - we've already verified one of these will work
163 wfIncrStats( "rl-$filter-cache-misses" );
166 $result = JavaScriptMinifier
::minify( $data,
167 $wgResourceLoaderMinifierStatementsOnOwnLine,
168 $wgResourceLoaderMinifierMaxLineLength
170 $result .= "\n/* cache key: $key */";
173 $result = CSSMin
::minify( $data );
174 $result .= "\n/* cache key: $key */";
178 // Save filtered text to Memcached
179 $cache->set( $key, $result );
180 } catch ( Exception
$e ) {
181 MWExceptionHandler
::logException( $e );
182 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
183 $this->hasErrors
= true;
184 // Return exception as a comment
185 $result = self
::formatException( $e );
188 wfProfileOut( __METHOD__
);
196 * Registers core modules and runs registration hooks.
198 public function __construct() {
199 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
201 wfProfileIn( __METHOD__
);
203 // Add 'local' source first
204 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
207 $this->addSource( $wgResourceLoaderSources );
209 // Register core modules
210 $this->register( include "$IP/resources/Resources.php" );
211 // Register extension modules
212 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
213 $this->register( $wgResourceModules );
215 if ( $wgEnableJavaScriptTest === true ) {
216 $this->registerTestModules();
219 wfProfileOut( __METHOD__
);
223 * Registers a module with the ResourceLoader system.
225 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
226 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
227 * this may also be a ResourceLoaderModule object. Optional when using
228 * multiple-registration calling style.
229 * @throws MWException: If a duplicate module registration is attempted
230 * @throws MWException: If a module name contains illegal characters (pipes or commas)
231 * @throws MWException: If something other than a ResourceLoaderModule is being registered
232 * @return Boolean: False if there were any errors, in which case one or more modules were not
235 public function register( $name, $info = null ) {
236 wfProfileIn( __METHOD__
);
238 // Allow multiple modules to be registered in one call
239 $registrations = is_array( $name ) ?
$name : array( $name => $info );
240 foreach ( $registrations as $name => $info ) {
241 // Disallow duplicate registrations
242 if ( isset( $this->moduleInfos
[$name] ) ) {
243 wfProfileOut( __METHOD__
);
244 // A module has already been registered by this name
245 throw new MWException(
246 'ResourceLoader duplicate registration error. ' .
247 'Another module has already been registered as ' . $name
251 // Check $name for validity
252 if ( !self
::isValidModuleName( $name ) ) {
253 wfProfileOut( __METHOD__
);
254 throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" );
258 if ( is_object( $info ) ) {
259 // Old calling convention
260 // Validate the input
261 if ( !( $info instanceof ResourceLoaderModule
) ) {
262 wfProfileOut( __METHOD__
);
263 throw new MWException( 'ResourceLoader invalid module error. ' .
264 'Instances of ResourceLoaderModule expected.' );
267 $this->moduleInfos
[$name] = array( 'object' => $info );
268 $info->setName( $name );
269 $this->modules
[$name] = $info;
271 // New calling convention
272 $this->moduleInfos
[$name] = $info;
276 wfProfileOut( __METHOD__
);
281 public function registerTestModules() {
282 global $IP, $wgEnableJavaScriptTest;
284 if ( $wgEnableJavaScriptTest !== true ) {
285 throw new MWException( 'Attempt to register JavaScript test modules but <code>$wgEnableJavaScriptTest</code> is false. Edit your <code>LocalSettings.php</code> to enable it.' );
288 wfProfileIn( __METHOD__
);
290 // Get core test suites
291 $testModules = array();
292 $testModules['qunit'] = array();
293 // Get other test suites (e.g. from extensions)
294 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
296 // Add the testrunner (which configures QUnit) to the dependencies.
297 // Since it must be ready before any of the test suites are executed.
298 foreach ( $testModules['qunit'] as &$module ) {
299 // Make sure all test modules are top-loading so that when QUnit starts
300 // on document-ready, it will run once and finish. If some tests arrive
301 // later (possibly after QUnit has already finished) they will be ignored.
302 $module['position'] = 'top';
303 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
306 $testModules['qunit'] = ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
308 foreach ( $testModules as $id => $names ) {
309 // Register test modules
310 $this->register( $testModules[$id] );
312 // Keep track of their names so that they can be loaded together
313 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
316 wfProfileOut( __METHOD__
);
320 * Add a foreign source of modules.
323 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
325 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
326 * @param array $properties source properties
327 * @throws MWException
329 public function addSource( $id, $properties = null ) {
330 // Allow multiple sources to be registered in one call
331 if ( is_array( $id ) ) {
332 foreach ( $id as $key => $value ) {
333 $this->addSource( $key, $value );
338 // Disallow duplicates
339 if ( isset( $this->sources
[$id] ) ) {
340 throw new MWException(
341 'ResourceLoader duplicate source addition error. ' .
342 'Another source has already been registered as ' . $id
346 // Validate properties
347 foreach ( self
::$requiredSourceProperties as $prop ) {
348 if ( !isset( $properties[$prop] ) ) {
349 throw new MWException( "Required property $prop missing from source ID $id" );
353 $this->sources
[$id] = $properties;
357 * Get a list of module names
359 * @return Array: List of module names
361 public function getModuleNames() {
362 return array_keys( $this->moduleInfos
);
366 * Get a list of test module names for one (or all) frameworks.
367 * If the given framework id is unknkown, or if the in-object variable is not an array,
368 * then it will return an empty array.
370 * @param string $framework Optional. Get only the test module names for one
371 * particular framework.
374 public function getTestModuleNames( $framework = 'all' ) {
375 /// @todo api siteinfo prop testmodulenames modulenames
376 if ( $framework == 'all' ) {
377 return $this->testModuleNames
;
378 } elseif ( isset( $this->testModuleNames
[$framework] ) && is_array( $this->testModuleNames
[$framework] ) ) {
379 return $this->testModuleNames
[$framework];
386 * Get the ResourceLoaderModule object for a given module name.
388 * @param string $name Module name
389 * @return ResourceLoaderModule if module has been registered, null otherwise
391 public function getModule( $name ) {
392 if ( !isset( $this->modules
[$name] ) ) {
393 if ( !isset( $this->moduleInfos
[$name] ) ) {
397 // Construct the requested object
398 $info = $this->moduleInfos
[$name];
399 /** @var ResourceLoaderModule $object */
400 if ( isset( $info['object'] ) ) {
401 // Object given in info array
402 $object = $info['object'];
404 if ( !isset( $info['class'] ) ) {
405 $class = 'ResourceLoaderFileModule';
407 $class = $info['class'];
409 $object = new $class( $info );
411 $object->setName( $name );
412 $this->modules
[$name] = $object;
415 return $this->modules
[$name];
419 * Get the list of sources
421 * @return Array: array( id => array of properties, .. )
423 public function getSources() {
424 return $this->sources
;
428 * Outputs a response to a resource load-request, including a content-type header.
430 * @param $context ResourceLoaderContext: Context in which a response should be formed
432 public function respond( ResourceLoaderContext
$context ) {
433 global $wgCacheEpoch, $wgUseFileCache;
435 // Use file cache if enabled and available...
436 if ( $wgUseFileCache ) {
437 $fileCache = ResourceFileCache
::newFromContext( $context );
438 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
439 return; // output handled
443 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
444 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
445 // is used: ob_clean() will clear the GZIP header in that case and it won't come
446 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
447 // the whole thing in our own output buffer to be sure the active buffer
448 // doesn't use ob_gzhandler.
449 // See http://bugs.php.net/bug.php?id=36514
452 wfProfileIn( __METHOD__
);
455 // Find out which modules are missing and instantiate the others
458 foreach ( $context->getModules() as $name ) {
459 if ( isset( $this->moduleInfos
[$name] ) ) {
460 $module = $this->getModule( $name );
461 // Do not allow private modules to be loaded from the web.
462 // This is a security issue, see bug 34907.
463 if ( $module->getGroup() === 'private' ) {
464 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
465 $this->hasErrors
= true;
466 // Add exception to the output as a comment
467 $errors .= self
::makeComment( "Cannot show private module \"$name\"" );
471 $modules[$name] = $module;
477 // Preload information needed to the mtime calculation below
479 $this->preloadModuleInfo( array_keys( $modules ), $context );
480 } catch ( Exception
$e ) {
481 MWExceptionHandler
::logException( $e );
482 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
483 $this->hasErrors
= true;
484 // Add exception to the output as a comment
485 $errors .= self
::formatException( $e );
488 wfProfileIn( __METHOD__
. '-getModifiedTime' );
490 // To send Last-Modified and support If-Modified-Since, we need to detect
491 // the last modified time
492 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
493 foreach ( $modules as $module ) {
495 * @var $module ResourceLoaderModule
498 // Calculate maximum modified time
499 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
500 } catch ( Exception
$e ) {
501 MWExceptionHandler
::logException( $e );
502 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
503 $this->hasErrors
= true;
504 // Add exception to the output as a comment
505 $errors .= self
::formatException( $e );
509 wfProfileOut( __METHOD__
. '-getModifiedTime' );
511 // If there's an If-Modified-Since header, respond with a 304 appropriately
512 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
513 wfProfileOut( __METHOD__
);
514 return; // output handled (buffers cleared)
517 // Generate a response
518 $response = $this->makeModuleResponse( $context, $modules, $missing );
520 // Prepend comments indicating exceptions
521 $response = $errors . $response;
523 // Capture any PHP warnings from the output buffer and append them to the
524 // response in a comment if we're in debug mode.
525 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
526 $response = self
::makeComment( $warnings ) . $response;
527 $this->hasErrors
= true;
530 // Save response to file cache unless there are errors
531 if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
532 // Cache single modules...and other requests if there are enough hits
533 if ( ResourceFileCache
::useFileCache( $context ) ) {
534 if ( $fileCache->isCacheWorthy() ) {
535 $fileCache->saveText( $response );
537 $fileCache->incrMissesRecent( $context->getRequest() );
542 // Send content type and cache related headers
543 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
545 // Remove the output buffer and output the response
549 wfProfileOut( __METHOD__
);
553 * Send content type and last modified headers to the client.
554 * @param $context ResourceLoaderContext
555 * @param string $mtime TS_MW timestamp to use for last-modified
556 * @param bool $errors Whether there are commented-out errors in the response
559 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
560 global $wgResourceLoaderMaxage;
561 // If a version wasn't specified we need a shorter expiry time for updates
562 // to propagate to clients quickly
563 // If there were errors, we also need a shorter expiry time so we can recover quickly
564 if ( is_null( $context->getVersion() ) ||
$errors ) {
565 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
566 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
567 // If a version was specified we can use a longer expiry time since changing
568 // version numbers causes cache misses
570 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
571 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
573 if ( $context->getOnly() === 'styles' ) {
574 header( 'Content-Type: text/css; charset=utf-8' );
575 header( 'Access-Control-Allow-Origin: *' );
577 header( 'Content-Type: text/javascript; charset=utf-8' );
579 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
580 if ( $context->getDebug() ) {
581 // Do not cache debug responses
582 header( 'Cache-Control: private, no-cache, must-revalidate' );
583 header( 'Pragma: no-cache' );
585 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
586 $exp = min( $maxage, $smaxage );
587 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
592 * If there's an If-Modified-Since header, respond with a 304 appropriately
593 * and clear out the output buffer. If the client cache is too old then do nothing.
594 * @param $context ResourceLoaderContext
595 * @param string $mtime The TS_MW timestamp to check the header against
596 * @return bool True if 304 header sent and output handled
598 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
599 // If there's an If-Modified-Since header, respond with a 304 appropriately
600 // Some clients send "timestamp;length=123". Strip the part after the first ';'
601 // so we get a valid timestamp.
602 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
603 // Never send 304s in debug mode
604 if ( $ims !== false && !$context->getDebug() ) {
605 $imsTS = strtok( $ims, ';' );
606 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
607 // There's another bug in ob_gzhandler (see also the comment at
608 // the top of this function) that causes it to gzip even empty
609 // responses, meaning it's impossible to produce a truly empty
610 // response (because the gzip header is always there). This is
611 // a problem because 304 responses have to be completely empty
612 // per the HTTP spec, and Firefox behaves buggily when they're not.
613 // See also http://bugs.php.net/bug.php?id=51579
614 // To work around this, we tear down all output buffering before
616 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
618 header( 'HTTP/1.0 304 Not Modified' );
619 header( 'Status: 304 Not Modified' );
627 * Send out code for a response from file cache if possible
629 * @param $fileCache ResourceFileCache: Cache object for this request URL
630 * @param $context ResourceLoaderContext: Context in which to generate a response
631 * @return bool If this found a cache file and handled the response
633 protected function tryRespondFromFileCache(
634 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
636 global $wgResourceLoaderMaxage;
637 // Buffer output to catch warnings.
639 // Get the maximum age the cache can be
640 $maxage = is_null( $context->getVersion() )
641 ?
$wgResourceLoaderMaxage['unversioned']['server']
642 : $wgResourceLoaderMaxage['versioned']['server'];
643 // Minimum timestamp the cache file must have
644 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
646 try { // RL always hits the DB on file cache miss...
648 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
649 $good = $fileCache->isCacheGood(); // cache existence check
653 $ts = $fileCache->cacheTimestamp();
654 // Send content type and cache headers
655 $this->sendResponseHeaders( $context, $ts, false );
656 // If there's an If-Modified-Since header, respond with a 304 appropriately
657 if ( $this->tryRespondLastModified( $context, $ts ) ) {
658 return false; // output handled (buffers cleared)
660 $response = $fileCache->fetchText();
661 // Capture any PHP warnings from the output buffer and append them to the
662 // response in a comment if we're in debug mode.
663 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
664 $response = "/*\n$warnings\n*/\n" . $response;
666 // Remove the output buffer and output the response
668 echo $response . "\n/* Cached {$ts} */";
669 return true; // cache hit
674 return false; // cache miss
678 * Generate a CSS or JS comment block. Only use this for public data,
679 * not error message details.
681 * @param $text string
684 public static function makeComment( $text ) {
685 $encText = str_replace( '*/', '* /', $text );
686 return "/*\n$encText\n*/\n";
690 * Handle exception display
692 * @param Exception $e to be shown to the user
693 * @return string sanitized text that can be returned to the user
695 public static function formatException( $e ) {
696 global $wgShowExceptionDetails;
698 if ( $wgShowExceptionDetails ) {
699 return self
::makeComment( $e->__toString() );
701 return self
::makeComment( wfMessage( 'internalerror' )->text() );
706 * Generates code for a response
708 * @param $context ResourceLoaderContext Context in which to generate a response
709 * @param array $modules List of module objects keyed by module name
710 * @param array $missing List of requested module names that are unregistered (optional)
711 * @return string Response data
713 public function makeModuleResponse( ResourceLoaderContext
$context,
714 array $modules, array $missing = array()
720 if ( !count( $modules ) && !count( $missing ) ) {
721 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
722 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
723 no modules were requested. Max made me put this here. */";
726 wfProfileIn( __METHOD__
);
729 if ( $context->shouldIncludeMessages() ) {
731 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
732 } catch ( Exception
$e ) {
733 MWExceptionHandler
::logException( $e );
734 wfDebugLog( 'resourceloader', __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e" );
735 $this->hasErrors
= true;
736 // Add exception to the output as a comment
737 $exceptions .= self
::formatException( $e );
743 foreach ( $missing as $name ) {
744 $states[$name] = 'missing';
749 foreach ( $modules as $name => $module ) {
751 * @var $module ResourceLoaderModule
754 wfProfileIn( __METHOD__
. '-' . $name );
757 if ( $context->shouldIncludeScripts() ) {
758 // If we are in debug mode, we'll want to return an array of URLs if possible
759 // However, we can't do this if the module doesn't support it
760 // We also can't do this if there is an only= parameter, because we have to give
761 // the module a way to return a load.php URL without causing an infinite loop
762 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
763 $scripts = $module->getScriptURLsForDebug( $context );
765 $scripts = $module->getScript( $context );
766 if ( is_string( $scripts ) && strlen( $scripts ) && substr( $scripts, -1 ) !== ';' ) {
767 // bug 27054: Append semicolon to prevent weird bugs
768 // caused by files not terminating their statements right
775 if ( $context->shouldIncludeStyles() ) {
776 // Don't create empty stylesheets like array( '' => '' ) for modules
777 // that don't *have* any stylesheets (bug 38024).
778 $stylePairs = $module->getStyles( $context );
779 if ( count ( $stylePairs ) ) {
780 // If we are in debug mode without &only= set, we'll want to return an array of URLs
781 // See comment near shouldIncludeScripts() for more details
782 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
784 'url' => $module->getStyleURLsForDebug( $context )
787 // Minify CSS before embedding in mw.loader.implement call
788 // (unless in debug mode)
789 if ( !$context->getDebug() ) {
790 foreach ( $stylePairs as $media => $style ) {
791 // Can be either a string or an array of strings.
792 if ( is_array( $style ) ) {
793 $stylePairs[$media] = array();
794 foreach ( $style as $cssText ) {
795 if ( is_string( $cssText ) ) {
796 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
799 } elseif ( is_string( $style ) ) {
800 $stylePairs[$media] = $this->filter( 'minify-css', $style );
804 // Wrap styles into @media groups as needed and flatten into a numerical array
806 'css' => self
::makeCombinedStyles( $stylePairs )
813 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
816 switch ( $context->getOnly() ) {
818 if ( is_string( $scripts ) ) {
819 // Load scripts raw...
821 } elseif ( is_array( $scripts ) ) {
822 // ...except when $scripts is an array of URLs
823 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
827 // We no longer seperate into media, they are all combined now with
828 // custom media type groups into @media .. {} sections as part of the css string.
829 // Module returns either an empty array or a numerical array with css strings.
830 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
833 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
836 $out .= self
::makeLoaderImplementScript(
840 new XmlJsCode( $messagesBlob )
844 } catch ( Exception
$e ) {
845 MWExceptionHandler
::logException( $e );
846 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
847 $this->hasErrors
= true;
848 // Add exception to the output as a comment
849 $exceptions .= self
::formatException( $e );
851 // Respond to client with error-state instead of module implementation
852 $states[$name] = 'error';
853 unset( $modules[$name] );
855 $isRaw |
= $module->isRaw();
856 wfProfileOut( __METHOD__
. '-' . $name );
859 // Update module states
860 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
861 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
862 // Set the state of modules loaded as only scripts to ready as
863 // they don't have an mw.loader.implement wrapper that sets the state
864 foreach ( $modules as $name => $module ) {
865 $states[$name] = 'ready';
869 // Set the state of modules we didn't respond to with mw.loader.implement
870 if ( count( $states ) ) {
871 $out .= self
::makeLoaderStateScript( $states );
875 if ( !$context->getDebug() ) {
876 if ( $context->getOnly() === 'styles' ) {
877 $out = $this->filter( 'minify-css', $out );
879 $out = $this->filter( 'minify-js', $out );
883 wfProfileOut( __METHOD__
);
884 return $exceptions . $out;
890 * Returns JS code to call to mw.loader.implement for a module with
893 * @param string $name Module name
894 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
895 * @param $styles Mixed: Array of CSS strings keyed by media type, or an array of lists of URLs to
896 * CSS files keyed by media type
897 * @param $messages Mixed: List of messages associated with this module. May either be an
898 * associative array mapping message key to value, or a JSON-encoded message blob containing
899 * the same data, wrapped in an XmlJsCode object.
901 * @throws MWException
904 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
905 if ( is_string( $scripts ) ) {
906 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
907 } elseif ( !is_array( $scripts ) ) {
908 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
910 return Xml
::encodeJsCall(
911 'mw.loader.implement',
915 // Force objects. mw.loader.implement requires them to be javascript objects.
916 // Although these variables are associative arrays, which become javascript
917 // objects through json_encode. In many cases they will be empty arrays, and
918 // PHP/json_encode() consider empty arrays to be numerical arrays and
919 // output javascript "[]" instead of "{}". This fixes that.
923 ResourceLoader
::inDebugMode()
928 * Returns JS code which, when called, will register a given list of messages.
930 * @param $messages Mixed: Either an associative array mapping message key to value, or a
931 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
935 public static function makeMessageSetScript( $messages ) {
936 return Xml
::encodeJsCall(
938 array( (object)$messages ),
939 ResourceLoader
::inDebugMode()
944 * Combines an associative array mapping media type to CSS into a
945 * single stylesheet with "@media" blocks.
947 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings.
951 private static function makeCombinedStyles( array $stylePairs ) {
953 foreach ( $stylePairs as $media => $styles ) {
954 // ResourceLoaderFileModule::getStyle can return the styles
955 // as a string or an array of strings. This is to allow separation in
957 $styles = (array)$styles;
958 foreach ( $styles as $style ) {
959 $style = trim( $style );
960 // Don't output an empty "@media print { }" block (bug 40498)
961 if ( $style !== '' ) {
962 // Transform the media type based on request params and config
963 // The way that this relies on $wgRequest to propagate request params is slightly evil
964 $media = OutputPage
::transformCssMedia( $media );
966 if ( $media === '' ||
$media == 'all' ) {
968 } elseif ( is_string( $media ) ) {
969 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
979 * Returns a JS call to mw.loader.state, which sets the state of a
980 * module or modules to a given value. Has two calling conventions:
982 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
983 * Set the state of a single module called $name to $state
985 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
986 * Set the state of modules with the given names to the given states
988 * @param $name string
993 public static function makeLoaderStateScript( $name, $state = null ) {
994 if ( is_array( $name ) ) {
995 return Xml
::encodeJsCall(
998 ResourceLoader
::inDebugMode()
1001 return Xml
::encodeJsCall(
1003 array( $name, $state ),
1004 ResourceLoader
::inDebugMode()
1010 * Returns JS code which calls the script given by $script. The script will
1011 * be called with local variables name, version, dependencies and group,
1012 * which will have values corresponding to $name, $version, $dependencies
1013 * and $group as supplied.
1015 * @param string $name Module name
1016 * @param $version Integer: Module version number as a timestamp
1017 * @param array $dependencies List of module names on which this module depends
1018 * @param string $group Group which the module is in.
1019 * @param string $source Source of the module, or 'local' if not foreign.
1020 * @param string $script JavaScript code
1024 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
1025 $script = str_replace( "\n", "\n\t", trim( $script ) );
1026 return Xml
::encodeJsCall(
1027 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1028 array( $name, $version, $dependencies, $group, $source ),
1029 ResourceLoader
::inDebugMode()
1034 * Returns JS code which calls mw.loader.register with the given
1035 * parameters. Has three calling conventions:
1037 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
1038 * Register a single module.
1040 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1041 * Register modules with the given names.
1043 * - ResourceLoader::makeLoaderRegisterScript( array(
1044 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
1045 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
1048 * Registers modules with the given names and parameters.
1050 * @param string $name Module name
1051 * @param $version Integer: Module version number as a timestamp
1052 * @param array $dependencies List of module names on which this module depends
1053 * @param string $group group which the module is in.
1054 * @param string $source source of the module, or 'local' if not foreign
1058 public static function makeLoaderRegisterScript( $name, $version = null,
1059 $dependencies = null, $group = null, $source = null
1061 if ( is_array( $name ) ) {
1062 return Xml
::encodeJsCall(
1063 'mw.loader.register',
1065 ResourceLoader
::inDebugMode()
1068 $version = (int)$version > 1 ?
(int)$version : 1;
1069 return Xml
::encodeJsCall(
1070 'mw.loader.register',
1071 array( $name, $version, $dependencies, $group, $source ),
1072 ResourceLoader
::inDebugMode()
1078 * Returns JS code which calls mw.loader.addSource() with the given
1079 * parameters. Has two calling conventions:
1081 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1082 * Register a single source
1084 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1085 * Register sources with the given IDs and properties.
1087 * @param string $id source ID
1088 * @param array $properties source properties (see addSource())
1092 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1093 if ( is_array( $id ) ) {
1094 return Xml
::encodeJsCall(
1095 'mw.loader.addSource',
1097 ResourceLoader
::inDebugMode()
1100 return Xml
::encodeJsCall(
1101 'mw.loader.addSource',
1102 array( $id, $properties ),
1103 ResourceLoader
::inDebugMode()
1109 * Returns JS code which runs given JS code if the client-side framework is
1112 * @param string $script JavaScript code
1116 public static function makeLoaderConditionalScript( $script ) {
1117 return "if(window.mw){\n" . trim( $script ) . "\n}";
1121 * Returns JS code which will set the MediaWiki configuration array to
1124 * @param array $configuration List of configuration values keyed by variable name
1128 public static function makeConfigSetScript( array $configuration ) {
1129 return Xml
::encodeJsCall(
1131 array( $configuration ),
1132 ResourceLoader
::inDebugMode()
1137 * Convert an array of module names to a packed query string.
1139 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1140 * becomes 'foo.bar,baz|bar.baz,quux'
1141 * @param array $modules of module names (strings)
1142 * @return string Packed query string
1144 public static function makePackedModulesString( $modules ) {
1145 $groups = array(); // array( prefix => array( suffixes ) )
1146 foreach ( $modules as $module ) {
1147 $pos = strrpos( $module, '.' );
1148 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1149 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1150 $groups[$prefix][] = $suffix;
1154 foreach ( $groups as $prefix => $suffixes ) {
1155 $p = $prefix === '' ?
'' : $prefix . '.';
1156 $arr[] = $p . implode( ',', $suffixes );
1158 $str = implode( '|', $arr );
1163 * Determine whether debug mode was requested
1164 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1167 public static function inDebugMode() {
1168 global $wgRequest, $wgResourceLoaderDebug;
1169 static $retval = null;
1170 if ( is_null( $retval ) ) {
1171 $retval = $wgRequest->getFuzzyBool( 'debug',
1172 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1178 * Build a load.php URL
1179 * @param array $modules of module names (strings)
1180 * @param string $lang Language code
1181 * @param string $skin Skin name
1182 * @param string|null $user User name. If null, the &user= parameter is omitted
1183 * @param string|null $version Versioning timestamp
1184 * @param bool $debug Whether the request should be in debug mode
1185 * @param string|null $only &only= parameter
1186 * @param bool $printable Printable mode
1187 * @param bool $handheld Handheld mode
1188 * @param array $extraQuery Extra query parameters to add
1189 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1191 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1192 $printable = false, $handheld = false, $extraQuery = array() ) {
1193 global $wgLoadScript;
1194 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1195 $only, $printable, $handheld, $extraQuery
1198 // Prevent the IE6 extension check from being triggered (bug 28840)
1199 // by appending a character that's invalid in Windows extensions ('*')
1200 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1204 * Build a query array (array representation of query string) for load.php. Helper
1205 * function for makeLoaderURL().
1207 * @param array $modules
1208 * @param string $lang
1209 * @param string $skin
1210 * @param string $user
1211 * @param string $version
1212 * @param bool $debug
1213 * @param string $only
1214 * @param bool $printable
1215 * @param bool $handheld
1216 * @param array $extraQuery
1220 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1221 $printable = false, $handheld = false, $extraQuery = array() ) {
1223 'modules' => self
::makePackedModulesString( $modules ),
1226 'debug' => $debug ?
'true' : 'false',
1228 if ( $user !== null ) {
1229 $query['user'] = $user;
1231 if ( $version !== null ) {
1232 $query['version'] = $version;
1234 if ( $only !== null ) {
1235 $query['only'] = $only;
1238 $query['printable'] = 1;
1241 $query['handheld'] = 1;
1243 $query +
= $extraQuery;
1245 // Make queries uniform in order
1251 * Check a module name for validity.
1253 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1254 * at most 255 bytes.
1256 * @param string $moduleName Module name to check
1257 * @return bool Whether $moduleName is a valid module name
1259 public static function isValidModuleName( $moduleName ) {
1260 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1264 * Returns LESS compiler set up for use with MediaWiki
1269 public static function getLessCompiler() {
1270 global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths;
1272 // When called from the installer, it is possible that a required PHP extension
1273 // is missing (at least for now; see bug 47564). If this is the case, throw an
1274 // exception (caught by the installer) to prevent a fatal error later on.
1275 if ( !function_exists( 'ctype_digit' ) ) {
1276 throw new MWException( 'lessc requires the Ctype extension' );
1279 $less = new lessc();
1280 $less->setPreserveComments( true );
1281 $less->setVariables( self
::getLESSVars() );
1282 $less->setImportDir( $wgResourceLoaderLESSImportPaths );
1283 foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) {
1284 $less->registerFunction( $name, $func );
1290 * Get global LESS variables.
1293 * @return array: Map of variable names to string CSS values.
1295 public static function getLESSVars() {
1296 global $wgResourceLoaderLESSVars;
1298 static $lessVars = null;
1299 if ( $lessVars === null ) {
1300 $lessVars = $wgResourceLoaderLESSVars;
1301 // Sort by key to ensure consistent hashing for cache lookups.