3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @author Roan Kattouw
20 * @author Trevor Parscal
24 * Dynamic JavaScript and CSS resource loading system.
26 * Most of the documention is on the MediaWiki documentation wiki starting at:
27 * http://www.mediawiki.org/wiki/ResourceLoader
29 class ResourceLoader
{
31 /* Protected Static Members */
32 protected static $filterCacheVersion = 4;
33 protected static $requiredSourceProperties = array( 'loadScript' );
35 /** Array: List of module name/ResourceLoaderModule object pairs */
36 protected $modules = array();
38 /** Associative array mapping module name to info associative array */
39 protected $moduleInfos = array();
41 /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
42 protected $sources = array();
44 /* Protected Methods */
47 * Loads information stored in the database about modules.
49 * This method grabs modules dependencies from the database and updates modules
52 * This is not inside the module code because it is much faster to
53 * request all of the information at once than it is to have each module
54 * requests its own information. This sacrifice of modularity yields a substantial
55 * performance improvement.
57 * @param $modules Array: List of module names to preload information for
58 * @param $context ResourceLoaderContext: Context to load the information within
60 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
61 if ( !count( $modules ) ) {
62 return; // or else Database*::select() will explode, plus it's cheaper!
64 $dbr = wfGetDB( DB_SLAVE
);
65 $skin = $context->getSkin();
66 $lang = $context->getLanguage();
68 // Get file dependency information
69 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
70 'md_module' => $modules,
75 // Set modules' dependencies
76 $modulesWithDeps = array();
77 foreach ( $res as $row ) {
78 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
79 FormatJson
::decode( $row->md_deps
, true )
81 $modulesWithDeps[] = $row->md_module
;
84 // Register the absence of a dependency row too
85 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
86 $this->getModule( $name )->setFileDependencies( $skin, array() );
89 // Get message blob mtimes. Only do this for modules with messages
90 $modulesWithMessages = array();
91 foreach ( $modules as $name ) {
92 if ( count( $this->getModule( $name )->getMessages() ) ) {
93 $modulesWithMessages[] = $name;
96 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
97 if ( count( $modulesWithMessages ) ) {
98 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
99 'mr_resource' => $modulesWithMessages,
103 foreach ( $res as $row ) {
104 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
105 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
106 unset( $modulesWithoutMessages[$row->mr_resource
] );
109 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
110 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
115 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
117 * Available filters are:
118 * - minify-js \see JavaScriptMinifier::minify
119 * - minify-css \see CSSMin::minify
121 * If $data is empty, only contains whitespace or the filter was unknown,
122 * $data is returned unmodified.
124 * @param $filter String: Name of filter to run
125 * @param $data String: Text to filter, such as JavaScript or CSS text
126 * @return String: Filtered data, or a comment containing an error message
128 protected function filter( $filter, $data ) {
129 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
130 wfProfileIn( __METHOD__
);
132 // For empty/whitespace-only data or for unknown filters, don't perform
133 // any caching or processing
134 if ( trim( $data ) === ''
135 ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
137 wfProfileOut( __METHOD__
);
142 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
143 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
144 $cache = wfGetCache( CACHE_ANYTHING
);
145 $cacheEntry = $cache->get( $key );
146 if ( is_string( $cacheEntry ) ) {
147 wfProfileOut( __METHOD__
);
152 // Run the filter - we've already verified one of these will work
156 $result = JavaScriptMinifier
::minify( $data,
157 $wgResourceLoaderMinifierStatementsOnOwnLine,
158 $wgResourceLoaderMinifierMaxLineLength
160 $result .= "\n\n/* cache key: $key */\n";
163 $result = CSSMin
::minify( $data );
164 $result .= "\n\n/* cache key: $key */\n";
168 // Save filtered text to Memcached
169 $cache->set( $key, $result );
170 } catch ( Exception
$exception ) {
171 // Return exception as a comment
172 $result = "/*\n{$exception->__toString()}\n*/\n";
175 wfProfileOut( __METHOD__
);
183 * Registers core modules and runs registration hooks.
185 public function __construct() {
186 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript;
188 wfProfileIn( __METHOD__
);
190 // Add 'local' source first
191 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript ) );
194 $this->addSource( $wgResourceLoaderSources );
196 // Register core modules
197 $this->register( include( "$IP/resources/Resources.php" ) );
198 // Register extension modules
199 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
200 $this->register( $wgResourceModules );
202 wfProfileOut( __METHOD__
);
206 * Registers a module with the ResourceLoader system.
208 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
209 * @param $info Module info array. For backwards compatibility with 1.17alpha,
210 * this may also be a ResourceLoaderModule object. Optional when using
211 * multiple-registration calling style.
212 * @throws MWException: If a duplicate module registration is attempted
213 * @throws MWException: If a module name contains illegal characters (pipes or commas)
214 * @throws MWException: If something other than a ResourceLoaderModule is being registered
215 * @return Boolean: False if there were any errors, in which case one or more modules were not
218 public function register( $name, $info = null ) {
219 wfProfileIn( __METHOD__
);
221 // Allow multiple modules to be registered in one call
222 if ( is_array( $name ) ) {
223 foreach ( $name as $key => $value ) {
224 $this->register( $key, $value );
226 wfProfileOut( __METHOD__
);
230 // Disallow duplicate registrations
231 if ( isset( $this->moduleInfos
[$name] ) ) {
232 // A module has already been registered by this name
233 throw new MWException(
234 'ResourceLoader duplicate registration error. ' .
235 'Another module has already been registered as ' . $name
239 // Check $name for illegal characters
240 if ( preg_match( '/[|,!]/', $name ) ) {
241 throw new MWException( "ResourceLoader module name '$name' is invalid. Names may not contain pipes (|), commas (,) or exclamation marks (!)" );
245 if ( is_object( $info ) ) {
246 // Old calling convention
247 // Validate the input
248 if ( !( $info instanceof ResourceLoaderModule
) ) {
249 throw new MWException( 'ResourceLoader invalid module error. ' .
250 'Instances of ResourceLoaderModule expected.' );
253 $this->moduleInfos
[$name] = array( 'object' => $info );
254 $info->setName( $name );
255 $this->modules
[$name] = $info;
257 // New calling convention
258 $this->moduleInfos
[$name] = $info;
261 wfProfileOut( __METHOD__
);
265 * Add a foreign source of modules.
268 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
270 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
271 * @param $properties Array: source properties
273 public function addSource( $id, $properties = null) {
274 // Allow multiple sources to be registered in one call
275 if ( is_array( $id ) ) {
276 foreach ( $id as $key => $value ) {
277 $this->addSource( $key, $value );
282 // Disallow duplicates
283 if ( isset( $this->sources
[$id] ) ) {
284 throw new MWException(
285 'ResourceLoader duplicate source addition error. ' .
286 'Another source has already been registered as ' . $id
290 // Validate properties
291 foreach ( self
::$requiredSourceProperties as $prop ) {
292 if ( !isset( $properties[$prop] ) ) {
293 throw new MWException( "Required property $prop missing from source ID $id" );
297 $this->sources
[$id] = $properties;
301 * Get a list of module names
303 * @return Array: List of module names
305 public function getModuleNames() {
306 return array_keys( $this->moduleInfos
);
310 * Get the ResourceLoaderModule object for a given module name.
312 * @param $name String: Module name
313 * @return ResourceLoaderModule if module has been registered, null otherwise
315 public function getModule( $name ) {
316 if ( !isset( $this->modules
[$name] ) ) {
317 if ( !isset( $this->moduleInfos
[$name] ) ) {
321 // Construct the requested object
322 $info = $this->moduleInfos
[$name];
323 if ( isset( $info['object'] ) ) {
324 // Object given in info array
325 $object = $info['object'];
327 if ( !isset( $info['class'] ) ) {
328 $class = 'ResourceLoaderFileModule';
330 $class = $info['class'];
332 $object = new $class( $info );
334 $object->setName( $name );
335 $this->modules
[$name] = $object;
338 return $this->modules
[$name];
342 * Get the list of sources
344 * @return Array: array( id => array of properties, .. )
346 public function getSources() {
347 return $this->sources
;
351 * Outputs a response to a resource load-request, including a content-type header.
353 * @param $context ResourceLoaderContext: Context in which a response should be formed
355 public function respond( ResourceLoaderContext
$context ) {
356 global $wgResourceLoaderMaxage, $wgCacheEpoch;
358 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
359 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
360 // is used: ob_clean() will clear the GZIP header in that case and it won't come
361 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
362 // the whole thing in our own output buffer to be sure the active buffer
363 // doesn't use ob_gzhandler.
364 // See http://bugs.php.net/bug.php?id=36514
367 wfProfileIn( __METHOD__
);
370 // Split requested modules into two groups, modules and missing
373 foreach ( $context->getModules() as $name ) {
374 if ( isset( $this->moduleInfos
[$name] ) ) {
375 $modules[$name] = $this->getModule( $name );
381 // If a version wasn't specified we need a shorter expiry time for updates
382 // to propagate to clients quickly
383 if ( is_null( $context->getVersion() ) ) {
384 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
385 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
387 // If a version was specified we can use a longer expiry time since changing
388 // version numbers causes cache misses
390 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
391 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
394 // Preload information needed to the mtime calculation below
396 $this->preloadModuleInfo( array_keys( $modules ), $context );
397 } catch( Exception
$e ) {
398 // Add exception to the output as a comment
399 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
402 wfProfileIn( __METHOD__
.'-getModifiedTime' );
405 // To send Last-Modified and support If-Modified-Since, we need to detect
406 // the last modified time
407 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
408 foreach ( $modules as $module ) {
410 // Bypass Squid and other shared caches if the request includes any private modules
411 if ( $module->getGroup() === 'private' ) {
414 // Calculate maximum modified time
415 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
416 } catch ( Exception
$e ) {
417 // Add exception to the output as a comment
418 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
422 wfProfileOut( __METHOD__
.'-getModifiedTime' );
424 if ( $context->getOnly() === 'styles' ) {
425 header( 'Content-Type: text/css; charset=utf-8' );
427 header( 'Content-Type: text/javascript; charset=utf-8' );
429 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
430 if ( $context->getDebug() ) {
431 // Do not cache debug responses
432 header( 'Cache-Control: private, no-cache, must-revalidate' );
433 header( 'Pragma: no-cache' );
436 header( "Cache-Control: private, max-age=$maxage" );
439 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
440 $exp = min( $maxage, $smaxage );
442 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
445 // If there's an If-Modified-Since header, respond with a 304 appropriately
446 // Some clients send "timestamp;length=123". Strip the part after the first ';'
447 // so we get a valid timestamp.
448 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
449 // Never send 304s in debug mode
450 if ( $ims !== false && !$context->getDebug() ) {
451 $imsTS = strtok( $ims, ';' );
452 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
453 // There's another bug in ob_gzhandler (see also the comment at
454 // the top of this function) that causes it to gzip even empty
455 // responses, meaning it's impossible to produce a truly empty
456 // response (because the gzip header is always there). This is
457 // a problem because 304 responses have to be completely empty
458 // per the HTTP spec, and Firefox behaves buggily when they're not.
459 // See also http://bugs.php.net/bug.php?id=51579
460 // To work around this, we tear down all output buffering before
462 // On some setups, ob_get_level() doesn't seem to go down to zero
463 // no matter how often we call ob_get_clean(), so instead of doing
464 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
465 // we have to be safe here and avoid an infinite loop.
466 for ( $i = 0; $i < ob_get_level(); $i++
) {
470 header( 'HTTP/1.0 304 Not Modified' );
471 header( 'Status: 304 Not Modified' );
472 wfProfileOut( __METHOD__
);
477 // Generate a response
478 $response = $this->makeModuleResponse( $context, $modules, $missing );
480 // Prepend comments indicating exceptions
481 $response = $exceptions . $response;
483 // Capture any PHP warnings from the output buffer and append them to the
484 // response in a comment if we're in debug mode.
485 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
486 $response = "/*\n$warnings\n*/\n" . $response;
489 // Remove the output buffer and output the response
493 wfProfileOut( __METHOD__
);
497 * Generates code for a response
499 * @param $context ResourceLoaderContext: Context in which to generate a response
500 * @param $modules Array: List of module objects keyed by module name
501 * @param $missing Array: List of unavailable modules (optional)
502 * @return String: Response data
504 public function makeModuleResponse( ResourceLoaderContext
$context,
505 array $modules, $missing = array() )
509 if ( $modules === array() && $missing === array() ) {
510 return '/* No modules requested. Max made me put this here */';
513 wfProfileIn( __METHOD__
);
515 if ( $context->shouldIncludeMessages() ) {
517 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
518 } catch ( Exception
$e ) {
519 // Add exception to the output as a comment
520 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
527 foreach ( $modules as $name => $module ) {
528 wfProfileIn( __METHOD__
. '-' . $name );
531 if ( $context->shouldIncludeScripts() ) {
532 $scripts = $module->getScript( $context );
533 if ( is_string( $scripts ) ) {
534 // bug 27054: Append semicolon to prevent weird bugs
535 // caused by files not terminating their statements right
541 if ( $context->shouldIncludeStyles() ) {
542 $styles = $module->getStyles( $context );
546 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
549 switch ( $context->getOnly() ) {
551 if ( is_string( $scripts ) ) {
553 } elseif ( is_array( $scripts ) ) {
554 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
558 $out .= self
::makeCombinedStyles( $styles );
561 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
564 // Minify CSS before embedding in mw.loader.implement call
565 // (unless in debug mode)
566 if ( !$context->getDebug() ) {
567 foreach ( $styles as $media => $style ) {
568 if ( is_string( $style ) ) {
569 $styles[$media] = $this->filter( 'minify-css', $style );
573 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
574 new XmlJsCode( $messagesBlob ) );
577 } catch ( Exception
$e ) {
578 // Add exception to the output as a comment
579 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
581 // Register module as missing
583 unset( $modules[$name] );
585 wfProfileOut( __METHOD__
. '-' . $name );
588 // Update module states
589 if ( $context->shouldIncludeScripts() ) {
590 // Set the state of modules loaded as only scripts to ready
591 if ( count( $modules ) && $context->getOnly() === 'scripts'
592 && !isset( $modules['startup'] ) )
594 $out .= self
::makeLoaderStateScript(
595 array_fill_keys( array_keys( $modules ), 'ready' ) );
597 // Set the state of modules which were requested but unavailable as missing
598 if ( is_array( $missing ) && count( $missing ) ) {
599 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
603 if ( !$context->getDebug() ) {
604 if ( $context->getOnly() === 'styles' ) {
605 $out = $this->filter( 'minify-css', $out );
607 $out = $this->filter( 'minify-js', $out );
611 wfProfileOut( __METHOD__
);
612 return $exceptions . $out;
618 * Returns JS code to call to mw.loader.implement for a module with
621 * @param $name Module name
622 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
623 * @param $styles Mixed: List of CSS strings keyed by media type, or list of lists of URLs to
624 * CSS files keyed by media type
625 * @param $messages Mixed: List of messages associated with this module. May either be an
626 * associative array mapping message key to value, or a JSON-encoded message blob containing
627 * the same data, wrapped in an XmlJsCode object.
631 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
632 if ( is_string( $scripts ) ) {
633 $scripts = new XmlJsCode( "function( $ ) {{$scripts}}" );
634 } elseif ( !is_array( $scripts ) ) {
635 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
637 return Xml
::encodeJsCall(
638 'mw.loader.implement',
648 * Returns JS code which, when called, will register a given list of messages.
650 * @param $messages Mixed: Either an associative array mapping message key to value, or a
651 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
655 public static function makeMessageSetScript( $messages ) {
656 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
660 * Combines an associative array mapping media type to CSS into a
661 * single stylesheet with @media blocks.
663 * @param $styles Array: List of CSS strings keyed by media type
667 public static function makeCombinedStyles( array $styles ) {
669 foreach ( $styles as $media => $style ) {
670 // Transform the media type based on request params and config
671 // The way that this relies on $wgRequest to propagate request params is slightly evil
672 $media = OutputPage
::transformCssMedia( $media );
674 if ( $media === null ) {
676 } elseif ( $media === '' ||
$media == 'all' ) {
677 // Don't output invalid or frivolous @media statements
680 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
687 * Returns a JS call to mw.loader.state, which sets the state of a
688 * module or modules to a given value. Has two calling conventions:
690 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
691 * Set the state of a single module called $name to $state
693 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
694 * Set the state of modules with the given names to the given states
696 * @param $name string
701 public static function makeLoaderStateScript( $name, $state = null ) {
702 if ( is_array( $name ) ) {
703 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
705 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
710 * Returns JS code which calls the script given by $script. The script will
711 * be called with local variables name, version, dependencies and group,
712 * which will have values corresponding to $name, $version, $dependencies
713 * and $group as supplied.
715 * @param $name String: Module name
716 * @param $version Integer: Module version number as a timestamp
717 * @param $dependencies Array: List of module names on which this module depends
718 * @param $group String: Group which the module is in.
719 * @param $source String: Source of the module, or 'local' if not foreign.
720 * @param $script String: JavaScript code
724 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
725 $script = str_replace( "\n", "\n\t", trim( $script ) );
726 return Xml
::encodeJsCall(
727 "( function( name, version, dependencies, group, source ) {\n\t$script\n} )",
728 array( $name, $version, $dependencies, $group, $source ) );
732 * Returns JS code which calls mw.loader.register with the given
733 * parameters. Has three calling conventions:
735 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
736 * Register a single module.
738 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
739 * Register modules with the given names.
741 * - ResourceLoader::makeLoaderRegisterScript( array(
742 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
743 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
746 * Registers modules with the given names and parameters.
748 * @param $name String: Module name
749 * @param $version Integer: Module version number as a timestamp
750 * @param $dependencies Array: List of module names on which this module depends
751 * @param $group String: group which the module is in.
752 * @param $source String: source of the module, or 'local' if not foreign
756 public static function makeLoaderRegisterScript( $name, $version = null,
757 $dependencies = null, $group = null, $source = null )
759 if ( is_array( $name ) ) {
760 return Xml
::encodeJsCall( 'mw.loader.register', array( $name ) );
762 $version = (int) $version > 1 ?
(int) $version : 1;
763 return Xml
::encodeJsCall( 'mw.loader.register',
764 array( $name, $version, $dependencies, $group, $source ) );
769 * Returns JS code which calls mw.loader.addSource() with the given
770 * parameters. Has two calling conventions:
772 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
773 * Register a single source
775 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
776 * Register sources with the given IDs and properties.
778 * @param $id String: source ID
779 * @param $properties Array: source properties (see addSource())
781 public static function makeLoaderSourcesScript( $id, $properties = null ) {
782 if ( is_array( $id ) ) {
783 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id ) );
785 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
790 * Returns JS code which runs given JS code if the client-side framework is
793 * @param $script String: JavaScript code
797 public static function makeLoaderConditionalScript( $script ) {
798 $script = str_replace( "\n", "\n\t", trim( $script ) );
799 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
803 * Returns JS code which will set the MediaWiki configuration array to
806 * @param $configuration Array: List of configuration values keyed by variable name
810 public static function makeConfigSetScript( array $configuration ) {
811 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ) );
815 * Convert an array of module names to a packed query string.
817 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
818 * becomes 'foo.bar,baz|bar.baz,quux'
819 * @param $modules array of module names (strings)
820 * @return string Packed query string
822 public static function makePackedModulesString( $modules ) {
823 $groups = array(); // array( prefix => array( suffixes ) )
824 foreach ( $modules as $module ) {
825 $pos = strrpos( $module, '.' );
826 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
827 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
828 $groups[$prefix][] = $suffix;
832 foreach ( $groups as $prefix => $suffixes ) {
833 $p = $prefix === '' ?
'' : $prefix . '.';
834 $arr[] = $p . implode( ',', $suffixes );
836 $str = implode( '|', $arr );
841 * Determine whether debug mode was requested
842 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
845 public static function inDebugMode() {
846 global $wgRequest, $wgResourceLoaderDebug;
847 static $retval = null;
848 if ( !is_null( $retval ) ) {
851 return $retval = $wgRequest->getFuzzyBool( 'debug',
852 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );