Don't look for pipes in the root node.
[lhc/web/wiklou.git] / includes / OutputPage.php
index 4510b09..960b293 100644 (file)
@@ -4,61 +4,210 @@ if ( !defined( 'MEDIAWIKI' ) ) {
 }
 
 /**
+ * This class should be covered by a general architecture document which does
+ * not exist as of january 2011.  This is one of the Core class and should
+ * be read at least once by any new developers.
+ *
+ * This class is used to prepare the final rendering. A skin is then
+ * applied to the output parameters (links, javascript, html, categories ...).
+ * 
+ * Another class (fixme) handle sending the whole page to the client.
+ * 
+ * Some comments comes from a pairing session between Zak Greant and Ashar Voultoiz
+ * in november 2010.
+ *
  * @todo document
  */
 class OutputPage {
-       var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
+       /// Should be private. Used with addMeta() which adds <meta>
+       var $mMetatags = array();
+
+       /// <meta keyworkds="stuff"> most of the time the first 10 links to an article
+       var $mKeywords = array();
+
+       var $mLinktags = array();
+
+       /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
        var $mExtStyles = array();
-       var $mPagetitle = '', $mBodytext = '';
+
+       /// Should be private - has getter and setter. Contains the HTML title
+       var $mPagetitle = '';
+
+       /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
+       var $mBodytext = '';
 
        /**
         * Holds the debug lines that will be outputted as comments in page source if
         * $wgDebugComments is enabled. See also $wgShowDebug.
         * TODO: make a getter method for this
         */
-       public $mDebugtext = '';
+       public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
+
+       /// Should be private. Stores contents of <title> tag
+       var $mHTMLtitle = '';
+
+       /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
+       var $mIsarticle = true;
+
+       /**
+        * Should be private. We have to set isPrintable(). Some pages should
+        * never be printed (ex: redirections).
+        */
+       var $mPrintable = false;
+
+       /**
+        * Should be private. We have set/get/append methods.
+        *
+        * Contains the page subtitle. Special pages usually have some links here.
+        * Don't confuse with site subtitle added by skins.
+        */
+       var $mSubtitle = '';
+
+       var $mRedirect = '';
+       var $mStatusCode;
 
-       var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
-       var $mSubtitle = '', $mRedirect = '', $mStatusCode;
-       var $mLastModified = '', $mETag = false;
-       var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
+       /**
+        * mLastModified and mEtag are used for sending cache control.
+        * The whole caching system should probably be moved in its own class.
+        */
+       var $mLastModified = '';
+
+       /**
+        * Should be private. No getter but used in sendCacheControl();
+        * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
+        * as a unique identifier for the content. It is later used by the client
+        * to compare its cache version with the server version. Client sends
+        * headers If-Match and If-None-Match containing its local cache ETAG value.
+        *
+        * To get more information, you will have to look at HTTP1/1 protocols which
+        * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
+        */
+       var $mETag = false;
+
+       var $mCategoryLinks = array();
+       var $mCategories = array();
+
+       /// Should be private. Associative array mapping language code to the page name
+       var $mLanguageLinks = array();
+
+       /**
+        * Should be private. Used for JavaScript (pre resource loader)
+        * We should split js / css.
+        * mScripts content is inserted as is in <head> by Skin. This might contains
+        * either a link to a stylesheet or inline css.
+        */
+       var $mScripts = '';
+
+       /**
+        * Inline CSS styles. Use addInlineStyle() sparsingly
+        */
+       var $mInlineStyles = '';
 
-       var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
+       //
+       var $mLinkColours;
+
+       /**
+        * Used by skin template.
+        * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
+        */
+       var $mPageLinkTitle = '';
+
+       /// Array of elements in <head>. Parser might add its own headers!
+       var $mHeadItems = array();
+
+       // Next variables probably comes from the resource loader @todo FIXME
        var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
+       var $mResourceLoader;
+
+       /** @fixme is this still used ?*/
        var $mInlineMsg = array();
 
        var $mTemplateIds = array();
 
+       /** Initialized with a global value. Let us override it.
+        *  Should probably get deleted / rewritten ... */
        var $mAllowUserJs;
+
+       /**
+        * This was for the old skins and for users with 640x480 screen.
+        * Please note old skins are still used and might prove useful for
+        * users having old computers or visually impaired.
+        */
        var $mSuppressQuickbar = false;
+
+       /**
+        * @EasterEgg I just love the name for this self documenting variable.
+        * @todo document
+        */
        var $mDoNothing = false;
+
+       // Parser related.
        var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
+
+       /**
+        * Should be private. Has get/set methods properly documented.
+        * Stores "article flag" toggle.
+        */
        var $mIsArticleRelated = true;
-       protected $mParserOptions = null; // lazy initialised, use parserOptions()
 
+       /// lazy initialised, use parserOptions()
+       protected $mParserOptions = null;
+
+       /**
+        * Handles the atom / rss links.
+        * We probably only support atom in 2011.
+        * Looks like a private variable.
+        * @see $wgAdvertisedFeedTypes
+        */
        var $mFeedLinks = array();
 
+       // Gwicke work on squid caching? Roughly from 2003.
        var $mEnableClientCache = true;
+
+       /**
+        * Flag if output should only contain the body of the article.
+        * Should be private.
+        */
        var $mArticleBodyOnly = false;
 
        var $mNewSectionLink = false;
        var $mHideNewSectionLink = false;
+
+       /**
+        * Comes from the parser. This was probably made to load CSS/JS only
+        * if we had <gallery>. Used directly in CategoryPage.php
+        * Looks like resource loader can replace this.
+        */
        var $mNoGallery = false;
+
+       // should be private.
        var $mPageTitleActionText = '';
        var $mParseWarnings = array();
+
+       // Cache stuff. Looks like mEnableClientCache
        var $mSquidMaxage = 0;
+
+       // @todo document
+       var $mPreventClickjacking = true;
+
+       /// should be private. To include the variable {{REVISIONID}}
        var $mRevisionId = null;
+
+       /// Stores a Title object (of the current page).
        protected $mTitle = null;
 
        /**
         * An array of stylesheet filenames (relative from skins path), with options
         * for CSS media, IE conditions, and RTL/LTR direction.
         * For internal use; add settings in the skin via $this->addStyle()
+        *
+        * Style again! This seems like a code duplication since we already have
+        * mStyles. This is what makes OpenSource amazing.
         */
        var $styles = array();
 
        /**
-        * Whether to load jQuery core.
+        * Whether jQuery is already handled.
         */
        protected $mJQueryDone = false;
 
@@ -103,7 +252,6 @@ class OutputPage {
         * Set the HTTP status code to send with the output.
         *
         * @param $statusCode Integer
-        * @return nothing
         */
        public function setStatusCode( $statusCode ) {
                $this->mStatusCode = $statusCode;
@@ -113,8 +261,8 @@ class OutputPage {
         * Add a new <meta> tag
         * To add an http-equiv meta tag, precede the name with "http:"
         *
-        * @param $name tag name
-        * @param $val tag value
+        * @param $name String tag name
+        * @param $val String tag value
         */
        function addMeta( $name, $val ) {
                array_push( $this->mMetatags, array( $name, $val ) );
@@ -179,7 +327,7 @@ class OutputPage {
        }
 
        /**
-        * Get all links added by extensions
+        * Get all styles added by extensions
         *
         * @return Array
         */
@@ -231,7 +379,7 @@ class OutputPage {
         * @return Array of module names
         */
        public function getModules() {
-               return $this->mModules;
+               return array_values( array_unique( $this->mModules ) );
        }
 
        /**
@@ -250,7 +398,7 @@ class OutputPage {
         * @return array of module names
         */
        public function getModuleScripts() {
-               return $this->mModuleScripts;
+               return array_values( array_unique( $this->mModuleScripts ) );
        }
 
        /**
@@ -270,7 +418,7 @@ class OutputPage {
         * @return Array of module names
         */
        public function getModuleStyles() {
-               return $this->mModuleStyles;
+               return array_values( array_unique( $this->mModuleStyles ) );
        }
 
        /**
@@ -290,7 +438,7 @@ class OutputPage {
         * @return Array of module names
         */
        public function getModuleMessages() {
-               return $this->mModuleMessages;
+               return array_values( array_unique( $this->mModuleMessages ) );
        }
 
        /**
@@ -562,11 +710,6 @@ class OutputPage {
                $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
                $this->mPagetitle = $nameWithTags;
 
-               $taction = $this->getPageTitleActionText();
-               if( !empty( $taction ) ) {
-                       $name .= ' - '.$taction;
-               }
-
                # change "<i>foo&amp;bar</i>" to "foo&bar"
                $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
        }
@@ -1003,14 +1146,6 @@ class OutputPage {
                $this->mDebugtext .= $text;
        }
 
-       /**
-        * @deprecated use parserOptions() instead
-        */
-       public function setParserOptions( $options ) {
-               wfDeprecated( __METHOD__ );
-               return $this->parserOptions( $options );
-       }
-
        /**
         * Get/set the ParserOptions object to use for wikitext parsing
         *
@@ -1121,43 +1256,6 @@ class OutputPage {
                wfProfileOut( __METHOD__ );
        }
 
-       /**
-        * Add wikitext to the buffer, assuming that this is the primary text for a page view
-        * Saves the text into the parser cache if possible.
-        *
-        * @param $text String: wikitext
-        * @param $article Article object
-        * @param $cache Boolean
-        * @deprecated Use Article::outputWikitext
-        */
-       public function addPrimaryWikiText( $text, $article, $cache = true ) {
-               global $wgParser;
-
-               wfDeprecated( __METHOD__ );
-
-               $popts = $this->parserOptions();
-               $popts->setTidy( true );
-               $parserOutput = $wgParser->parse(
-                       $text, $article->mTitle,
-                       $popts, true, true, $this->mRevisionId
-               );
-               $popts->setTidy( false );
-               if ( $cache && $article && $parserOutput->isCacheable() ) {
-                       $parserCache = ParserCache::singleton();
-                       $parserCache->save( $parserOutput, $article, $popts );
-               }
-
-               $this->addParserOutput( $parserOutput );
-       }
-
-       /**
-        * @deprecated use addWikiTextTidy()
-        */
-       public function addSecondaryWikiText( $text, $linestart = true ) {
-               wfDeprecated( __METHOD__ );
-               $this->addWikiTextTitleTidy( $text, $this->getTitle(), $linestart );
-       }
-
        /**
         * Add a ParserOutput object, but without Html
         *
@@ -1230,24 +1328,44 @@ class OutputPage {
         * @param $interface Boolean: use interface language ($wgLang instead of
         *                   $wgContLang) while parsing language sensitive magic
         *                   words like GRAMMAR and PLURAL
+        * @param $language  Language object: target language object, will override
+        *                   $interface
         * @return String: HTML
         */
-       public function parse( $text, $linestart = true, $interface = false ) {
+       public function parse( $text, $linestart = true, $interface = false, $language = null ) {
+               // Check one for one common cause for parser state resetting
+               $callers = wfGetAllCallers( 10 );
+               if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
+                       throw new MWException( "wfMsg* function with parsing cannot be used " .
+                               "inside a tag hook. Should use parser->recursiveTagParse() instead" );
+               }
+
                global $wgParser;
+
                if( is_null( $this->getTitle() ) ) {
                        throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
                }
+
                $popts = $this->parserOptions();
                if ( $interface ) {
                        $popts->setInterfaceMessage( true );
                }
+               if ( $language !== null ) {
+                       $oldLang = $popts->setTargetLanguage( $language );
+               }
+
                $parserOutput = $wgParser->parse(
                        $text, $this->getTitle(), $popts,
                        $linestart, true, $this->mRevisionId
                );
+
                if ( $interface ) {
                        $popts->setInterfaceMessage( false );
                }
+               if ( $language !== null ) {
+                       $popts->setTargetLanguage( $oldLang );
+               }
+
                return $parserOutput->getText();
        }
 
@@ -1272,24 +1390,6 @@ class OutputPage {
                return $parsed;
        }
 
-       /**
-        * @deprecated
-        *
-        * @param $article Article
-        * @return Boolean: true if successful, else false.
-        */
-       public function tryParserCache( &$article ) {
-               wfDeprecated( __METHOD__ );
-               $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
-
-               if ( $parserOutput !== false ) {
-                       $this->addParserOutput( $parserOutput );
-                       return true;
-               } else {
-                       return false;
-               }
-       }
-
        /**
         * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
         *
@@ -1429,13 +1529,58 @@ class OutputPage {
                                if( $variant === $wgContLang->getCode() ) {
                                        continue;
                                } else {
-                                       $aloption[] = "string-contains=$variant";
+                                       $aloption[] = 'string-contains=' . $variant;
+
+                                       // IE and some other browsers use another form of language code
+                                       // in their Accept-Language header, like "zh-CN" or "zh-TW".
+                                       // We should handle these too.
+                                       $ievariant = explode( '-', $variant );
+                                       if ( count( $ievariant ) == 2 ) {
+                                               $ievariant[1] = strtoupper( $ievariant[1] );
+                                               $ievariant = implode( '-', $ievariant );
+                                               $aloption[] = 'string-contains=' . $ievariant;
+                                       }
                                }
                        }
                        $this->addVaryHeader( 'Accept-Language', $aloption );
                }
        }
 
+       /**
+        * Set a flag which will cause an X-Frame-Options header appropriate for 
+        * edit pages to be sent. The header value is controlled by 
+        * $wgEditPageFrameOptions.
+        *
+        * This is the default for special pages. If you display a CSRF-protected 
+        * form on an ordinary view page, then you need to call this function.
+        */
+       public function preventClickjacking( $enable = true ) {
+               $this->mPreventClickjacking = $enable;
+       }
+
+       /**
+        * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
+        * This can be called from pages which do not contain any CSRF-protected
+        * HTML form.
+        */
+       public function allowClickjacking() {
+               $this->mPreventClickjacking = false;
+       }
+
+       /**
+        * Get the X-Frame-Options header value (without the name part), or false 
+        * if there isn't one. This is used by Skin to determine whether to enable 
+        * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
+        */
+       public function getFrameOptions() {
+               global $wgBreakFrames, $wgEditPageFrameOptions;
+               if ( $wgBreakFrames ) {
+                       return 'DENY';
+               } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
+                       return $wgEditPageFrameOptions;
+               }
+       }
+
        /**
         * Send cache control HTTP headers
         */
@@ -1572,7 +1717,6 @@ class OutputPage {
                global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
                global $wgUseAjax, $wgAjaxWatch;
                global $wgEnableMWSuggest, $wgUniversalEditButton;
-               global $wgArticle;
 
                if( $this->mDoNothing ) {
                        return;
@@ -1609,10 +1753,10 @@ class OutputPage {
                }
 
                $sk = $wgUser->getSkin();
-               
+
                // Add base resources
-               $this->addModules( array( 'mediawiki.legacy.wikibits' ) );
-               
+               $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
+
                // Add various resources if required
                if ( $wgUseAjax ) {
                        $this->addModules( 'mediawiki.legacy.ajax' );
@@ -1620,7 +1764,7 @@ class OutputPage {
                        wfRunHooks( 'AjaxAddScript', array( &$this ) );
 
                        if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
-                               $this->addModules( 'mediawiki.legacy.ajaxwatch' );
+                               $this->addModules( 'mediawiki.action.watch.ajax' );
                        }
 
                        if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
@@ -1629,11 +1773,11 @@ class OutputPage {
                }
 
                if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
-                       $this->addModules( 'mediawiki.legacy.rightclickedit' );
+                       $this->addModules( 'mediawiki.action.view.rightClickEdit' );
                }
 
                if( $wgUniversalEditButton ) {
-                       if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
+                       if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
                                && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
                                // Original UniversalEditButton
                                $msg = wfMsg( 'edit' );
@@ -1659,6 +1803,12 @@ class OutputPage {
                $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
                $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
 
+               // Prevent framing, if requested
+               $frameOptions = $this->getFrameOptions();
+               if ( $frameOptions ) {
+                       $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
+               }
+
                if ( $this->mArticleBodyOnly ) {
                        $this->out( $this->mBodytext );
                } else {
@@ -1695,32 +1845,6 @@ class OutputPage {
                print $outs;
        }
 
-       /**
-        * @todo document
-        */
-       public static function setEncodings() {
-               global $wgInputEncoding, $wgOutputEncoding;
-
-               $wgInputEncoding = strtolower( $wgInputEncoding );
-
-               if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
-                       $wgOutputEncoding = strtolower( $wgOutputEncoding );
-                       return;
-               }
-               $wgOutputEncoding = $wgInputEncoding;
-       }
-
-       /**
-        * @deprecated use wfReportTime() instead.
-        *
-        * @return String
-        */
-       public function reportTime() {
-               wfDeprecated( __METHOD__ );
-               $time = wfReportTime();
-               return $time;
-       }
-
        /**
         * Produce a "user is blocked" page.
         *
@@ -1811,9 +1935,7 @@ class OutputPage {
                $this->mRedirect = '';
                $this->mBodytext = '';
 
-               array_unshift( $params, 'parse' );
-               array_unshift( $params, $msg );
-               $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
+               $this->addWikiMsgArray( $msg, $params );
 
                $this->returnToMain();
        }
@@ -1898,7 +2020,7 @@ class OutputPage {
                $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
                $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
                $this->setRobotPolicy( 'noindex,nofollow' );
-               $this->setArticleFlag( false );
+               $this->setArticleRelated( false );
 
                $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
                $loginLink = $skin->link(
@@ -2044,7 +2166,6 @@ class OutputPage {
         * @return none
         */
        public function addPasswordSecurity( $passwordId, $retypeId ) {
-               $this->includeJQuery();
                $data = array(
                        'password' => '#' . $passwordId,
                        'retype' => '#' . $retypeId,
@@ -2059,53 +2180,6 @@ class OutputPage {
                $this->addModules( 'mediawiki.legacy.password' );
        }
 
-       /** @deprecated */
-       public function errorpage( $title, $msg ) {
-               wfDeprecated( __METHOD__ );
-               throw new ErrorPageError( $title, $msg );
-       }
-
-       /** @deprecated */
-       public function databaseError( $fname, $sql, $error, $errno ) {
-               throw new MWException( "OutputPage::databaseError is obsolete\n" );
-       }
-
-       /** @deprecated */
-       public function fatalError( $message ) {
-               wfDeprecated( __METHOD__ );
-               throw new FatalError( $message );
-       }
-
-       /** @deprecated */
-       public function unexpectedValueError( $name, $val ) {
-               wfDeprecated( __METHOD__ );
-               throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
-       }
-
-       /** @deprecated */
-       public function fileCopyError( $old, $new ) {
-               wfDeprecated( __METHOD__ );
-               throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
-       }
-
-       /** @deprecated */
-       public function fileRenameError( $old, $new ) {
-               wfDeprecated( __METHOD__ );
-               throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
-       }
-
-       /** @deprecated */
-       public function fileDeleteError( $name ) {
-               wfDeprecated( __METHOD__ );
-               throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
-       }
-
-       /** @deprecated */
-       public function fileNotFoundError( $name ) {
-               wfDeprecated( __METHOD__ );
-               throw new FatalError( wfMsg( 'filenotfound', $name ) );
-       }
-
        public function showFatalError( $message ) {
                $this->setPageTitle( wfMsg( 'internalerror' ) );
                $this->setRobotPolicy( 'noindex,nofollow' );
@@ -2226,12 +2300,9 @@ class OutputPage {
 
                $ret .= implode( "\n", array(
                        $this->getHeadLinks( $sk ),
-                       $this->buildCssLinks(),
-                       $this->getHeadItems(),
+                       $this->buildCssLinks( $sk ),
+                       $this->getHeadItems()
                ) );
-               if ( $sk->usercss ) {
-                       $ret .= Html::inlineStyle( $sk->usercss );
-               }
 
                if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
                        $ret .= $this->getTitle()->trackbackRDF();
@@ -2275,30 +2346,144 @@ class OutputPage {
                $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
                $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
 
+               $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
+               wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
+
                $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
 
                return $ret;
        }
-       
-       static function makeResourceLoaderLink( $skin, $modules, $only, $media = 'all' ) {
-               global $wgUser, $wgLang, $wgRequest;
+
+       /**
+        * Get a ResourceLoader object associated with this OutputPage
+        */
+       public function getResourceLoader() {
+               if ( is_null( $this->mResourceLoader ) ) {
+                       $this->mResourceLoader = new ResourceLoader();
+               }
+               return $this->mResourceLoader;
+       }               
+
+       /**
+        * TODO: Document
+        * @param $skin Skin
+        * @param $modules Array/string with the module name
+        * @param $only string May be styles, messages or scripts
+        * @param $useESI boolean
+        * @return string html <script> and <style> tags
+        */
+       protected function makeResourceLoaderLink( Skin $skin, $modules, $only, $useESI = false ) {
+               global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
+                       $wgResourceLoaderInlinePrivateModules, $wgRequest;
+               // Lazy-load ResourceLoader
                // TODO: Should this be a static function of ResourceLoader instead?
+               // TODO: Divide off modules starting with "user", and add the user parameter to them
                $query = array(
-                       'modules' => implode( '|', array_unique( (array) $modules ) ),
                        'lang' => $wgLang->getCode(),
-                       'debug' => $wgRequest->getBool( 'debug' ) && $wgRequest->getVal( 'debug' ) !== 'false',
-                       'skin' => $wgUser->getSkin()->getSkinName(),
+                       'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
+                       'skin' => $skin->getSkinName(),
                        'only' => $only,
                );
-               // Automatically select style/script elements
-               if ( $only === 'styles' ) {
-                       $query['media'] = $media;
-                       return Html::linkedStyle( wfAppendQuery( wfScript( 'load' ), $query ), $media );
-               } else {
-                       return Html::linkedScript( wfAppendQuery( wfScript( 'load' ), $query ) );
+               // Propagate printable and handheld parameters if present
+               if ( $wgRequest->getBool( 'printable' ) ) {
+                       $query['printable'] = 1;
                }
+               if ( $wgRequest->getBool( 'handheld' ) ) {
+                       $query['handheld'] = 1;
+               }
+
+               if ( !count( $modules ) ) {
+                       return '';
+               }
+
+               if ( count( $modules ) > 1 ) {
+                       // Remove duplicate module requests
+                       $modules = array_unique( (array) $modules );
+                       // Sort module names so requests are more uniform
+                       sort( $modules );
+
+                       if ( ResourceLoader::inDebugMode() ) {
+                               // Recursively call us for every item
+                               $links = '';
+                               foreach ( $modules as $name ) {
+                                       $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
+                               }
+                               return $links;
+                       }
+               }
+
+               // Create keyed-by-group list of module objects from modules list
+               $groups = array();
+               $resourceLoader = $this->getResourceLoader();
+               foreach ( (array) $modules as $name ) {
+                       $module = $resourceLoader->getModule( $name );
+                       $group = $module->getGroup();
+                       if ( !isset( $groups[$group] ) ) {
+                               $groups[$group] = array();
+                       }
+                       $groups[$group][$name] = $module;
+               }
+               $links = '';
+               foreach ( $groups as $group => $modules ) {
+                       $query['modules'] = implode( '|', array_keys( $modules ) );
+                       // Special handling for user-specific groups
+                       if ( ( $group === 'user' || $group === 'private' ) && $wgUser->isLoggedIn() ) {
+                               $query['user'] = $wgUser->getName();
+                       }
+                       // Support inlining of private modules if configured as such
+                       if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
+                               $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
+                               if ( $only == 'styles' ) {
+                                       $links .= Html::inlineStyle(
+                                               $resourceLoader->makeModuleResponse( $context, $modules )
+                                       );
+                               } else {
+                                       $links .= Html::inlineScript(
+                                               ResourceLoader::makeLoaderConditionalScript(
+                                                       $resourceLoader->makeModuleResponse( $context, $modules )
+                                               )
+                                       );
+                               }
+                               continue;
+                       }
+                       // Special handling for user and site groups; because users might change their stuff
+                       // on-wiki like site or user pages, or user preferences; we need to find the highest
+                       // timestamp of these user-changable modules so we can ensure cache misses on change
+                       if ( $group === 'user' || $group === 'site' ) {
+                               // Create a fake request based on the one we are about to make so modules return
+                               // correct times
+                               $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
+                               // Get the maximum timestamp
+                               $timestamp = 1;
+                               foreach ( $modules as $module ) {
+                                       $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
+                               }
+                               // Add a version parameter so cache will break when things change
+                               $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, round( $timestamp, -2 ) );
+                       }
+                       // Make queries uniform in order
+                       ksort( $query );
+
+                       $url = wfAppendQuery( $wgLoadScript, $query );
+                       if ( $useESI && $wgResourceLoaderUseESI ) {
+                               $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
+                               if ( $only == 'styles' ) {
+                                       $links .= Html::inlineStyle( $esi );
+                               } else {
+                                       $links .= Html::inlineScript( $esi );
+                               }
+                       } else {
+                               // Automatically select style/script elements
+                               if ( $only === 'styles' ) {
+                                       $links .= Html::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
+                               } else {
+                                       $links .= Html::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
+                               }
+                       }
+               }
+               return $links;
        }
-       
+
        /**
         * Gets the global variables and mScripts; also adds userjs to the end if
         * enabled. Despite the name, these scripts are no longer put in the
@@ -2308,66 +2493,55 @@ class OutputPage {
         * @return String: HTML fragment
         */
        function getHeadScripts( Skin $sk ) {
-               global $wgUser, $wgRequest, $wgJsMimeType;
-               global $wgUseSiteJs;
-               
-               // Statup - this will immediately load jquery and mediawiki modules
-               $scripts = self::makeResourceLoaderLink( $sk, 'startup', 'scripts' );
-               // Configuration
+               global $wgUser, $wgRequest, $wgUseSiteJs;
+
+               // Startup - this will immediately load jquery and mediawiki modules
+               $scripts = $this->makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
+
+               // Configuration -- This could be merged together with the load and go, but
+               // makeGlobalVariablesScript returns a whole script tag -- grumble grumble...
                $scripts .= Skin::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
-               // Support individual script requests in debug mode
-               if ( $wgRequest->getBool( 'debug' ) && $wgRequest->getVal( 'debug' ) !== 'false' ) {
-                       // Scripts
-                       foreach ( $this->getModuleScripts() as $name ) {
-                               $scripts .= self::makeResourceLoaderLink( $sk, $name, 'scripts' );
-                       }
-                       // Messages
-                       foreach ( $this->getModuleMessages() as $name ) {
-                               $scripts .= self::makeResourceLoaderLink( $sk, $name, 'messages' );
-                       }
-               } else {
-                       // Scripts
-                       if ( count( $this->getModuleScripts() ) ) {
-                               $scripts .= self::makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
-                       }
-                       // Messages
-                       if ( count( $this->getModuleMessages() ) ) {
-                               $scripts .= self::makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
-                       }
-               }
+
+               // Script and Messages "only" requests
+               $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
+               $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
+
+               // Modules requests - let the client calculate dependencies and batch requests as it likes
                if ( $this->getModules() ) {
-                       // Modules - let the client calculate dependencies and batch requests as it likes
-                       $modules = FormatJson::encode( $this->getModules() );
                        $scripts .= Html::inlineScript(
-                               "if ( mediaWiki !== undefined ) { mediaWiki.loader.load( {$modules} ); }"
-                       );
+                               ResourceLoader::makeLoaderConditionalScript(
+                                       Xml::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules() ) ) .
+                                       Xml::encodeJsCall( 'mediaWiki.loader.go', array() )
+                               )
+                       ) . "\n";
+               }
+
+               // Legacy Scripts
+               $scripts .= "\n" . $this->mScripts;
+
+               // Add site JS if enabled
+               if ( $wgUseSiteJs ) {
+                       $scripts .= $this->makeResourceLoaderLink( $sk, 'site', 'scripts' );
                }
-               // TODO: User Scripts should be included using the resource loader
-               // Add user JS if enabled
-               if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
+
+               // Add user JS if enabled - trying to load user.options as a bundle if possible
+               $userOptionsAdded = false;
+               if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
                        $action = $wgRequest->getVal( 'action', 'view' );
                        if( $this->mTitle && $this->mTitle->isJsSubpage() && $sk->userCanPreview( $action ) ) {
                                # XXX: additional security check/prompt?
-                               $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
+                               $scripts .= Html::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
                        } else {
-                               $userpage = $wgUser->getUserPage();
-                               foreach( array( 'common', $sk->getSkinName() ) as $name ) {
-                                       $scriptpage = Title::makeTitleSafe( NS_USER, $userpage->getDBkey() . '/' . $name . '.js' );
-                                       if ( $scriptpage && $scriptpage->exists() && ( $scriptpage->getLength() > 0 ) ) {
-                                               $userjs = $scriptpage->getLocalURL( 'action=raw&ctype=' . $wgJsMimeType );
-                                               $this->addScriptFile( $userjs, $scriptpage->getLatestRevID() );
-                                       }
-                               }
+                               $scripts .= $this->makeResourceLoaderLink(
+                                       $sk, array( 'user', 'user.options' ), 'scripts'
+                               );
+                               $userOptionsAdded = true;
                        }
                }
-               $scripts .= "\n" . $this->mScripts;
-               // This should be at the bottom of the body - below ALL other scripts
-               $scripts .= Html::inlineScript( "if ( mediaWiki !== undefined ) { mediaWiki.loader.go(); }" );
-               // Add site JS if enabled
-               if ( $wgUseSiteJs ) {
-                       $scripts .= self::makeResourceLoaderLink( $sk, 'sitejs', 'scripts' );
+               if ( !$userOptionsAdded ) {
+                       $scripts .= $this->makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
                }
-               
+
                return $scripts;
        }
 
@@ -2415,8 +2589,8 @@ class OutputPage {
        /**
         * @return string HTML tag links to be put in the header.
         */
-       public function getHeadLinks( $sk ) {
-               global $wgFeed, $wgRequest;
+       public function getHeadLinks( Skin $sk ) {
+               global $wgFeed;
 
                // Ideally this should happen earlier, somewhere. :P
                $this->addDefaultMeta();
@@ -2485,22 +2659,6 @@ class OutputPage {
                                }
                        }
                }
-
-               // Support individual script requests in debug mode
-               if ( $wgRequest->getBool( 'debug' ) && $wgRequest->getVal( 'debug' ) !== 'false' ) {
-                       foreach ( $this->getModuleStyles() as $name ) {
-                               $tags[] = self::makeResourceLoaderLink( $sk, $name, 'styles', 'all' );
-                               $tags[] = self::makeResourceLoaderLink( $sk, $name, 'styles', 'screen' );
-                               $tags[] = self::makeResourceLoaderLink( $sk, $name, 'styles', 'print' );
-                       }
-               } else {
-                       if ( count( $this->getModuleStyles() ) ) {
-                               $tags[] = self::makeResourceLoaderLink( $sk, $this->getModuleStyles(), 'styles', 'all' );
-                               $tags[] = self::makeResourceLoaderLink( $sk, $this->getModuleStyles(), 'styles', 'screen' );
-                               $tags[] = self::makeResourceLoaderLink( $sk, $this->getModuleStyles(), 'styles', 'print' );
-                       }
-               }
-               
                return implode( "\n", $tags );
        }
 
@@ -2551,15 +2709,42 @@ class OutputPage {
         * @param $style_css Mixed: inline CSS
         */
        public function addInlineStyle( $style_css ){
-               $this->mScripts .= Html::inlineStyle( $style_css );
+               $this->mInlineStyles .= Html::inlineStyle( $style_css );
        }
 
        /**
         * Build a set of <link>s for the stylesheets specified in the $this->styles array.
         * These will be applied to various media & IE conditionals.
-        */
-       public function buildCssLinks() {
-               return implode( "\n", $this->buildCssLinksArray() );
+        * @param $sk Skin object
+        */
+       public function buildCssLinks( $sk ) {
+               $ret = '';
+               // Add ResourceLoader styles
+               // Split the styles into three groups
+               $styles = array( 'other' => array(), 'user' => array(), 'site' => array() );
+               $resourceLoader = $this->getResourceLoader();
+               foreach ( $this->getModuleStyles() as $name ) {
+                       $group = $resourceLoader->getModule( $name )->getGroup();
+                       // Modules in groups named "other" or anything different than "user" or "site" will
+                       // be placed in the "other" group
+                       $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
+               }
+
+               // We want site and user styles to override dynamically added styles from modules, but we want
+               // dynamically added styles to override statically added styles from other modules. So the order
+               // has to be other, dynamic, site, user
+               // Add statically added styles for other modules
+               $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
+               // Add normal styles added through addStyle()/addInlineStyle() here
+               $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
+               // Add marker tag to mark the place where the client-side loader should inject dynamic styles
+               // We use a <meta> tag with a made-up name for this because that's valid HTML
+               $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
+               // Add site and user styles
+               $ret .= $this->makeResourceLoaderLink(
+                       $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
+               );
+               return $ret;
        }
 
        public function buildCssLinksArray() {
@@ -2590,7 +2775,7 @@ class OutputPage {
                }
 
                if( isset( $options['media'] ) ) {
-                       $media = $this->transformCssMedia( $options['media'] );
+                       $media = self::transformCssMedia( $options['media'] );
                        if( is_null( $media ) ) {
                                return '';
                        }
@@ -2622,7 +2807,7 @@ class OutputPage {
         * @param $media String: current value of the "media" attribute
         * @return String: modified value of the "media" attribute
         */
-       function transformCssMedia( $media ) {
+       public static function transformCssMedia( $media ) {
                global $wgRequest, $wgHandheldForIPhone;
 
                // Switch in on-screen display for media testing
@@ -2771,7 +2956,7 @@ class OutputPage {
         * @param $modules Array: list of jQuery modules which should be loaded
         * @return Array: the list of modules which were not loaded.
         * @since 1.16
-        * @deprecated No longer needed as of 1.17
+        * @deprecated @since 1.17
         */
        public function includeJQuery( $modules = array() ) {
                return array();