summaryrefslogtreecommitdiff
path: root/includes/resourceloader
diff options
context:
space:
mode:
authorPierre Schmitz <pierre@archlinux.de>2012-05-03 13:01:35 +0200
committerPierre Schmitz <pierre@archlinux.de>2012-05-03 13:01:35 +0200
commitd9022f63880ce039446fba8364f68e656b7bf4cb (patch)
tree16b40fbf17bf7c9ee6f4ead25b16dd192378050a /includes/resourceloader
parent27cf83d177256813e2e802241085fce5dd0f3fb9 (diff)
Update to MediaWiki 1.19.0
Diffstat (limited to 'includes/resourceloader')
-rw-r--r--includes/resourceloader/ResourceLoader.php390
-rw-r--r--includes/resourceloader/ResourceLoaderContext.php32
-rw-r--r--includes/resourceloader/ResourceLoaderFileModule.php99
-rw-r--r--includes/resourceloader/ResourceLoaderFilePageModule.php7
-rw-r--r--includes/resourceloader/ResourceLoaderModule.php99
-rw-r--r--includes/resourceloader/ResourceLoaderStartUpModule.php51
-rw-r--r--includes/resourceloader/ResourceLoaderUserCSSPrefsModule.php113
-rw-r--r--includes/resourceloader/ResourceLoaderUserModule.php25
-rw-r--r--includes/resourceloader/ResourceLoaderUserOptionsModule.php53
-rw-r--r--includes/resourceloader/ResourceLoaderUserTokensModule.php6
-rw-r--r--includes/resourceloader/ResourceLoaderWikiModule.php57
11 files changed, 690 insertions, 242 deletions
diff --git a/includes/resourceloader/ResourceLoader.php b/includes/resourceloader/ResourceLoader.php
index 01b70e8e..9175b10d 100644
--- a/includes/resourceloader/ResourceLoader.php
+++ b/includes/resourceloader/ResourceLoader.php
@@ -29,12 +29,21 @@
class ResourceLoader {
/* Protected Static Members */
- protected static $filterCacheVersion = 4;
+ protected static $filterCacheVersion = 7;
+ protected static $requiredSourceProperties = array( 'loadScript' );
/** Array: List of module name/ResourceLoaderModule object pairs */
protected $modules = array();
+
/** Associative array mapping module name to info associative array */
protected $moduleInfos = array();
+
+ /** Associative array mapping framework ids to a list of names of test suite modules */
+ /** like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. ) */
+ protected $testModuleNames = array();
+
+ /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
+ protected $sources = array();
/* Protected Methods */
@@ -178,16 +187,27 @@ class ResourceLoader {
* Registers core modules and runs registration hooks.
*/
public function __construct() {
- global $IP, $wgResourceModules;
+ global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
wfProfileIn( __METHOD__ );
+ // Add 'local' source first
+ $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
+
+ // Add other sources
+ $this->addSource( $wgResourceLoaderSources );
+
// Register core modules
$this->register( include( "$IP/resources/Resources.php" ) );
// Register extension modules
wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
$this->register( $wgResourceModules );
+ if ( $wgEnableJavaScriptTest === true ) {
+ $this->registerTestModules();
+ }
+
+
wfProfileOut( __METHOD__ );
}
@@ -208,49 +228,114 @@ class ResourceLoader {
wfProfileIn( __METHOD__ );
// Allow multiple modules to be registered in one call
- if ( is_array( $name ) ) {
- foreach ( $name as $key => $value ) {
- $this->register( $key, $value );
+ $registrations = is_array( $name ) ? $name : array( $name => $info );
+ foreach ( $registrations as $name => $info ) {
+ // Disallow duplicate registrations
+ if ( isset( $this->moduleInfos[$name] ) ) {
+ // A module has already been registered by this name
+ throw new MWException(
+ 'ResourceLoader duplicate registration error. ' .
+ 'Another module has already been registered as ' . $name
+ );
+ }
+
+ // Check $name for illegal characters
+ if ( preg_match( '/[|,!]/', $name ) ) {
+ throw new MWException( "ResourceLoader module name '$name' is invalid. Names may not contain pipes (|), commas (,) or exclamation marks (!)" );
+ }
+
+ // Attach module
+ if ( is_object( $info ) ) {
+ // Old calling convention
+ // Validate the input
+ if ( !( $info instanceof ResourceLoaderModule ) ) {
+ throw new MWException( 'ResourceLoader invalid module error. ' .
+ 'Instances of ResourceLoaderModule expected.' );
+ }
+
+ $this->moduleInfos[$name] = array( 'object' => $info );
+ $info->setName( $name );
+ $this->modules[$name] = $info;
+ } else {
+ // New calling convention
+ $this->moduleInfos[$name] = $info;
}
- wfProfileOut( __METHOD__ );
- return;
}
- // Disallow duplicate registrations
- if ( isset( $this->moduleInfos[$name] ) ) {
- // A module has already been registered by this name
- throw new MWException(
- 'ResourceLoader duplicate registration error. ' .
- 'Another module has already been registered as ' . $name
- );
+ wfProfileOut( __METHOD__ );
+ }
+
+ /**
+ */
+ public function registerTestModules() {
+ global $IP, $wgEnableJavaScriptTest;
+
+ if ( $wgEnableJavaScriptTest !== true ) {
+ throw new MWException( 'Attempt to register JavaScript test modules but <tt>$wgEnableJavaScriptTest</tt> is false. Edit your <tt>LocalSettings.php</tt> to enable it.' );
}
- // Check $name for illegal characters
- if ( preg_match( '/[|,!]/', $name ) ) {
- throw new MWException( "ResourceLoader module name '$name' is invalid. Names may not contain pipes (|), commas (,) or exclamation marks (!)" );
+ wfProfileIn( __METHOD__ );
+
+ // Get core test suites
+ $testModules = array();
+ $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';
}
- // Attach module
- if ( is_object( $info ) ) {
- // Old calling convention
- // Validate the input
- if ( !( $info instanceof ResourceLoaderModule ) ) {
- throw new MWException( 'ResourceLoader invalid module error. ' .
- 'Instances of ResourceLoaderModule expected.' );
- }
+ foreach( $testModules as $id => $names ) {
+ // Register test modules
+ $this->register( $testModules[$id] );
- $this->moduleInfos[$name] = array( 'object' => $info );
- $info->setName( $name );
- $this->modules[$name] = $info;
- } else {
- // New calling convention
- $this->moduleInfos[$name] = $info;
+ // Keep track of their names so that they can be loaded together
+ $this->testModuleNames[$id] = array_keys( $testModules[$id] );
}
wfProfileOut( __METHOD__ );
}
- /**
+ /**
+ * Add a foreign source of modules.
+ *
+ * Source properties:
+ * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
+ *
+ * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
+ * @param $properties Array: source properties
+ */
+ public function addSource( $id, $properties = null) {
+ // Allow multiple sources to be registered in one call
+ if ( is_array( $id ) ) {
+ foreach ( $id as $key => $value ) {
+ $this->addSource( $key, $value );
+ }
+ return;
+ }
+
+ // Disallow duplicates
+ if ( isset( $this->sources[$id] ) ) {
+ throw new MWException(
+ 'ResourceLoader duplicate source addition error. ' .
+ 'Another source has already been registered as ' . $id
+ );
+ }
+
+ // Validate properties
+ foreach ( self::$requiredSourceProperties as $prop ) {
+ if ( !isset( $properties[$prop] ) ) {
+ throw new MWException( "Required property $prop missing from source ID $id" );
+ }
+ }
+
+ $this->sources[$id] = $properties;
+ }
+
+ /**
* Get a list of module names
*
* @return Array: List of module names
@@ -258,6 +343,25 @@ class ResourceLoader {
public function getModuleNames() {
return array_keys( $this->moduleInfos );
}
+
+ /**
+ * Get a list of test module names for one (or all) frameworks.
+ * If the given framework id is unknkown, or if the in-object variable is not an array,
+ * then it will return an empty array.
+ *
+ * @param $framework String: Optional. Get only the test module names for one
+ * particular framework.
+ * @return Array
+ */
+ public function getTestModuleNames( $framework = 'all' ) {
+ if ( $framework == 'all' ) {
+ return $this->testModuleNames;
+ } elseif ( isset( $this->testModuleNames[$framework] ) && is_array( $this->testModuleNames[$framework] ) ) {
+ return $this->testModuleNames[$framework];
+ } else {
+ return array();
+ }
+ }
/**
* Get the ResourceLoaderModule object for a given module name.
@@ -292,12 +396,29 @@ class ResourceLoader {
}
/**
+ * Get the list of sources
+ *
+ * @return Array: array( id => array of properties, .. )
+ */
+ public function getSources() {
+ return $this->sources;
+ }
+
+ /**
* Outputs a response to a resource load-request, including a content-type header.
*
* @param $context ResourceLoaderContext: Context in which a response should be formed
*/
public function respond( ResourceLoaderContext $context ) {
- global $wgResourceLoaderMaxage, $wgCacheEpoch;
+ global $wgCacheEpoch, $wgUseFileCache;
+
+ // Use file cache if enabled and available...
+ if ( $wgUseFileCache ) {
+ $fileCache = ResourceFileCache::newFromContext( $context );
+ if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
+ return; // output handled
+ }
+ }
// Buffer output to catch warnings. Normally we'd use ob_clean() on the
// top-level output buffer to clear warnings, but that breaks when ob_gzhandler
@@ -329,19 +450,6 @@ class ResourceLoader {
}
}
- // If a version wasn't specified we need a shorter expiry time for updates
- // to propagate to clients quickly
- if ( is_null( $context->getVersion() ) ) {
- $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
- $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
- }
- // If a version was specified we can use a longer expiry time since changing
- // version numbers causes cache misses
- else {
- $maxage = $wgResourceLoaderMaxage['versioned']['client'];
- $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
- }
-
// Preload information needed to the mtime calculation below
try {
$this->preloadModuleInfo( array_keys( $modules ), $context );
@@ -356,6 +464,9 @@ class ResourceLoader {
// the last modified time
$mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
foreach ( $modules as $module ) {
+ /**
+ * @var $module ResourceLoaderModule
+ */
try {
// Calculate maximum modified time
$mtime = max( $mtime, $module->getModifiedTime( $context ) );
@@ -367,6 +478,65 @@ class ResourceLoader {
wfProfileOut( __METHOD__.'-getModifiedTime' );
+ // Send content type and cache related headers
+ $this->sendResponseHeaders( $context, $mtime );
+
+ // If there's an If-Modified-Since header, respond with a 304 appropriately
+ if ( $this->tryRespondLastModified( $context, $mtime ) ) {
+ wfProfileOut( __METHOD__ );
+ return; // output handled (buffers cleared)
+ }
+
+ // Generate a response
+ $response = $this->makeModuleResponse( $context, $modules, $missing );
+
+ // Prepend comments indicating exceptions
+ $response = $errors . $response;
+
+ // 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;
+ }
+
+ // Remove the output buffer and output the response
+ ob_end_clean();
+ echo $response;
+
+ // Save response to file cache unless there are errors
+ if ( isset( $fileCache ) && !$errors && !$missing ) {
+ // Cache single modules...and other requests if there are enough hits
+ if ( ResourceFileCache::useFileCache( $context ) ) {
+ if ( $fileCache->isCacheWorthy() ) {
+ $fileCache->saveText( $response );
+ } else {
+ $fileCache->incrMissesRecent( $context->getRequest() );
+ }
+ }
+ }
+
+ wfProfileOut( __METHOD__ );
+ }
+
+ /**
+ * Send content type and last modified headers to the client.
+ * @param $context ResourceLoaderContext
+ * @param $mtime string TS_MW timestamp to use for last-modified
+ * @return void
+ */
+ protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime ) {
+ global $wgResourceLoaderMaxage;
+ // If a version wasn't specified we need a shorter expiry time for updates
+ // to propagate to clients quickly
+ if ( is_null( $context->getVersion() ) ) {
+ $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
+ $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
+ // If a version was specified we can use a longer expiry time since changing
+ // version numbers causes cache misses
+ } else {
+ $maxage = $wgResourceLoaderMaxage['versioned']['client'];
+ $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
+ }
if ( $context->getOnly() === 'styles' ) {
header( 'Content-Type: text/css; charset=utf-8' );
} else {
@@ -382,7 +552,16 @@ class ResourceLoader {
$exp = min( $maxage, $smaxage );
header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
}
+ }
+ /**
+ * If there's an If-Modified-Since header, respond with a 304 appropriately
+ * and clear out the output buffer. If the client cache is too old then do nothing.
+ * @param $context ResourceLoaderContext
+ * @param $mtime string The TS_MW timestamp to check the header against
+ * @return bool True iff 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
// Some clients send "timestamp;length=123". Strip the part after the first ';'
// so we get a valid timestamp.
@@ -410,28 +589,61 @@ class ResourceLoader {
header( 'HTTP/1.0 304 Not Modified' );
header( 'Status: 304 Not Modified' );
- wfProfileOut( __METHOD__ );
- return;
+ return true;
}
}
+ return false;
+ }
- // Generate a response
- $response = $this->makeModuleResponse( $context, $modules, $missing );
-
- // Prepend comments indicating exceptions
- $response = $errors . $response;
-
- // 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;
+ /**
+ * Send out code for a response from file cache if possible
+ *
+ * @param $fileCache ObjectFileCache: Cache object for this request URL
+ * @param $context ResourceLoaderContext: Context in which to generate a response
+ * @return bool If this found a cache file and handled the response
+ */
+ protected function tryRespondFromFileCache(
+ ResourceFileCache $fileCache, ResourceLoaderContext $context
+ ) {
+ global $wgResourceLoaderMaxage;
+ // Buffer output to catch warnings.
+ ob_start();
+ // Get the maximum age the cache can be
+ $maxage = is_null( $context->getVersion() )
+ ? $wgResourceLoaderMaxage['unversioned']['server']
+ : $wgResourceLoaderMaxage['versioned']['server'];
+ // Minimum timestamp the cache file must have
+ $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
+ 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
+ $good = $fileCache->isCacheGood(); // cache existence check
+ }
}
-
- // Remove the output buffer and output the response
+ if ( $good ) {
+ $ts = $fileCache->cacheTimestamp();
+ // Send content type and cache headers
+ $this->sendResponseHeaders( $context, $ts, false );
+ // If there's an If-Modified-Since header, respond with a 304 appropriately
+ if ( $this->tryRespondLastModified( $context, $ts ) ) {
+ return false; // output handled (buffers cleared)
+ }
+ $response = $fileCache->fetchText();
+ // Capture any PHP warnings from the output buffer and append them to the
+ // response in a comment if we're in debug mode.
+ if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
+ $response = "/*\n$warnings\n*/\n" . $response;
+ }
+ // Remove the output buffer and output the response
+ ob_end_clean();
+ echo $response . "\n/* Cached {$ts} */";
+ return true; // cache hit
+ }
+ // Clear buffer
ob_end_clean();
- echo $response;
- wfProfileOut( __METHOD__ );
+ return false; // cache miss
}
protected function makeComment( $text ) {
@@ -471,6 +683,10 @@ class ResourceLoader {
// Generate output
foreach ( $modules as $name => $module ) {
+ /**
+ * @var $module ResourceLoaderModule
+ */
+
wfProfileIn( __METHOD__ . '-' . $name );
try {
$scripts = '';
@@ -509,8 +725,10 @@ class ResourceLoader {
switch ( $context->getOnly() ) {
case 'scripts':
if ( is_string( $scripts ) ) {
+ // Load scripts raw...
$out .= $scripts;
} elseif ( is_array( $scripts ) ) {
+ // ...except when $scripts is an array of URLs
$out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
}
break;
@@ -676,30 +894,31 @@ class ResourceLoader {
* @param $version Integer: Module version number as a timestamp
* @param $dependencies Array: List of module names on which this module depends
* @param $group String: Group which the module is in.
+ * @param $source String: Source of the module, or 'local' if not foreign.
* @param $script String: JavaScript code
*
* @return string
*/
- public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
+ public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
$script = str_replace( "\n", "\n\t", trim( $script ) );
return Xml::encodeJsCall(
- "( function( name, version, dependencies, group ) {\n\t$script\n} )",
- array( $name, $version, $dependencies, $group ) );
+ "( function( name, version, dependencies, group, source ) {\n\t$script\n} )",
+ array( $name, $version, $dependencies, $group, $source ) );
}
/**
* Returns JS code which calls mw.loader.register with the given
* parameters. Has three calling conventions:
*
- * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
+ * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
* Register a single module.
*
* - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
* Register modules with the given names.
*
* - ResourceLoader::makeLoaderRegisterScript( array(
- * array( $name1, $version1, $dependencies1, $group1 ),
- * array( $name2, $version2, $dependencies1, $group2 ),
+ * array( $name1, $version1, $dependencies1, $group1, $source1 ),
+ * array( $name2, $version2, $dependencies1, $group2, $source2 ),
* ...
* ) ):
* Registers modules with the given names and parameters.
@@ -708,18 +927,42 @@ class ResourceLoader {
* @param $version Integer: Module version number as a timestamp
* @param $dependencies Array: List of module names on which this module depends
* @param $group String: group which the module is in.
+ * @param $source String: source of the module, or 'local' if not foreign
*
* @return string
*/
public static function makeLoaderRegisterScript( $name, $version = null,
- $dependencies = null, $group = 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;
return Xml::encodeJsCall( 'mw.loader.register',
- array( $name, $version, $dependencies, $group ) );
+ array( $name, $version, $dependencies, $group, $source ) );
+ }
+ }
+
+ /**
+ * Returns JS code which calls mw.loader.addSource() with the given
+ * parameters. Has two calling conventions:
+ *
+ * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
+ * Register a single source
+ *
+ * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
+ * Register sources with the given IDs and properties.
+ *
+ * @param $id String: source ID
+ * @param $properties Array: source properties (see addSource())
+ *
+ * @return string
+ */
+ public static function makeLoaderSourcesScript( $id, $properties = null ) {
+ if ( is_array( $id ) ) {
+ return Xml::encodeJsCall( 'mw.loader.addSource', array( $id ) );
+ } else {
+ return Xml::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
}
}
@@ -732,8 +975,7 @@ class ResourceLoader {
* @return string
*/
public static function makeLoaderConditionalScript( $script ) {
- $script = str_replace( "\n", "\n\t", trim( $script ) );
- return "if(window.mw){\n\t$script\n}\n";
+ return "if(window.mw){\n".trim( $script )."\n}";
}
/**
@@ -809,7 +1051,7 @@ class ResourceLoader {
$query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
$only, $printable, $handheld, $extraQuery
);
-
+
// Prevent the IE6 extension check from being triggered (bug 28840)
// by appending a character that's invalid in Windows extensions ('*')
return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
@@ -844,7 +1086,7 @@ class ResourceLoader {
$query['handheld'] = 1;
}
$query += $extraQuery;
-
+
// Make queries uniform in order
ksort( $query );
return $query;
diff --git a/includes/resourceloader/ResourceLoaderContext.php b/includes/resourceloader/ResourceLoaderContext.php
index 326b7c4a..dd69bb01 100644
--- a/includes/resourceloader/ResourceLoaderContext.php
+++ b/includes/resourceloader/ResourceLoaderContext.php
@@ -21,7 +21,7 @@
*/
/**
- * Object passed around to modules which contains information about the state
+ * Object passed around to modules which contains information about the state
* of a specific loader request
*/
class ResourceLoaderContext {
@@ -42,7 +42,11 @@ class ResourceLoaderContext {
/* Methods */
- public function __construct( ResourceLoader $resourceLoader, WebRequest $request ) {
+ /**
+ * @param $resourceLoader ResourceLoader
+ * @param $request WebRequest
+ */
+ public function __construct( $resourceLoader, WebRequest $request ) {
global $wgDefaultSkin, $wgResourceLoaderDebug;
$this->resourceLoader = $resourceLoader;
@@ -59,11 +63,13 @@ class ResourceLoaderContext {
$this->only = $request->getVal( 'only' );
$this->version = $request->getVal( 'version' );
- if ( !$this->skin ) {
+ $skinnames = Skin::getSkinNames();
+ // If no skin is specified, or we don't recognize the skin, use the default skin
+ if ( !$this->skin || !isset( $skinnames[$this->skin] ) ) {
$this->skin = $wgDefaultSkin;
}
}
-
+
/**
* Expand a string of the form jquery.foo,bar|jquery.ui.baz,quux to
* an array of module names like array( 'jquery.foo', 'jquery.bar',
@@ -101,6 +107,14 @@ class ResourceLoaderContext {
}
/**
+ * Return a dummy ResourceLoaderContext object suitable for passing into things that don't "really" need a context
+ * @return ResourceLoaderContext
+ */
+ public static function newDummyContext() {
+ return new self( null, new FauxRequest( array() ) );
+ }
+
+ /**
* @return ResourceLoader
*/
public function getResourceLoader() {
@@ -150,14 +164,14 @@ class ResourceLoaderContext {
}
/**
- * @return string
+ * @return string|null
*/
public function getSkin() {
return $this->skin;
}
/**
- * @return string
+ * @return string|null
*/
public function getUser() {
return $this->user;
@@ -171,14 +185,14 @@ class ResourceLoaderContext {
}
/**
- * @return String
+ * @return String|null
*/
public function getOnly() {
return $this->only;
}
/**
- * @return String
+ * @return String|null
*/
public function getVersion() {
return $this->version;
@@ -211,7 +225,7 @@ class ResourceLoaderContext {
public function getHash() {
if ( !isset( $this->hash ) ) {
$this->hash = implode( '|', array(
- $this->getLanguage(), $this->getDirection(), $this->skin, $this->user,
+ $this->getLanguage(), $this->getDirection(), $this->skin, $this->user,
$this->debug, $this->only, $this->version
) );
}
diff --git a/includes/resourceloader/ResourceLoaderFileModule.php b/includes/resourceloader/ResourceLoaderFileModule.php
index f38c60ae..3d657e1c 100644
--- a/includes/resourceloader/ResourceLoaderFileModule.php
+++ b/includes/resourceloader/ResourceLoaderFileModule.php
@@ -33,47 +33,74 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
protected $remoteBasePath = '';
/**
* Array: List of paths to JavaScript files to always include
- * @example array( [file-path], [file-path], ... )
+ * @par Usage:
+ * @code
+ * array( [file-path], [file-path], ... )
+ * @endcode
*/
protected $scripts = array();
/**
* Array: List of JavaScript files to include when using a specific language
- * @example array( [language-code] => array( [file-path], [file-path], ... ), ... )
+ * @par Usage:
+ * @code
+ * array( [language-code] => array( [file-path], [file-path], ... ), ... )
+ * @endcode
*/
protected $languageScripts = array();
/**
* Array: List of JavaScript files to include when using a specific skin
- * @example array( [skin-name] => array( [file-path], [file-path], ... ), ... )
+ * @par Usage:
+ * @code
+ * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
+ * @endcode
*/
protected $skinScripts = array();
/**
* Array: List of paths to JavaScript files to include in debug mode
- * @example array( [skin-name] => array( [file-path], [file-path], ... ), ... )
+ * @par Usage:
+ * @code
+ * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
+ * @endcode
*/
protected $debugScripts = array();
/**
* Array: List of paths to JavaScript files to include in the startup module
- * @example array( [file-path], [file-path], ... )
+ * @par Usage:
+ * @code
+ * array( [file-path], [file-path], ... )
+ * @endcode
*/
protected $loaderScripts = array();
/**
* Array: List of paths to CSS files to always include
- * @example array( [file-path], [file-path], ... )
+ * @par Usage:
+ * @code
+ * array( [file-path], [file-path], ... )
+ * @endcode
*/
protected $styles = array();
/**
* Array: List of paths to CSS files to include when using specific skins
- * @example array( [file-path], [file-path], ... )
+ * @par Usage:
+ * @code
+ * array( [file-path], [file-path], ... )
+ * @endcode
*/
protected $skinStyles = array();
/**
* Array: List of modules this module depends on
- * @example array( [file-path], [file-path], ... )
+ * @par Usage:
+ * @code
+ * array( [file-path], [file-path], ... )
+ * @endcode
*/
protected $dependencies = array();
/**
* Array: List of message keys used by this module
- * @example array( [message-key], [message-key], ... )
+ * @par Usage:
+ * @code
+ * array( [message-key], [message-key], ... )
+ * @endcode
*/
protected $messages = array();
/** String: Name of group to load this module in */
@@ -84,12 +111,18 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
protected $debugRaw = true;
/**
* Array: Cache for mtime
- * @example array( [hash] => [mtime], [hash] => [mtime], ... )
+ * @par Usage:
+ * @code
+ * array( [hash] => [mtime], [hash] => [mtime], ... )
+ * @endcode
*/
protected $modifiedTime = array();
/**
* Array: Place where readStyleFile() tracks file dependencies
- * @example array( [file-path], [file-path], ... )
+ * @par Usage:
+ * @code
+ * array( [file-path], [file-path], ... )
+ * @endcode
*/
protected $localFileRefs = array();
@@ -106,6 +139,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
* to $wgScriptPath
*
* Below is a description for the $options array:
+ * @par Construction options:
* @code
* array(
* // Base path to prepend to all local paths in $options. Defaults to $IP
@@ -223,7 +257,11 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
$files = $this->getScriptFiles( $context );
return $this->readScriptFiles( $files );
}
-
+
+ /**
+ * @param $context ResourceLoaderContext
+ * @return array
+ */
public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
$urls = array();
foreach ( $this->getScriptFiles( $context ) as $file ) {
@@ -232,6 +270,9 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
return $urls;
}
+ /**
+ * @return bool
+ */
public function supportsURLLoading() {
return $this->debugRaw;
}
@@ -275,6 +316,10 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
return $styles;
}
+ /**
+ * @param $context ResourceLoaderContext
+ * @return array
+ */
public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
$urls = array();
foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
@@ -377,7 +422,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
}
wfProfileIn( __METHOD__.'-filemtime' );
- $filesMtime = max( array_map( 'filemtime', $files ) );
+ $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
wfProfileOut( __METHOD__.'-filemtime' );
$this->modifiedTime[$context->getHash()] = max(
$filesMtime,
@@ -503,10 +548,10 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
$js = '';
foreach ( array_unique( $scripts ) as $fileName ) {
$localPath = $this->getLocalPath( $fileName );
- $contents = file_get_contents( $localPath );
- if ( $contents === false ) {
+ if ( !file_exists( $localPath ) ) {
throw new MWException( __METHOD__.": script file not found: \"$localPath\"" );
}
+ $contents = file_get_contents( $localPath );
if ( $wgResourceLoaderValidateStaticJS ) {
// Static files don't really need to be checked as often; unlike
// on-wiki module they shouldn't change unexpectedly without
@@ -552,17 +597,18 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
*
* This method can be used as a callback for array_map()
*
- * @param $path String: File path of script file to read
+ * @param $path String: File path of style file to read
* @param $flip bool
*
* @return String: CSS data in script file
+ * @throws MWException if the file doesn't exist
*/
protected function readStyleFile( $path, $flip ) {
$localPath = $this->getLocalPath( $path );
- $style = file_get_contents( $localPath );
- if ( $style === false ) {
+ if ( !file_exists( $localPath ) ) {
throw new MWException( __METHOD__.": style file not found: \"$localPath\"" );
}
+ $style = file_get_contents( $localPath );
if ( $flip ) {
$style = CSSJanus::transform( $style, true, false );
}
@@ -583,6 +629,23 @@ class ResourceLoaderFileModule extends ResourceLoaderModule {
}
/**
+ * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
+ * but returns 1 instead.
+ * @param $filename string File name
+ * @return int UNIX timestamp, or 1 if the file doesn't exist
+ */
+ protected static function safeFilemtime( $filename ) {
+ if ( file_exists( $filename ) ) {
+ return filemtime( $filename );
+ } else {
+ // We only ever map this function on an array if we're gonna call max() after,
+ // so return our standard minimum timestamps here. This is 1, not 0, because
+ // wfTimestamp(0) == NOW
+ return 1;
+ }
+ }
+
+ /**
* Get whether CSS for this module should be flipped
* @param $context ResourceLoaderContext
* @return bool
diff --git a/includes/resourceloader/ResourceLoaderFilePageModule.php b/includes/resourceloader/ResourceLoaderFilePageModule.php
index fc9aef1b..e3b719bb 100644
--- a/includes/resourceloader/ResourceLoaderFilePageModule.php
+++ b/includes/resourceloader/ResourceLoaderFilePageModule.php
@@ -1,8 +1,13 @@
<?php
-/*
+/**
* ResourceLoader definition for MediaWiki:Filepage.css
*/
class ResourceLoaderFilePageModule extends ResourceLoaderWikiModule {
+
+ /**
+ * @param $context ResourceLoaderContext
+ * @return array
+ */
protected function getPages( ResourceLoaderContext $context ) {
return array(
'MediaWiki:Filepage.css' => array( 'type' => 'style' ),
diff --git a/includes/resourceloader/ResourceLoaderModule.php b/includes/resourceloader/ResourceLoaderModule.php
index ae1be5af..1a232ec2 100644
--- a/includes/resourceloader/ResourceLoaderModule.php
+++ b/includes/resourceloader/ResourceLoaderModule.php
@@ -52,11 +52,11 @@ abstract class ResourceLoaderModule {
# limit the types of scripts and styles we allow to load on, say, sensitive special
# pages like Special:UserLogin and Special:Preferences
protected $origin = self::ORIGIN_CORE_SITEWIDE;
-
+
/* Protected Members */
protected $name = null;
-
+
// In-object cache for file dependencies
protected $fileDeps = array();
// In-object cache for message blob mtime
@@ -126,35 +126,36 @@ abstract class ResourceLoaderModule {
// Stub, override expected
return '';
}
-
+
/**
* Get the URL or URLs to load for this module's JS in debug mode.
* The default behavior is to return a load.php?only=scripts URL for
* the module, but file-based modules will want to override this to
* load the files directly.
- *
+ *
* This function is called only when 1) we're in debug mode, 2) there
* is no only= parameter and 3) supportsURLLoading() returns true.
* #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
*/
public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
- global $wgLoadScript; // TODO factor out to ResourceLoader static method and deduplicate from makeResourceLoaderLink()
- $query = array(
- 'modules' => $this->getName(),
- 'only' => 'scripts',
- 'skin' => $context->getSkin(),
- 'user' => $context->getUser(),
- 'debug' => 'true',
- 'version' => $context->getVersion()
+ $url = ResourceLoader::makeLoaderURL(
+ array( $this->getName() ),
+ $context->getLanguage(),
+ $context->getSkin(),
+ $context->getUser(),
+ $context->getVersion(),
+ true, // debug
+ 'scripts', // only
+ $context->getRequest()->getBool( 'printable' ),
+ $context->getRequest()->getBool( 'handheld' )
);
- ksort( $query );
- return array( wfAppendQuery( $wgLoadScript, $query ) . '&*' );
+ return array( $url );
}
-
+
/**
* Whether this module supports URL loading. If this function returns false,
* getScript() will be used even in cases (debug mode, no only param) where
@@ -175,28 +176,29 @@ abstract class ResourceLoaderModule {
// Stub, override expected
return array();
}
-
+
/**
* Get the URL or URLs to load for this module's CSS in debug mode.
* The default behavior is to return a load.php?only=styles URL for
* 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, ... ), ... )
*/
public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
- global $wgLoadScript; // TODO factor out to ResourceLoader static method and deduplicate from makeResourceLoaderLink()
- $query = array(
- 'modules' => $this->getName(),
- 'only' => 'styles',
- 'skin' => $context->getSkin(),
- 'user' => $context->getUser(),
- 'debug' => 'true',
- 'version' => $context->getVersion()
+ $url = ResourceLoader::makeLoaderURL(
+ array( $this->getName() ),
+ $context->getLanguage(),
+ $context->getSkin(),
+ $context->getUser(),
+ $context->getVersion(),
+ true, // debug
+ 'styles', // only
+ $context->getRequest()->getBool( 'printable' ),
+ $context->getRequest()->getBool( 'handheld' )
);
- ksort( $query );
- return array( 'all' => array( wfAppendQuery( $wgLoadScript, $query ) . '&*' ) );
+ return array( 'all' => array( $url ) );
}
/**
@@ -210,17 +212,27 @@ abstract class ResourceLoaderModule {
// Stub, override expected
return array();
}
-
+
/**
* Get the group this module is in.
- *
+ *
* @return String: Group name
*/
public function getGroup() {
// Stub, override expected
return null;
}
-
+
+ /**
+ * Get the origin of this module. Should only be overridden for foreign modules.
+ *
+ * @return String: Origin name, 'local' for local modules
+ */
+ public function getSource() {
+ // Stub, override expected
+ return 'local';
+ }
+
/**
* Where on the HTML page should this module's JS be loaded?
* 'top': in the <head>
@@ -261,7 +273,7 @@ abstract class ResourceLoaderModule {
// Stub, override expected
return array();
}
-
+
/**
* Get the files this module depends on indirectly for a given skin.
* Currently these are only image files referenced by the module's CSS.
@@ -288,7 +300,7 @@ abstract class ResourceLoaderModule {
}
return $this->fileDeps[$skin];
}
-
+
/**
* Set preloaded file dependency information. Used so we can load this
* information for all modules at once.
@@ -298,7 +310,7 @@ abstract class ResourceLoaderModule {
public function setFileDependencies( $skin, $deps ) {
$this->fileDeps[$skin] = $deps;
}
-
+
/**
* Get the last modification timestamp of the message blob for this
* module in a given language.
@@ -309,7 +321,7 @@ abstract class ResourceLoaderModule {
if ( !isset( $this->msgBlobMtime[$lang] ) ) {
if ( !count( $this->getMessages() ) )
return 0;
-
+
$dbr = wfGetDB( DB_SLAVE );
$msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
'mr_resource' => $this->getName(),
@@ -325,7 +337,7 @@ abstract class ResourceLoaderModule {
}
return $this->msgBlobMtime[$lang];
}
-
+
/**
* Set a preloaded message blob last modification timestamp. Used so we
* can load this information for all modules at once.
@@ -335,9 +347,9 @@ abstract class ResourceLoaderModule {
public function setMsgBlobMtime( $lang, $mtime ) {
$this->msgBlobMtime[$lang] = $mtime;
}
-
+
/* Abstract Methods */
-
+
/**
* Get this module's last modification timestamp for a given
* combination of language, skin and debug mode flag. This is typically
@@ -345,6 +357,10 @@ abstract class ResourceLoaderModule {
* timestamps. Whenever anything happens that changes the module's
* contents for these parameters, the mtime should increase.
*
+ * NOTE: The mtime of the module's messages is NOT automatically included.
+ * 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
*/
@@ -352,7 +368,7 @@ abstract class ResourceLoaderModule {
// 0 would mean now
return 1;
}
-
+
/**
* 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
@@ -400,7 +416,7 @@ abstract class ResourceLoaderModule {
$err = $e->getMessage();
$result = "throw new Error(" . Xml::encodeJsVar("JavaScript parse error: $err") . ");";
}
-
+
$cache->set( $key, $result );
return $result;
} else {
@@ -408,6 +424,9 @@ abstract class ResourceLoaderModule {
}
}
+ /**
+ * @return JSParser
+ */
protected static function javaScriptParser() {
if ( !self::$jsParser ) {
self::$jsParser = new JSParser();
diff --git a/includes/resourceloader/ResourceLoaderStartUpModule.php b/includes/resourceloader/ResourceLoaderStartUpModule.php
index 43f1dbd2..5dbce439 100644
--- a/includes/resourceloader/ResourceLoaderStartUpModule.php
+++ b/includes/resourceloader/ResourceLoaderStartUpModule.php
@@ -38,21 +38,8 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule {
$wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgVersion,
$wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest,
$wgSitename, $wgFileExtensions, $wgExtensionAssetsPath,
- $wgCookiePrefix, $wgResourceLoaderMaxQueryLength, $wgLegacyJavaScriptGlobals;
+ $wgCookiePrefix, $wgResourceLoaderMaxQueryLength;
- // Pre-process information
- $separatorTransTable = $wgContLang->separatorTransformTable();
- $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
- $compactSeparatorTransTable = array(
- implode( "\t", array_keys( $separatorTransTable ) ),
- implode( "\t", $separatorTransTable ),
- );
- $digitTransTable = $wgContLang->digitTransformTable();
- $digitTransTable = $digitTransTable ? $digitTransTable : array();
- $compactDigitTransTable = array(
- implode( "\t", array_keys( $digitTransTable ) ),
- implode( "\t", $digitTransTable ),
- );
$mainPage = Title::newMainPage();
/**
@@ -81,7 +68,9 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule {
'wgScriptExtension' => $wgScriptExtension,
'wgScript' => $wgScript,
'wgVariantArticlePath' => $wgVariantArticlePath,
- 'wgActionPaths' => $wgActionPaths,
+ // Force object to avoid "empty" associative array from
+ // becoming [] instead of {} in JS (bug 34604)
+ 'wgActionPaths' => (object)$wgActionPaths,
'wgServer' => $wgServer,
'wgUserLanguage' => $context->getLanguage(),
'wgContentLanguage' => $wgContLang->getCode(),
@@ -91,8 +80,6 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule {
'wgDefaultDateFormat' => $wgContLang->getDefaultDateFormat(),
'wgMonthNames' => $wgContLang->getMonthNamesArray(),
'wgMonthNamesShort' => $wgContLang->getMonthAbbreviationsArray(),
- 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
- 'wgDigitTransformTable' => $compactDigitTransTable,
'wgMainPageTitle' => $mainPage ? $mainPage->getPrefixedText() : null,
'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
'wgNamespaceIds' => $namespaceIds,
@@ -107,7 +94,6 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule {
// MediaWiki sets cookies to have this prefix by default
'wgCookiePrefix' => $wgCookiePrefix,
'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength,
- 'wgLegacyJavaScriptGlobals' => $wgLegacyJavaScriptGlobals,
'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
);
if ( $wgUseAjax && $wgEnableMWSuggest ) {
@@ -132,6 +118,11 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule {
$out = '';
$registrations = array();
$resourceLoader = $context->getResourceLoader();
+
+ // Register sources
+ $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
+
+ // Register modules
foreach ( $resourceLoader->getModuleNames() as $name ) {
$module = $resourceLoader->getModule( $name );
// Support module loader scripts
@@ -139,9 +130,10 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule {
if ( $loader !== false ) {
$deps = $module->getDependencies();
$group = $module->getGroup();
+ $source = $module->getSource();
$version = wfTimestamp( TS_ISO_8601_BASIC,
$module->getModifiedTime( $context ) );
- $out .= ResourceLoader::makeCustomLoaderScript( $name, $version, $deps, $group, $loader );
+ $out .= ResourceLoader::makeCustomLoaderScript( $name, $version, $deps, $group, $source, $loader );
}
// Automatically register module
else {
@@ -149,23 +141,29 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule {
// seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
$moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
$mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $wgCacheEpoch ) );
- // Modules without dependencies or a group pass two arguments (name, timestamp) to
+ // Modules without dependencies, a group or a foreign source pass two arguments (name, timestamp) to
// mw.loader.register()
- if ( !count( $module->getDependencies() && $module->getGroup() === null ) ) {
+ if ( !count( $module->getDependencies() && $module->getGroup() === null && $module->getSource() === 'local' ) ) {
$registrations[] = array( $name, $mtime );
}
- // Modules with dependencies but no group pass three arguments
+ // Modules with dependencies but no group or foreign source pass three arguments
// (name, timestamp, dependencies) to mw.loader.register()
- elseif ( $module->getGroup() === null ) {
+ elseif ( $module->getGroup() === null && $module->getSource() === 'local' ) {
$registrations[] = array(
$name, $mtime, $module->getDependencies() );
}
- // Modules with dependencies pass four arguments (name, timestamp, dependencies, group)
+ // Modules with a group but no foreign source pass four arguments (name, timestamp, dependencies, group)
// to mw.loader.register()
- else {
+ elseif ( $module->getSource() === 'local' ) {
$registrations[] = array(
$name, $mtime, $module->getDependencies(), $module->getGroup() );
}
+ // Modules with a foreign source pass five arguments (name, timestamp, dependencies, group, source)
+ // to mw.loader.register()
+ else {
+ $registrations[] = array(
+ $name, $mtime, $module->getDependencies(), $module->getGroup(), $module->getSource() );
+ }
}
}
$out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
@@ -229,6 +227,9 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule {
return $out;
}
+ /**
+ * @return bool
+ */
public function supportsURLLoading() {
return false;
}
diff --git a/includes/resourceloader/ResourceLoaderUserCSSPrefsModule.php b/includes/resourceloader/ResourceLoaderUserCSSPrefsModule.php
new file mode 100644
index 00000000..02693d3e
--- /dev/null
+++ b/includes/resourceloader/ResourceLoaderUserCSSPrefsModule.php
@@ -0,0 +1,113 @@
+<?php
+/**
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @author Trevor Parscal
+ * @author Roan Kattouw
+ */
+
+/**
+ * Module for user preference customizations
+ */
+class ResourceLoaderUserCSSPrefsModule extends ResourceLoaderModule {
+
+ /* Protected Members */
+
+ protected $modifiedTime = array();
+
+ protected $origin = self::ORIGIN_CORE_INDIVIDUAL;
+
+ /* Methods */
+
+ /**
+ * @param $context ResourceLoaderContext
+ * @return array|int|Mixed
+ */
+ public function getModifiedTime( ResourceLoaderContext $context ) {
+ $hash = $context->getHash();
+ if ( isset( $this->modifiedTime[$hash] ) ) {
+ return $this->modifiedTime[$hash];
+ }
+
+ global $wgUser;
+ return $this->modifiedTime[$hash] = wfTimestamp( TS_UNIX, $wgUser->getTouched() );
+ }
+
+ /**
+ * @param $context ResourceLoaderContext
+ * @return array
+ */
+ public function getStyles( ResourceLoaderContext $context ) {
+ global $wgAllowUserCssPrefs, $wgUser;
+
+ if ( $wgAllowUserCssPrefs ) {
+ $options = $wgUser->getOptions();
+
+ // 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(fa),a:lang(kk-arab), ' .
+ 'a:lang(mzn), a:lang(ps), a:lang(ur) { text-decoration: none; }';
+ }
+ if ( $options['highlightbroken'] ) {
+ $rules[] = "a.new, #quickbar a.new { color: #ba0000; }\n";
+ } else {
+ $rules[] = "a.new, #quickbar a.new, a.stub, #quickbar a.stub { color: inherit; }";
+ $rules[] = "a.new:after, #quickbar a.new:after { content: '?'; color: #ba0000; }";
+ $rules[] = "a.stub:after, #quickbar a.stub:after { content: '!'; color: #772233; }";
+ }
+ 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' ) {
+ $rules[] = "textarea { font-family: {$options['editfont']}; }\n";
+ }
+ $style = implode( "\n", $rules );
+ if ( $this->getFlip( $context ) ) {
+ $style = CSSJanus::transform( $style, true, false );
+ }
+ return array( 'all' => $style );
+ }
+ return array();
+ }
+
+ /**
+ * @return string
+ */
+ public function getGroup() {
+ return 'private';
+ }
+
+ /**
+ * @return array
+ */
+ public function getDependencies() {
+ return array( 'mediawiki.user' );
+ }
+}
diff --git a/includes/resourceloader/ResourceLoaderUserModule.php b/includes/resourceloader/ResourceLoaderUserModule.php
index 892e8462..338b6322 100644
--- a/includes/resourceloader/ResourceLoaderUserModule.php
+++ b/includes/resourceloader/ResourceLoaderUserModule.php
@@ -34,15 +34,30 @@ class ResourceLoaderUserModule extends ResourceLoaderWikiModule {
*/
protected function getPages( ResourceLoaderContext $context ) {
if ( $context->getUser() ) {
+ // Get the normalized title of the user's user page
$username = $context->getUser();
- return array(
- "User:$username/common.js" => array( 'type' => 'script' ),
- "User:$username/" . $context->getSkin() . '.js' =>
+ $userpageTitle = Title::makeTitleSafe( NS_USER, $username );
+ $userpage = $userpageTitle->getPrefixedDBkey(); // Needed so $excludepages works
+
+ $pages = array(
+ "$userpage/common.js" => array( 'type' => 'script' ),
+ "$userpage/" . $context->getSkin() . '.js' =>
array( 'type' => 'script' ),
- "User:$username/common.css" => array( 'type' => 'style' ),
- "User:$username/" . $context->getSkin() . '.css' =>
+ "$userpage/common.css" => array( 'type' => 'style' ),
+ "$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
+ // parameter will be set to the name of the page we need to exclude.
+ $excludepage = $context->getRequest()->getVal( 'excludepage' );
+ if ( isset( $pages[$excludepage] ) ) {
+ // This works because $excludepage is generated with getPrefixedDBkey(),
+ // just like the keys in $pages[] above
+ unset( $pages[$excludepage] );
+ }
+ return $pages;
}
return array();
}
diff --git a/includes/resourceloader/ResourceLoaderUserOptionsModule.php b/includes/resourceloader/ResourceLoaderUserOptionsModule.php
index 78548416..7b162205 100644
--- a/includes/resourceloader/ResourceLoaderUserOptionsModule.php
+++ b/includes/resourceloader/ResourceLoaderUserOptionsModule.php
@@ -42,9 +42,8 @@ class ResourceLoaderUserOptionsModule extends ResourceLoaderModule {
if ( isset( $this->modifiedTime[$hash] ) ) {
return $this->modifiedTime[$hash];
}
-
+
global $wgUser;
-
return $this->modifiedTime[$hash] = wfTimestamp( TS_UNIX, $wgUser->getTouched() );
}
@@ -54,59 +53,11 @@ class ResourceLoaderUserOptionsModule extends ResourceLoaderModule {
*/
public function getScript( ResourceLoaderContext $context ) {
global $wgUser;
- return Xml::encodeJsCall( 'mw.user.options.set',
+ return Xml::encodeJsCall( 'mw.user.options.set',
array( $wgUser->getOptions() ) );
}
/**
- * @param $context ResourceLoaderContext
- * @return array
- */
- public function getStyles( ResourceLoaderContext $context ) {
- global $wgAllowUserCssPrefs, $wgUser;
-
- if ( $wgAllowUserCssPrefs ) {
- $options = $wgUser->getOptions();
-
- // Build CSS rules
- $rules = array();
- 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['highlightbroken'] ) {
- $rules[] = "a.new, #quickbar a.new { color: #ba0000; }\n";
- } else {
- $rules[] = "a.new, #quickbar a.new, a.stub, #quickbar a.stub { color: inherit; }";
- $rules[] = "a.new:after, #quickbar a.new:after { content: '?'; color: #ba0000; }";
- $rules[] = "a.stub:after, #quickbar a.stub:after { content: '!'; color: #772233; }";
- }
- 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' ) {
- $rules[] = "textarea { font-family: {$options['editfont']}; }\n";
- }
- $style = implode( "\n", $rules );
- if ( $this->getFlip( $context ) ) {
- $style = CSSJanus::transform( $style, true, false );
- }
- return array( 'all' => $style );
- }
- return array();
- }
-
- /**
* @return string
*/
public function getGroup() {
diff --git a/includes/resourceloader/ResourceLoaderUserTokensModule.php b/includes/resourceloader/ResourceLoaderUserTokensModule.php
index 9403534c..e1a52388 100644
--- a/includes/resourceloader/ResourceLoaderUserTokensModule.php
+++ b/includes/resourceloader/ResourceLoaderUserTokensModule.php
@@ -32,7 +32,7 @@ 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
*/
@@ -40,7 +40,7 @@ class ResourceLoaderUserTokensModule extends ResourceLoaderModule {
global $wgUser;
return array(
- 'editToken' => $wgUser->edittoken(),
+ 'editToken' => $wgUser->getEditToken(),
'watchToken' => ApiQueryInfo::getWatchToken(null, null),
);
}
@@ -50,7 +50,7 @@ class ResourceLoaderUserTokensModule extends ResourceLoaderModule {
* @return string
*/
public function getScript( ResourceLoaderContext $context ) {
- return Xml::encodeJsCall( 'mw.user.tokens.set',
+ return Xml::encodeJsCall( 'mw.user.tokens.set',
array( $this->contextUserTokens( $context ) ) );
}
diff --git a/includes/resourceloader/ResourceLoaderWikiModule.php b/includes/resourceloader/ResourceLoaderWikiModule.php
index bad61cb9..91a51f89 100644
--- a/includes/resourceloader/ResourceLoaderWikiModule.php
+++ b/includes/resourceloader/ResourceLoaderWikiModule.php
@@ -24,28 +24,47 @@ defined( 'MEDIAWIKI' ) || die( 1 );
/**
* Abstraction for resource loader modules which pull from wiki pages
- *
- * This can only be used for wiki pages in the MediaWiki and User namespaces,
- * because of its dependence on the functionality of
- * Title::isValidCssJsSubpage.
+ *
+ * This can only be used for wiki pages in the MediaWiki and User namespaces,
+ * because of its dependence on the functionality of
+ * Title::isCssJsSubpage.
*/
abstract class ResourceLoaderWikiModule extends ResourceLoaderModule {
-
+
/* Protected Members */
# Origin is user-supplied code
protected $origin = self::ORIGIN_USER_SITEWIDE;
-
+
// In-object cache for title mtimes
protected $titleMtimes = array();
-
+
/* Abstract Protected Methods */
-
+
+ /**
+ * @abstract
+ * @param $context ResourceLoaderContext
+ */
abstract protected function getPages( ResourceLoaderContext $context );
-
+
/* Protected Methods */
/**
+ * Get the Database object used in getTitleMTimes(). Defaults to the local slave DB
+ * but subclasses may want to override this to return a remote DB object, or to return
+ * null if getTitleMTimes() shouldn't access the DB at all.
+ *
+ * NOTE: This ONLY works for getTitleMTimes() and getModifiedTime(), NOT FOR ANYTHING ELSE.
+ * In particular, it doesn't work for getting the content of JS and CSS pages. That functionality
+ * will use the local DB irrespective of the return value of this method.
+ *
+ * @return DatabaseBase|null
+ */
+ protected function getDB() {
+ return wfGetDB( DB_SLAVE );
+ }
+
+ /**
* @param $title Title
* @return null|string
*/
@@ -54,7 +73,7 @@ abstract class ResourceLoaderWikiModule extends ResourceLoaderModule {
$message = wfMessage( $title->getDBkey() )->inContentLanguage();
return $message->exists() ? $message->plain() : '';
}
- if ( !$title->isCssJsSubpage() ) {
+ if ( !$title->isCssJsSubpage() && !$title->isCssOrJsPage() ) {
return null;
}
$revision = Revision::newFromTitle( $title );
@@ -63,7 +82,7 @@ abstract class ResourceLoaderWikiModule extends ResourceLoaderModule {
}
return $revision->getRawText();
}
-
+
/* Methods */
/**
@@ -98,7 +117,7 @@ abstract class ResourceLoaderWikiModule extends ResourceLoaderModule {
*/
public function getStyles( ResourceLoaderContext $context ) {
global $wgScriptPath;
-
+
$styles = array();
foreach ( $this->getPages( $context ) as $titleText => $options ) {
if ( $options['type'] !== 'style' ) {
@@ -107,7 +126,7 @@ abstract class ResourceLoaderWikiModule extends ResourceLoaderModule {
$title = Title::newFromText( $titleText );
if ( !$title || $title->isRedirect() ) {
continue;
- }
+ }
$media = isset( $options['media'] ) ? $options['media'] : 'all';
$style = $this->getContent( $title );
if ( strval( $style ) === '' ) {
@@ -138,6 +157,7 @@ abstract class ResourceLoaderWikiModule extends ResourceLoaderModule {
if ( count( $mtimes ) ) {
$modifiedTime = max( $modifiedTime, max( $mtimes ) );
}
+ $modifiedTime = max( $modifiedTime, $this->getMsgBlobMtime( $context->getLanguage() ) );
return $modifiedTime;
}
@@ -156,19 +176,24 @@ abstract class ResourceLoaderWikiModule extends ResourceLoaderModule {
* @return array( prefixed DB key => UNIX timestamp ), nonexistent titles are dropped
*/
protected function getTitleMtimes( ResourceLoaderContext $context ) {
+ $dbr = $this->getDB();
+ if ( !$dbr ) {
+ // We're dealing with a subclass that doesn't have a DB
+ return array();
+ }
+
$hash = $context->getHash();
if ( isset( $this->titleMtimes[$hash] ) ) {
return $this->titleMtimes[$hash];
}
-
+
$this->titleMtimes[$hash] = array();
$batch = new LinkBatch;
foreach ( $this->getPages( $context ) as $titleText => $options ) {
$batch->addObj( Title::newFromText( $titleText ) );
}
-
+
if ( !$batch->isEmpty() ) {
- $dbr = wfGetDB( DB_SLAVE );
$res = $dbr->select( 'page',
array( 'page_namespace', 'page_title', 'page_touched' ),
$batch->constructSet( 'page', $dbr ),