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 return; // or else Database*::select() will explode, plus it's cheaper!
73 $dbr = wfGetDB( DB_SLAVE
);
74 $skin = $context->getSkin();
75 $lang = $context->getLanguage();
77 // Get file dependency information
78 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
79 'md_module' => $modules,
84 // Set modules' dependencies
85 $modulesWithDeps = array();
86 foreach ( $res as $row ) {
87 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
88 FormatJson
::decode( $row->md_deps
, true )
90 $modulesWithDeps[] = $row->md_module
;
93 // Register the absence of a dependency row too
94 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
95 $this->getModule( $name )->setFileDependencies( $skin, array() );
98 // Get message blob mtimes. Only do this for modules with messages
99 $modulesWithMessages = array();
100 foreach ( $modules as $name ) {
101 if ( count( $this->getModule( $name )->getMessages() ) ) {
102 $modulesWithMessages[] = $name;
105 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
106 if ( count( $modulesWithMessages ) ) {
107 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
108 'mr_resource' => $modulesWithMessages,
112 foreach ( $res as $row ) {
113 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
114 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
115 unset( $modulesWithoutMessages[$row->mr_resource
] );
118 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
119 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
124 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
126 * Available filters are:
127 * - minify-js \see JavaScriptMinifier::minify
128 * - minify-css \see CSSMin::minify
130 * If $data is empty, only contains whitespace or the filter was unknown,
131 * $data is returned unmodified.
133 * @param string $filter Name of filter to run
134 * @param string $data Text to filter, such as JavaScript or CSS text
135 * @return String: Filtered data, or a comment containing an error message
137 protected function filter( $filter, $data ) {
138 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
139 wfProfileIn( __METHOD__
);
141 // For empty/whitespace-only data or for unknown filters, don't perform
142 // any caching or processing
143 if ( trim( $data ) === ''
144 ||
!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
$exception ) {
182 $exception->logException();
183 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $exception" );
184 $this->hasErrors
= true;
185 // Return exception as a comment
186 $result = self
::formatException( $exception );
189 wfProfileOut( __METHOD__
);
197 * Registers 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 * Registers a module with the ResourceLoader system.
226 * @param $name Mixed: 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 not
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'] = include "$IP/tests/qunit/QUnitTestResources.php";
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'][] = 'mediawiki.tests.qunit.testrunner';
307 foreach ( $testModules as $id => $names ) {
308 // Register test modules
309 $this->register( $testModules[$id] );
311 // Keep track of their names so that they can be loaded together
312 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
315 wfProfileOut( __METHOD__
);
319 * Add a foreign source of modules.
322 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
324 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
325 * @param array $properties source properties
326 * @throws MWException
328 public function addSource( $id, $properties = null ) {
329 // Allow multiple sources to be registered in one call
330 if ( is_array( $id ) ) {
331 foreach ( $id as $key => $value ) {
332 $this->addSource( $key, $value );
337 // Disallow duplicates
338 if ( isset( $this->sources
[$id] ) ) {
339 throw new MWException(
340 'ResourceLoader duplicate source addition error. ' .
341 'Another source has already been registered as ' . $id
345 // Validate properties
346 foreach ( self
::$requiredSourceProperties as $prop ) {
347 if ( !isset( $properties[$prop] ) ) {
348 throw new MWException( "Required property $prop missing from source ID $id" );
352 $this->sources
[$id] = $properties;
356 * Get a list of module names
358 * @return Array: List of module names
360 public function getModuleNames() {
361 return array_keys( $this->moduleInfos
);
365 * Get a list of test module names for one (or all) frameworks.
366 * If the given framework id is unknkown, or if the in-object variable is not an array,
367 * then it will return an empty array.
369 * @param string $framework Optional. Get only the test module names for one
370 * particular framework.
373 public function getTestModuleNames( $framework = 'all' ) {
374 /// @todo api siteinfo prop testmodulenames modulenames
375 if ( $framework == 'all' ) {
376 return $this->testModuleNames
;
377 } elseif ( isset( $this->testModuleNames
[$framework] ) && is_array( $this->testModuleNames
[$framework] ) ) {
378 return $this->testModuleNames
[$framework];
385 * Get the ResourceLoaderModule object for a given module name.
387 * @param string $name Module name
388 * @return ResourceLoaderModule if module has been registered, null otherwise
390 public function getModule( $name ) {
391 if ( !isset( $this->modules
[$name] ) ) {
392 if ( !isset( $this->moduleInfos
[$name] ) ) {
396 // Construct the requested object
397 $info = $this->moduleInfos
[$name];
398 /** @var ResourceLoaderModule $object */
399 if ( isset( $info['object'] ) ) {
400 // Object given in info array
401 $object = $info['object'];
403 if ( !isset( $info['class'] ) ) {
404 $class = 'ResourceLoaderFileModule';
406 $class = $info['class'];
408 $object = new $class( $info );
410 $object->setName( $name );
411 $this->modules
[$name] = $object;
414 return $this->modules
[$name];
418 * Get the list of sources
420 * @return Array: array( id => array of properties, .. )
422 public function getSources() {
423 return $this->sources
;
427 * Outputs a response to a resource load-request, including a content-type header.
429 * @param $context ResourceLoaderContext: Context in which a response should be formed
431 public function respond( ResourceLoaderContext
$context ) {
432 global $wgCacheEpoch, $wgUseFileCache;
434 // Use file cache if enabled and available...
435 if ( $wgUseFileCache ) {
436 $fileCache = ResourceFileCache
::newFromContext( $context );
437 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
438 return; // output handled
442 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
443 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
444 // is used: ob_clean() will clear the GZIP header in that case and it won't come
445 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
446 // the whole thing in our own output buffer to be sure the active buffer
447 // doesn't use ob_gzhandler.
448 // See http://bugs.php.net/bug.php?id=36514
451 wfProfileIn( __METHOD__
);
454 // Split requested modules into two groups, modules and missing
457 foreach ( $context->getModules() as $name ) {
458 if ( isset( $this->moduleInfos
[$name] ) ) {
459 $module = $this->getModule( $name );
460 // Do not allow private modules to be loaded from the web.
461 // This is a security issue, see bug 34907.
462 if ( $module->getGroup() === 'private' ) {
463 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
464 $this->hasErrors
= true;
465 // Add exception to the output as a comment
466 $errors .= self
::makeComment( "Cannot show private module \"$name\"" );
470 $modules[$name] = $module;
476 // Preload information needed to the mtime calculation below
478 $this->preloadModuleInfo( array_keys( $modules ), $context );
479 } catch ( Exception
$e ) {
481 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
482 $this->hasErrors
= true;
483 // Add exception to the output as a comment
484 $errors .= self
::formatException( $e );
487 wfProfileIn( __METHOD__
. '-getModifiedTime' );
489 // To send Last-Modified and support If-Modified-Since, we need to detect
490 // the last modified time
491 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
492 foreach ( $modules as $module ) {
494 * @var $module ResourceLoaderModule
497 // Calculate maximum modified time
498 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
499 } catch ( Exception
$e ) {
501 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
502 $this->hasErrors
= true;
503 // Add exception to the output as a comment
504 $errors .= self
::formatException( $e );
508 wfProfileOut( __METHOD__
. '-getModifiedTime' );
510 // If there's an If-Modified-Since header, respond with a 304 appropriately
511 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
512 wfProfileOut( __METHOD__
);
513 return; // output handled (buffers cleared)
516 // Generate a response
517 $response = $this->makeModuleResponse( $context, $modules, $missing );
519 // Prepend comments indicating exceptions
520 $response = $errors . $response;
522 // Capture any PHP warnings from the output buffer and append them to the
523 // response in a comment if we're in debug mode.
524 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
525 $response = self
::makeComment( $warnings ) . $response;
526 $this->hasErrors
= true;
529 // Save response to file cache unless there are errors
530 if ( isset( $fileCache ) && !$errors && !$missing ) {
531 // Cache single modules...and other requests if there are enough hits
532 if ( ResourceFileCache
::useFileCache( $context ) ) {
533 if ( $fileCache->isCacheWorthy() ) {
534 $fileCache->saveText( $response );
536 $fileCache->incrMissesRecent( $context->getRequest() );
541 // Send content type and cache related headers
542 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors
);
544 // Remove the output buffer and output the response
548 wfProfileOut( __METHOD__
);
552 * Send content type and last modified headers to the client.
553 * @param $context ResourceLoaderContext
554 * @param string $mtime TS_MW timestamp to use for last-modified
555 * @param bool $errors Whether there are commented-out errors in the response
558 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
559 global $wgResourceLoaderMaxage;
560 // If a version wasn't specified we need a shorter expiry time for updates
561 // to propagate to clients quickly
562 // If there were errors, we also need a shorter expiry time so we can recover quickly
563 if ( is_null( $context->getVersion() ) ||
$errors ) {
564 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
565 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
566 // If a version was specified we can use a longer expiry time since changing
567 // version numbers causes cache misses
569 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
570 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
572 if ( $context->getOnly() === 'styles' ) {
573 header( 'Content-Type: text/css; charset=utf-8' );
574 header( 'Access-Control-Allow-Origin: *' );
576 header( 'Content-Type: text/javascript; charset=utf-8' );
578 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
579 if ( $context->getDebug() ) {
580 // Do not cache debug responses
581 header( 'Cache-Control: private, no-cache, must-revalidate' );
582 header( 'Pragma: no-cache' );
584 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
585 $exp = min( $maxage, $smaxage );
586 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
591 * If there's an If-Modified-Since header, respond with a 304 appropriately
592 * and clear out the output buffer. If the client cache is too old then do nothing.
593 * @param $context ResourceLoaderContext
594 * @param string $mtime The TS_MW timestamp to check the header against
595 * @return bool True iff 304 header sent and output handled
597 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
598 // If there's an If-Modified-Since header, respond with a 304 appropriately
599 // Some clients send "timestamp;length=123". Strip the part after the first ';'
600 // so we get a valid timestamp.
601 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
602 // Never send 304s in debug mode
603 if ( $ims !== false && !$context->getDebug() ) {
604 $imsTS = strtok( $ims, ';' );
605 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
606 // There's another bug in ob_gzhandler (see also the comment at
607 // the top of this function) that causes it to gzip even empty
608 // responses, meaning it's impossible to produce a truly empty
609 // response (because the gzip header is always there). This is
610 // a problem because 304 responses have to be completely empty
611 // per the HTTP spec, and Firefox behaves buggily when they're not.
612 // See also http://bugs.php.net/bug.php?id=51579
613 // To work around this, we tear down all output buffering before
615 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
617 header( 'HTTP/1.0 304 Not Modified' );
618 header( 'Status: 304 Not Modified' );
626 * Send out code for a response from file cache if possible
628 * @param $fileCache ResourceFileCache: Cache object for this request URL
629 * @param $context ResourceLoaderContext: Context in which to generate a response
630 * @return bool If this found a cache file and handled the response
632 protected function tryRespondFromFileCache(
633 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
635 global $wgResourceLoaderMaxage;
636 // Buffer output to catch warnings.
638 // Get the maximum age the cache can be
639 $maxage = is_null( $context->getVersion() )
640 ?
$wgResourceLoaderMaxage['unversioned']['server']
641 : $wgResourceLoaderMaxage['versioned']['server'];
642 // Minimum timestamp the cache file must have
643 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
645 try { // RL always hits the DB on file cache miss...
647 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
648 $good = $fileCache->isCacheGood(); // cache existence check
652 $ts = $fileCache->cacheTimestamp();
653 // Send content type and cache headers
654 $this->sendResponseHeaders( $context, $ts, false );
655 // If there's an If-Modified-Since header, respond with a 304 appropriately
656 if ( $this->tryRespondLastModified( $context, $ts ) ) {
657 return false; // output handled (buffers cleared)
659 $response = $fileCache->fetchText();
660 // Capture any PHP warnings from the output buffer and append them to the
661 // response in a comment if we're in debug mode.
662 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
663 $response = "/*\n$warnings\n*/\n" . $response;
665 // Remove the output buffer and output the response
667 echo $response . "\n/* Cached {$ts} */";
668 return true; // cache hit
673 return false; // cache miss
677 * Generate a CSS or JS comment block. Only use this for public data,
678 * not error message details.
680 * @param $text string
683 public static function makeComment( $text ) {
684 $encText = str_replace( '*/', '* /', $text );
685 return "/*\n$encText\n*/\n";
689 * Handle exception display
691 * @param Exception $e to be shown to the user
692 * @return string sanitized text that can be returned to the user
694 public static function formatException( $e ) {
695 global $wgShowExceptionDetails;
697 if ( $wgShowExceptionDetails ) {
698 return self
::makeComment( $e->__toString() );
700 return self
::makeComment( wfMessage( 'internalerror' )->text() );
705 * Generates code for a response
707 * @param $context ResourceLoaderContext: Context in which to generate a response
708 * @param array $modules List of module objects keyed by module name
709 * @param array $missing List of unavailable modules (optional)
710 * @return String: Response data
712 public function makeModuleResponse( ResourceLoaderContext
$context,
713 array $modules, $missing = array()
717 if ( $modules === array() && $missing === array() ) {
718 return '/* No modules requested. Max made me put this here */';
721 wfProfileIn( __METHOD__
);
723 if ( $context->shouldIncludeMessages() ) {
725 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
726 } catch ( Exception
$e ) {
728 wfDebugLog( 'resourceloader', __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e" );
729 $this->hasErrors
= true;
730 // Add exception to the output as a comment
731 $exceptions .= self
::formatException( $e );
739 foreach ( $modules as $name => $module ) {
741 * @var $module ResourceLoaderModule
744 wfProfileIn( __METHOD__
. '-' . $name );
747 if ( $context->shouldIncludeScripts() ) {
748 // If we are in debug mode, we'll want to return an array of URLs if possible
749 // However, we can't do this if the module doesn't support it
750 // We also can't do this if there is an only= parameter, because we have to give
751 // the module a way to return a load.php URL without causing an infinite loop
752 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
753 $scripts = $module->getScriptURLsForDebug( $context );
755 $scripts = $module->getScript( $context );
756 if ( is_string( $scripts ) && strlen( $scripts ) && substr( $scripts, -1 ) !== ';' ) {
757 // bug 27054: Append semicolon to prevent weird bugs
758 // caused by files not terminating their statements right
765 if ( $context->shouldIncludeStyles() ) {
766 // Don't create empty stylesheets like array( '' => '' ) for modules
767 // that don't *have* any stylesheets (bug 38024).
768 $stylePairs = $module->getStyles( $context );
769 if ( count ( $stylePairs ) ) {
770 // If we are in debug mode without &only= set, we'll want to return an array of URLs
771 // See comment near shouldIncludeScripts() for more details
772 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
774 'url' => $module->getStyleURLsForDebug( $context )
777 // Minify CSS before embedding in mw.loader.implement call
778 // (unless in debug mode)
779 if ( !$context->getDebug() ) {
780 foreach ( $stylePairs as $media => $style ) {
781 // Can be either a string or an array of strings.
782 if ( is_array( $style ) ) {
783 $stylePairs[$media] = array();
784 foreach ( $style as $cssText ) {
785 if ( is_string( $cssText ) ) {
786 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
789 } elseif ( is_string( $style ) ) {
790 $stylePairs[$media] = $this->filter( 'minify-css', $style );
794 // Wrap styles into @media groups as needed and flatten into a numerical array
796 'css' => self
::makeCombinedStyles( $stylePairs )
803 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
806 switch ( $context->getOnly() ) {
808 if ( is_string( $scripts ) ) {
809 // Load scripts raw...
811 } elseif ( is_array( $scripts ) ) {
812 // ...except when $scripts is an array of URLs
813 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
817 // We no longer seperate into media, they are all combined now with
818 // custom media type groups into @media .. {} sections as part of the css string.
819 // Module returns either an empty array or a numerical array with css strings.
820 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
823 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
826 $out .= self
::makeLoaderImplementScript(
830 new XmlJsCode( $messagesBlob )
834 } catch ( Exception
$e ) {
836 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
837 $this->hasErrors
= true;
838 // Add exception to the output as a comment
839 $exceptions .= self
::formatException( $e );
841 // Register module as missing
843 unset( $modules[$name] );
845 $isRaw |
= $module->isRaw();
846 wfProfileOut( __METHOD__
. '-' . $name );
849 // Update module states
850 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
851 // Set the state of modules loaded as only scripts to ready
852 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
853 $out .= self
::makeLoaderStateScript(
854 array_fill_keys( array_keys( $modules ), 'ready' ) );
856 // Set the state of modules which were requested but unavailable as missing
857 if ( is_array( $missing ) && count( $missing ) ) {
858 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
862 if ( !$context->getDebug() ) {
863 if ( $context->getOnly() === 'styles' ) {
864 $out = $this->filter( 'minify-css', $out );
866 $out = $this->filter( 'minify-js', $out );
870 wfProfileOut( __METHOD__
);
871 return $exceptions . $out;
877 * Returns JS code to call to mw.loader.implement for a module with
880 * @param string $name Module name
881 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
882 * @param $styles Mixed: Array of CSS strings keyed by media type, or an array of lists of URLs to
883 * CSS files keyed by media type
884 * @param $messages Mixed: List of messages associated with this module. May either be an
885 * associative array mapping message key to value, or a JSON-encoded message blob containing
886 * the same data, wrapped in an XmlJsCode object.
888 * @throws MWException
891 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
892 if ( is_string( $scripts ) ) {
893 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
894 } elseif ( !is_array( $scripts ) ) {
895 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
897 return Xml
::encodeJsCall(
898 'mw.loader.implement',
902 // Force objects. mw.loader.implement requires them to be javascript objects.
903 // Although these variables are associative arrays, which become javascript
904 // objects through json_encode. In many cases they will be empty arrays, and
905 // PHP/json_encode() consider empty arrays to be numerical arrays and
906 // output javascript "[]" instead of "{}". This fixes that.
910 ResourceLoader
::inDebugMode()
915 * Returns JS code which, when called, will register a given list of messages.
917 * @param $messages Mixed: Either an associative array mapping message key to value, or a
918 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
922 public static function makeMessageSetScript( $messages ) {
923 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
927 * Combines an associative array mapping media type to CSS into a
928 * single stylesheet with "@media" blocks.
930 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings.
934 private static function makeCombinedStyles( array $stylePairs ) {
936 foreach ( $stylePairs as $media => $styles ) {
937 // ResourceLoaderFileModule::getStyle can return the styles
938 // as a string or an array of strings. This is to allow separation in
940 $styles = (array)$styles;
941 foreach ( $styles as $style ) {
942 $style = trim( $style );
943 // Don't output an empty "@media print { }" block (bug 40498)
944 if ( $style !== '' ) {
945 // Transform the media type based on request params and config
946 // The way that this relies on $wgRequest to propagate request params is slightly evil
947 $media = OutputPage
::transformCssMedia( $media );
949 if ( $media === '' ||
$media == 'all' ) {
951 } elseif ( is_string( $media ) ) {
952 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
962 * Returns a JS call to mw.loader.state, which sets the state of a
963 * module or modules to a given value. Has two calling conventions:
965 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
966 * Set the state of a single module called $name to $state
968 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
969 * Set the state of modules with the given names to the given states
971 * @param $name string
976 public static function makeLoaderStateScript( $name, $state = null ) {
977 if ( is_array( $name ) ) {
978 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
980 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
985 * Returns JS code which calls the script given by $script. The script will
986 * be called with local variables name, version, dependencies and group,
987 * which will have values corresponding to $name, $version, $dependencies
988 * and $group as supplied.
990 * @param string $name Module name
991 * @param $version Integer: Module version number as a timestamp
992 * @param array $dependencies List of module names on which this module depends
993 * @param string $group Group which the module is in.
994 * @param string $source Source of the module, or 'local' if not foreign.
995 * @param string $script JavaScript code
999 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
1000 $script = str_replace( "\n", "\n\t", trim( $script ) );
1001 return Xml
::encodeJsCall(
1002 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1003 array( $name, $version, $dependencies, $group, $source ) );
1007 * Returns JS code which calls mw.loader.register with the given
1008 * parameters. Has three calling conventions:
1010 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
1011 * Register a single module.
1013 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1014 * Register modules with the given names.
1016 * - ResourceLoader::makeLoaderRegisterScript( array(
1017 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
1018 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
1021 * Registers modules with the given names and parameters.
1023 * @param string $name Module name
1024 * @param $version Integer: Module version number as a timestamp
1025 * @param array $dependencies List of module names on which this module depends
1026 * @param string $group group which the module is in.
1027 * @param string $source source of the module, or 'local' if not foreign
1031 public static function makeLoaderRegisterScript( $name, $version = null,
1032 $dependencies = null, $group = null, $source = null
1034 if ( is_array( $name ) ) {
1035 return Xml
::encodeJsCall( 'mw.loader.register', array( $name ) );
1037 $version = (int)$version > 1 ?
(int)$version : 1;
1038 return Xml
::encodeJsCall( 'mw.loader.register',
1039 array( $name, $version, $dependencies, $group, $source ) );
1044 * Returns JS code which calls mw.loader.addSource() with the given
1045 * parameters. Has two calling conventions:
1047 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1048 * Register a single source
1050 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1051 * Register sources with the given IDs and properties.
1053 * @param string $id source ID
1054 * @param array $properties source properties (see addSource())
1058 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1059 if ( is_array( $id ) ) {
1060 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id ) );
1062 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
1067 * Returns JS code which runs given JS code if the client-side framework is
1070 * @param string $script JavaScript code
1074 public static function makeLoaderConditionalScript( $script ) {
1075 return "if(window.mw){\n" . trim( $script ) . "\n}";
1079 * Returns JS code which will set the MediaWiki configuration array to
1082 * @param array $configuration List of configuration values keyed by variable name
1086 public static function makeConfigSetScript( array $configuration ) {
1087 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ), ResourceLoader
::inDebugMode() );
1091 * Convert an array of module names to a packed query string.
1093 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1094 * becomes 'foo.bar,baz|bar.baz,quux'
1095 * @param array $modules of module names (strings)
1096 * @return string Packed query string
1098 public static function makePackedModulesString( $modules ) {
1099 $groups = array(); // array( prefix => array( suffixes ) )
1100 foreach ( $modules as $module ) {
1101 $pos = strrpos( $module, '.' );
1102 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1103 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1104 $groups[$prefix][] = $suffix;
1108 foreach ( $groups as $prefix => $suffixes ) {
1109 $p = $prefix === '' ?
'' : $prefix . '.';
1110 $arr[] = $p . implode( ',', $suffixes );
1112 $str = implode( '|', $arr );
1117 * Determine whether debug mode was requested
1118 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1121 public static function inDebugMode() {
1122 global $wgRequest, $wgResourceLoaderDebug;
1123 static $retval = null;
1124 if ( !is_null( $retval ) ) {
1127 return $retval = $wgRequest->getFuzzyBool( 'debug',
1128 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1132 * Build a load.php URL
1133 * @param array $modules of module names (strings)
1134 * @param string $lang Language code
1135 * @param string $skin Skin name
1136 * @param string|null $user User name. If null, the &user= parameter is omitted
1137 * @param string|null $version Versioning timestamp
1138 * @param bool $debug Whether the request should be in debug mode
1139 * @param string|null $only &only= parameter
1140 * @param bool $printable Printable mode
1141 * @param bool $handheld Handheld mode
1142 * @param array $extraQuery Extra query parameters to add
1143 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1145 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1146 $printable = false, $handheld = false, $extraQuery = array() ) {
1147 global $wgLoadScript;
1148 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1149 $only, $printable, $handheld, $extraQuery
1152 // Prevent the IE6 extension check from being triggered (bug 28840)
1153 // by appending a character that's invalid in Windows extensions ('*')
1154 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1158 * Build a query array (array representation of query string) for load.php. Helper
1159 * function for makeLoaderURL().
1161 * @param array $modules
1162 * @param string $lang
1163 * @param string $skin
1164 * @param string $user
1165 * @param string $version
1166 * @param bool $debug
1167 * @param string $only
1168 * @param bool $printable
1169 * @param bool $handheld
1170 * @param array $extraQuery
1174 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1175 $printable = false, $handheld = false, $extraQuery = array() ) {
1177 'modules' => self
::makePackedModulesString( $modules ),
1180 'debug' => $debug ?
'true' : 'false',
1182 if ( $user !== null ) {
1183 $query['user'] = $user;
1185 if ( $version !== null ) {
1186 $query['version'] = $version;
1188 if ( $only !== null ) {
1189 $query['only'] = $only;
1192 $query['printable'] = 1;
1195 $query['handheld'] = 1;
1197 $query +
= $extraQuery;
1199 // Make queries uniform in order
1205 * Check a module name for validity.
1207 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1208 * at most 255 bytes.
1210 * @param string $moduleName Module name to check
1211 * @return bool Whether $moduleName is a valid module name
1213 public static function isValidModuleName( $moduleName ) {
1214 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1218 * Returns LESS compiler set up for use with MediaWiki
1223 public static function getLessCompiler() {
1224 global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths;
1226 $less = new lessc();
1227 $less->setPreserveComments( true );
1228 $less->setVariables( self
::getLESSVars() );
1229 $less->setImportDir( $wgResourceLoaderLESSImportPaths );
1230 foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) {
1231 $less->registerFunction( $name, $func );
1237 * Get global LESS variables.
1240 * @return array: Map of variable names to string CSS values.
1242 public static function getLESSVars() {
1243 global $wgResourceLoaderLESSVars;
1245 static $lessVars = null;
1246 if ( $lessVars === null ) {
1247 $lessVars = $wgResourceLoaderLESSVars;
1248 // Sort by key to ensure consistent hashing for cache lookups.