wiki.techinc.nl/includes/resourceloader/ResourceLoaderFileModule.php

675 lines
20 KiB
PHP
Raw Normal View History

<?php
/**
* Resource loader module based on local JavaScript/CSS files.
*
* 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
*/
/**
* ResourceLoader module based on local JavaScript/CSS files.
*/
class ResourceLoaderFileModule extends ResourceLoaderModule {
/* Protected Members */
2010-10-19 23:02:15 +00:00
/** String: Local base path, see __construct() */
protected $localBasePath = '';
/** String: Remote base path, see __construct() */
protected $remoteBasePath = '';
/**
* Array: List of paths to JavaScript files to always include
* @par Usage:
* @code
* array( [file-path], [file-path], ... )
* @endcode
*/
protected $scripts = array();
/**
* Array: List of JavaScript files to include when using a specific language
* @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
* @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
* @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
* @par Usage:
* @code
* array( [file-path], [file-path], ... )
* @endcode
*/
protected $loaderScripts = array();
/**
* Array: List of paths to CSS files to always include
* @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
* @par Usage:
* @code
* array( [file-path], [file-path], ... )
* @endcode
*/
protected $skinStyles = array();
/**
* Array: List of modules this module depends on
* @par Usage:
* @code
* array( [file-path], [file-path], ... )
* @endcode
*/
protected $dependencies = array();
/**
* Array: List of message keys used by this module
* @par Usage:
* @code
* array( [message-key], [message-key], ... )
* @endcode
*/
2010-10-26 20:17:32 +00:00
protected $messages = array();
/** String: Name of group to load this module in */
protected $group;
/** String: Position on the page to load this module at */
protected $position = 'bottom';
/** Boolean: Link to raw files in debug mode */
protected $debugRaw = true;
/** Boolean: Whether mw.loader.state() call should be omitted */
protected $raw = false;
protected $targets = array( 'desktop' );
/**
* Array: Cache for mtime
* @par Usage:
* @code
* array( [hash] => [mtime], [hash] => [mtime], ... )
* @endcode
*/
protected $modifiedTime = array();
/**
* Array: Place where readStyleFile() tracks file dependencies
* @par Usage:
* @code
* array( [file-path], [file-path], ... )
* @endcode
*/
protected $localFileRefs = array();
/* Methods */
/**
* Constructs a new module from an options array.
*
* @param array $options List of options; if not given or empty, an empty module will be
* constructed
* @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
* to $IP
* @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
* to $wgScriptPath
2011-03-02 20:28:32 +00:00
*
* Below is a description for the $options array:
* @throws MWException
* @par Construction options:
2011-03-02 20:28:32 +00:00
* @code
* array(
* // Base path to prepend to all local paths in $options. Defaults to $IP
* 'localBasePath' => [base path],
* // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
* 'remoteBasePath' => [base path],
* // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
* 'remoteExtPath' => [base path],
* // Scripts to always include
* 'scripts' => [file path string or array of file path strings],
* // Scripts to include in specific language contexts
* 'languageScripts' => array(
* [language code] => [file path string or array of file path strings],
* ),
* // Scripts to include in specific skin contexts
* 'skinScripts' => array(
* [skin name] => [file path string or array of file path strings],
* ),
* // Scripts to include in debug contexts
* 'debugScripts' => [file path string or array of file path strings],
* // Scripts to include in the startup module
* 'loaderScripts' => [file path string or array of file path strings],
* // Modules which must be loaded before this module
* 'dependencies' => [module name string or array of module name strings],
* // Styles to always load
* 'styles' => [file path string or array of file path strings],
* // Styles to include in specific skin contexts
* 'skinStyles' => array(
* [skin name] => [file path string or array of file path strings],
* ),
* // Messages to always load
* 'messages' => [array of message key strings],
* // Group which this module should be loaded together with
* 'group' => [group name string],
* // Position on the page to load this module at
* 'position' => ['bottom' (default) or 'top']
* )
2011-03-02 20:28:32 +00:00
* @endcode
*/
public function __construct( $options = array(), $localBasePath = null,
$remoteBasePath = null
) {
2011-10-03 13:37:47 +00:00
global $IP, $wgScriptPath, $wgResourceBasePath;
$this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
2011-10-03 13:37:47 +00:00
if ( $remoteBasePath !== null ) {
$this->remoteBasePath = $remoteBasePath;
} else {
$this->remoteBasePath = $wgResourceBasePath === null ? $wgScriptPath : $wgResourceBasePath;
}
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler. * Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage. * Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself. * Modified ResourceLoader::register() to optionally accept an info array instead of an object. * Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely. * Moved ResourceLoader settings to their own section in DefaultSettings.php * Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known. * Added OutputPage::getResourceLoader(), mostly for debugging. * The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs. Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
if ( isset( $options['remoteExtPath'] ) ) {
global $wgExtensionAssetsPath;
$this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
}
foreach ( $options as $member => $option ) {
switch ( $member ) {
// Lists of file paths
case 'scripts':
case 'debugScripts':
case 'loaderScripts':
case 'styles':
$this->{$member} = (array)$option;
break;
// Collated lists of file paths
case 'languageScripts':
case 'skinScripts':
case 'skinStyles':
if ( !is_array( $option ) ) {
throw new MWException(
"Invalid collated file path list error. " .
"'$option' given, array expected."
);
}
foreach ( $option as $key => $value ) {
if ( !is_string( $key ) ) {
throw new MWException(
"Invalid collated file path list key error. " .
"'$key' given, string expected."
);
}
$this->{$member}[$key] = (array)$value;
}
break;
// Lists of strings
case 'dependencies':
case 'messages':
case 'targets':
$this->{$member} = (array)$option;
break;
// Single strings
case 'group':
case 'position':
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler. * Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage. * Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself. * Modified ResourceLoader::register() to optionally accept an info array instead of an object. * Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely. * Moved ResourceLoader settings to their own section in DefaultSettings.php * Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known. * Added OutputPage::getResourceLoader(), mostly for debugging. * The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs. Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
case 'localBasePath':
case 'remoteBasePath':
$this->{$member} = (string)$option;
break;
// Single booleans
case 'debugRaw':
case 'raw':
$this->{$member} = (bool)$option;
break;
}
}
// Make sure the remote base path is a complete valid URL,
// but possibly protocol-relative to avoid cache pollution
2011-08-03 13:11:42 +00:00
$this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
}
/**
* Gets all scripts for a given context concatenated together.
*
* @param $context ResourceLoaderContext: Context in which to generate script
* @return String: JavaScript code for $context
*/
public function getScript( ResourceLoaderContext $context ) {
$files = $this->getScriptFiles( $context );
return $this->readScriptFiles( $files );
}
/**
* @param $context ResourceLoaderContext
* @return array
*/
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
$urls = array();
foreach ( $this->getScriptFiles( $context ) as $file ) {
$urls[] = $this->getRemotePath( $file );
}
return $urls;
}
/**
* @return bool
*/
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
public function supportsURLLoading() {
return $this->debugRaw;
}
/**
* Gets loader script.
*
* @return String: JavaScript code to be added to startup module
*/
public function getLoaderScript() {
if ( count( $this->loaderScripts ) == 0 ) {
return false;
}
return $this->readScriptFiles( $this->loaderScripts );
}
/**
* Gets all styles for a given context concatenated together.
*
* @param $context ResourceLoaderContext: Context in which to generate styles
* @return String: CSS code for $context
*/
public function getStyles( ResourceLoaderContext $context ) {
$styles = $this->readStyleFiles(
$this->getStyleFiles( $context ),
$this->getFlip( $context )
);
// Collect referenced files
$this->localFileRefs = array_unique( $this->localFileRefs );
// If the list has been modified since last time we cached it, update the cache
try {
if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
$dbw = wfGetDB( DB_MASTER );
$dbw->replace( 'module_deps',
array( array( 'md_module', 'md_skin' ) ), array(
'md_module' => $this->getName(),
'md_skin' => $context->getSkin(),
'md_deps' => FormatJson::encode( $this->localFileRefs ),
)
);
}
} catch ( Exception $e ) {
wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
}
return $styles;
}
/**
* @param $context ResourceLoaderContext
* @return array
*/
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
$urls = array();
foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
$urls[$mediaType] = array();
foreach ( $list as $file ) {
$urls[$mediaType][] = $this->getRemotePath( $file );
}
}
return $urls;
}
/**
* Gets list of message keys used by this module.
*
* @return Array: List of message keys
*/
public function getMessages() {
return $this->messages;
}
/**
* Gets the name of the group this module should be loaded in.
*
* @return String: Group name
*/
public function getGroup() {
return $this->group;
}
/**
* @return string
*/
public function getPosition() {
return $this->position;
}
/**
* Gets list of names of modules this module depends on.
*
* @return Array: List of module names
*/
public function getDependencies() {
return $this->dependencies;
}
/**
* @return bool
*/
public function isRaw() {
return $this->raw;
}
/**
* Get the last modified timestamp of this module.
*
* Last modified timestamps are calculated from the highest last modified
* timestamp of this module's constituent files as well as the files it
* depends on. This function is context-sensitive, only performing
* calculations on files relevant to the given language, skin and debug
* mode.
*
* @param $context ResourceLoaderContext: Context in which to calculate
* the modified time
* @return Integer: UNIX timestamp
* @see ResourceLoaderModule::getFileDependencies
*/
public function getModifiedTime( ResourceLoaderContext $context ) {
if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
return $this->modifiedTime[$context->getHash()];
}
wfProfileIn( __METHOD__ );
2010-10-19 23:47:56 +00:00
$files = array();
2010-10-19 23:47:56 +00:00
// Flatten style files into $files
$styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
foreach ( $styles as $styleFiles ) {
$files = array_merge( $files, $styleFiles );
}
$skinFiles = self::tryForKey(
self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
$context->getSkin(),
'default'
);
foreach ( $skinFiles as $styleFiles ) {
2010-10-19 23:47:56 +00:00
$files = array_merge( $files, $styleFiles );
}
// Final merge, this should result in a master list of dependent files
$files = array_merge(
2010-10-19 23:47:56 +00:00
$files,
$this->scripts,
$context->getDebug() ? $this->debugScripts : array(),
self::tryForKey( $this->languageScripts, $context->getLanguage() ),
self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
$this->loaderScripts
);
$files = array_map( array( $this, 'getLocalPath' ), $files );
// File deps need to be treated separately because they're already prefixed
$files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
// If a module is nothing but a list of dependencies, we need to avoid
// giving max() an empty array
if ( count( $files ) === 0 ) {
2011-02-10 16:39:53 +00:00
wfProfileOut( __METHOD__ );
return $this->modifiedTime[$context->getHash()] = 1;
}
wfProfileIn( __METHOD__ . '-filemtime' );
$filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
wfProfileOut( __METHOD__ . '-filemtime' );
$this->modifiedTime[$context->getHash()] = max(
$filesMtime,
$this->getMsgBlobMtime( $context->getLanguage() ) );
2011-02-10 16:39:53 +00:00
wfProfileOut( __METHOD__ );
return $this->modifiedTime[$context->getHash()];
}
/* Protected Methods */
/**
* @param $path string
* @return string
*/
protected function getLocalPath( $path ) {
return "{$this->localBasePath}/$path";
}
/**
* @param $path string
* @return string
*/
protected function getRemotePath( $path ) {
return "{$this->remoteBasePath}/$path";
}
/**
* 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
2010-11-08 10:19:28 +00:00
* @param $default Mixed: 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 ) {
if ( is_int( $key ) ) {
// File name as the value
if ( !isset( $collatedFiles[$default] ) ) {
$collatedFiles[$default] = array();
}
$collatedFiles[$default][] = $value;
} elseif ( is_array( $value ) ) {
// File name as the key, options array as the value
$optionValue = isset( $value[$option] ) ? $value[$option] : $default;
if ( !isset( $collatedFiles[$optionValue] ) ) {
$collatedFiles[$optionValue] = array();
}
$collatedFiles[$optionValue][] = $key;
}
}
return $collatedFiles;
}
/**
* Gets a list of element that match a key, optionally using a fallback key.
*
* @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,
* or an empty list in case of no match
*/
protected static function tryForKey( array $list, $key, $fallback = null ) {
if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
return $list[$key];
} elseif ( is_string( $fallback )
&& isset( $list[$fallback] )
&& is_array( $list[$fallback] ) )
{
return $list[$fallback];
}
return array();
}
/**
* 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
*/
protected function getScriptFiles( ResourceLoaderContext $context ) {
$files = array_merge(
$this->scripts,
self::tryForKey( $this->languageScripts, $context->getLanguage() ),
self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
);
if ( $context->getDebug() ) {
$files = array_merge( $files, $this->debugScripts );
}
return array_unique( $files );
}
/**
* 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
*/
protected function getStyleFiles( ResourceLoaderContext $context ) {
return array_merge_recursive(
self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
self::collateFilePathListByOption(
self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ), 'media', 'all'
)
);
}
/**
* 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
*/
protected function readScriptFiles( array $scripts ) {
global $wgResourceLoaderValidateStaticJS;
if ( empty( $scripts ) ) {
return '';
}
$js = '';
foreach ( array_unique( $scripts ) as $fileName ) {
$localPath = $this->getLocalPath( $fileName );
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
// admin interference.
$contents = $this->validateScriptFile( $fileName, $contents );
}
$js .= $contents . "\n";
}
return $js;
}
/**
* Gets the contents of a list of CSS files.
*
* @param array $styles List of media type/list of file paths pairs, to read, remap and
* concetenate
*
* @param $flip bool
*
* @return Array: List of concatenated and remapped CSS data from $styles,
* keyed by media type
*/
protected function readStyleFiles( array $styles, $flip ) {
if ( empty( $styles ) ) {
return array();
}
foreach ( $styles as $media => $files ) {
$uniqueFiles = array_unique( $files );
$styles[$media] = implode(
"\n",
array_map(
array( $this, 'readStyleFile' ),
$uniqueFiles,
array_fill( 0, count( $uniqueFiles ), $flip )
)
);
}
return $styles;
}
/**
* Reads a style file.
*
* This method can be used as a callback for array_map()
*
* @param string $path 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 );
if ( !file_exists( $localPath ) ) {
$msg = __METHOD__ . ": style file not found: \"$localPath\"";
wfDebugLog( 'resourceloader', $msg );
throw new MWException( $msg );
}
$style = file_get_contents( $localPath );
if ( $flip ) {
$style = CSSJanus::transform( $style, true, false );
}
2011-01-09 12:48:30 +00:00
$dirname = dirname( $path );
if ( $dirname == '.' ) {
// If $path doesn't have a directory component, don't prepend a dot
$dirname = '';
}
$dir = $this->getLocalPath( $dirname );
$remoteDir = $this->getRemotePath( $dirname );
// Get and register local file references
$this->localFileRefs = array_merge(
$this->localFileRefs,
ResourceLoader: Refactor style loading Fixes: * bug 31676: Work around IE stylesheet limit. * bug 35562: @import styles broken in modules that combine multiple stylesheets. * bug 40498: Don't output empty "@media print { }" blocks. * bug 40500: Don't ignore media-type for urls in debug mode. Approach: * Re-use the same <style> tag so that we stay under the 31 stylesheet limit in IE. Unless the to-be-added css text from the being-loaded module contains @import, in which case we do create a new <style> tag and then re-use that one from that point on (bug 31676). * Return stylesheets as arrays, instead of a concatenated string. This fixes bug 35562, because @import only works when at the top of a stylesheet. By not unconditionally concatenating files within a module on the server side already, @import will work in e.g. module 'site' that contains 2 wiki pages. This is normalized in ResourceLoader::makeCombinedStyles(), so far only ResourceLoaderWikiModule makes use of this. Misc. clean up and bug fixes: * Reducing usage of jQuery() and mw.html.element() where native DOM would be very simple and faster. Aside from simplicity and speed, this is also working towards a more stand-alone ResourceLoader. * Trim server output a little bit more - Redundant new line after minify-css (it is now an array, so no need to keep space afterwards) - Redundant semi-colon after minify-js if it ends in a colon * Allow space in styleTest.css.php * Clean up and extend unit tests to cover for these features and bug fixes. * Don't set styleEl.rel = 'stylesheet'; that has no business on a <style> tag. * Fix bug in mw.loader's addStyleTag(). It turns out IE6 has an odd security measure that does not allow manipulation of elements (at least style tags) that are created by a different script (even if that script was served from the same domain/origin etc.). We didn't ran into this before because we only created new style tags, never appended to them. Now that we do, this came up. Took a while to figure out because it was created by mediawiki.js but it calls jQuery which did the actual dom insertion. Odd thing is, we load jquery.js and mediawiki.js in the same request even... Without this all css-url related mw.loader tests would fail in IE6. * mediawiki.js and mediawiki.test.js now pass jshint again. Tested (and passing qunit/?module=mediawiki; 123 of 123): * Chrome 14, 21 * Firefox 3.0, 3.6, 4, 7, 14, 15, 16beta * IE 6, 7, 8, 9 * Safari 4.0, 5.0, 5.1 * Opera 10.0, 11.1, 11.5, 11.6, 12.0, 12.5beta * iPhone 3GS / iOS 3.0 / Mobile Safari 4.0 iPhone 4 / iOS 4.0.1 / Mobile Safari 4.0.5 iPhone 4S / iOS 6.0 Beta / Mobile Safari 6.0 Change-Id: I3e8227ddb87fd9441071ca935439fc6467751dab
2012-07-25 21:20:21 +00:00
CSSMin::getLocalFileReferences( $style, $dir )
);
return CSSMin::remap(
$style, $dir, $remoteDir, true
);
}
/**
* Get whether CSS for this module should be flipped
* @param $context ResourceLoaderContext
* @return bool
*/
public function getFlip( $context ) {
return $context->getDirection() === 'rtl';
}
/**
* Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
*
* @return array of strings
*/
public function getTargets() {
return $this->targets;
}
}