Implement page status indicators
[lhc/web/wiklou.git] / includes / OutputPage.php
index 6ea4953..3bb2175 100644 (file)
@@ -122,6 +122,9 @@ class OutputPage extends ContextSource {
        /** @var array */
        protected $mCategories = array();
 
+       /** @var array */
+       protected $mIndicators = array();
+
        /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
        private $mLanguageLinks = array();
 
@@ -179,14 +182,12 @@ class OutputPage extends ContextSource {
 
        protected $mFeedLinksAppendQuery = null;
 
-       /** @var array
-        * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
+       /**
+        * @var int
+        * The level of 'untrustworthiness' allowed for modules loaded on this page.
         * @see ResourceLoaderModule::$origin
-        * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
         */
-       protected $mAllowedModules = array(
-               ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
-       );
+       protected $mAllowedModuleOrigin = ResourceLoaderModule::ORIGIN_ALL;
 
        /** @var bool Whether output is disabled.  If this is true, the 'output' method will do nothing. */
        protected $mDoNothing = false;
@@ -449,15 +450,14 @@ class OutputPage extends ContextSource {
         * @param string $version Style version of the file. Defaults to $wgStyleVersion
         */
        public function addScriptFile( $file, $version = null ) {
-               global $wgStylePath, $wgStyleVersion;
                // See if $file parameter is an absolute URL or begins with a slash
                if ( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
                        $path = $file;
                } else {
-                       $path = "{$wgStylePath}/common/{$file}";
+                       $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
                }
                if ( is_null( $version ) ) {
-                       $version = $wgStyleVersion;
+                       $version = $this->getConfig()->get( 'StyleVersion' );
                }
                $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
        }
@@ -733,13 +733,12 @@ class OutputPage extends ContextSource {
         * @return bool True if cache-ok headers was sent.
         */
        public function checkLastModified( $timestamp ) {
-               global $wgCachePages, $wgCacheEpoch, $wgUseSquid, $wgSquidMaxage;
-
                if ( !$timestamp || $timestamp == '19700101000000' ) {
                        wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
                        return false;
                }
-               if ( !$wgCachePages ) {
+               $config = $this->getConfig();
+               if ( !$config->get( 'CachePages' ) ) {
                        wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
                        return false;
                }
@@ -748,11 +747,11 @@ class OutputPage extends ContextSource {
                $modifiedTimes = array(
                        'page' => $timestamp,
                        'user' => $this->getUser()->getTouched(),
-                       'epoch' => $wgCacheEpoch
+                       'epoch' => $config->get( 'CacheEpoch' )
                );
-               if ( $wgUseSquid ) {
+               if ( $config->get( 'UseSquid' ) ) {
                        // bug 44570: the core page itself may not change, but resources might
-                       $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $wgSquidMaxage );
+                       $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $config->get( 'SquidMaxage' ) );
                }
                wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
 
@@ -1107,11 +1106,9 @@ class OutputPage extends ContextSource {
         *        default links
         */
        public function setFeedAppendQuery( $val ) {
-               global $wgAdvertisedFeedTypes;
-
                $this->mFeedLinks = array();
 
-               foreach ( $wgAdvertisedFeedTypes as $type ) {
+               foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
                        $query = "feed=$type";
                        if ( is_string( $val ) ) {
                                $query .= '&' . $val;
@@ -1127,9 +1124,7 @@ class OutputPage extends ContextSource {
         * @param string $href URL
         */
        public function addFeedLink( $format, $href ) {
-               global $wgAdvertisedFeedTypes;
-
-               if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
+               if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
                        $this->mFeedLinks[$format] = $href;
                }
        }
@@ -1253,9 +1248,15 @@ class OutputPage extends ContextSource {
 
                # Fetch existence plus the hiddencat property
                $dbr = wfGetDB( DB_SLAVE );
+               $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
+                       'page_is_redirect', 'page_latest', 'pp_value' );
+
+               if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
+                       $fields[] = 'page_content_model';
+               }
+
                $res = $dbr->select( array( 'page', 'page_props' ),
-                       array( 'page_id', 'page_namespace', 'page_title', 'page_len',
-                               'page_is_redirect', 'page_latest', 'pp_value' ),
+                       $fields,
                        $lb->constructSet( 'page', $dbr ),
                        __METHOD__,
                        array(),
@@ -1332,48 +1333,91 @@ class OutputPage extends ContextSource {
        }
 
        /**
-        * Do not allow scripts which can be modified by wiki users to load on this page;
-        * only allow scripts bundled with, or generated by, the software.
+        * Add an array of indicators, with their identifiers as array keys and HTML contents as values.
+        *
+        * In case of duplicate keys, existing values are overwritten.
+        *
+        * @param array $indicators
+        * @since 1.25
+        */
+       public function setIndicators( array $indicators ) {
+               $this->mIndicators = $indicators + $this->mIndicators;
+               // Keep ordered by key
+               ksort( $this->mIndicators );
+       }
+
+       /**
+        * Get the indicators associated with this page.
+        *
+        * The array will be internally ordered by item keys.
+        *
+        * @return array Keys: identifiers, values: HTML contents
+        * @since 1.25
+        */
+       public function getIndicators() {
+               return $this->mIndicators;
+       }
+
+       /**
+        * Restrict the page to loading modules bundled the software.
+        *
+        * Disallows the queue to contain any modules which can be modified by wiki
+        * users to load on this page.
         */
        public function disallowUserJs() {
-               $this->reduceAllowedModules(
-                       ResourceLoaderModule::TYPE_SCRIPTS,
-                       ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
-               );
+               $this->reduceAllowedModuleOrigin( ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL );
        }
 
        /**
-        * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
+        * Get the level of JavaScript / CSS untrustworthiness allowed on this page.
+        *
         * @see ResourceLoaderModule::$origin
-        * @param string $type ResourceLoaderModule TYPE_ constant
+        * @param string $type Unused: Module origin allowance used to be fragmented by
+        *  ResourceLoaderModule TYPE_ constants.
         * @return int ResourceLoaderModule ORIGIN_ class constant
         */
-       public function getAllowedModules( $type ) {
-               if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
-                       return min( array_values( $this->mAllowedModules ) );
-               } else {
-                       return isset( $this->mAllowedModules[$type] )
-                               ? $this->mAllowedModules[$type]
-                               : ResourceLoaderModule::ORIGIN_ALL;
-               }
+       public function getAllowedModules( $type = null ) {
+               return $this->mAllowedModuleOrigin;
        }
 
        /**
         * Set the highest level of CSS/JS untrustworthiness allowed
+        *
+        * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
+        *  Use reduceAllowedModuleOrigin() instead.
+        *
         * @param string $type ResourceLoaderModule TYPE_ constant
-        * @param int $level ResourceLoaderModule class constant
+        * @param int $level ResourceLoaderModule ORIGIN_ constant
         */
        public function setAllowedModules( $type, $level ) {
-               $this->mAllowedModules[$type] = $level;
+               wfDeprecated( __METHOD__, '1.24' );
+               $this->reduceAllowedModuleOrigin( $level );
        }
 
        /**
-        * As for setAllowedModules(), but don't inadvertently make the page more accessible
-        * @param string $type
-        * @param int $level ResourceLoaderModule class constant
+        * Limit the highest level of CSS/JS untrustworthiness allowed.
+        *
+        * @deprecated since 1.24 Module allowance is no longer fragmented by content type.
+        *  Use reduceAllowedModuleOrigin() instead.
+        *
+        * @param string $type ResourceLoaderModule TYPE_ constant
+        * @param int $level ResourceLoaderModule ORIGIN_ class constant
         */
        public function reduceAllowedModules( $type, $level ) {
-               $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
+               wfDeprecated( __METHOD__, '1.24' );
+               $this->reduceAllowedModuleOrigin( $level );
+       }
+
+       /**
+        * Limit the highest level of CSS/JS untrustworthiness allowed.
+        *
+        * If passed the same or a higher level than the current level of untrustworthiness set, the
+        * level will remain unchanged.
+        *
+        * @param int $level ResourceLoaderModule class constant
+        */
+       public function reduceAllowedModuleOrigin( $level ) {
+               $this->mAllowedModuleOrigin = min( $this->mAllowedModuleOrigin, $level );
        }
 
        /**
@@ -1611,7 +1655,7 @@ class OutputPage extends ContextSource {
         * @deprecated since 1.24, use addParserOutputMetadata() instead.
         * @param ParserOutput $parserOutput
         */
-       public function addParserOutputNoText( &$parserOutput ) {
+       public function addParserOutputNoText( $parserOutput ) {
                $this->addParserOutputMetadata( $parserOutput );
        }
 
@@ -1623,9 +1667,10 @@ class OutputPage extends ContextSource {
         * @since 1.24
         * @param ParserOutput $parserOutput
         */
-       public function addParserOutputMetadata( &$parserOutput ) {
+       public function addParserOutputMetadata( $parserOutput ) {
                $this->mLanguageLinks += $parserOutput->getLanguageLinks();
                $this->addCategoryLinks( $parserOutput->getCategories() );
+               $this->setIndicators( $parserOutput->getIndicators() );
                $this->mNewSectionLink = $parserOutput->getNewSection();
                $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
 
@@ -1657,11 +1702,11 @@ class OutputPage extends ContextSource {
                }
 
                // Hooks registered in the object
-               global $wgParserOutputHooks;
+               $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
                foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
                        list( $hookName, $data ) = $hookInfo;
-                       if ( isset( $wgParserOutputHooks[$hookName] ) ) {
-                               call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
+                       if ( isset( $parserOutputHooks[$hookName] ) ) {
+                               call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
                        }
                }
 
@@ -1679,7 +1724,7 @@ class OutputPage extends ContextSource {
         * @since 1.24
         * @param ParserOutput $parserOutput
         */
-       public function addParserOutputContent( &$parserOutput ) {
+       public function addParserOutputContent( $parserOutput ) {
                $this->addParserOutputText( $parserOutput );
 
                $this->addModules( $parserOutput->getModules() );
@@ -1696,7 +1741,7 @@ class OutputPage extends ContextSource {
         * @since 1.24
         * @param ParserOutput $parserOutput
         */
-       public function addParserOutputText( &$parserOutput ) {
+       public function addParserOutputText( $parserOutput ) {
                $text = $parserOutput->getText();
                wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
                $this->addHTML( $text );
@@ -1707,7 +1752,7 @@ class OutputPage extends ContextSource {
         *
         * @param ParserOutput $parserOutput
         */
-       function addParserOutput( &$parserOutput ) {
+       function addParserOutput( $parserOutput ) {
                $this->addParserOutputMetadata( $parserOutput );
                $parserOutput->setTOCEnabled( $this->mEnableTOC );
 
@@ -1811,17 +1856,17 @@ class OutputPage extends ContextSource {
         * @return array
         */
        function getCacheVaryCookies() {
-               global $wgCookiePrefix, $wgCacheVaryCookies;
                static $cookies;
                if ( $cookies === null ) {
+                       $config = $this->getConfig();
                        $cookies = array_merge(
                                array(
-                                       "{$wgCookiePrefix}Token",
-                                       "{$wgCookiePrefix}LoggedOut",
+                                       $config->get( 'CookiePrefix' ) . 'Token',
+                                       $config->get( 'CookiePrefix' ) . 'LoggedOut',
                                        "forceHTTPS",
                                        session_name()
                                ),
-                               $wgCacheVaryCookies
+                               $config->get( 'CacheVaryCookies' )
                        );
                        wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
                }
@@ -1987,11 +2032,11 @@ class OutputPage extends ContextSource {
         * @return string
         */
        public function getFrameOptions() {
-               global $wgBreakFrames, $wgEditPageFrameOptions;
-               if ( $wgBreakFrames ) {
+               $config = $this->getConfig();
+               if ( $config->get( 'BreakFrames' ) ) {
                        return 'DENY';
-               } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
-                       return $wgEditPageFrameOptions;
+               } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
+                       return $config->get( 'EditPageFrameOptions' );
                }
                return false;
        }
@@ -2000,10 +2045,9 @@ class OutputPage extends ContextSource {
         * Send cache control HTTP headers
         */
        public function sendCacheControl() {
-               global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
-
                $response = $this->getRequest()->response();
-               if ( $wgUseETag && $this->mETag ) {
+               $config = $this->getConfig();
+               if ( $config->get( 'UseETag' ) && $this->mETag ) {
                        $response->header( "ETag: $this->mETag" );
                }
 
@@ -2014,24 +2058,24 @@ class OutputPage extends ContextSource {
                # maintain different caches for logged-in users and non-logged in ones
                $response->header( $this->getVaryHeader() );
 
-               if ( $wgUseXVO ) {
+               if ( $config->get( 'UseXVO' ) ) {
                        # Add an X-Vary-Options header for Squid with Wikimedia patches
                        $response->header( $this->getXVO() );
                }
 
                if ( $this->mEnableClientCache ) {
                        if (
-                               $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
+                               $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
                                $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
                        ) {
-                               if ( $wgUseESI ) {
+                               if ( $config->get( 'UseESI' ) ) {
                                        # We'll purge the proxy cache explicitly, but require end user agents
                                        # to revalidate against the proxy on each visit.
                                        # Surrogate-Control controls our Squid, Cache-Control downstream caches
                                        wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
                                        # start with a shorter timeout for initial testing
                                        # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
-                                       $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage
+                                       $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
                                                . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
                                        $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
                                } else {
@@ -2071,9 +2115,6 @@ class OutputPage extends ContextSource {
         * the object, let's actually output it:
         */
        public function output() {
-               global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP,
-                       $wgResponsiveImages;
-
                if ( $this->mDoNothing ) {
                        return;
                }
@@ -2081,6 +2122,7 @@ class OutputPage extends ContextSource {
                wfProfileIn( __METHOD__ );
 
                $response = $this->getRequest()->response();
+               $config = $this->getConfig();
 
                if ( $this->mRedirect != '' ) {
                        # Standards require redirect URLs to be absolute
@@ -2091,19 +2133,19 @@ class OutputPage extends ContextSource {
 
                        if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
                                if ( $code == '301' || $code == '303' ) {
-                                       if ( !$wgDebugRedirects ) {
+                                       if ( !$config->get( 'DebugRedirects' ) ) {
                                                $message = HttpStatus::getMessage( $code );
                                                $response->header( "HTTP/1.1 $code $message" );
                                        }
                                        $this->mLastModified = wfTimestamp( TS_RFC2822 );
                                }
-                               if ( $wgVaryOnXFP ) {
+                               if ( $config->get( 'VaryOnXFP' ) ) {
                                        $this->addVaryHeader( 'X-Forwarded-Proto' );
                                }
                                $this->sendCacheControl();
 
                                $response->header( "Content-Type: text/html; charset=utf-8" );
-                               if ( $wgDebugRedirects ) {
+                               if ( $config->get( 'DebugRedirects' ) ) {
                                        $url = htmlspecialchars( $redirect );
                                        print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
                                        print "<p>Location: <a href=\"$url\">$url</a></p>\n";
@@ -2125,8 +2167,8 @@ class OutputPage extends ContextSource {
                # Buffer output; final headers may depend on later processing
                ob_start();
 
-               $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
-               $response->header( 'Content-language: ' . $wgLanguageCode );
+               $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
+               $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
 
                // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
                // jQuery etc. can work correctly.
@@ -2154,7 +2196,7 @@ class OutputPage extends ContextSource {
                        );
 
                        // Support for high-density display images if enabled
-                       if ( $wgResponsiveImages ) {
+                       if ( $config->get( 'ResponsiveImages' ) ) {
                                $coreModules[] = 'mediawiki.hidpi';
                        }
 
@@ -2400,90 +2442,32 @@ class OutputPage extends ContextSource {
        }
 
        /**
-        * Display a page stating that the Wiki is in read-only mode,
-        * and optionally show the source of the page that the user
-        * was trying to edit.  Should only be called (for this
-        * purpose) after wfReadOnly() has returned true.
+        * Display a page stating that the Wiki is in read-only mode.
+        * Should only be called after wfReadOnly() has returned true.
         *
-        * For historical reasons, this function is _also_ used to
-        * show the error message when a user tries to edit a page
-        * they are not allowed to edit.  (Unless it's because they're
-        * blocked, then we show blockedPage() instead.)  In this
-        * case, the second parameter should be set to true and a list
-        * of reasons supplied as the third parameter.
+        * Historically, this function was used to show the source of the page that the user
+        * was trying to edit and _also_ permissions error messages. The relevant code was
+        * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
         *
-        * @todo Needs to be split into multiple functions.
-        *
-        * @param string $source Source code to show (or null).
-        * @param bool $protected Is this a permissions error?
-        * @param array $reasons List of reasons for this error, as returned by
-        *   Title::getUserPermissionsErrors().
-        * @param string $action Action that was denied or null if unknown
+        * @deprecated since 1.25; throw the exception directly
         * @throws ReadOnlyError
         */
-       public function readOnlyPage( $source = null, $protected = false,
-               array $reasons = array(), $action = null
-       ) {
-               $this->setRobotPolicy( 'noindex,nofollow' );
-               $this->setArticleRelated( false );
-
-               // If no reason is given, just supply a default "I can't let you do
-               // that, Dave" message.  Should only occur if called by legacy code.
-               if ( $protected && empty( $reasons ) ) {
-                       $reasons[] = array( 'badaccess-group0' );
-               }
-
-               if ( !empty( $reasons ) ) {
-                       // Permissions error
-                       if ( $source ) {
-                               $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
-                               $this->addBacklinkSubtitle( $this->getTitle() );
-                       } else {
-                               $this->setPageTitle( $this->msg( 'badaccess' ) );
-                       }
-                       $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
-               } else {
-                       // Wiki is read only
-                       throw new ReadOnlyError;
-               }
-
-               // Show source, if supplied
-               if ( is_string( $source ) ) {
-                       $this->addWikiMsg( 'viewsourcetext' );
-
-                       $pageLang = $this->getTitle()->getPageLanguage();
-                       $params = array(
-                               'id' => 'wpTextbox1',
-                               'name' => 'wpTextbox1',
-                               'cols' => $this->getUser()->getOption( 'cols' ),
-                               'rows' => $this->getUser()->getOption( 'rows' ),
-                               'readonly' => 'readonly',
-                               'lang' => $pageLang->getHtmlCode(),
-                               'dir' => $pageLang->getDir(),
-                       );
-                       $this->addHTML( Html::element( 'textarea', $params, $source ) );
-
-                       // Show templates used by this article
-                       $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
-                       $this->addHTML( "<div class='templatesUsed'>
-$templates
-</div>
-" );
+       public function readOnlyPage() {
+               if ( func_num_args() > 0 ) {
+                       throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
                }
 
-               # If the title doesn't exist, it's fairly pointless to print a return
-               # link to it.  After all, you just tried editing it and couldn't, so
-               # what's there to do there?
-               if ( $this->getTitle()->exists() ) {
-                       $this->returnToMain( null, $this->getTitle() );
-               }
+               throw new ReadOnlyError;
        }
 
        /**
         * Turn off regular page output and return an error response
         * for when rate limiting has triggered.
+        *
+        * @deprecated since 1.25; throw the exception directly
         */
        public function rateLimited() {
+               wfDeprecated( __METHOD__, '1.25' );
                throw new ThrottledError;
        }
 
@@ -2497,9 +2481,9 @@ $templates
         * @param int $lag Slave lag
         */
        public function showLagWarning( $lag ) {
-               global $wgSlaveLagWarning, $wgSlaveLagCritical;
-               if ( $lag >= $wgSlaveLagWarning ) {
-                       $message = $lag < $wgSlaveLagCritical
+               $config = $this->getConfig();
+               if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
+                       $message = $lag < $config->get( 'SlaveLagCritical' )
                                ? 'lag-warn-normal'
                                : 'lag-warn-high';
                        $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
@@ -2586,7 +2570,9 @@ $templates
         * @return string The doctype, opening "<html>", and head element.
         */
        public function headElement( Skin $sk, $includeStyle = true ) {
-               global $wgContLang, $wgMimeType;
+               global $wgContLang;
+
+               $section = new ProfileSection( __METHOD__ );
 
                $userdir = $this->getLanguage()->getDir();
                $sitedir = $wgContLang->getDir();
@@ -2603,7 +2589,7 @@ $templates
                        $ret .= "$openHead\n";
                }
 
-               if ( !Html::isXmlMimeType( $wgMimeType ) ) {
+               if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
                        // Add <meta charset="UTF-8">
                        // This should be before <title> since it defines the charset used by
                        // text including the text inside <title>.
@@ -2673,7 +2659,7 @@ $templates
         */
        public function getResourceLoader() {
                if ( is_null( $this->mResourceLoader ) ) {
-                       $this->mResourceLoader = new ResourceLoader();
+                       $this->mResourceLoader = new ResourceLoader( $this->getConfig() );
                }
                return $this->mResourceLoader;
        }
@@ -2692,8 +2678,6 @@ $templates
        protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
                array $extraQuery = array(), $loadCall = false
        ) {
-               global $wgResourceLoaderUseESI;
-
                $modules = (array)$modules;
 
                $links = array(
@@ -2729,6 +2713,7 @@ $templates
                // Create keyed-by-source and then keyed-by-group list of module objects from modules list
                $sortedModules = array();
                $resourceLoader = $this->getResourceLoader();
+               $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
                foreach ( $modules as $name ) {
                        $module = $resourceLoader->getModule( $name );
                        # Check that we're allowed to include this module on this page
@@ -2771,7 +2756,9 @@ $templates
                                );
                                $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
 
-                               // Extract modules that know they're empty
+                               // Extract modules that know they're empty and see if we have one or more
+                               // raw modules
+                               $isRaw = false;
                                foreach ( $grpModules as $key => $module ) {
                                        // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
                                        // If we're only getting the styles, we don't need to do anything for empty modules.
@@ -2781,6 +2768,8 @@ $templates
                                                        $links['states'][$key] = 'ready';
                                                }
                                        }
+
+                                       $isRaw |= $module->isRaw();
                                }
 
                                // If there are no non-empty modules, skip this group
@@ -2799,7 +2788,9 @@ $templates
                                                );
                                        } else {
                                                $links['html'] .= Html::inlineScript(
-                                                       $resourceLoader->makeModuleResponse( $context, $grpModules )
+                                                       ResourceLoader::makeLoaderConditionalScript(
+                                                               $resourceLoader->makeModuleResponse( $context, $grpModules )
+                                                       )
                                                );
                                        }
                                        $links['html'] .= "\n";
@@ -2826,7 +2817,7 @@ $templates
                                $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
                                $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
 
-                               if ( $useESI && $wgResourceLoaderUseESI ) {
+                               if ( $useESI && $resourceLoaderUseESI ) {
                                        $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
                                        if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
                                                $link = Html::inlineStyle( $esi );
@@ -2845,6 +2836,17 @@ $templates
                                                );
                                        } else {
                                                $link = Html::linkedScript( $url );
+                                               if ( $context->getOnly() === 'scripts' && !$context->getRaw() && !$isRaw ) {
+                                                       // Wrap only=script requests in a conditional as browsers not supported
+                                                       // by the startup module would unconditionally execute this module.
+                                                       // Otherwise users will get "ReferenceError: mw is undefined" or
+                                                       // "jQuery is undefined" from e.g. a "site" module.
+                                                       $link = Html::inlineScript(
+                                                               ResourceLoader::makeLoaderConditionalScript(
+                                                                       Xml::encodeJsCall( 'document.write', array( $link ) )
+                                                               )
+                                                       );
+                                               }
 
                                                // For modules requested directly in the html via <link> or <script>,
                                                // tell mw.loader they are being loading to prevent duplicate requests.
@@ -2903,8 +2905,6 @@ $templates
         * @return string HTML fragment
         */
        function getHeadScripts() {
-               global $wgResourceLoaderExperimentalAsyncLoading;
-
                // Startup - this will immediately load jquery and mediawiki modules
                $links = array();
                $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
@@ -2944,7 +2944,7 @@ $templates
                        );
                }
 
-               if ( $wgResourceLoaderExperimentalAsyncLoading ) {
+               if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
                        $links[] = $this->getScriptsForBottomQueue( true );
                }
 
@@ -2963,8 +2963,6 @@ $templates
         * @return string
         */
        function getScriptsForBottomQueue( $inHead ) {
-               global $wgAllowUserJs;
-
                // Scripts and messages "only" requests marked for bottom inclusion
                // If we're in the <head>, use load() calls rather than <script src="..."> tags
                // Messages should go first
@@ -2998,7 +2996,7 @@ $templates
                );
 
                // Add user JS if enabled
-               if ( $wgAllowUserJs
+               if ( $this->getConfig()->get( 'AllowUserJs' )
                        && $this->getUser()->isLoggedIn()
                        && $this->getTitle()
                        && $this->getTitle()->isJsSubpage()
@@ -3037,15 +3035,13 @@ $templates
         * @return string
         */
        function getBottomScripts() {
-               global $wgResourceLoaderExperimentalAsyncLoading;
-
                // Optimise jQuery ready event cross-browser.
                // This also enforces $.isReady to be true at </body> which fixes the
                // mw.loader bug in Firefox with using document.write between </body>
                // and the DOMContentReady event (bug 47457).
                $html = Html::inlineScript( 'window.jQuery && jQuery.ready();' );
 
-               if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
+               if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
                        $html .= $this->getScriptsForBottomQueue( false );
                }
 
@@ -3232,13 +3228,10 @@ $templates
         * @return array Array in format "link name or number => 'link html'".
         */
        public function getHeadLinksArray() {
-               global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
-                       $wgSitename, $wgVersion,
-                       $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
-                       $wgDisableLangConversion, $wgCanonicalLanguageLinks,
-                       $wgRightsPage, $wgRightsUrl;
+               global $wgVersion;
 
                $tags = array();
+               $config = $this->getConfig();
 
                $canonicalUrl = $this->mCanonicalUrl;
 
@@ -3281,7 +3274,7 @@ $templates
                }
 
                # Universal edit button
-               if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
+               if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
                        $user = $this->getUser();
                        if ( $this->getTitle()->quickUserCan( 'edit', $user )
                                && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
@@ -3306,17 +3299,17 @@ $templates
                # should not matter, but Konqueror (3.5.9 at least) incorrectly
                # uses whichever one appears later in the HTML source. Make sure
                # apple-touch-icon is specified first to avoid this.
-               if ( $wgAppleTouchIcon !== false ) {
+               if ( $config->get( 'AppleTouchIcon' ) !== false ) {
                        $tags['apple-touch-icon'] = Html::element( 'link', array(
                                'rel' => 'apple-touch-icon',
-                               'href' => $wgAppleTouchIcon
+                               'href' => $config->get( 'AppleTouchIcon' )
                        ) );
                }
 
-               if ( $wgFavicon !== false ) {
+               if ( $config->get( 'Favicon' ) !== false ) {
                        $tags['favicon'] = Html::element( 'link', array(
                                'rel' => 'shortcut icon',
-                               'href' => $wgFavicon
+                               'href' => $config->get( 'Favicon' )
                        ) );
                }
 
@@ -3328,7 +3321,7 @@ $templates
                        'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
                ) );
 
-               if ( $wgEnableAPI ) {
+               if ( $config->get( 'EnableAPI' ) ) {
                        # Real Simple Discovery link, provides auto-discovery information
                        # for the MediaWiki API (and potentially additional custom API
                        # support such as WordPress or Twitter-compatible APIs for a
@@ -3347,39 +3340,37 @@ $templates
                }
 
                # Language variants
-               if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
+               if ( !$config->get( 'DisableLangConversion' ) ) {
                        $lang = $this->getTitle()->getPageLanguage();
                        if ( $lang->hasVariants() ) {
-
-                               $urlvar = $lang->getURLVariant();
-
-                               if ( !$urlvar ) {
-                                       $variants = $lang->getVariants();
-                                       foreach ( $variants as $_v ) {
-                                               $tags["variant-$_v"] = Html::element( 'link', array(
-                                                       'rel' => 'alternate',
-                                                       'hreflang' => wfBCP47( $_v ),
-                                                       'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
-                                               );
-                                       }
-                               } else {
-                                       $canonicalUrl = $this->getTitle()->getLocalURL();
+                               $variants = $lang->getVariants();
+                               foreach ( $variants as $_v ) {
+                                       $tags["variant-$_v"] = Html::element( 'link', array(
+                                               'rel' => 'alternate',
+                                               'hreflang' => wfBCP47( $_v ),
+                                               'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
+                                       );
                                }
                        }
+                       # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
+                       $tags["variant-x-default"] = Html::element( 'link', array(
+                               'rel' => 'alternate',
+                               'hreflang' => 'x-default',
+                               'href' => $this->getTitle()->getLocalURL() ) );
                }
 
                # Copyright
                $copyright = '';
-               if ( $wgRightsPage ) {
-                       $copy = Title::newFromText( $wgRightsPage );
+               if ( $config->get( 'RightsPage' ) ) {
+                       $copy = Title::newFromText( $config->get( 'RightsPage' ) );
 
                        if ( $copy ) {
                                $copyright = $copy->getLocalURL();
                        }
                }
 
-               if ( !$copyright && $wgRightsUrl ) {
-                       $copyright = $wgRightsUrl;
+               if ( !$copyright && $config->get( 'RightsUrl' ) ) {
+                       $copyright = $config->get( 'RightsUrl' );
                }
 
                if ( $copyright ) {
@@ -3390,7 +3381,7 @@ $templates
                }
 
                # Feeds
-               if ( $wgFeed ) {
+               if ( $config->get( 'Feed' ) ) {
                        foreach ( $this->getSyndicationLinks() as $format => $link ) {
                                # Use the page name for the title.  In principle, this could
                                # lead to issues with having the same name for different feeds
@@ -3412,31 +3403,31 @@ $templates
                        # like to promote instead of the RC feed (maybe like a "Recent New Articles"
                        # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
                        # If so, use it instead.
-                       if ( $wgOverrideSiteFeed ) {
-                               foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
+                       $sitename = $config->get( 'Sitename' );
+                       if ( $config->get( 'OverrideSiteFeed' ) ) {
+                               foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
                                        // Note, this->feedLink escapes the url.
                                        $tags[] = $this->feedLink(
                                                $type,
                                                $feedUrl,
-                                               $this->msg( "site-{$type}-feed", $wgSitename )->text()
+                                               $this->msg( "site-{$type}-feed", $sitename )->text()
                                        );
                                }
                        } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
                                $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
-                               foreach ( $wgAdvertisedFeedTypes as $format ) {
+                               foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
                                        $tags[] = $this->feedLink(
                                                $format,
                                                $rctitle->getLocalURL( array( 'feed' => $format ) ),
                                                # For grep: 'site-rss-feed', 'site-atom-feed'
-                                               $this->msg( "site-{$format}-feed", $wgSitename )->text()
+                                               $this->msg( "site-{$format}-feed", $sitename )->text()
                                        );
                                }
                        }
                }
 
                # Canonical URL
-               global $wgEnableCanonicalServerLink;
-               if ( $wgEnableCanonicalServerLink ) {
+               if ( $config->get( 'EnableCanonicalServerLink' ) ) {
                        if ( $canonicalUrl !== false ) {
                                $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
                        } else {
@@ -3526,7 +3517,7 @@ $templates
         * @return string
         */
        public function buildCssLinks() {
-               global $wgAllowUserCss, $wgContLang;
+               global $wgContLang;
 
                $this->getSkin()->setupSkinUserCss( $this );
 
@@ -3551,7 +3542,9 @@ $templates
                $moduleStyles[] = 'user.groups';
 
                // Per-user custom styles
-               if ( $wgAllowUserCss && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
+               if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
+                       && $this->userCanPreview()
+               ) {
                        // We're on a preview of a CSS subpage
                        // Exclude this page from the user module in case it's in there (bug 26283)
                        $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
@@ -3663,8 +3656,8 @@ $templates
                        substr( $style, 0, 6 ) == 'https:' ) {
                        $url = $style;
                } else {
-                       global $wgStylePath, $wgStyleVersion;
-                       $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
+                       $config = $this->getConfig();
+                       $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
                }
 
                $link = Html::linkedStyle( $url, $media );