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 * https://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 * Load 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 ResourceLoaderContext $context 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 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
127 * Available filters are:
129 * - minify-js \see JavaScriptMinifier::minify
130 * - minify-css \see CSSMin::minify
132 * If $data is empty, only contains whitespace or the filter was unknown,
133 * $data is returned unmodified.
135 * @param string $filter Name of filter to run
136 * @param string $data Text to filter, such as JavaScript or CSS text
137 * @return string Filtered data, or a comment containing an error message
139 protected function filter( $filter, $data ) {
140 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
141 wfProfileIn( __METHOD__
);
143 // For empty/whitespace-only data or for unknown filters, don't perform
144 // any caching or processing
145 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
146 wfProfileOut( __METHOD__
);
151 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
152 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
153 $cache = wfGetCache( CACHE_ANYTHING
);
154 $cacheEntry = $cache->get( $key );
155 if ( is_string( $cacheEntry ) ) {
156 wfIncrStats( "rl-$filter-cache-hits" );
157 wfProfileOut( __METHOD__
);
162 // Run the filter - we've already verified one of these will work
164 wfIncrStats( "rl-$filter-cache-misses" );
167 $result = JavaScriptMinifier
::minify( $data,
168 $wgResourceLoaderMinifierStatementsOnOwnLine,
169 $wgResourceLoaderMinifierMaxLineLength
171 $result .= "\n/* cache key: $key */";
174 $result = CSSMin
::minify( $data );
175 $result .= "\n/* cache key: $key */";
179 // Save filtered text to Memcached
180 $cache->set( $key, $result );
181 } catch ( Exception
$e ) {
182 MWExceptionHandler
::logException( $e );
183 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
184 $this->hasErrors
= true;
185 // Return exception as a comment
186 $result = self
::formatException( $e );
189 wfProfileOut( __METHOD__
);
197 * Register core modules and runs registration hooks.
199 public function __construct() {
200 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
202 wfProfileIn( __METHOD__
);
204 // Add 'local' source first
205 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
208 $this->addSource( $wgResourceLoaderSources );
210 // Register core modules
211 $this->register( include "$IP/resources/Resources.php" );
212 // Register extension modules
213 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
214 $this->register( $wgResourceModules );
216 if ( $wgEnableJavaScriptTest === true ) {
217 $this->registerTestModules();
220 wfProfileOut( __METHOD__
);
224 * Register a module with the ResourceLoader system.
226 * @param mixed $name Name of module as a string or List of name/object pairs as an array
227 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
228 * this may also be a ResourceLoaderModule object. Optional when using
229 * multiple-registration calling style.
230 * @throws MWException: If a duplicate module registration is attempted
231 * @throws MWException: If a module name contains illegal characters (pipes or commas)
232 * @throws MWException: If something other than a ResourceLoaderModule is being registered
233 * @return boolean False if there were any errors, in which case one or more modules were
236 public function register( $name, $info = null ) {
237 wfProfileIn( __METHOD__
);
239 // Allow multiple modules to be registered in one call
240 $registrations = is_array( $name ) ?
$name : array( $name => $info );
241 foreach ( $registrations as $name => $info ) {
242 // Disallow duplicate registrations
243 if ( isset( $this->moduleInfos
[$name] ) ) {
244 wfProfileOut( __METHOD__
);
245 // A module has already been registered by this name
246 throw new MWException(
247 'ResourceLoader duplicate registration error. ' .
248 'Another module has already been registered as ' . $name
252 // Check $name for validity
253 if ( !self
::isValidModuleName( $name ) ) {
254 wfProfileOut( __METHOD__
);
255 throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" );
259 if ( is_object( $info ) ) {
260 // Old calling convention
261 // Validate the input
262 if ( !( $info instanceof ResourceLoaderModule
) ) {
263 wfProfileOut( __METHOD__
);
264 throw new MWException( 'ResourceLoader invalid module error. ' .
265 'Instances of ResourceLoaderModule expected.' );
268 $this->moduleInfos
[$name] = array( 'object' => $info );
269 $info->setName( $name );
270 $this->modules
[$name] = $info;
272 // New calling convention
273 $this->moduleInfos
[$name] = $info;
277 wfProfileOut( __METHOD__
);
282 public function registerTestModules() {
283 global $IP, $wgEnableJavaScriptTest;
285 if ( $wgEnableJavaScriptTest !== true ) {
286 throw new MWException( 'Attempt to register JavaScript test modules but <code>$wgEnableJavaScriptTest</code> is false. Edit your <code>LocalSettings.php</code> to enable it.' );
289 wfProfileIn( __METHOD__
);
291 // Get core test suites
292 $testModules = array();
293 $testModules['qunit'] = array();
294 // Get other test suites (e.g. from extensions)
295 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
297 // Add the testrunner (which configures QUnit) to the dependencies.
298 // Since it must be ready before any of the test suites are executed.
299 foreach ( $testModules['qunit'] as &$module ) {
300 // Make sure all test modules are top-loading so that when QUnit starts
301 // on document-ready, it will run once and finish. If some tests arrive
302 // later (possibly after QUnit has already finished) they will be ignored.
303 $module['position'] = 'top';
304 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
307 $testModules['qunit'] = ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
309 foreach ( $testModules as $id => $names ) {
310 // Register test modules
311 $this->register( $testModules[$id] );
313 // Keep track of their names so that they can be loaded together
314 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
317 wfProfileOut( __METHOD__
);
321 * Add a foreign source of modules.
324 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
326 * @param mixed $id Source ID (string), or array( id1 => props1, id2 => props2, ... )
327 * @param array $properties Source properties
328 * @throws MWException
330 public function addSource( $id, $properties = null ) {
331 // Allow multiple sources to be registered in one call
332 if ( is_array( $id ) ) {
333 foreach ( $id as $key => $value ) {
334 $this->addSource( $key, $value );
339 // Disallow duplicates
340 if ( isset( $this->sources
[$id] ) ) {
341 throw new MWException(
342 'ResourceLoader duplicate source addition error. ' .
343 'Another source has already been registered as ' . $id
347 // Validate properties
348 foreach ( self
::$requiredSourceProperties as $prop ) {
349 if ( !isset( $properties[$prop] ) ) {
350 throw new MWException( "Required property $prop missing from source ID $id" );
354 $this->sources
[$id] = $properties;
358 * Get a list of module names.
360 * @return array List of module names
362 public function getModuleNames() {
363 return array_keys( $this->moduleInfos
);
367 * Get a list of test module names for one (or all) frameworks.
369 * If the given framework id is unknkown, or if the in-object variable is not an array,
370 * then it will return an empty array.
372 * @param string $framework Get only the test module names for one
373 * particular framework (optional)
376 public function getTestModuleNames( $framework = 'all' ) {
377 /// @todo api siteinfo prop testmodulenames modulenames
378 if ( $framework == 'all' ) {
379 return $this->testModuleNames
;
380 } elseif ( isset( $this->testModuleNames
[$framework] ) && is_array( $this->testModuleNames
[$framework] ) ) {
381 return $this->testModuleNames
[$framework];
388 * Get the ResourceLoaderModule object for a given module name.
390 * @param string $name Module name
391 * @return ResourceLoaderModule if module has been registered, null otherwise
393 public function getModule( $name ) {
394 if ( !isset( $this->modules
[$name] ) ) {
395 if ( !isset( $this->moduleInfos
[$name] ) ) {
399 // Construct the requested object
400 $info = $this->moduleInfos
[$name];
401 /** @var ResourceLoaderModule $object */
402 if ( isset( $info['object'] ) ) {
403 // Object given in info array
404 $object = $info['object'];
406 if ( !isset( $info['class'] ) ) {
407 $class = 'ResourceLoaderFileModule';
409 $class = $info['class'];
411 $object = new $class( $info );
413 $object->setName( $name );
414 $this->modules
[$name] = $object;
417 return $this->modules
[$name];
421 * Get the list of sources.
423 * @return array Like array( id => array of properties, .. )
425 public function getSources() {
426 return $this->sources
;
430 * Output a response to a load request, including the content-type header.
432 * @param ResourceLoaderContext $context Context in which a response should be formed
434 public function respond( ResourceLoaderContext
$context ) {
435 global $wgCacheEpoch, $wgUseFileCache;
437 // Use file cache if enabled and available...
438 if ( $wgUseFileCache ) {
439 $fileCache = ResourceFileCache
::newFromContext( $context );
440 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
441 return; // output handled
445 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
446 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
447 // is used: ob_clean() will clear the GZIP header in that case and it won't come
448 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
449 // the whole thing in our own output buffer to be sure the active buffer
450 // doesn't use ob_gzhandler.
451 // See http://bugs.php.net/bug.php?id=36514
454 wfProfileIn( __METHOD__
);
457 // Find out which modules are missing and instantiate the others
460 foreach ( $context->getModules() as $name ) {
461 if ( isset( $this->moduleInfos
[$name] ) ) {
462 $module = $this->getModule( $name );
463 // Do not allow private modules to be loaded from the web.
464 // This is a security issue, see bug 34907.
465 if ( $module->getGroup() === 'private' ) {
466 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
467 $this->hasErrors
= true;
468 // Add exception to the output as a comment
469 $errors .= self
::makeComment( "Cannot show private module \"$name\"" );
473 $modules[$name] = $module;
479 // Preload information needed to the mtime calculation below
481 $this->preloadModuleInfo( array_keys( $modules ), $context );
482 } catch ( Exception
$e ) {
483 MWExceptionHandler
::logException( $e );
484 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
485 $this->hasErrors
= true;
486 // Add exception to the output as a comment
487 $errors .= self
::formatException( $e );
490 wfProfileIn( __METHOD__
. '-getModifiedTime' );
492 // To send Last-Modified and support If-Modified-Since, we need to detect
493 // the last modified time
494 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
495 foreach ( $modules as $module ) {
497 * @var $module ResourceLoaderModule
500 // Calculate maximum modified time
501 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
502 } catch ( Exception
$e ) {
503 MWExceptionHandler
::logException( $e );
504 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
505 $this->hasErrors
= true;
506 // Add exception to the output as a comment
507 $errors .= self
::formatException( $e );
511 wfProfileOut( __METHOD__
. '-getModifiedTime' );
513 // If there's an If-Modified-Since header, respond with a 304 appropriately
514 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
515 wfProfileOut( __METHOD__
);
516 return; // output handled (buffers cleared)
519 // Generate a response
520 $response = $this->makeModuleResponse( $context, $modules, $missing );
522 // Prepend comments indicating exceptions
523 $response = $errors . $response;
525 // Capture any PHP warnings from the output buffer and append them to the
526 // response in a comment if we're in debug mode.
527 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
528 $response = self
::makeComment( $warnings ) . $response;
529 $this->hasErrors
= true;
532 // Save response to file cache unless there are errors
533 if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
534 // Cache single modules...and other requests if there are enough hits
535 if ( ResourceFileCache
::useFileCache( $context ) ) {
536 if ( $fileCache->isCacheWorthy() ) {
537 $fileCache->saveText( $response );
539 $fileCache->incrMissesRecent( $context->getRequest() );
544 // Send content type and cache related headers
545 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
547 // Remove the output buffer and output the response
551 wfProfileOut( __METHOD__
);
555 * Send content type and last modified headers to the client.
556 * @param ResourceLoaderContext $context
557 * @param string $mtime TS_MW timestamp to use for last-modified
558 * @param bool $errors Whether there are commented-out errors in the response
561 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
562 global $wgResourceLoaderMaxage;
563 // If a version wasn't specified we need a shorter expiry time for updates
564 // to propagate to clients quickly
565 // If there were errors, we also need a shorter expiry time so we can recover quickly
566 if ( is_null( $context->getVersion() ) ||
$errors ) {
567 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
568 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
569 // If a version was specified we can use a longer expiry time since changing
570 // version numbers causes cache misses
572 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
573 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
575 if ( $context->getOnly() === 'styles' ) {
576 header( 'Content-Type: text/css; charset=utf-8' );
577 header( 'Access-Control-Allow-Origin: *' );
579 header( 'Content-Type: text/javascript; charset=utf-8' );
581 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
582 if ( $context->getDebug() ) {
583 // Do not cache debug responses
584 header( 'Cache-Control: private, no-cache, must-revalidate' );
585 header( 'Pragma: no-cache' );
587 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
588 $exp = min( $maxage, $smaxage );
589 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
594 * Respond with 304 Last Modified if appropiate.
596 * If there's an If-Modified-Since header, respond with a 304 appropriately
597 * and clear out the output buffer. If the client cache is too old then do nothing.
599 * @param $context ResourceLoaderContext
600 * @param string $mtime The TS_MW timestamp to check the header against
601 * @return bool True if 304 header sent and output handled
603 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
604 // If there's an If-Modified-Since header, respond with a 304 appropriately
605 // Some clients send "timestamp;length=123". Strip the part after the first ';'
606 // so we get a valid timestamp.
607 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
608 // Never send 304s in debug mode
609 if ( $ims !== false && !$context->getDebug() ) {
610 $imsTS = strtok( $ims, ';' );
611 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
612 // There's another bug in ob_gzhandler (see also the comment at
613 // the top of this function) that causes it to gzip even empty
614 // responses, meaning it's impossible to produce a truly empty
615 // response (because the gzip header is always there). This is
616 // a problem because 304 responses have to be completely empty
617 // per the HTTP spec, and Firefox behaves buggily when they're not.
618 // See also http://bugs.php.net/bug.php?id=51579
619 // To work around this, we tear down all output buffering before
621 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
623 header( 'HTTP/1.0 304 Not Modified' );
624 header( 'Status: 304 Not Modified' );
632 * Send out code for a response from file cache if possible.
634 * @param ResourceFileCache $fileCache Cache object for this request URL
635 * @param ResourceLoaderContext $context Context in which to generate a response
636 * @return bool If this found a cache file and handled the response
638 protected function tryRespondFromFileCache(
639 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
641 global $wgResourceLoaderMaxage;
642 // Buffer output to catch warnings.
644 // Get the maximum age the cache can be
645 $maxage = is_null( $context->getVersion() )
646 ?
$wgResourceLoaderMaxage['unversioned']['server']
647 : $wgResourceLoaderMaxage['versioned']['server'];
648 // Minimum timestamp the cache file must have
649 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
651 try { // RL always hits the DB on file cache miss...
653 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
654 $good = $fileCache->isCacheGood(); // cache existence check
658 $ts = $fileCache->cacheTimestamp();
659 // Send content type and cache headers
660 $this->sendResponseHeaders( $context, $ts, false );
661 // If there's an If-Modified-Since header, respond with a 304 appropriately
662 if ( $this->tryRespondLastModified( $context, $ts ) ) {
663 return false; // output handled (buffers cleared)
665 $response = $fileCache->fetchText();
666 // Capture any PHP warnings from the output buffer and append them to the
667 // response in a comment if we're in debug mode.
668 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
669 $response = "/*\n$warnings\n*/\n" . $response;
671 // Remove the output buffer and output the response
673 echo $response . "\n/* Cached {$ts} */";
674 return true; // cache hit
679 return false; // cache miss
683 * Generate a CSS or JS comment block.
685 * Only use this for public data, not error message details.
687 * @param string $text
690 public static function makeComment( $text ) {
691 $encText = str_replace( '*/', '* /', $text );
692 return "/*\n$encText\n*/\n";
696 * Handle exception display.
698 * @param Exception $e to be shown to the user
699 * @return string sanitized text that can be returned to the user
701 public static function formatException( $e ) {
702 global $wgShowExceptionDetails;
704 if ( $wgShowExceptionDetails ) {
705 return self
::makeComment( $e->__toString() );
707 return self
::makeComment( wfMessage( 'internalerror' )->text() );
712 * Generate code for a response.
714 * @param $context ResourceLoaderContext Context in which to generate a response
715 * @param array $modules List of module objects keyed by module name
716 * @param array $missing List of requested module names that are unregistered (optional)
717 * @return string Response data
719 public function makeModuleResponse( ResourceLoaderContext
$context,
720 array $modules, array $missing = array()
726 if ( !count( $modules ) && !count( $missing ) ) {
727 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
728 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
729 no modules were requested. Max made me put this here. */";
732 wfProfileIn( __METHOD__
);
735 if ( $context->shouldIncludeMessages() ) {
737 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
738 } catch ( Exception
$e ) {
739 MWExceptionHandler
::logException( $e );
740 wfDebugLog( 'resourceloader', __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e" );
741 $this->hasErrors
= true;
742 // Add exception to the output as a comment
743 $exceptions .= self
::formatException( $e );
749 foreach ( $missing as $name ) {
750 $states[$name] = 'missing';
755 foreach ( $modules as $name => $module ) {
757 * @var $module ResourceLoaderModule
760 wfProfileIn( __METHOD__
. '-' . $name );
763 if ( $context->shouldIncludeScripts() ) {
764 // If we are in debug mode, we'll want to return an array of URLs if possible
765 // However, we can't do this if the module doesn't support it
766 // We also can't do this if there is an only= parameter, because we have to give
767 // the module a way to return a load.php URL without causing an infinite loop
768 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
769 $scripts = $module->getScriptURLsForDebug( $context );
771 $scripts = $module->getScript( $context );
772 if ( is_string( $scripts ) && strlen( $scripts ) && substr( $scripts, -1 ) !== ';' ) {
773 // bug 27054: Append semicolon to prevent weird bugs
774 // caused by files not terminating their statements right
781 if ( $context->shouldIncludeStyles() ) {
782 // Don't create empty stylesheets like array( '' => '' ) for modules
783 // that don't *have* any stylesheets (bug 38024).
784 $stylePairs = $module->getStyles( $context );
785 if ( count ( $stylePairs ) ) {
786 // If we are in debug mode without &only= set, we'll want to return an array of URLs
787 // See comment near shouldIncludeScripts() for more details
788 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
790 'url' => $module->getStyleURLsForDebug( $context )
793 // Minify CSS before embedding in mw.loader.implement call
794 // (unless in debug mode)
795 if ( !$context->getDebug() ) {
796 foreach ( $stylePairs as $media => $style ) {
797 // Can be either a string or an array of strings.
798 if ( is_array( $style ) ) {
799 $stylePairs[$media] = array();
800 foreach ( $style as $cssText ) {
801 if ( is_string( $cssText ) ) {
802 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
805 } elseif ( is_string( $style ) ) {
806 $stylePairs[$media] = $this->filter( 'minify-css', $style );
810 // Wrap styles into @media groups as needed and flatten into a numerical array
812 'css' => self
::makeCombinedStyles( $stylePairs )
819 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
822 switch ( $context->getOnly() ) {
824 if ( is_string( $scripts ) ) {
825 // Load scripts raw...
827 } elseif ( is_array( $scripts ) ) {
828 // ...except when $scripts is an array of URLs
829 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
833 // We no longer seperate into media, they are all combined now with
834 // custom media type groups into @media .. {} sections as part of the css string.
835 // Module returns either an empty array or a numerical array with css strings.
836 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
839 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
842 $out .= self
::makeLoaderImplementScript(
846 new XmlJsCode( $messagesBlob )
850 } catch ( Exception
$e ) {
851 MWExceptionHandler
::logException( $e );
852 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
853 $this->hasErrors
= true;
854 // Add exception to the output as a comment
855 $exceptions .= self
::formatException( $e );
857 // Respond to client with error-state instead of module implementation
858 $states[$name] = 'error';
859 unset( $modules[$name] );
861 $isRaw |
= $module->isRaw();
862 wfProfileOut( __METHOD__
. '-' . $name );
865 // Update module states
866 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
867 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
868 // Set the state of modules loaded as only scripts to ready as
869 // they don't have an mw.loader.implement wrapper that sets the state
870 foreach ( $modules as $name => $module ) {
871 $states[$name] = 'ready';
875 // Set the state of modules we didn't respond to with mw.loader.implement
876 if ( count( $states ) ) {
877 $out .= self
::makeLoaderStateScript( $states );
881 if ( !$context->getDebug() ) {
882 if ( $context->getOnly() === 'styles' ) {
883 $out = $this->filter( 'minify-css', $out );
885 $out = $this->filter( 'minify-js', $out );
889 wfProfileOut( __METHOD__
);
890 return $exceptions . $out;
896 * Return JS code that calls mw.loader.implement with given module properties.
898 * @param string $name Module name
899 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
900 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
901 * to CSS files keyed by media type
902 * @param mixed $messages List of messages associated with this module. May either be an
903 * associative array mapping message key to value, or a JSON-encoded message blob containing
904 * the same data, wrapped in an XmlJsCode object.
905 * @throws MWException
908 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
909 if ( is_string( $scripts ) ) {
910 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
911 } elseif ( !is_array( $scripts ) ) {
912 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
914 return Xml
::encodeJsCall(
915 'mw.loader.implement',
919 // Force objects. mw.loader.implement requires them to be javascript objects.
920 // Although these variables are associative arrays, which become javascript
921 // objects through json_encode. In many cases they will be empty arrays, and
922 // PHP/json_encode() consider empty arrays to be numerical arrays and
923 // output javascript "[]" instead of "{}". This fixes that.
927 ResourceLoader
::inDebugMode()
932 * Returns JS code which, when called, will register a given list of messages.
934 * @param mixed $messages Either an associative array mapping message key to value, or a
935 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
938 public static function makeMessageSetScript( $messages ) {
939 return Xml
::encodeJsCall(
941 array( (object)$messages ),
942 ResourceLoader
::inDebugMode()
947 * Combines an associative array mapping media type to CSS into a
948 * single stylesheet with "@media" blocks.
950 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
953 private static function makeCombinedStyles( array $stylePairs ) {
955 foreach ( $stylePairs as $media => $styles ) {
956 // ResourceLoaderFileModule::getStyle can return the styles
957 // as a string or an array of strings. This is to allow separation in
959 $styles = (array)$styles;
960 foreach ( $styles as $style ) {
961 $style = trim( $style );
962 // Don't output an empty "@media print { }" block (bug 40498)
963 if ( $style !== '' ) {
964 // Transform the media type based on request params and config
965 // The way that this relies on $wgRequest to propagate request params is slightly evil
966 $media = OutputPage
::transformCssMedia( $media );
968 if ( $media === '' ||
$media == 'all' ) {
970 } elseif ( is_string( $media ) ) {
971 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
981 * Returns a JS call to mw.loader.state, which sets the state of a
982 * module or modules to a given value. Has two calling conventions:
984 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
985 * Set the state of a single module called $name to $state
987 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
988 * Set the state of modules with the given names to the given states
990 * @param string $name
994 public static function makeLoaderStateScript( $name, $state = null ) {
995 if ( is_array( $name ) ) {
996 return Xml
::encodeJsCall(
999 ResourceLoader
::inDebugMode()
1002 return Xml
::encodeJsCall(
1004 array( $name, $state ),
1005 ResourceLoader
::inDebugMode()
1011 * Returns JS code which calls the script given by $script. The script will
1012 * be called with local variables name, version, dependencies and group,
1013 * which will have values corresponding to $name, $version, $dependencies
1014 * and $group as supplied.
1016 * @param string $name Module name
1017 * @param int $version Module version number as a timestamp
1018 * @param array $dependencies List of module names on which this module depends
1019 * @param string $group Group which the module is in.
1020 * @param string $source Source of the module, or 'local' if not foreign.
1021 * @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 int $version 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
1057 public static function makeLoaderRegisterScript( $name, $version = null,
1058 $dependencies = null, $group = null, $source = null
1060 if ( is_array( $name ) ) {
1061 return Xml
::encodeJsCall(
1062 'mw.loader.register',
1064 ResourceLoader
::inDebugMode()
1067 $version = (int)$version > 1 ?
(int)$version : 1;
1068 return Xml
::encodeJsCall(
1069 'mw.loader.register',
1070 array( $name, $version, $dependencies, $group, $source ),
1071 ResourceLoader
::inDebugMode()
1077 * Returns JS code which calls mw.loader.addSource() with the given
1078 * parameters. Has two calling conventions:
1080 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1081 * Register a single source
1083 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1084 * Register sources with the given IDs and properties.
1086 * @param string $id source ID
1087 * @param array $properties source properties (see addSource())
1090 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1091 if ( is_array( $id ) ) {
1092 return Xml
::encodeJsCall(
1093 'mw.loader.addSource',
1095 ResourceLoader
::inDebugMode()
1098 return Xml
::encodeJsCall(
1099 'mw.loader.addSource',
1100 array( $id, $properties ),
1101 ResourceLoader
::inDebugMode()
1107 * Returns JS code which runs given JS code if the client-side framework is
1110 * @param string $script JavaScript code
1113 public static function makeLoaderConditionalScript( $script ) {
1114 return "if(window.mw){\n" . trim( $script ) . "\n}";
1118 * Returns JS code which will set the MediaWiki configuration array to
1121 * @param array $configuration List of configuration values keyed by variable name
1124 public static function makeConfigSetScript( array $configuration ) {
1125 return Xml
::encodeJsCall(
1127 array( $configuration ),
1128 ResourceLoader
::inDebugMode()
1133 * Convert an array of module names to a packed query string.
1135 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1136 * becomes 'foo.bar,baz|bar.baz,quux'
1137 * @param array $modules List of module names (strings)
1138 * @return string Packed query string
1140 public static function makePackedModulesString( $modules ) {
1141 $groups = array(); // array( prefix => array( suffixes ) )
1142 foreach ( $modules as $module ) {
1143 $pos = strrpos( $module, '.' );
1144 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1145 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1146 $groups[$prefix][] = $suffix;
1150 foreach ( $groups as $prefix => $suffixes ) {
1151 $p = $prefix === '' ?
'' : $prefix . '.';
1152 $arr[] = $p . implode( ',', $suffixes );
1154 $str = implode( '|', $arr );
1159 * Determine whether debug mode was requested
1160 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1163 public static function inDebugMode() {
1164 global $wgRequest, $wgResourceLoaderDebug;
1165 static $retval = null;
1166 if ( is_null( $retval ) ) {
1167 $retval = $wgRequest->getFuzzyBool( 'debug',
1168 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1174 * Build a load.php URL
1175 * @param array $modules of module names (strings)
1176 * @param string $lang Language code
1177 * @param string $skin Skin name
1178 * @param string|null $user User name. If null, the &user= parameter is omitted
1179 * @param string|null $version Versioning timestamp
1180 * @param bool $debug Whether the request should be in debug mode
1181 * @param string|null $only &only= parameter
1182 * @param bool $printable Printable mode
1183 * @param bool $handheld Handheld mode
1184 * @param array $extraQuery Extra query parameters to add
1185 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1187 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1188 $printable = false, $handheld = false, $extraQuery = array() ) {
1189 global $wgLoadScript;
1190 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1191 $only, $printable, $handheld, $extraQuery
1194 // Prevent the IE6 extension check from being triggered (bug 28840)
1195 // by appending a character that's invalid in Windows extensions ('*')
1196 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1200 * Build a query array (array representation of query string) for load.php. Helper
1201 * function for makeLoaderURL().
1203 * @param array $modules
1204 * @param string $lang
1205 * @param string $skin
1206 * @param string $user
1207 * @param string $version
1208 * @param bool $debug
1209 * @param string $only
1210 * @param bool $printable
1211 * @param bool $handheld
1212 * @param array $extraQuery
1216 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1217 $printable = false, $handheld = false, $extraQuery = array() ) {
1219 'modules' => self
::makePackedModulesString( $modules ),
1222 'debug' => $debug ?
'true' : 'false',
1224 if ( $user !== null ) {
1225 $query['user'] = $user;
1227 if ( $version !== null ) {
1228 $query['version'] = $version;
1230 if ( $only !== null ) {
1231 $query['only'] = $only;
1234 $query['printable'] = 1;
1237 $query['handheld'] = 1;
1239 $query +
= $extraQuery;
1241 // Make queries uniform in order
1247 * Check a module name for validity.
1249 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1250 * at most 255 bytes.
1252 * @param string $moduleName Module name to check
1253 * @return bool Whether $moduleName is a valid module name
1255 public static function isValidModuleName( $moduleName ) {
1256 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1260 * Returns LESS compiler set up for use with MediaWiki
1265 public static function getLessCompiler() {
1266 global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths;
1268 // When called from the installer, it is possible that a required PHP extension
1269 // is missing (at least for now; see bug 47564). If this is the case, throw an
1270 // exception (caught by the installer) to prevent a fatal error later on.
1271 if ( !function_exists( 'ctype_digit' ) ) {
1272 throw new MWException( 'lessc requires the Ctype extension' );
1275 $less = new lessc();
1276 $less->setPreserveComments( true );
1277 $less->setVariables( self
::getLESSVars() );
1278 $less->setImportDir( $wgResourceLoaderLESSImportPaths );
1279 foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) {
1280 $less->registerFunction( $name, $func );
1286 * Get global LESS variables.
1289 * @return array: Map of variable names to string CSS values.
1291 public static function getLESSVars() {
1292 global $wgResourceLoaderLESSVars;
1294 static $lessVars = null;
1295 if ( $lessVars === null ) {
1296 $lessVars = $wgResourceLoaderLESSVars;
1297 // Sort by key to ensure consistent hashing for cache lookups.