Resolved bug 26791 by replacing JSMin with a new library called JavaScriptDistiller...
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoader.php
index 3ce7148..ba5ae11 100644 (file)
@@ -30,8 +30,10 @@ class ResourceLoader {
 
        /* Protected Static Members */
 
-       /** @var {array} List of module name/ResourceLoaderModule object pairs */
+       /** Array: List of module name/ResourceLoaderModule object pairs */
        protected $modules = array();
+       /** Associative array mapping module name to info associative array */
+       protected $moduleInfos = array();
 
        /* Protected Methods */
 
@@ -41,15 +43,15 @@ class ResourceLoader {
         * This method grabs modules dependencies from the database and updates modules 
         * objects.
         * 
-        * This is not inside the module code because it's so much more performant to 
+        * This is not inside the module code because it is much faster to 
         * request all of the information at once than it is to have each module 
-        * requests its own information. This sacrifice of modularity yields a profound
+        * requests its own information. This sacrifice of modularity yields a substantial
         * performance improvement.
         * 
-        * @param $modules Array: list of module names to preload information for
-        * @param $context ResourceLoaderContext: context to load the information within
+        * @param $modules Array: List of module names to preload information for
+        * @param $context ResourceLoaderContext: Context to load the information within
         */
-       protected function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
+       public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
                if ( !count( $modules ) ) {
                        return; // or else Database*::select() will explode, plus it's cheaper!
                }
@@ -64,10 +66,10 @@ class ResourceLoader {
                        ), __METHOD__
                );
 
-               // Set modules' dependecies             
+               // Set modules' dependencies
                $modulesWithDeps = array();
                foreach ( $res as $row ) {
-                       $this->modules[$row->md_module]->setFileDependencies( $skin,
+                       $this->getModule( $row->md_module )->setFileDependencies( $skin,
                                FormatJson::decode( $row->md_deps, true )
                        );
                        $modulesWithDeps[] = $row->md_module;
@@ -75,19 +77,17 @@ class ResourceLoader {
 
                // Register the absence of a dependency row too
                foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
-                       $this->modules[$name]->setFileDependencies( $skin, array() );
+                       $this->getModule( $name )->setFileDependencies( $skin, array() );
                }
                
                // Get message blob mtimes. Only do this for modules with messages
                $modulesWithMessages = array();
-               $modulesWithoutMessages = array();
                foreach ( $modules as $name ) {
-                       if ( count( $this->modules[$name]->getMessages() ) ) {
+                       if ( count( $this->getModule( $name )->getMessages() ) ) {
                                $modulesWithMessages[] = $name;
-                       } else {
-                               $modulesWithoutMessages[] = $name;
                        }
                }
+               $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
                if ( count( $modulesWithMessages ) ) {
                        $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
                                        'mr_resource' => $modulesWithMessages,
@@ -95,11 +95,12 @@ class ResourceLoader {
                                ), __METHOD__
                        );
                        foreach ( $res as $row ) {
-                               $this->modules[$row->mr_resource]->setMsgBlobMtime( $lang, $row->mr_timestamp );
+                               $this->getModule( $row->mr_resource )->setMsgBlobMtime( $lang, $row->mr_timestamp );
+                               unset( $modulesWithoutMessages[$row->mr_resource] );
                        }
-               }
-               foreach ( $modulesWithoutMessages as $name ) {
-                       $this->modules[$name]->setMsgBlobMtime( $lang, 0 );
+               } 
+               foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
+                       $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
                }
        }
 
@@ -107,34 +108,35 @@ class ResourceLoader {
         * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
         * 
         * Available filters are:
-        *  - minify-js \see JSMin::minify
+        *  - minify-js \see JavaScriptDistiller::stripWhiteSpace
         *  - minify-css \see CSSMin::minify
-        *  - flip-css \see CSSJanus::transform
         * 
         * If $data is empty, only contains whitespace or the filter was unknown, 
         * $data is returned unmodified.
         * 
-        * @param $filter String: name of filter to run
-        * @param $data String: text to filter, such as JavaScript or CSS text
-        * @return String: filtered data
+        * @param $filter String: Name of filter to run
+        * @param $data String: Text to filter, such as JavaScript or CSS text
+        * @return String: Filtered data, or a comment containing an error message
         */
        protected function filter( $filter, $data ) {
-               global $wgMemc;
-               
+               global $wgResourceLoaderMinifyJSVerticalSpace;
+
                wfProfileIn( __METHOD__ );
 
                // For empty/whitespace-only data or for unknown filters, don't perform 
                // any caching or processing
                if ( trim( $data ) === '' 
-                       || !in_array( $filter, array( 'minify-js', 'minify-css', 'flip-css' ) ) ) 
+                       || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) 
                {
                        wfProfileOut( __METHOD__ );
                        return $data;
                }
 
-               // Try for Memcached hit
+               // Try for cache hit
+               // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
                $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
-               $cacheEntry = $wgMemc->get( $key );
+               $cache = wfGetCache( CACHE_ANYTHING );
+               $cacheEntry = $cache->get( $key );
                if ( is_string( $cacheEntry ) ) {
                        wfProfileOut( __METHOD__ );
                        return $cacheEntry;
@@ -144,23 +146,22 @@ class ResourceLoader {
                try {
                        switch ( $filter ) {
                                case 'minify-js':
-                                       $result = JSMin::minify( $data );
+                                       $result = JavaScriptDistiller::stripWhiteSpace(
+                                               $data, $wgResourceLoaderMinifyJSVerticalSpace
+                                       );
                                        break;
                                case 'minify-css':
                                        $result = CSSMin::minify( $data );
                                        break;
-                               case 'flip-css':
-                                       $result = CSSJanus::transform( $data, true, false );
-                                       break;
                        }
+
+                       // Save filtered text to Memcached
+                       $cache->set( $key, $result );
                } catch ( Exception $exception ) {
-                       throw new MWException( 'ResourceLoader filter error. ' . 
-                               'Exception was thrown: ' . $exception->getMessage() );
+                       // Return exception as a comment
+                       $result = "/*\n{$exception->__toString()}\n*/\n";
                }
 
-               // Save filtered text to Memcached
-               $wgMemc->set( $key, $result );
-
                wfProfileOut( __METHOD__ );
                
                return $result;
@@ -172,7 +173,7 @@ class ResourceLoader {
         * Registers core modules and runs registration hooks.
         */
        public function __construct() {
-               global $IP;
+               global $IP, $wgResourceModules;
                
                wfProfileIn( __METHOD__ );
                
@@ -180,6 +181,7 @@ class ResourceLoader {
                $this->register( include( "$IP/resources/Resources.php" ) );
                // Register extension modules
                wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
+               $this->register( $wgResourceModules );
                
                wfProfileOut( __METHOD__ );
        }
@@ -187,32 +189,28 @@ class ResourceLoader {
        /**
         * Registers a module with the ResourceLoader system.
         * 
-        * @param $name Mixed: string of name of module or array of name/object pairs
-        * @param $object ResourceLoaderModule: module object (optional when using 
-        *   multiple-registration calling style)
-        * @throws MWException If a duplicate module registration is attempted
-        * @throws MWException If something other than a ResourceLoaderModule is being 
-        *   registered
-        * @return Boolean: false if there were any errors, in which case one or more 
-        *   modules were not registered
+        * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
+        * @param $info Module info array. For backwards compatibility with 1.17alpha, 
+        *   this may also be a ResourceLoaderModule object. Optional when using 
+        *   multiple-registration calling style.
+        * @throws MWException: If a duplicate module registration is attempted
+        * @throws MWException: If something other than a ResourceLoaderModule is being registered
+        * @return Boolean: False if there were any errors, in which case one or more modules were not
+        *     registered
         */
-       public function register( $name, ResourceLoaderModule $object = null ) {
-
+       public function register( $name, $info = null ) {
                wfProfileIn( __METHOD__ );
 
                // Allow multiple modules to be registered in one call
-               if ( is_array( $name ) && !isset( $object ) ) {
+               if ( is_array( $name ) ) {
                        foreach ( $name as $key => $value ) {
                                $this->register( $key, $value );
                        }
-
-                       wfProfileOut( __METHOD__ );
-
                        return;
                }
 
                // Disallow duplicate registrations
-               if ( isset( $this->modules[$name] ) ) {
+               if ( isset( $this->moduleInfos[$name] ) ) {
                        // A module has already been registered by this name
                        throw new MWException(
                                'ResourceLoader duplicate registration error. ' . 
@@ -220,54 +218,93 @@ class ResourceLoader {
                        );
                }
 
-               // Validate the input (type hinting lets null through)
-               if ( !( $object instanceof ResourceLoaderModule ) ) {
-                       throw new MWException( 'ResourceLoader invalid module error. ' . 
-                               'Instances of ResourceLoaderModule expected.' );
+               // Attach module
+               if ( is_object( $info ) ) {
+                       // Old calling convention
+                       // Validate the input
+                       if ( !( $info instanceof ResourceLoaderModule ) ) {
+                               throw new MWException( 'ResourceLoader invalid module error. ' . 
+                                       'Instances of ResourceLoaderModule expected.' );
+                       }
+
+                       $this->moduleInfos[$name] = array( 'object' => $info );
+                       $info->setName( $name );
+                       $this->modules[$name] = $info;
+               } else {
+                       // New calling convention
+                       $this->moduleInfos[$name] = $info;
                }
 
-               // Attach module
-               $this->modules[$name] = $object;
-               $object->setName( $name );
-               
                wfProfileOut( __METHOD__ );
        }
 
-       /**
-        * Gets a map of all modules and their options
+       /**
+        * Get a list of module names
         *
-        * @return Array: array( modulename => ResourceLoaderModule )
+        * @return Array: List of module names
         */
-       public function getModules() {
-               return $this->modules;
+       public function getModuleNames() {
+               return array_keys( $this->moduleInfos );
        }
 
        /**
         * Get the ResourceLoaderModule object for a given module name.
         *
-        * @param $name String: module name
+        * @param $name String: Module name
         * @return Mixed: ResourceLoaderModule if module has been registered, null otherwise
         */
        public function getModule( $name ) {
-               return isset( $this->modules[$name] ) ? $this->modules[$name] : null;
+               if ( !isset( $this->modules[$name] ) ) {
+                       if ( !isset( $this->moduleInfos[$name] ) ) {
+                               // No such module
+                               return null;
+                       }
+                       // Construct the requested object
+                       $info = $this->moduleInfos[$name];
+                       if ( isset( $info['object'] ) ) {
+                               // Object given in info array
+                               $object = $info['object'];
+                       } else {
+                               if ( !isset( $info['class'] ) ) {
+                                       $class = 'ResourceLoaderFileModule';
+                               } else {
+                                       $class = $info['class'];
+                               }
+                               $object = new $class( $info );
+                       }
+                       $object->setName( $name );
+                       $this->modules[$name] = $object;
+               }
+
+               return $this->modules[$name];
        }
 
        /**
         * Outputs a response to a resource load-request, including a content-type header.
         *
-        * @param $context ResourceLoaderContext: context in which a response should be formed
+        * @param $context ResourceLoaderContext: Context in which a response should be formed
         */
        public function respond( ResourceLoaderContext $context ) {
                global $wgResourceLoaderMaxage, $wgCacheEpoch;
+               
+               // Buffer output to catch warnings. Normally we'd use ob_clean() on the
+               // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
+               // is used: ob_clean() will clear the GZIP header in that case and it won't come
+               // back for subsequent output, resulting in invalid GZIP. So we have to wrap
+               // the whole thing in our own output buffer to be sure the active buffer
+               // doesn't use ob_gzhandler.
+               // See http://bugs.php.net/bug.php?id=36514
+               ob_start();
 
                wfProfileIn( __METHOD__ );
+               $exceptions = '';
 
                // Split requested modules into two groups, modules and missing
                $modules = array();
                $missing = array();
                foreach ( $context->getModules() as $name ) {
-                       if ( isset( $this->modules[$name] ) ) {
-                               $modules[$name] = $this->modules[$name];
+                       if ( isset( $this->moduleInfos[$name] ) ) {
+                               $modules[$name] = $this->getModule( $name );
                        } else {
                                $missing[] = $name;
                        }
@@ -287,20 +324,31 @@ class ResourceLoader {
                }
 
                // Preload information needed to the mtime calculation below
-               $this->preloadModuleInfo( array_keys( $modules ), $context );
+               try {
+                       $this->preloadModuleInfo( array_keys( $modules ), $context );
+               } catch( Exception $e ) {
+                       // Add exception to the output as a comment
+                       $exceptions .= "/*\n{$e->__toString()}\n*/\n";
+               }
 
                wfProfileIn( __METHOD__.'-getModifiedTime' );
 
+               $private = false;
                // To send Last-Modified and support If-Modified-Since, we need to detect 
                // the last modified time
                $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
                foreach ( $modules as $module ) {
-                       // Bypass squid cache if the request includes any private modules
-                       if ( $module->getGroup() === 'private' ) {
-                               $smaxage = 0;
+                       try {
+                               // Bypass Squid and other shared caches if the request includes any private modules
+                               if ( $module->getGroup() === 'private' ) {
+                                       $private = true;
+                               }
+                               // Calculate maximum modified time
+                               $mtime = max( $mtime, $module->getModifiedTime( $context ) );
+                       } catch ( Exception $e ) {
+                               // Add exception to the output as a comment
+                               $exceptions .= "/*\n{$e->__toString()}\n*/\n";
                        }
-                       // Calculate maximum modified time
-                       $mtime = max( $mtime, $module->getModifiedTime( $context ) );
                }
 
                wfProfileOut( __METHOD__.'-getModifiedTime' );
@@ -312,31 +360,65 @@ class ResourceLoader {
                }
                header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
                if ( $context->getDebug() ) {
-                       header( 'Cache-Control: must-revalidate' );
+                       // Do not cache debug responses
+                       header( 'Cache-Control: private, no-cache, must-revalidate' );
+                       header( 'Pragma: no-cache' );
                } else {
-                       header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
-                       header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
+                       if ( $private ) {
+                               header( "Cache-Control: private, max-age=$maxage" );
+                               $exp = $maxage;
+                       } else {
+                               header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
+                               $exp = min( $maxage, $smaxage );
+                       }
+                       header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
                }
 
                // If there's an If-Modified-Since header, respond with a 304 appropriately
+               // Some clients send "timestamp;length=123". Strip the part after the first ';'
+               // so we get a valid timestamp.
                $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
-               if ( $ims !== false && $mtime <= wfTimestamp( TS_UNIX, $ims ) ) {
-                       header( 'HTTP/1.0 304 Not Modified' );
-                       header( 'Status: 304 Not Modified' );
-                       wfProfileOut( __METHOD__ );
-                       return;
+               if ( $ims !== false ) {
+                       $imsTS = strtok( $ims, ';' );
+                       if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
+                               // There's another bug in ob_gzhandler (see also the comment at
+                               // the top of this function) that causes it to gzip even empty
+                               // responses, meaning it's impossible to produce a truly empty
+                               // response (because the gzip header is always there). This is
+                               // a problem because 304 responses have to be completely empty
+                               // per the HTTP spec, and Firefox behaves buggily when they're not.
+                               // See also http://bugs.php.net/bug.php?id=51579
+                               // To work around this, we tear down all output buffering before
+                               // sending the 304.
+                               // On some setups, ob_get_level() doesn't seem to go down to zero
+                               // no matter how often we call ob_get_clean(), so instead of doing
+                               // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
+                               // we have to be safe here and avoid an infinite loop.
+                               for ( $i = 0; $i < ob_get_level(); $i++ ) {
+                                       ob_end_clean();
+                               }
+                               
+                               header( 'HTTP/1.0 304 Not Modified' );
+                               header( 'Status: 304 Not Modified' );
+                               wfProfileOut( __METHOD__ );
+                               return;
+                       }
                }
                
                // Generate a response
                $response = $this->makeModuleResponse( $context, $modules, $missing );
+               
+               // Prepend comments indicating exceptions
+               $response = $exceptions . $response;
 
-               // Tack on PHP warnings as a comment in debug mode
+               // Capture any PHP warnings from the output buffer and append them to the
+               // response in a comment if we're in debug mode.
                if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
-                       $response .= "/*\n$warnings\n*/";
+                       $response = "/*\n$warnings\n*/\n" . $response;
                }
 
-               // Clear any warnings from the buffer
-               ob_clean();
+               // Remove the output buffer and output the response
+               ob_end_clean();
                echo $response;
 
                wfProfileOut( __METHOD__ );
@@ -345,72 +427,82 @@ class ResourceLoader {
        /**
         * Generates code for a response
         * 
-        * @param $context ResourceLoaderContext: context in which to generate a response
-        * @param $modules Array: list of module objects keyed by module name
-        * @param $missing Array: list of unavailable modules (optional)
-        * @return String: response data
+        * @param $context ResourceLoaderContext: Context in which to generate a response
+        * @param $modules Array: List of module objects keyed by module name
+        * @param $missing Array: List of unavailable modules (optional)
+        * @return String: Response data
         */
        public function makeModuleResponse( ResourceLoaderContext $context, 
                array $modules, $missing = array() ) 
        {
+               $out = '';
+               $exceptions = '';
+               if ( $modules === array() && $missing === array() ) {
+                       return '/* No modules requested. Max made me put this here */';
+               }
+               
                // Pre-fetch blobs
                if ( $context->shouldIncludeMessages() ) {
-                       $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
+                       try {
+                               $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
+                       } catch ( Exception $e ) {
+                               // Add exception to the output as a comment
+                               $exceptions .= "/*\n{$e->__toString()}\n*/\n";
+                       }
                } else {
                        $blobs = array();
                }
 
                // Generate output
-               $out = '';
                foreach ( $modules as $name => $module ) {
-
                        wfProfileIn( __METHOD__ . '-' . $name );
-
-                       // Scripts
-                       $scripts = '';
-                       if ( $context->shouldIncludeScripts() ) {
-                               $scripts .= $module->getScript( $context ) . "\n";
-                       }
-
-                       // Styles
-                       $styles = array();
-                       if ( $context->shouldIncludeStyles() ) {
-                               $styles = $module->getStyles( $context );
-                               // Flip CSS on a per-module basis
-                               if ( $styles && $this->modules[$name]->getFlip( $context ) ) {
-                                       foreach ( $styles as $media => $style ) {
-                                               $styles[$media] = $this->filter( 'flip-css', $style );
-                                       }
+                       try {
+                               // Scripts
+                               $scripts = '';
+                               if ( $context->shouldIncludeScripts() ) {
+                                       $scripts .= $module->getScript( $context ) . "\n";
                                }
-                       }
 
-                       // Messages
-                       $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : array();
+                               // Styles
+                               $styles = array();
+                               if ( $context->shouldIncludeStyles() ) {
+                                       $styles = $module->getStyles( $context );
+                               }
 
-                       // Append output
-                       switch ( $context->getOnly() ) {
-                               case 'scripts':
-                                       $out .= $scripts;
-                                       break;
-                               case 'styles':
-                                       $out .= self::makeCombinedStyles( $styles );
-                                       break;
-                               case 'messages':
-                                       $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
-                                       break;
-                               default:
-                                       // Minify CSS before embedding in mediaWiki.loader.implement call 
-                                       // (unless in debug mode)
-                                       if ( !$context->getDebug() ) {
-                                               foreach ( $styles as $media => $style ) {
-                                                       $styles[$media] = $this->filter( 'minify-css', $style );
+                               // Messages
+                               $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
+
+                               // Append output
+                               switch ( $context->getOnly() ) {
+                                       case 'scripts':
+                                               $out .= $scripts;
+                                               break;
+                                       case 'styles':
+                                               $out .= self::makeCombinedStyles( $styles );
+                                               break;
+                                       case 'messages':
+                                               $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
+                                               break;
+                                       default:
+                                               // Minify CSS before embedding in mediaWiki.loader.implement call
+                                               // (unless in debug mode)
+                                               if ( !$context->getDebug() ) {
+                                                       foreach ( $styles as $media => $style ) {
+                                                               $styles[$media] = $this->filter( 'minify-css', $style );
+                                                       }
                                                }
-                                       }
-                                       $out .= self::makeLoaderImplementScript( $name, $scripts, $styles, 
-                                               new XmlJsCode( $messagesBlob ) );
-                                       break;
-                       }
+                                               $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
+                                                       new XmlJsCode( $messagesBlob ) );
+                                               break;
+                               }
+                       } catch ( Exception $e ) {
+                               // Add exception to the output as a comment
+                               $exceptions .= "/*\n{$e->__toString()}\n*/\n";
 
+                               // Register module as missing
+                               $missing[] = $name;
+                               unset( $modules[$name] );
+                       }
                        wfProfileOut( __METHOD__ . '-' . $name );
                }
 
@@ -430,12 +522,12 @@ class ResourceLoader {
                }
 
                if ( $context->getDebug() ) {
-                       return $out;
+                       return $exceptions . $out;
                } else {
                        if ( $context->getOnly() === 'styles' ) {
-                               return $this->filter( 'minify-css', $out );
+                               return $exceptions . $this->filter( 'minify-css', $out );
                        } else {
-                               return $this->filter( 'minify-js', $out );
+                               return $exceptions . $this->filter( 'minify-js', $out );
                        }
                }
        }
@@ -447,12 +539,12 @@ class ResourceLoader {
         * given properties.
         *
         * @param $name Module name
-        * @param $scripts Array of JavaScript code snippets to be executed after the 
+        * @param $scripts Array: List of JavaScript code snippets to be executed after the 
         *     module is loaded
-        * @param $styles Associative array mapping media type to associated CSS string
-        * @param $messages Messages associated with this module. May either be an 
-        *     associative array mapping message key to value, or a JSON-encoded message blob
-        *     containing the same data, wrapped in an XmlJsCode object.
+        * @param $styles Array: List of CSS strings keyed by media type
+        * @param $messages Mixed: List of messages associated with this module. May either be an 
+        *     associative array mapping message key to value, or a JSON-encoded message blob containing
+        *     the same data, wrapped in an XmlJsCode object.
         */
        public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
                if ( is_array( $scripts ) ) {
@@ -462,7 +554,7 @@ class ResourceLoader {
                        'mediaWiki.loader.implement', 
                        array(
                                $name,
-                               new XmlJsCode( "function() {{$scripts}}" ),
+                               new XmlJsCode( "function( $, mw ) {{$scripts}}" ),
                                (object)$styles,
                                (object)$messages
                        ) );
@@ -471,9 +563,8 @@ class ResourceLoader {
        /**
         * Returns JS code which, when called, will register a given list of messages.
         *
-        * @param $messages May either be an associative array mapping message key 
-        *     to value, or a JSON-encoded message blob containing the same data, 
-        *     wrapped in an XmlJsCode object.
+        * @param $messages Mixed: Either an associative array mapping message key to value, or a
+        *     JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
         */
        public static function makeMessageSetScript( $messages ) {
                return Xml::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
@@ -483,12 +574,23 @@ class ResourceLoader {
         * Combines an associative array mapping media type to CSS into a 
         * single stylesheet with @media blocks.
         *
-        * @param $styles Array of CSS strings
+        * @param $styles Array: List of CSS strings keyed by media type
         */
        public static function makeCombinedStyles( array $styles ) {
                $out = '';
                foreach ( $styles as $media => $style ) {
-                       $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
+                       // Transform the media type based on request params and config
+                       // The way that this relies on $wgRequest to propagate request params is slightly evil
+                       $media = OutputPage::transformCssMedia( $media );
+                       
+                       if ( $media === null ) {
+                               // Skip
+                       } else if ( $media === '' || $media == 'all' ) {
+                               // Don't output invalid or frivolous @media statements
+                               $out .= "$style\n";
+                       } else {
+                               $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
+                       }
                }
                return $out;
        }
@@ -517,11 +619,11 @@ class ResourceLoader {
         * which will have values corresponding to $name, $version, $dependencies 
         * and $group as supplied. 
         *
-        * @param $name The module name
-        * @param $version The module version string
-        * @param $dependencies Array of module names on which this module depends
-        * @param $group The group which the module is in.
-        * @param $script The JS loader script
+        * @param $name String: Module name
+        * @param $version Integer: Module version number as a timestamp
+        * @param $dependencies Array: List of module names on which this module depends
+        * @param $group String: Group which the module is in.
+        * @param $script String: JavaScript code
         */
        public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
                $script = str_replace( "\n", "\n\t", trim( $script ) );
@@ -547,10 +649,10 @@ class ResourceLoader {
         *     ) ):
         *        Registers modules with the given names and parameters.
         *
-        * @param $name The module name
-        * @param $version The module version string
-        * @param $dependencies Array of module names on which this module depends
-        * @param $group The group which the module is in.
+        * @param $name String: Module name
+        * @param $version Integer: Module version number as a timestamp
+        * @param $dependencies Array: List of module names on which this module depends
+        * @param $group String: group which the module is in.
         */
        public static function makeLoaderRegisterScript( $name, $version = null, 
                $dependencies = null, $group = null ) 
@@ -568,7 +670,7 @@ class ResourceLoader {
         * Returns JS code which runs given JS code if the client-side framework is 
         * present.
         *
-        * @param $script JS code to run
+        * @param $script String: JavaScript code
         */
        public static function makeLoaderConditionalScript( $script ) {
                $script = str_replace( "\n", "\n\t", trim( $script ) );
@@ -579,9 +681,23 @@ class ResourceLoader {
         * Returns JS code which will set the MediaWiki configuration array to 
         * the given value.
         *
-        * @param $configuration Associative array of configuration parameters
+        * @param $configuration Array: List of configuration values keyed by variable name
         */
        public static function makeConfigSetScript( array $configuration ) {
                return Xml::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
        }
+       
+       /**
+        * Determine whether debug mode was requested
+        * Order of priority is 1) request param, 2) cookie, 3) $wg setting
+        * @return bool
+        */
+       public static function inDebugMode() {
+               global $wgRequest, $wgResourceLoaderDebug;
+               static $retval = null;
+               if ( !is_null( $retval ) )
+                       return $retval;
+               return $retval = $wgRequest->getFuzzyBool( 'debug',
+                       $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
+       }
 }