From 4ac9fa081a7c045f6a9f1cfc529d82423f485b2e Mon Sep 17 00:00:00 2001 From: Pierre Schmitz Date: Sun, 8 Dec 2013 09:55:49 +0100 Subject: Update to MediaWiki 1.22.0 --- includes/resourceloader/ResourceLoader.php | 181 +++++++++++++++------ includes/resourceloader/ResourceLoaderContext.php | 2 +- .../resourceloader/ResourceLoaderFileModule.php | 176 +++++++++++++++----- .../resourceloader/ResourceLoaderLESSFunctions.php | 67 ++++++++ .../ResourceLoaderLanguageDataModule.php | 31 ++-- includes/resourceloader/ResourceLoaderModule.php | 102 ++++++++---- .../resourceloader/ResourceLoaderSiteModule.php | 23 ++- .../resourceloader/ResourceLoaderStartUpModule.php | 10 +- .../ResourceLoaderUserCSSPrefsModule.php | 67 ++++---- .../ResourceLoaderUserGroupsModule.php | 15 +- .../resourceloader/ResourceLoaderUserModule.php | 21 ++- .../ResourceLoaderUserOptionsModule.php | 4 +- .../ResourceLoaderUserTokensModule.php | 9 +- .../resourceloader/ResourceLoaderWikiModule.php | 4 +- 14 files changed, 509 insertions(+), 203 deletions(-) create mode 100644 includes/resourceloader/ResourceLoaderLESSFunctions.php (limited to 'includes/resourceloader') diff --git a/includes/resourceloader/ResourceLoader.php b/includes/resourceloader/ResourceLoader.php index 4e047be4..6380efcf 100644 --- a/includes/resourceloader/ResourceLoader.php +++ b/includes/resourceloader/ResourceLoader.php @@ -47,6 +47,9 @@ class ResourceLoader { /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/ protected $sources = array(); + /** @var bool */ + protected $hasErrors = false; + /* Protected Methods */ /** @@ -150,6 +153,7 @@ class ResourceLoader { $cache = wfGetCache( CACHE_ANYTHING ); $cacheEntry = $cache->get( $key ); if ( is_string( $cacheEntry ) ) { + wfIncrStats( "rl-$filter-cache-hits" ); wfProfileOut( __METHOD__ ); return $cacheEntry; } @@ -157,6 +161,7 @@ class ResourceLoader { $result = ''; // Run the filter - we've already verified one of these will work try { + wfIncrStats( "rl-$filter-cache-misses" ); switch ( $filter ) { case 'minify-js': $result = JavaScriptMinifier::minify( $data, @@ -173,10 +178,12 @@ class ResourceLoader { // Save filtered text to Memcached $cache->set( $key, $result ); - } catch ( Exception $exception ) { - // Return exception as a comment - $result = $this->formatException( $exception ); + } catch ( Exception $e ) { + MWExceptionHandler::logException( $e ); + wfDebugLog( 'resourceloader', __METHOD__ . ": minification failed: $e" ); $this->hasErrors = true; + // Return exception as a comment + $result = self::formatException( $e ); } wfProfileOut( __METHOD__ ); @@ -201,7 +208,7 @@ class ResourceLoader { $this->addSource( $wgResourceLoaderSources ); // Register core modules - $this->register( include( "$IP/resources/Resources.php" ) ); + $this->register( include "$IP/resources/Resources.php" ); // Register extension modules wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) ); $this->register( $wgResourceModules ); @@ -234,6 +241,7 @@ class ResourceLoader { foreach ( $registrations as $name => $info ) { // Disallow duplicate registrations if ( isset( $this->moduleInfos[$name] ) ) { + wfProfileOut( __METHOD__ ); // A module has already been registered by this name throw new MWException( 'ResourceLoader duplicate registration error. ' . @@ -243,6 +251,7 @@ class ResourceLoader { // Check $name for validity if ( !self::isValidModuleName( $name ) ) { + wfProfileOut( __METHOD__ ); throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" ); } @@ -251,6 +260,7 @@ class ResourceLoader { // Old calling convention // Validate the input if ( !( $info instanceof ResourceLoaderModule ) ) { + wfProfileOut( __METHOD__ ); throw new MWException( 'ResourceLoader invalid module error. ' . 'Instances of ResourceLoaderModule expected.' ); } @@ -273,24 +283,28 @@ class ResourceLoader { global $IP, $wgEnableJavaScriptTest; if ( $wgEnableJavaScriptTest !== true ) { - throw new MWException( 'Attempt to register JavaScript test modules but $wgEnableJavaScriptTest is false. Edit your LocalSettings.php to enable it.' ); + throw new MWException( 'Attempt to register JavaScript test modules but $wgEnableJavaScriptTest is false. Edit your LocalSettings.php to enable it.' ); } wfProfileIn( __METHOD__ ); // Get core test suites $testModules = array(); - $testModules['qunit'] = include( "$IP/tests/qunit/QUnitTestResources.php" ); + $testModules['qunit'] = include "$IP/tests/qunit/QUnitTestResources.php"; // Get other test suites (e.g. from extensions) wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) ); // Add the testrunner (which configures QUnit) to the dependencies. // Since it must be ready before any of the test suites are executed. - foreach( $testModules['qunit'] as $moduleName => $moduleProps ) { - $testModules['qunit'][$moduleName]['dependencies'][] = 'mediawiki.tests.qunit.testrunner'; + foreach ( $testModules['qunit'] as &$module ) { + // Make sure all test modules are top-loading so that when QUnit starts + // on document-ready, it will run once and finish. If some tests arrive + // later (possibly after QUnit has already finished) they will be ignored. + $module['position'] = 'top'; + $module['dependencies'][] = 'mediawiki.tests.qunit.testrunner'; } - foreach( $testModules as $id => $names ) { + foreach ( $testModules as $id => $names ) { // Register test modules $this->register( $testModules[$id] ); @@ -311,7 +325,7 @@ class ResourceLoader { * @param array $properties source properties * @throws MWException */ - public function addSource( $id, $properties = null) { + public function addSource( $id, $properties = null ) { // Allow multiple sources to be registered in one call if ( is_array( $id ) ) { foreach ( $id as $key => $value ) { @@ -357,7 +371,7 @@ class ResourceLoader { * @return Array */ public function getTestModuleNames( $framework = 'all' ) { - /// @TODO: api siteinfo prop testmodulenames modulenames + /// @todo api siteinfo prop testmodulenames modulenames if ( $framework == 'all' ) { return $this->testModuleNames; } elseif ( isset( $this->testModuleNames[$framework] ) && is_array( $this->testModuleNames[$framework] ) ) { @@ -381,6 +395,7 @@ class ResourceLoader { } // Construct the requested object $info = $this->moduleInfos[$name]; + /** @var ResourceLoaderModule $object */ if ( isset( $info['object'] ) ) { // Object given in info array $object = $info['object']; @@ -435,7 +450,6 @@ class ResourceLoader { wfProfileIn( __METHOD__ ); $errors = ''; - $this->hasErrors = false; // Split requested modules into two groups, modules and missing $modules = array(); @@ -446,8 +460,11 @@ class ResourceLoader { // Do not allow private modules to be loaded from the web. // This is a security issue, see bug 34907. if ( $module->getGroup() === 'private' ) { - $errors .= $this->makeComment( "Cannot show private module \"$name\"" ); + wfDebugLog( 'resourceloader', __METHOD__ . ": request for private module '$name' denied" ); $this->hasErrors = true; + // Add exception to the output as a comment + $errors .= self::makeComment( "Cannot show private module \"$name\"" ); + continue; } $modules[$name] = $module; @@ -459,13 +476,15 @@ class ResourceLoader { // Preload information needed to the mtime calculation below try { $this->preloadModuleInfo( array_keys( $modules ), $context ); - } catch( Exception $e ) { - // Add exception to the output as a comment - $errors .= $this->formatException( $e ); + } catch ( Exception $e ) { + MWExceptionHandler::logException( $e ); + wfDebugLog( 'resourceloader', __METHOD__ . ": preloading module info failed: $e" ); $this->hasErrors = true; + // Add exception to the output as a comment + $errors .= self::formatException( $e ); } - wfProfileIn( __METHOD__.'-getModifiedTime' ); + wfProfileIn( __METHOD__ . '-getModifiedTime' ); // To send Last-Modified and support If-Modified-Since, we need to detect // the last modified time @@ -478,13 +497,15 @@ class ResourceLoader { // Calculate maximum modified time $mtime = max( $mtime, $module->getModifiedTime( $context ) ); } catch ( Exception $e ) { - // Add exception to the output as a comment - $errors .= $this->formatException( $e ); + MWExceptionHandler::logException( $e ); + wfDebugLog( 'resourceloader', __METHOD__ . ": calculating maximum modified time failed: $e" ); $this->hasErrors = true; + // Add exception to the output as a comment + $errors .= self::formatException( $e ); } } - wfProfileOut( __METHOD__.'-getModifiedTime' ); + wfProfileOut( __METHOD__ . '-getModifiedTime' ); // If there's an If-Modified-Since header, respond with a 304 appropriately if ( $this->tryRespondLastModified( $context, $mtime ) ) { @@ -501,7 +522,7 @@ class ResourceLoader { // Capture any PHP warnings from the output buffer and append them to the // response in a comment if we're in debug mode. if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) { - $response = $this->makeComment( $warnings ) . $response; + $response = self::makeComment( $warnings ) . $response; $this->hasErrors = true; } @@ -531,7 +552,7 @@ class ResourceLoader { * Send content type and last modified headers to the client. * @param $context ResourceLoaderContext * @param string $mtime TS_MW timestamp to use for last-modified - * @param bool $error Whether there are commented-out errors in the response + * @param bool $errors Whether there are commented-out errors in the response * @return void */ protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $errors ) { @@ -550,6 +571,7 @@ class ResourceLoader { } if ( $context->getOnly() === 'styles' ) { header( 'Content-Type: text/css; charset=utf-8' ); + header( 'Access-Control-Allow-Origin: *' ); } else { header( 'Content-Type: text/javascript; charset=utf-8' ); } @@ -570,7 +592,7 @@ class ResourceLoader { * and clear out the output buffer. If the client cache is too old then do nothing. * @param $context ResourceLoaderContext * @param string $mtime The TS_MW timestamp to check the header against - * @return bool True iff 304 header sent and output handled + * @return bool True if 304 header sent and output handled */ protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) { // If there's an If-Modified-Since header, respond with a 304 appropriately @@ -590,13 +612,7 @@ class ResourceLoader { // See also http://bugs.php.net/bug.php?id=51579 // To work around this, we tear down all output buffering before // sending the 304. - // On some setups, ob_get_level() doesn't seem to go down to zero - // no matter how often we call ob_get_clean(), so instead of doing - // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean(); - // we have to be safe here and avoid an infinite loop. - for ( $i = 0; $i < ob_get_level(); $i++ ) { - ob_end_clean(); - } + wfResetOutputBuffers( /* $resetGzipEncoding = */ true ); header( 'HTTP/1.0 304 Not Modified' ); header( 'Status: 304 Not Modified' ); @@ -628,7 +644,7 @@ class ResourceLoader { if ( !$good ) { try { // RL always hits the DB on file cache miss... wfGetDB( DB_SLAVE ); - } catch( DBConnectionError $e ) { // ...check if we need to fallback to cache + } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache $good = $fileCache->isCacheGood(); // cache existence check } } @@ -657,7 +673,14 @@ class ResourceLoader { return false; // cache miss } - protected function makeComment( $text ) { + /** + * Generate a CSS or JS comment block. Only use this for public data, + * not error message details. + * + * @param $text string + * @return string + */ + public static function makeComment( $text ) { $encText = str_replace( '*/', '* /', $text ); return "/*\n$encText\n*/\n"; } @@ -668,13 +691,13 @@ class ResourceLoader { * @param Exception $e to be shown to the user * @return string sanitized text that can be returned to the user */ - protected function formatException( $e ) { + public static function formatException( $e ) { global $wgShowExceptionDetails; if ( $wgShowExceptionDetails ) { - return $this->makeComment( $e->__toString() ); + return self::makeComment( $e->__toString() ); } else { - return $this->makeComment( wfMessage( 'internalerror' )->text() ); + return self::makeComment( wfMessage( 'internalerror' )->text() ); } } @@ -687,8 +710,8 @@ class ResourceLoader { * @return String: Response data */ public function makeModuleResponse( ResourceLoaderContext $context, - array $modules, $missing = array() ) - { + array $modules, $missing = array() + ) { $out = ''; $exceptions = ''; if ( $modules === array() && $missing === array() ) { @@ -701,9 +724,11 @@ class ResourceLoader { try { $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() ); } catch ( Exception $e ) { - // Add exception to the output as a comment - $exceptions .= $this->formatException( $e ); + MWExceptionHandler::logException( $e ); + wfDebugLog( 'resourceloader', __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e" ); $this->hasErrors = true; + // Add exception to the output as a comment + $exceptions .= self::formatException( $e ); } } else { $blobs = array(); @@ -807,9 +832,11 @@ class ResourceLoader { break; } } catch ( Exception $e ) { - // Add exception to the output as a comment - $exceptions .= $this->formatException( $e ); + MWExceptionHandler::logException( $e ); + wfDebugLog( 'resourceloader', __METHOD__ . ": generating module package failed: $e" ); $this->hasErrors = true; + // Add exception to the output as a comment + $exceptions .= self::formatException( $e ); // Register module as missing $missing[] = $name; @@ -879,7 +906,9 @@ class ResourceLoader { // output javascript "[]" instead of "{}". This fixes that. (object)$styles, (object)$messages - ) ); + ), + ResourceLoader::inDebugMode() + ); } /** @@ -908,7 +937,7 @@ class ResourceLoader { // ResourceLoaderFileModule::getStyle can return the styles // as a string or an array of strings. This is to allow separation in // the front-end. - $styles = (array) $styles; + $styles = (array)$styles; foreach ( $styles as $style ) { $style = trim( $style ); // Don't output an empty "@media print { }" block (bug 40498) @@ -919,7 +948,7 @@ class ResourceLoader { if ( $media === '' || $media == 'all' ) { $out[] = $style; - } else if ( is_string( $media ) ) { + } elseif ( is_string( $media ) ) { $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}"; } // else: skip @@ -1000,12 +1029,12 @@ class ResourceLoader { * @return string */ public static function makeLoaderRegisterScript( $name, $version = null, - $dependencies = null, $group = null, $source = null ) - { + $dependencies = null, $group = null, $source = null + ) { if ( is_array( $name ) ) { return Xml::encodeJsCall( 'mw.loader.register', array( $name ) ); } else { - $version = (int) $version > 1 ? (int) $version : 1; + $version = (int)$version > 1 ? (int)$version : 1; return Xml::encodeJsCall( 'mw.loader.register', array( $name, $version, $dependencies, $group, $source ) ); } @@ -1055,7 +1084,7 @@ class ResourceLoader { * @return string */ public static function makeConfigSetScript( array $configuration ) { - return Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ); + return Xml::encodeJsCall( 'mw.config.set', array( $configuration ), ResourceLoader::inDebugMode() ); } /** @@ -1128,6 +1157,18 @@ class ResourceLoader { /** * Build a query array (array representation of query string) for load.php. Helper * function for makeLoaderURL(). + * + * @param array $modules + * @param string $lang + * @param string $skin + * @param string $user + * @param string $version + * @param bool $debug + * @param string $only + * @param bool $printable + * @param bool $handheld + * @param array $extraQuery + * * @return array */ public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null, @@ -1172,4 +1213,48 @@ class ResourceLoader { public static function isValidModuleName( $moduleName ) { return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255; } + + /** + * Returns LESS compiler set up for use with MediaWiki + * + * @since 1.22 + * @return lessc + */ + public static function getLessCompiler() { + global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths; + + // When called from the installer, it is possible that a required PHP extension + // is missing (at least for now; see bug 47564). If this is the case, throw an + // exception (caught by the installer) to prevent a fatal error later on. + if ( !function_exists( 'ctype_digit' ) ) { + throw new MWException( 'lessc requires the Ctype extension' ); + } + + $less = new lessc(); + $less->setPreserveComments( true ); + $less->setVariables( self::getLESSVars() ); + $less->setImportDir( $wgResourceLoaderLESSImportPaths ); + foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) { + $less->registerFunction( $name, $func ); + } + return $less; + } + + /** + * Get global LESS variables. + * + * $since 1.22 + * @return array: Map of variable names to string CSS values. + */ + public static function getLESSVars() { + global $wgResourceLoaderLESSVars; + + static $lessVars = null; + if ( $lessVars === null ) { + $lessVars = $wgResourceLoaderLESSVars; + // Sort by key to ensure consistent hashing for cache lookups. + ksort( $lessVars ); + } + return $lessVars; + } } diff --git a/includes/resourceloader/ResourceLoaderContext.php b/includes/resourceloader/ResourceLoaderContext.php index 4588015f..22ff6a7e 100644 --- a/includes/resourceloader/ResourceLoaderContext.php +++ b/includes/resourceloader/ResourceLoaderContext.php @@ -96,7 +96,7 @@ class ResourceLoaderContext { $pos = strrpos( $group, '.' ); if ( $pos === false ) { // Prefixless modules, i.e. without dots - $retval = explode( ',', $group ); + $retval = array_merge( $retval, explode( ',', $group ) ); } else { // We have a prefix and a bunch of suffixes $prefix = substr( $group, 0, $pos ); // 'foo' diff --git a/includes/resourceloader/ResourceLoaderFileModule.php b/includes/resourceloader/ResourceLoaderFileModule.php index cedb5dcc..9ed181ed 100644 --- a/includes/resourceloader/ResourceLoaderFileModule.php +++ b/includes/resourceloader/ResourceLoaderFileModule.php @@ -115,6 +115,12 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { protected $raw = false; protected $targets = array( 'desktop' ); + /** + * Boolean: Whether getStyleURLsForDebug should return raw file paths, + * or return load.php urls + */ + protected $hasGeneratedStyles = false; + /** * Array: Cache for mtime * @par Usage: @@ -187,8 +193,8 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { * @endcode */ public function __construct( $options = array(), $localBasePath = null, - $remoteBasePath = null ) - { + $remoteBasePath = null + ) { global $IP, $wgScriptPath, $wgResourceBasePath; $this->localBasePath = $localBasePath === null ? $IP : $localBasePath; if ( $remoteBasePath !== null ) { @@ -209,7 +215,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { case 'debugScripts': case 'loaderScripts': case 'styles': - $this->{$member} = (array) $option; + $this->{$member} = (array)$option; break; // Collated lists of file paths case 'languageScripts': @@ -228,26 +234,26 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { "'$key' given, string expected." ); } - $this->{$member}[$key] = (array) $value; + $this->{$member}[$key] = (array)$value; } break; // Lists of strings case 'dependencies': case 'messages': case 'targets': - $this->{$member} = (array) $option; + $this->{$member} = (array)$option; break; // Single strings case 'group': case 'position': case 'localBasePath': case 'remoteBasePath': - $this->{$member} = (string) $option; + $this->{$member} = (string)$option; break; // Single booleans case 'debugRaw': case 'raw': - $this->{$member} = (bool) $option; + $this->{$member} = (bool)$option; break; } } @@ -259,8 +265,8 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /** * Gets all scripts for a given context concatenated together. * - * @param $context ResourceLoaderContext: Context in which to generate script - * @return String: JavaScript code for $context + * @param ResourceLoaderContext $context Context in which to generate script + * @return string: JavaScript code for $context */ public function getScript( ResourceLoaderContext $context ) { $files = $this->getScriptFiles( $context ); @@ -268,7 +274,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { } /** - * @param $context ResourceLoaderContext + * @param ResourceLoaderContext $context * @return array */ public function getScriptURLsForDebug( ResourceLoaderContext $context ) { @@ -289,7 +295,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /** * Gets loader script. * - * @return String: JavaScript code to be added to startup module + * @return string: JavaScript code to be added to startup module */ public function getLoaderScript() { if ( count( $this->loaderScripts ) == 0 ) { @@ -301,8 +307,8 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /** * Gets all styles for a given context concatenated together. * - * @param $context ResourceLoaderContext: Context in which to generate styles - * @return String: CSS code for $context + * @param ResourceLoaderContext $context Context in which to generate styles + * @return string: CSS code for $context */ public function getStyles( ResourceLoaderContext $context ) { $styles = $this->readStyleFiles( @@ -324,16 +330,23 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { ); } } catch ( Exception $e ) { - wfDebug( __METHOD__ . " failed to update DB: $e\n" ); + wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" ); } return $styles; } /** - * @param $context ResourceLoaderContext + * @param ResourceLoaderContext $context * @return array */ public function getStyleURLsForDebug( ResourceLoaderContext $context ) { + if ( $this->hasGeneratedStyles ) { + // Do the default behaviour of returning a url back to load.php + // but with only=styles. + return parent::getStyleURLsForDebug( $context ); + } + // Our module consists entirely of real css files, + // in debug mode we can load those directly. $urls = array(); foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) { $urls[$mediaType] = array(); @@ -347,7 +360,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /** * Gets list of message keys used by this module. * - * @return Array: List of message keys + * @return array: List of message keys */ public function getMessages() { return $this->messages; @@ -356,7 +369,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /** * Gets the name of the group this module should be loaded in. * - * @return String: Group name + * @return string: Group name */ public function getGroup() { return $this->group; @@ -372,7 +385,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /** * Gets list of names of modules this module depends on. * - * @return Array: List of module names + * @return array: List of module names */ public function getDependencies() { return $this->dependencies; @@ -394,9 +407,9 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { * calculations on files relevant to the given language, skin and debug * mode. * - * @param $context ResourceLoaderContext: Context in which to calculate + * @param ResourceLoaderContext $context Context in which to calculate * the modified time - * @return Integer: UNIX timestamp + * @return int: UNIX timestamp * @see ResourceLoaderModule::getFileDependencies */ public function getModifiedTime( ResourceLoaderContext $context ) { @@ -455,7 +468,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /* Protected Methods */ /** - * @param $path string + * @param string $path * @return string */ protected function getLocalPath( $path ) { @@ -463,25 +476,36 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { } /** - * @param $path string + * @param string $path * @return string */ protected function getRemotePath( $path ) { return "{$this->remoteBasePath}/$path"; } + /** + * Infer the stylesheet language from a stylesheet file path. + * + * @since 1.22 + * @param string $path + * @return string: the stylesheet language name + */ + public function getStyleSheetLang( $path ) { + return preg_match( '/\.less$/i', $path ) ? 'less' : 'css'; + } + /** * Collates file paths by option (where provided). * * @param array $list List of file paths in any combination of index/path * or path/options pairs * @param string $option option name - * @param $default Mixed: default value if the option isn't set - * @return Array: List of file paths, collated by $option + * @param mixed $default default value if the option isn't set + * @return array: List of file paths, collated by $option */ protected static function collateFilePathListByOption( array $list, $option, $default ) { $collatedFiles = array(); - foreach ( (array) $list as $key => $value ) { + foreach ( (array)$list as $key => $value ) { if ( is_int( $key ) ) { // File name as the value if ( !isset( $collatedFiles[$default] ) ) { @@ -506,7 +530,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { * @param array $list List of lists to select from * @param string $key Key to look for in $map * @param string $fallback Key to look for in $list if $key doesn't exist - * @return Array: List of elements from $map which matched $key or $fallback, + * @return array: List of elements from $map which matched $key or $fallback, * or an empty list in case of no match */ protected static function tryForKey( array $list, $key, $fallback = null ) { @@ -524,8 +548,8 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /** * Gets a list of file paths for all scripts in this module, in order of propper execution. * - * @param $context ResourceLoaderContext: Context - * @return Array: List of file paths + * @param ResourceLoaderContext $context + * @return array: List of file paths */ protected function getScriptFiles( ResourceLoaderContext $context ) { $files = array_merge( @@ -543,8 +567,8 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /** * Gets a list of file paths for all styles in this module, in order of propper inclusion. * - * @param $context ResourceLoaderContext: Context - * @return Array: List of file paths + * @param ResourceLoaderContext $context + * @return array: List of file paths */ protected function getStyleFiles( ResourceLoaderContext $context ) { return array_merge_recursive( @@ -555,12 +579,29 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { ); } + /** + * Returns all style files used by this module + * @return array + */ + public function getAllStyleFiles() { + $files = array(); + foreach( (array)$this->styles as $key => $value ) { + if ( is_array( $value ) ) { + $path = $key; + } else { + $path = $value; + } + $files[] = $this->getLocalPath( $path ); + } + return $files; + } + /** * Gets the contents of a list of JavaScript files. * * @param array $scripts List of file paths to scripts to read, remap and concetenate * @throws MWException - * @return String: Concatenated and remapped JavaScript data from $scripts + * @return string: Concatenated and remapped JavaScript data from $scripts */ protected function readScriptFiles( array $scripts ) { global $wgResourceLoaderValidateStaticJS; @@ -591,9 +632,9 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { * @param array $styles List of media type/list of file paths pairs, to read, remap and * concetenate * - * @param $flip bool + * @param bool $flip * - * @return Array: List of concatenated and remapped CSS data from $styles, + * @return array: List of concatenated and remapped CSS data from $styles, * keyed by media type */ protected function readStyleFiles( array $styles, $flip ) { @@ -620,9 +661,9 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { * This method can be used as a callback for array_map() * * @param string $path File path of style file to read - * @param $flip bool + * @param bool $flip * - * @return String: CSS data in script file + * @return string: CSS data in script file * @throws MWException if the file doesn't exist */ protected function readStyleFile( $path, $flip ) { @@ -632,7 +673,14 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { wfDebugLog( 'resourceloader', $msg ); throw new MWException( $msg ); } - $style = file_get_contents( $localPath ); + + if ( $this->getStyleSheetLang( $path ) === 'less' ) { + $style = $this->compileLESSFile( $localPath ); + $this->hasGeneratedStyles = true; + } else { + $style = file_get_contents( $localPath ); + } + if ( $flip ) { $style = CSSJanus::transform( $style, true, false ); } @@ -655,7 +703,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { /** * Get whether CSS for this module should be flipped - * @param $context ResourceLoaderContext + * @param ResourceLoaderContext $context * @return bool */ public function getFlip( $context ) { @@ -671,4 +719,58 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { return $this->targets; } + /** + * Generate a cache key for a LESS file. + * + * The cache key varies on the file name and the names and values of global + * LESS variables. + * + * @since 1.22 + * @param string $fileName File name of root LESS file. + * @return string: Cache key + */ + protected static function getLESSCacheKey( $fileName ) { + $vars = json_encode( ResourceLoader::getLESSVars() ); + $hash = md5( $fileName . $vars ); + return wfMemcKey( 'resourceloader', 'less', $hash ); + } + + /** + * Compile a LESS file into CSS. + * + * If invalid, returns replacement CSS source consisting of the compilation + * error message encoded as a comment. To save work, we cache a result object + * which comprises the compiled CSS and the names & mtimes of the files + * that were processed. lessphp compares the cached & current mtimes and + * recompiles as necessary. + * + * @since 1.22 + * @param string $fileName File path of LESS source + * @return string: CSS source + */ + protected function compileLESSFile( $fileName ) { + $key = self::getLESSCacheKey( $fileName ); + $cache = wfGetCache( CACHE_ANYTHING ); + + // The input to lessc. Either an associative array representing the + // cached results of a previous compilation, or the string file name if + // no cache result exists. + $source = $cache->get( $key ); + if ( !is_array( $source ) || !isset( $source['root'] ) ) { + $source = $fileName; + } + + $compiler = ResourceLoader::getLessCompiler(); + $result = null; + + $result = $compiler->cachedCompile( $source ); + + if ( !is_array( $result ) ) { + throw new MWException( 'LESS compiler result has type ' . gettype( $result ) . '; array expected.' ); + } + + $this->localFileRefs += array_keys( $result['files'] ); + $cache->set( $key, $result ); + return $result['compiled']; + } } diff --git a/includes/resourceloader/ResourceLoaderLESSFunctions.php b/includes/resourceloader/ResourceLoaderLESSFunctions.php new file mode 100644 index 00000000..c7570f64 --- /dev/null +++ b/includes/resourceloader/ResourceLoaderLESSFunctions.php @@ -0,0 +1,67 @@ +parser->sourceName, PATHINFO_DIRNAME ); + $url = $frame[2][0]; + $file = realpath( $base . '/' . $url ); + return $less->toBool( $file + && strpos( $url, '//' ) === false + && filesize( $file ) < CSSMin::EMBED_SIZE_LIMIT + && CSSMin::getMimeType( $file ) !== false ); + } + + /** + * Convert an image URI to a base64-encoded data URI. + * + * @par Example: + * @code + * .fancy-button { + * background-image: embed('../images/button-bg.png'); + * } + * @endcode + */ + public static function embed( $frame, $less ) { + $base = pathinfo( $less->parser->sourceName, PATHINFO_DIRNAME ); + $url = $frame[2][0]; + $file = realpath( $base . '/' . $url ); + + $data = CSSMin::encodeImageAsDataURI( $file ); + $less->addParsedFile( $file ); + return 'url(' . $data . ')'; + } +} diff --git a/includes/resourceloader/ResourceLoaderLanguageDataModule.php b/includes/resourceloader/ResourceLoaderLanguageDataModule.php index 0f8e54ce..fa0fbf85 100644 --- a/includes/resourceloader/ResourceLoaderLanguageDataModule.php +++ b/includes/resourceloader/ResourceLoaderLanguageDataModule.php @@ -75,9 +75,10 @@ class ResourceLoaderLanguageDataModule extends ResourceLoaderModule { return $this->language->separatorTransformTable(); } - /** - * Get all the dynamic data for the content language to an array + * Get all the dynamic data for the content language to an array. + * + * NOTE: Before calling this you HAVE to make sure $this->language is set. * * @return array */ @@ -105,26 +106,20 @@ class ResourceLoaderLanguageDataModule extends ResourceLoaderModule { /** * @param $context ResourceLoaderContext - * @return array|int|Mixed + * @return int: UNIX timestamp */ public function getModifiedTime( ResourceLoaderContext $context ) { - $this->language = Language::factory( $context ->getLanguage() ); - $cache = wfGetCache( CACHE_ANYTHING ); - $key = wfMemcKey( 'resourceloader', 'langdatamodule', 'changeinfo' ); + return max( 1, $this->getHashMtime( $context ) ); + } - $data = $this->getData(); - $hash = md5( serialize( $data ) ); + /** + * @param $context ResourceLoaderContext + * @return string: Hash + */ + public function getModifiedHash( ResourceLoaderContext $context ) { + $this->language = Language::factory( $context->getLanguage() ); - $result = $cache->get( $key ); - if ( is_array( $result ) && $result['hash'] === $hash ) { - return $result['timestamp']; - } - $timestamp = wfTimestamp(); - $cache->set( $key, array( - 'hash' => $hash, - 'timestamp' => $timestamp, - ) ); - return $timestamp; + return md5( serialize( $this->getData() ) ); } /** diff --git a/includes/resourceloader/ResourceLoaderModule.php b/includes/resourceloader/ResourceLoaderModule.php index 03f3cc37..11264fc8 100644 --- a/includes/resourceloader/ResourceLoaderModule.php +++ b/includes/resourceloader/ResourceLoaderModule.php @@ -71,7 +71,7 @@ abstract class ResourceLoaderModule { * Get this module's name. This is set when the module is registered * with ResourceLoader::register() * - * @return Mixed: Name (string) or null if no name was set + * @return mixed: Name (string) or null if no name was set */ public function getName() { return $this->name; @@ -91,7 +91,7 @@ abstract class ResourceLoaderModule { * Get this module's origin. This is set when the module is registered * with ResourceLoader::register() * - * @return Int ResourceLoaderModule class constant, the subclass default + * @return int: ResourceLoaderModule class constant, the subclass default * if not set manually */ public function getOrigin() { @@ -109,7 +109,7 @@ abstract class ResourceLoaderModule { } /** - * @param $context ResourceLoaderContext + * @param ResourceLoaderContext $context * @return bool */ public function getFlip( $context ) { @@ -122,8 +122,8 @@ abstract class ResourceLoaderModule { * Get all JS for this module for a given language and skin. * Includes all relevant JS except loader scripts. * - * @param $context ResourceLoaderContext: Context object - * @return String: JavaScript code + * @param ResourceLoaderContext $context + * @return string: JavaScript code */ public function getScript( ResourceLoaderContext $context ) { // Stub, override expected @@ -141,8 +141,8 @@ abstract class ResourceLoaderModule { * #2 is important to prevent an infinite loop, therefore this function * MUST return either an only= URL or a non-load.php URL. * - * @param $context ResourceLoaderContext: Context object - * @return Array of URLs + * @param ResourceLoaderContext $context + * @return array: Array of URLs */ public function getScriptURLsForDebug( ResourceLoaderContext $context ) { $url = ResourceLoader::makeLoaderURL( @@ -172,8 +172,8 @@ abstract class ResourceLoaderModule { /** * Get all CSS for this module for a given skin. * - * @param $context ResourceLoaderContext: Context object - * @return Array: List of CSS strings or array of CSS strings keyed by media type. + * @param ResourceLoaderContext $context + * @return array: List of CSS strings or array of CSS strings keyed by media type. * like array( 'screen' => '.foo { width: 0 }' ); * or array( 'screen' => array( '.foo { width: 0 }' ) ); */ @@ -188,8 +188,8 @@ abstract class ResourceLoaderModule { * the module, but file-based modules will want to override this to * load the files directly. See also getScriptURLsForDebug() * - * @param $context ResourceLoaderContext: Context object - * @return Array: array( mediaType => array( URL1, URL2, ... ), ... ) + * @param ResourceLoaderContext $context + * @return array: array( mediaType => array( URL1, URL2, ... ), ... ) */ public function getStyleURLsForDebug( ResourceLoaderContext $context ) { $url = ResourceLoader::makeLoaderURL( @@ -211,7 +211,7 @@ abstract class ResourceLoaderModule { * * To get a JSON blob with messages, use MessageBlobStore::get() * - * @return Array: List of message keys. Keys may occur more than once + * @return array: List of message keys. Keys may occur more than once */ public function getMessages() { // Stub, override expected @@ -221,7 +221,7 @@ abstract class ResourceLoaderModule { /** * Get the group this module is in. * - * @return String: Group name + * @return string: Group name */ public function getGroup() { // Stub, override expected @@ -231,7 +231,7 @@ abstract class ResourceLoaderModule { /** * Get the origin of this module. Should only be overridden for foreign modules. * - * @return String: Origin name, 'local' for local modules + * @return string: Origin name, 'local' for local modules */ public function getSource() { // Stub, override expected @@ -263,7 +263,7 @@ abstract class ResourceLoaderModule { /** * Get the loader JS for this module, if set. * - * @return Mixed: JavaScript loader code as a string or boolean false if no custom loader set + * @return mixed: JavaScript loader code as a string or boolean false if no custom loader set */ public function getLoaderScript() { // Stub, override expected @@ -274,16 +274,11 @@ abstract class ResourceLoaderModule { * Get a list of modules this module depends on. * * Dependency information is taken into account when loading a module - * on the client side. When adding a module on the server side, - * dependency information is NOT taken into account and YOU are - * responsible for adding dependent modules as well. If you don't do - * this, the client side loader will send a second request back to the - * server to fetch the missing modules, which kind of defeats the - * purpose of the resource loader. + * on the client side. * * To add dependencies dynamically on the client side, use a custom * loader script, see getLoaderScript() - * @return Array: List of module names as strings + * @return array: List of module names as strings */ public function getDependencies() { // Stub, override expected @@ -293,7 +288,7 @@ abstract class ResourceLoaderModule { /** * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile'] * - * @return array of strings + * @return array: Array of strings */ public function getTargets() { return $this->targets; @@ -304,7 +299,7 @@ abstract class ResourceLoaderModule { * Currently these are only image files referenced by the module's CSS. * * @param string $skin Skin name - * @return Array: List of files + * @return array: List of files */ public function getFileDependencies( $skin ) { // Try in-object cache first @@ -319,7 +314,7 @@ abstract class ResourceLoaderModule { ), __METHOD__ ); if ( !is_null( $deps ) ) { - $this->fileDeps[$skin] = (array) FormatJson::decode( $deps, true ); + $this->fileDeps[$skin] = (array)FormatJson::decode( $deps, true ); } else { $this->fileDeps[$skin] = array(); } @@ -340,7 +335,7 @@ abstract class ResourceLoaderModule { * Get the last modification timestamp of the message blob for this * module in a given language. * @param string $lang Language code - * @return Integer: UNIX timestamp, or 0 if the module doesn't have messages + * @return int: UNIX timestamp, or 0 if the module doesn't have messages */ public function getMsgBlobMtime( $lang ) { if ( !isset( $this->msgBlobMtime[$lang] ) ) { @@ -387,22 +382,67 @@ abstract class ResourceLoaderModule { * If you want this to happen, you'll need to call getMsgBlobMtime() * yourself and take its result into consideration. * - * @param $context ResourceLoaderContext: Context object - * @return Integer: UNIX timestamp + * NOTE: The mtime of the module's hash is NOT automatically included. + * If your module provides a getModifiedHash() method, you'll need to call getHashMtime() + * yourself and take its result into consideration. + * + * @param ResourceLoaderContext $context Context object + * @return integer UNIX timestamp */ public function getModifiedTime( ResourceLoaderContext $context ) { // 0 would mean now return 1; } + /** + * Helper method for calculating when the module's hash (if it has one) changed. + * + * @param ResourceLoaderContext $context + * @return integer: UNIX timestamp or 0 if there is no hash provided + */ + public function getHashMtime( ResourceLoaderContext $context ) { + $hash = $this->getModifiedHash( $context ); + if ( !is_string( $hash ) ) { + return 0; + } + + $cache = wfGetCache( CACHE_ANYTHING ); + $key = wfMemcKey( 'resourceloader', 'modulemodifiedhash', $this->getName() ); + + $data = $cache->get( $key ); + if ( is_array( $data ) && $data['hash'] === $hash ) { + // Hash is still the same, re-use the timestamp of when we first saw this hash. + return $data['timestamp']; + } + + $timestamp = wfTimestamp(); + $cache->set( $key, array( + 'hash' => $hash, + 'timestamp' => $timestamp, + ) ); + + return $timestamp; + } + + /** + * Get the last modification timestamp of the message blob for this + * module in a given language. + * + * @param ResourceLoaderContext $context + * @return string|null: Hash + */ + public function getModifiedHash( ResourceLoaderContext $context ) { + return null; + } + /** * Check whether this module is known to be empty. If a child class * has an easy and cheap way to determine that this module is * definitely going to be empty, it should override this method to * return true in that case. Callers may optimize the request for this * module away if this function returns true. - * @param $context ResourceLoaderContext: Context object - * @return Boolean + * @param ResourceLoaderContext $context + * @return bool */ public function isKnownEmpty( ResourceLoaderContext $context ) { return false; @@ -418,7 +458,7 @@ abstract class ResourceLoaderModule { * * @param string $fileName * @param string $contents - * @return string JS with the original, or a replacement error + * @return string: JS with the original, or a replacement error */ protected function validateScriptFile( $fileName, $contents ) { global $wgResourceLoaderValidateJS; diff --git a/includes/resourceloader/ResourceLoaderSiteModule.php b/includes/resourceloader/ResourceLoaderSiteModule.php index 1cc5c1a9..05754d37 100644 --- a/includes/resourceloader/ResourceLoaderSiteModule.php +++ b/includes/resourceloader/ResourceLoaderSiteModule.php @@ -37,20 +37,19 @@ class ResourceLoaderSiteModule extends ResourceLoaderWikiModule { * @return Array: List of pages */ protected function getPages( ResourceLoaderContext $context ) { - global $wgHandheldStyle; + global $wgUseSiteJs, $wgUseSiteCss; - $pages = array( - 'MediaWiki:Common.js' => array( 'type' => 'script' ), - 'MediaWiki:Common.css' => array( 'type' => 'style' ), - 'MediaWiki:' . ucfirst( $context->getSkin() ) . '.js' => array( 'type' => 'script' ), - 'MediaWiki:' . ucfirst( $context->getSkin() ) . '.css' => array( 'type' => 'style' ), - 'MediaWiki:Print.css' => array( 'type' => 'style', 'media' => 'print' ), - ); - if ( $wgHandheldStyle ) { - $pages['MediaWiki:Handheld.css'] = array( - 'type' => 'style', - 'media' => 'handheld' ); + $pages = array(); + if ( $wgUseSiteJs ) { + $pages['MediaWiki:Common.js'] = array( 'type' => 'script' ); + $pages['MediaWiki:' . ucfirst( $context->getSkin() ) . '.js'] = array( 'type' => 'script' ); } + if ( $wgUseSiteCss ) { + $pages['MediaWiki:Common.css'] = array( 'type' => 'style' ); + $pages['MediaWiki:' . ucfirst( $context->getSkin() ) . '.css'] = array( 'type' => 'style' ); + + } + $pages['MediaWiki:Print.css'] = array( 'type' => 'style', 'media' => 'print' ); return $pages; } diff --git a/includes/resourceloader/ResourceLoaderStartUpModule.php b/includes/resourceloader/ResourceLoaderStartUpModule.php index 32cf6b26..20f6e0ba 100644 --- a/includes/resourceloader/ResourceLoaderStartUpModule.php +++ b/includes/resourceloader/ResourceLoaderStartUpModule.php @@ -27,6 +27,7 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule { /* Protected Members */ protected $modifiedTime = array(); + protected $targets = array( 'desktop', 'mobile' ); /* Protected Methods */ @@ -51,7 +52,7 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule { */ $namespaceIds = $wgContLang->getNamespaceIds(); $caseSensitiveNamespaces = array(); - foreach( MWNamespace::getCanonicalNamespaces() as $index => $name ) { + foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) { $namespaceIds[$wgContLang->lc( $name )] = $index; if ( !MWNamespace::isCapitalized( $index ) ) { $caseSensitiveNamespaces[] = $index; @@ -83,7 +84,7 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule { 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), 'wgNamespaceIds' => $namespaceIds, 'wgSiteName' => $wgSitename, - 'wgFileExtensions' => array_values( $wgFileExtensions ), + 'wgFileExtensions' => array_values( array_unique( $wgFileExtensions ) ), 'wgDBname' => $wgDBname, // This sucks, it is only needed on Special:Upload, but I could // not find a way to add vars only for a certain module @@ -94,6 +95,7 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule { 'wgCookiePrefix' => $wgCookiePrefix, 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength, 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces, + 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ), ); wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$vars ) ); @@ -184,7 +186,7 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule { * @return string */ public function getScript( ResourceLoaderContext $context ) { - global $IP, $wgLoadScript, $wgLegacyJavaScriptGlobals; + global $IP, $wgLegacyJavaScriptGlobals; $out = file_get_contents( "$IP/resources/startup.js" ); if ( $context->getOnly() === 'scripts' ) { @@ -224,7 +226,7 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule { "};\n"; // Conditional script injection - $scriptTag = Html::linkedScript( $wgLoadScript . '?' . wfArrayToCgi( $query ) ); + $scriptTag = Html::linkedScript( wfAppendQuery( wfScript( 'load' ), $query ) ); $out .= "if ( isCompatible() ) {\n" . "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) . "}\n" . diff --git a/includes/resourceloader/ResourceLoaderUserCSSPrefsModule.php b/includes/resourceloader/ResourceLoaderUserCSSPrefsModule.php index bdb240e0..bda86539 100644 --- a/includes/resourceloader/ResourceLoaderUserCSSPrefsModule.php +++ b/includes/resourceloader/ResourceLoaderUserCSSPrefsModule.php @@ -56,43 +56,44 @@ class ResourceLoaderUserCSSPrefsModule extends ResourceLoaderModule { public function getStyles( ResourceLoaderContext $context ) { global $wgAllowUserCssPrefs, $wgUser; - if ( $wgAllowUserCssPrefs ) { - $options = $wgUser->getOptions(); + if ( !$wgAllowUserCssPrefs ) { + return array(); + } - // Build CSS rules - $rules = array(); + $options = $wgUser->getOptions(); - // Underline: 2 = browser default, 1 = always, 0 = never - if ( $options['underline'] < 2 ) { - $rules[] = "a { text-decoration: " . - ( $options['underline'] ? 'underline' : 'none' ) . "; }"; - } else { - # The scripts of these languages are very hard to read with underlines - $rules[] = 'a:lang(ar), a:lang(ckb), a:lang(fa),a:lang(kk-arab), ' . - 'a:lang(mzn), a:lang(ps), a:lang(ur) { text-decoration: none; }'; - } - if ( $options['justify'] ) { - $rules[] = "#article, #bodyContent, #mw_content { text-align: justify; }\n"; - } - if ( !$options['showtoc'] ) { - $rules[] = "#toc { display: none; }\n"; - } - if ( !$options['editsection'] ) { - $rules[] = ".editsection { display: none; }\n"; - } - if ( $options['editfont'] !== 'default' ) { - // Double-check that $options['editfont'] consists of safe characters only - if ( preg_match( '/^[a-zA-Z0-9_, -]+$/', $options['editfont'] ) ) { - $rules[] = "textarea { font-family: {$options['editfont']}; }\n"; - } - } - $style = implode( "\n", $rules ); - if ( $this->getFlip( $context ) ) { - $style = CSSJanus::transform( $style, true, false ); + // Build CSS rules + $rules = array(); + + // Underline: 2 = browser default, 1 = always, 0 = never + if ( $options['underline'] < 2 ) { + $rules[] = "a { text-decoration: " . + ( $options['underline'] ? 'underline' : 'none' ) . "; }"; + } else { + # The scripts of these languages are very hard to read with underlines + $rules[] = 'a:lang(ar), a:lang(ckb), a:lang(kk-arab), ' . + 'a:lang(mzn), a:lang(ps), a:lang(ur) { text-decoration: none; }'; + } + if ( $options['justify'] ) { + $rules[] = "#article, #bodyContent, #mw_content { text-align: justify; }\n"; + } + if ( !$options['showtoc'] ) { + $rules[] = "#toc { display: none; }\n"; + } + if ( !$options['editsection'] ) { + $rules[] = ".mw-editsection { display: none; }\n"; + } + if ( $options['editfont'] !== 'default' ) { + // Double-check that $options['editfont'] consists of safe characters only + if ( preg_match( '/^[a-zA-Z0-9_, -]+$/', $options['editfont'] ) ) { + $rules[] = "textarea { font-family: {$options['editfont']}; }\n"; } - return array( 'all' => $style ); } - return array(); + $style = implode( "\n", $rules ); + if ( $this->getFlip( $context ) ) { + $style = CSSJanus::transform( $style, true, false ); + } + return array( 'all' => $style ); } /** diff --git a/includes/resourceloader/ResourceLoaderUserGroupsModule.php b/includes/resourceloader/ResourceLoaderUserGroupsModule.php index 1316f423..9064263f 100644 --- a/includes/resourceloader/ResourceLoaderUserGroupsModule.php +++ b/includes/resourceloader/ResourceLoaderUserGroupsModule.php @@ -33,12 +33,15 @@ class ResourceLoaderUserGroupsModule extends ResourceLoaderWikiModule { * @return array */ protected function getPages( ResourceLoaderContext $context ) { - global $wgUser; + global $wgUser, $wgUseSiteJs, $wgUseSiteCss; $userName = $context->getUser(); if ( $userName === null ) { return array(); } + if ( !$wgUseSiteJs && !$wgUseSiteCss ) { + return array(); + } // Use $wgUser is possible; allows to skip a lot of code if ( is_object( $wgUser ) && $wgUser->getName() == $userName ) { @@ -51,12 +54,16 @@ class ResourceLoaderUserGroupsModule extends ResourceLoaderWikiModule { } $pages = array(); - foreach( $user->getEffectiveGroups() as $group ) { + foreach ( $user->getEffectiveGroups() as $group ) { if ( in_array( $group, array( '*', 'user' ) ) ) { continue; } - $pages["MediaWiki:Group-$group.js"] = array( 'type' => 'script' ); - $pages["MediaWiki:Group-$group.css"] = array( 'type' => 'style' ); + if ( $wgUseSiteJs ) { + $pages["MediaWiki:Group-$group.js"] = array( 'type' => 'script' ); + } + if ( $wgUseSiteCss ) { + $pages["MediaWiki:Group-$group.css"] = array( 'type' => 'style' ); + } } return $pages; } diff --git a/includes/resourceloader/ResourceLoaderUserModule.php b/includes/resourceloader/ResourceLoaderUserModule.php index 177302c5..7a04e473 100644 --- a/includes/resourceloader/ResourceLoaderUserModule.php +++ b/includes/resourceloader/ResourceLoaderUserModule.php @@ -35,11 +35,15 @@ class ResourceLoaderUserModule extends ResourceLoaderWikiModule { * @return array */ protected function getPages( ResourceLoaderContext $context ) { + global $wgAllowUserJs, $wgAllowUserCss; $username = $context->getUser(); if ( $username === null ) { return array(); } + if ( !$wgAllowUserJs && !$wgAllowUserCss ) { + return array(); + } // Get the normalized title of the user's user page $userpageTitle = Title::makeTitleSafe( NS_USER, $username ); @@ -50,14 +54,15 @@ class ResourceLoaderUserModule extends ResourceLoaderWikiModule { $userpage = $userpageTitle->getPrefixedDBkey(); // Needed so $excludepages works - $pages = array( - "$userpage/common.js" => array( 'type' => 'script' ), - "$userpage/" . $context->getSkin() . '.js' => - array( 'type' => 'script' ), - "$userpage/common.css" => array( 'type' => 'style' ), - "$userpage/" . $context->getSkin() . '.css' => - array( 'type' => 'style' ), - ); + $pages = array(); + if ( $wgAllowUserJs ) { + $pages["$userpage/common.js"] = array( 'type' => 'script' ); + $pages["$userpage/" . $context->getSkin() . '.js'] = array( 'type' => 'script' ); + } + if ( $wgAllowUserCss ) { + $pages["$userpage/common.css"] = array( 'type' => 'style' ); + $pages["$userpage/" . $context->getSkin() . '.css'] = array( 'type' => 'style' ); + } // Hack for bug 26283: if we're on a preview page for a CSS/JS page, // we need to exclude that page from this module. In that case, the excludepage diff --git a/includes/resourceloader/ResourceLoaderUserOptionsModule.php b/includes/resourceloader/ResourceLoaderUserOptionsModule.php index 4624cbce..0b7e1964 100644 --- a/includes/resourceloader/ResourceLoaderUserOptionsModule.php +++ b/includes/resourceloader/ResourceLoaderUserOptionsModule.php @@ -56,7 +56,9 @@ class ResourceLoaderUserOptionsModule extends ResourceLoaderModule { public function getScript( ResourceLoaderContext $context ) { global $wgUser; return Xml::encodeJsCall( 'mw.user.options.set', - array( $wgUser->getOptions() ) ); + array( $wgUser->getOptions() ), + ResourceLoader::inDebugMode() + ); } /** diff --git a/includes/resourceloader/ResourceLoaderUserTokensModule.php b/includes/resourceloader/ResourceLoaderUserTokensModule.php index 6d787c50..92ebbe93 100644 --- a/includes/resourceloader/ResourceLoaderUserTokensModule.php +++ b/includes/resourceloader/ResourceLoaderUserTokensModule.php @@ -35,10 +35,9 @@ class ResourceLoaderUserTokensModule extends ResourceLoaderModule { /** * Fetch the tokens for the current user. * - * @param $context ResourceLoaderContext: Context object - * @return Array: List of tokens keyed by token type + * @return array: List of tokens keyed by token type */ - protected function contextUserTokens( ResourceLoaderContext $context ) { + protected function contextUserTokens() { global $wgUser; return array( @@ -54,7 +53,9 @@ class ResourceLoaderUserTokensModule extends ResourceLoaderModule { */ public function getScript( ResourceLoaderContext $context ) { return Xml::encodeJsCall( 'mw.user.tokens.set', - array( $this->contextUserTokens( $context ) ) ); + array( $this->contextUserTokens() ), + ResourceLoader::inDebugMode() + ); } /** diff --git a/includes/resourceloader/ResourceLoaderWikiModule.php b/includes/resourceloader/ResourceLoaderWikiModule.php index 6c60d474..3f10ae53 100644 --- a/includes/resourceloader/ResourceLoaderWikiModule.php +++ b/includes/resourceloader/ResourceLoaderWikiModule.php @@ -92,14 +92,14 @@ abstract class ResourceLoaderWikiModule extends ResourceLoaderModule { $content = $revision->getContent( Revision::RAW ); if ( !$content ) { - wfDebug( __METHOD__ . "failed to load content of JS/CSS page!\n" ); + wfDebugLog( 'resourceloader', __METHOD__ . ': failed to load content of JS/CSS page!' ); return null; } $model = $content->getModel(); if ( $model !== CONTENT_MODEL_CSS && $model !== CONTENT_MODEL_JAVASCRIPT ) { - wfDebug( __METHOD__ . "bad content model $model for JS/CSS page!\n" ); + wfDebugLog( 'resourceloader', __METHOD__ . ': bad content model $model for JS/CSS page!' ); return null; } -- cgit v1.2.2